oculon 0.1.1 → 0.1.3

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.
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Oculon Analyst: the tool-using agent behind /ask, answering as an intelligence brief instead of chat prose.
3
+ * - Every source a tool touched gets a number; findings cite those numbers, and only those (invented links are dropped).
4
+ * - The brief carries a 0-100 confidence with its reason, what is still unknown and what would change the conclusion.
5
+ * - Cross-examination: other models re-read the same evidence and mark each finding supported, partly or unsupported.
6
+ * Models run through OpenRouter; the choice is the user's.
7
+ */
8
+ import { randomBytes } from 'node:crypto';
9
+ import { existsSync, readFileSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { runAgent } from './agent.js';
13
+ import { activeTools, SERVER_INFO } from './mcp.js';
14
+ import { chat } from './core/llm.js';
15
+ import { scrubSecrets } from './core/keys.js';
16
+ export const ANALYST_MODELS = {
17
+ haiku: { id: 'anthropic/claude-haiku-5.5', label: 'Claude Haiku 5.5', note: 'fast' },
18
+ opus: { id: 'anthropic/claude-opus-5.5', label: 'Claude Opus 5.5', note: 'thorough' },
19
+ gpt: { id: 'openai/gpt-6.2-astra', label: 'GPT-6.2 Astra', note: 'second view' },
20
+ };
21
+ export const isAnalystModel = (m) => typeof m === 'string' && m in ANALYST_MODELS;
22
+ const SYSTEM = `You are Oculon Analyst. You can answer any question, and you answer by researching it first, then writing a short brief with sources.
23
+ What you can reach:
24
+ - Questions about Oculon itself (what it is, features, install, CLI, MCP, SDK, API, configuration, limits, pricing, privacy): call oculon_docs (its sections are the full documentation text, so there is no need to open docs pages). Never guess about Oculon.
25
+ - Live world data that Oculon covers (outages, BGP, CVEs and exploits, quakes and disasters, weather and air, flights and military air, ships, satellites, fires, night lights, recalls, scams and risky links, email security, companies and filings, markets and prediction markets, research papers, country and travel risk, news): call the matching Oculon tools.
26
+ - Everything else (history, science, products, people, how-to, comparisons, current events beyond the tools): oculon_web_search, then oculon_read_page on the 1-3 best pages when snippets are not enough. Prefer official and primary sources (government, standards bodies, company sites, papers, established outlets) over forums and social posts.
27
+ How to work:
28
+ - First write ONE short line in this exact form, then call tools in the same turn: "Plan: <part 1> · <part 2> · <part 3>". Split the question into the parts it needs (1-4).
29
+ - Cover every part. Run independent searches and tools in parallel; search each part separately with specific queries (names, dates, places). If results are thin or conflict, search again or read a page before answering.
30
+ - Do not answer from memory when a tool can check it. Only general background that needs no checking may come from your own knowledge, and it gets no source number.
31
+ - Tool results end with "Numbered sources". Cite them as numbers. Never cite anything that is not in those lists, and never invent links.
32
+ - Sources marked ERROR or UNAVAILABLE returned nothing; never present them as evidence. When sources disagree, say so.
33
+ - Prefer concrete facts: numbers, dates, names, places. Separate what the data shows from what it suggests.
34
+ When you are done, reply with ONE JSON object and nothing else:
35
+ {
36
+ "headline": "the answer in at most 10 words",
37
+ "bottomLine": "1-3 sentences that answer the question directly",
38
+ "details": "optional: when the question asks how, why, steps or a comparison, a clear explanation in short paragraphs or '- ' bullet lines (at most 180 words), citing [n] inline; otherwise an empty string",
39
+ "confidence": 0-100 (how well the checked data supports the bottom line; low when sources are few, stale or failed),
40
+ "confidenceWhy": "one sentence: why this confidence",
41
+ "findings": [{"text": "one concrete finding", "sources": [1, 2]}] (2-6 findings, each with at least one source number),
42
+ "unknowns": ["what the data could not show"] (0-3 items),
43
+ "changeMyMind": "the new evidence that would change the bottom line",
44
+ "followUps": ["three short follow-up questions the user might ask next"],
45
+ "watch": "a plain-language monitor request worth setting up (e.g. 'internet outages in Iran'), or null"
46
+ }
47
+ Write every text field in the language of the user's question.`;
48
+ const REVIEW_SYSTEM = `You are a skeptical reviewer cross-examining an intelligence brief written by another analyst.
49
+ You get the evidence the analyst saw (tool results with numbered sources) and the brief.
50
+ Judge only against that evidence, not your own knowledge. Reply with ONE JSON object and nothing else:
51
+ {
52
+ "findings": [{"i": 0, "verdict": "supported" | "partly" | "unsupported", "note": "at most 15 words"}] (one per finding, same order),
53
+ "bottomLine": "agree" | "partly" | "disagree",
54
+ "missed": "one sentence on something important in the evidence the brief left out, or null"
55
+ }`;
56
+ const LINK_TEXT = ['title', 'headline', 'name', 'question', 'text', 'summary', 'description', 'id'];
57
+ /** Pull feed names (with their best status) and article-like links out of a tool result. */
58
+ function collectSources(raw, tool) {
59
+ const feeds = [];
60
+ const links = [];
61
+ const rank = ['LIVE', 'CACHED', 'UNAVAILABLE', 'ERROR'];
62
+ // Provenance comes either summarized ({ sources: { name: { LIVE: 2 } } }) or as the raw list of fetches.
63
+ const provRaw = raw?.provenance;
64
+ const counts = new Map();
65
+ if (Array.isArray(provRaw)) {
66
+ for (const p of provRaw) {
67
+ if (typeof p?.source !== 'string')
68
+ continue;
69
+ const c = counts.get(p.source) ?? {};
70
+ c[String(p.status)] = (c[String(p.status)] ?? 0) + 1;
71
+ counts.set(p.source, c);
72
+ }
73
+ }
74
+ else if (provRaw && typeof provRaw === 'object' && provRaw.sources) {
75
+ for (const [label, c] of Object.entries(provRaw.sources))
76
+ counts.set(label, c);
77
+ }
78
+ // Some tools (web search, page reader) report a single source at the top level instead.
79
+ const top = raw;
80
+ if (typeof top?.source === 'string' && typeof top?.status === 'string' && !counts.has(top.source))
81
+ counts.set(top.source, { [top.status]: 1 });
82
+ for (const [label, c] of counts)
83
+ feeds.push({ label, status: rank.find((s) => c[s]) ?? Object.keys(c)[0] ?? 'UNKNOWN' });
84
+ const seen = new Set();
85
+ const walk = (v, depth) => {
86
+ if (links.length >= 8 || depth > 6 || !v || typeof v !== 'object')
87
+ return;
88
+ if (Array.isArray(v)) {
89
+ for (const x of v.slice(0, 25))
90
+ walk(x, depth + 1);
91
+ return;
92
+ }
93
+ const o = v;
94
+ // CVE records often carry no link; their NVD page is the canonical one.
95
+ const cve = [o.cveID, o.cve, o.id].find((x) => typeof x === 'string' && /^CVE-\d{4}-\d{4,}$/.test(x));
96
+ const url = typeof o.url === 'string' ? o.url : typeof o.link === 'string' ? o.link : cve ? `https://nvd.nist.gov/vuln/detail/${cve}` : null;
97
+ if (url && /^https?:\/\//.test(url) && !seen.has(url) && !/[?&](api[_-]?key|key|token|apikey)=/i.test(url)) {
98
+ const named = LINK_TEXT.map((k) => o[k]).find((x) => typeof x === 'string' && x.trim().length > 2);
99
+ const text = cve ? `${cve}${typeof o.vulnerabilityName === 'string' ? ` · ${o.vulnerabilityName}` : named && named !== cve ? ` · ${named}` : ''}` : named;
100
+ if (text) {
101
+ seen.add(url);
102
+ links.push({ label: text.replace(/\s+/g, ' ').trim().slice(0, 140), url });
103
+ }
104
+ }
105
+ for (const [k, x] of Object.entries(o))
106
+ if (k !== 'provenance')
107
+ walk(x, depth + 1);
108
+ };
109
+ // The whole result, minus provenance (its URLs are API endpoints, not something to read).
110
+ walk(raw, 0);
111
+ void tool;
112
+ return { feeds, links };
113
+ }
114
+ /** Lenient JSON from a model reply: strips code fences and takes the outermost object. */
115
+ function parseJson(text) {
116
+ const t = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```\s*$/, '');
117
+ const a = t.indexOf('{');
118
+ const b = t.lastIndexOf('}');
119
+ if (a < 0 || b <= a)
120
+ return null;
121
+ try {
122
+ return JSON.parse(t.slice(a, b + 1));
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ }
128
+ const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
129
+ const strList = (v, n, max) => (Array.isArray(v) ? v.map((x) => str(x, max)).filter(Boolean).slice(0, n) : []);
130
+ function toBrief(answer, validN) {
131
+ const j = parseJson(answer);
132
+ if (!j) {
133
+ return { headline: '', bottomLine: answer.trim().slice(0, 1200) || 'No answer.', details: '', confidence: 0, confidenceWhy: 'The model did not return a structured brief.', findings: [], unknowns: [], changeMyMind: '', followUps: [], watch: null };
134
+ }
135
+ const findings = (Array.isArray(j.findings) ? j.findings : [])
136
+ .map((f) => {
137
+ const o = (f ?? {});
138
+ const sources = (Array.isArray(o.sources) ? o.sources : []).map(Number).filter((n) => validN.has(n));
139
+ return { text: str(o.text, 400), sources: [...new Set(sources)].slice(0, 6) };
140
+ })
141
+ .filter((f) => f.text)
142
+ .slice(0, 8);
143
+ const c = Number(j.confidence);
144
+ return {
145
+ headline: str(j.headline, 120),
146
+ bottomLine: str(j.bottomLine, 900),
147
+ // Inline citations may only point at real sources.
148
+ details: str(j.details, 2400).replace(/\[(\d+)\]/g, (m, n) => (validN.has(Number(n)) ? m : '')),
149
+ confidence: Number.isFinite(c) ? Math.max(0, Math.min(100, Math.round(c))) : 0,
150
+ confidenceWhy: str(j.confidenceWhy, 300),
151
+ findings,
152
+ unknowns: strList(j.unknowns, 4, 240),
153
+ changeMyMind: str(j.changeMyMind, 300),
154
+ followUps: strList(j.followUps, 3, 140),
155
+ watch: str(j.watch, 200) || null,
156
+ };
157
+ }
158
+ let docsCache = null;
159
+ const docSlug = (s) => s.toLowerCase().replace(/<[^>]+>/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
160
+ /** README.md split into its ## and ### sections (the same text the docs site renders). */
161
+ function docSections() {
162
+ if (docsCache)
163
+ return docsCache;
164
+ const here = dirname(fileURLToPath(import.meta.url));
165
+ const file = [join(here, '..', 'README.md'), join(here, '..', '..', 'README.md')].find((p) => existsSync(p));
166
+ const out = [];
167
+ if (file) {
168
+ let cur = null;
169
+ for (const line of readFileSync(file, 'utf8').replace(/\r\n/g, '\n').split('\n')) {
170
+ const h = /^(#{2,3})\s+(.*)$/.exec(line);
171
+ if (h) {
172
+ cur = { slug: docSlug(h[2]), title: h[2].trim(), text: '' };
173
+ out.push(cur);
174
+ continue;
175
+ }
176
+ if (cur && !/^\s*\[!\[/.test(line))
177
+ cur.text += line + '\n';
178
+ }
179
+ }
180
+ docsCache = out;
181
+ return out;
182
+ }
183
+ const STOP = new Set(['the', 'and', 'for', 'with', 'how', 'what', 'does', 'can', 'oculon', 'are', 'is', 'do', 'use', 'using', 'from', 'this', 'that', 'into', 'about', 'which', 'when', 'where', 'why', 'there', 'their', 'have', 'has', 'you', 'your', 'its']);
184
+ export function searchDocs(query, max = 3) {
185
+ const words = query.toLowerCase().match(/[a-z0-9][a-z0-9.-]{1,}/g)?.filter((w) => !STOP.has(w)) ?? [];
186
+ const domain = (process.env.OCULON_DOMAIN || 'oculon.live').trim();
187
+ const scored = docSections().filter((s) => s.slug !== 'contents').map((s) => {
188
+ const head = s.title.toLowerCase();
189
+ const body = s.text.toLowerCase();
190
+ let score = 0;
191
+ for (const w of words) {
192
+ if (head.includes(w))
193
+ score += 6;
194
+ score += Math.min(8, body.split(w).length - 1);
195
+ }
196
+ return { s, score };
197
+ });
198
+ return scored
199
+ .filter((x) => x.score > 0)
200
+ .sort((a, b) => b.score - a.score)
201
+ .slice(0, max)
202
+ .map(({ s }) => ({ title: `Oculon docs: ${s.title}`, url: `https://docs.${domain}/${s.slug}`, text: s.text.trim().slice(0, 4000) }));
203
+ }
204
+ const DOCS_TOOL = {
205
+ name: 'oculon_docs',
206
+ description: "Oculon's own documentation: what Oculon is, every module and its sources, install, CLI commands, MCP server (local and remote), SDK, web app, Telegram bot, API, configuration and keys, deployment, how it works, limits, privacy. Use it for any question about Oculon itself.",
207
+ inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'What to look up, e.g. "remote MCP Claude setup" or "which sources need a key"' } }, required: ['query'] },
208
+ run: (_o, a) => {
209
+ const sections = searchDocs(String(a.query ?? ''));
210
+ return { about: { version: SERVER_INFO.version, mcpTools: activeTools().length, site: 'https://oculon.live', docs: 'https://docs.oculon.live', analyst: 'https://oculon.live/ask', remoteMcp: 'https://mcp.oculon.live', repo: 'https://github.com/oculonlive/oculon', npm: 'https://www.npmjs.com/package/oculon' }, sections, source: 'oculon-docs', status: 'LIVE' };
211
+ },
212
+ };
213
+ /** "oculon_url_check" -> "URL check" */
214
+ export function toolLabel(name) {
215
+ const s = name.replace(/^oculon_/, '').replace(/_/g, ' ');
216
+ return s.replace(/\b(url|cve|cves|bgp|mcp|sdk|ip|faa|ais)\b/gi, (m) => m.toUpperCase()).replace(/^./, (c) => c.toUpperCase());
217
+ }
218
+ /** Evidence kept for cross-examination, by brief id, for two hours. */
219
+ const EVIDENCE = new Map();
220
+ function remember(id, v) {
221
+ const now = Date.now();
222
+ for (const [k, e] of EVIDENCE)
223
+ if (now - e.at > 2 * 3600_000 || EVIDENCE.size > 400)
224
+ EVIDENCE.delete(k);
225
+ EVIDENCE.set(id, { at: now, ...v });
226
+ }
227
+ export async function analyst(o, opts) {
228
+ const t0 = Date.now();
229
+ const model = ANALYST_MODELS[opts.model];
230
+ const emit = (e) => { try {
231
+ opts.onEvent?.(e);
232
+ }
233
+ catch { } };
234
+ const sources = [];
235
+ const byKey = new Map();
236
+ const steps = [];
237
+ const add = (key, s) => {
238
+ const had = byKey.get(key);
239
+ if (had)
240
+ return had;
241
+ const n = sources.length + 1;
242
+ sources.push({ n, ...s });
243
+ byKey.set(key, n);
244
+ return n;
245
+ };
246
+ emit({ type: 'start', model: opts.model, label: model.label });
247
+ const history = (opts.history ?? []).slice(-4).flatMap((h) => [
248
+ { role: 'user', content: h.q.slice(0, 500) },
249
+ { role: 'assistant', content: `(earlier brief) ${h.a.slice(0, 700)}` },
250
+ ]);
251
+ const run = await runAgent(o, SYSTEM, opts.question, {
252
+ route: model.id,
253
+ premium: false,
254
+ maxSteps: 8,
255
+ maxTokens: 3000,
256
+ history,
257
+ extraTools: [DOCS_TOOL],
258
+ onThought: (text) => {
259
+ const plan = /plan:\s*(.+)/i.exec(text)?.[1];
260
+ if (plan)
261
+ emit({ type: 'plan', parts: plan.split(/\s*[·•|;]\s*/).map((p) => p.trim()).filter(Boolean).slice(0, 5) });
262
+ },
263
+ onToolStart: ({ id, tool, args }) => emit({ type: 'step', id, tool, label: toolLabel(tool), args: scrubSecrets(JSON.stringify(args)).slice(0, 160) }),
264
+ onToolResult: ({ id, tool, args, ok, ms, raw }) => {
265
+ const { feeds, links } = ok ? collectSources(raw, tool) : { feeds: [], links: [] };
266
+ // A page that was read is a source itself; its result carries only the text.
267
+ if (ok && tool === 'oculon_read_page' && typeof args.url === 'string' && /^https?:\/\//.test(args.url)) {
268
+ const text = String(raw?.text ?? '');
269
+ const title = /^Title:\s*(.+)$/m.exec(text)?.[1] ?? /^#\s+(.+)$/m.exec(text)?.[1] ?? args.url;
270
+ links.unshift({ label: title.trim().slice(0, 140), url: args.url });
271
+ }
272
+ const lines = [];
273
+ const touched = [];
274
+ for (const f of feeds) {
275
+ const n = add(`feed:${f.label}`, { kind: 'feed', label: f.label, status: f.status, tool });
276
+ const s = sources[n - 1];
277
+ if (s.status !== 'LIVE' && f.status === 'LIVE')
278
+ s.status = 'LIVE';
279
+ touched.push(s);
280
+ lines.push(`[${n}] data feed: ${f.label} (${f.status})`);
281
+ }
282
+ for (const l of links) {
283
+ let host = '';
284
+ try {
285
+ host = new URL(l.url).hostname.replace(/^www\./, '');
286
+ }
287
+ catch { }
288
+ const n = add(`link:${l.url}`, { kind: 'link', label: l.label, url: l.url, host, tool });
289
+ touched.push(sources[n - 1]);
290
+ lines.push(`[${n}] ${l.label} (${host})`);
291
+ }
292
+ steps.push({ tool, label: toolLabel(tool), ok, ms });
293
+ emit({ type: 'stepdone', id, tool, ok, ms, sources: touched.map((s) => ({ n: s.n, kind: s.kind, label: s.label, status: s.status ?? null, host: s.host ?? null })) });
294
+ return lines.length ? `Numbered sources:\n${lines.join('\n')}` : undefined;
295
+ },
296
+ });
297
+ const brief = toBrief(run.answer, new Set(sources.map((s) => s.n)));
298
+ const id = randomBytes(9).toString('base64url');
299
+ const evidence = run.messages.filter((m) => m.role === 'tool').map((m) => `### ${m.name}\n${m.content ?? ''}`).join('\n\n').slice(0, 60_000);
300
+ remember(id, { question: opts.question, brief, evidence, model: opts.model });
301
+ const result = { id, question: opts.question, model: opts.model, brief, sources, steps, ms: Date.now() - t0 };
302
+ emit({ type: 'brief', ...result });
303
+ return result;
304
+ }
305
+ /** The other models re-read the same evidence and judge each finding. */
306
+ export async function crossExamine(id) {
307
+ const e = EVIDENCE.get(id);
308
+ if (!e)
309
+ throw new Error('this brief has expired; ask again to cross-examine it');
310
+ const reviewers = Object.keys(ANALYST_MODELS).filter((m) => m !== e.model);
311
+ const briefText = JSON.stringify({ question: e.question, bottomLine: e.brief.bottomLine, findings: e.brief.findings.map((f, i) => ({ i, text: f.text, sources: f.sources })) });
312
+ const reviews = await Promise.all(reviewers.map(async (m) => {
313
+ const label = ANALYST_MODELS[m].label;
314
+ try {
315
+ const r = await chat([
316
+ { role: 'system', content: REVIEW_SYSTEM },
317
+ { role: 'user', content: `EVIDENCE\n${e.evidence}\n\nBRIEF\n${briefText}` },
318
+ ], { route: ANALYST_MODELS[m].id, maxTokens: 1200, temperature: 0 });
319
+ const j = parseJson(r.message.content ?? '');
320
+ if (!j)
321
+ throw new Error('the reviewer did not return a verdict');
322
+ const verdicts = new Set(['supported', 'partly', 'unsupported']);
323
+ const findings = (Array.isArray(j.findings) ? j.findings : [])
324
+ .map((f) => f)
325
+ .filter((f) => Number.isInteger(Number(f.i)) && verdicts.has(String(f.verdict)))
326
+ .map((f) => ({ i: Number(f.i), verdict: String(f.verdict), note: str(f.note, 140) }));
327
+ const bl = String(j.bottomLine);
328
+ return { model: m, label, findings, bottomLine: bl === 'agree' || bl === 'disagree' ? bl : 'partly', missed: str(j.missed, 240) || null };
329
+ }
330
+ catch (err) {
331
+ return { model: m, label, findings: [], bottomLine: 'partly', missed: null, error: scrubSecrets(err.message).slice(0, 160) };
332
+ }
333
+ }));
334
+ return { id, reviews };
335
+ }
package/dist/cli/main.js CHANGED
@@ -161,7 +161,7 @@ ${c.bold('Live')}
161
161
  ${c.bold('Graph')}
162
162
  oculon connect <A> to <B> how two things are linked (shortest path)
163
163
  oculon resolve merge duplicates: org:nvidia = company:nvidia = nvidia.com
164
- oculon quota today's API usage vs free-tier budgets
164
+ oculon quota today's API usage vs daily budgets
165
165
 
166
166
  ${c.bold('Radar')}
167
167
  oculon radar what the world is suddenly paying attention to
@@ -52,6 +52,8 @@ export interface ChatOptions {
52
52
  * 'deep' picks the most capable model, for case investigations.
53
53
  */
54
54
  premium?: boolean | 'deep';
55
+ /** Call exactly this OpenRouter model (e.g. "anthropic/claude-opus-5.5"), with no fallback to other providers. */
56
+ route?: string;
55
57
  }
56
58
  export declare function setPaidQuota(fn: (source: string) => boolean): void;
57
59
  export declare const CLAUDE_MODEL: () => string;
package/dist/core/llm.js CHANGED
@@ -119,6 +119,12 @@ export function carryRaw(from, to) {
119
119
  /** One chat completion; falls through providers on errors and rate limits. */
120
120
  export async function chat(messages, opts = {}) {
121
121
  const doFetch = opts.fetch ?? fetch;
122
+ if (opts.route) {
123
+ const or = PROVIDERS.find((p) => p.name === 'openrouter');
124
+ if (!key(or.env))
125
+ throw new Error('OPENROUTER_API_KEY is not set');
126
+ return callProvider({ ...or, model: opts.route, reasoningHeadroom: 6000 }, messages, opts, doFetch, opts.timeoutMs ?? 180_000);
127
+ }
122
128
  const providers = PROVIDERS.filter((p) => key(p.env));
123
129
  const errors = [];
124
130
  if (opts.premium && key('ANTHROPIC_API_KEY')) {
@@ -170,6 +176,29 @@ export async function chat(messages, opts = {}) {
170
176
  }
171
177
  throw new Error(`all LLM providers failed: ${errors.join(' | ')}`);
172
178
  }
179
+ /** One OpenAI-compatible call to a single provider; throws on any failure. */
180
+ async function callProvider(p, messages, opts, doFetch, timeoutMs) {
181
+ const res = await doFetch(p.url, {
182
+ method: 'POST',
183
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key(p.env)}`, ...p.extraHeaders },
184
+ body: JSON.stringify({
185
+ model: p.model,
186
+ messages,
187
+ temperature: opts.temperature ?? 0.2,
188
+ max_tokens: (opts.maxTokens ?? 1500) + (p.reasoningHeadroom ?? 0),
189
+ ...(opts.tools?.length ? { tools: opts.tools, tool_choice: 'auto' } : {}),
190
+ }),
191
+ signal: AbortSignal.timeout(timeoutMs),
192
+ });
193
+ const text = await res.text();
194
+ if (!res.ok)
195
+ throw new Error(`${p.model}: HTTP ${res.status} ${scrubSecrets(text).replace(/\s+/g, ' ').slice(0, 160)}`);
196
+ const j = JSON.parse(text);
197
+ const message = j.choices?.[0]?.message;
198
+ if (!message || (!message.content?.trim() && !message.tool_calls?.length))
199
+ throw new Error(`${p.model}: empty response`);
200
+ return { message: { role: 'assistant', content: message.content ?? null, ...(message.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) }, provider: p.name, model: j.model ?? p.model };
201
+ }
173
202
  /** Plain-text completion helper. */
174
203
  export async function complete(system, user, opts = {}) {
175
204
  const r = await chat([
package/dist/mcp.js CHANGED
@@ -7,7 +7,7 @@ import { createInterface } from 'node:readline';
7
7
  import { Oculon, summarizeProvenance } from './index.js';
8
8
  import { ONCHAIN_TOOLS, onchainEnabled } from './core/features.js';
9
9
  import { availableKinds } from './modules/monitor.js';
10
- export const SERVER_INFO = { name: 'oculon', version: '0.1.1' };
10
+ export const SERVER_INFO = { name: 'oculon', version: '0.1.3' };
11
11
  const SUPPORTED = ['2025-06-18', '2025-03-26', '2024-11-05'];
12
12
  const str = (d) => ({ type: 'string', description: d });
13
13
  const num = (d) => ({ type: 'number', description: d });
@@ -84,7 +84,7 @@ export function emailStatus(ctx, owner) {
84
84
  const EMAIL_RE = /^[^\s@<>"']{1,64}@[a-z0-9.-]+\.[a-z]{2,}$/i;
85
85
  const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
86
86
  function shell(title, body, footer) {
87
- return `<!doctype html><html><body style="margin:0;background:#f4f6f6;padding:24px;font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;color:#111"><div style="max-width:560px;margin:0 auto;background:#fff;border:1px solid #e3e7e7;padding:28px"><div style="font:600 12px monospace;letter-spacing:.18em;color:#00838f">◉ OCULON</div><h1 style="font-size:20px;font-weight:600;margin:14px 0 16px">${title}</h1>${body}<p style="font-size:12px;color:#777;margin-top:28px;border-top:1px solid #eee;padding-top:14px">${footer}</p></div></body></html>`;
87
+ return `<!doctype html><html><body style="margin:0;background:#f4f6f6;padding:24px;font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;color:#111"><div style="max-width:560px;margin:0 auto;background:#fff;border:1px solid #e3e7e7;padding:28px"><div style="font:600 12px monospace;letter-spacing:.18em;color:#00838f">OCULON</div><h1 style="font-size:20px;font-weight:600;margin:14px 0 16px">${title}</h1>${body}<p style="font-size:12px;color:#777;margin-top:28px;border-top:1px solid #eee;padding-top:14px">${footer}</p></div></body></html>`;
88
88
  }
89
89
  /** Saves the address and sends a confirmation link. Limited to one email per owner every 10 minutes. */
90
90
  export async function requestEmail(ctx, owner, email, baseUrl) {