oculon 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -3
- package/dist/agent.d.ts +25 -1
- package/dist/agent.js +14 -4
- package/dist/analyst.d.ts +99 -0
- package/dist/analyst.js +335 -0
- package/dist/cli/main.js +1 -1
- package/dist/core/llm.d.ts +2 -0
- package/dist/core/llm.js +29 -0
- package/dist/mcp.d.ts +7 -0
- package/dist/mcp.js +47 -2
- package/dist/modules/contradictions.js +6 -4
- package/dist/modules/lynx.js +15 -9
- package/dist/modules/owl.js +4 -1
- package/dist/modules/personal.js +1 -1
- package/dist/web/ask.html +410 -0
- package/dist/web/assets/favicon-32.png +0 -0
- package/dist/web/assets/fx.js +25 -3
- package/dist/web/assets/icon-192.png +0 -0
- package/dist/web/assets/icon-512.png +0 -0
- package/dist/web/assets/icon-maskable-512.png +0 -0
- package/dist/web/assets/logo.svg +1 -0
- package/dist/web/assets/og-app.png +0 -0
- package/dist/web/assets/og-docs.png +0 -0
- package/dist/web/assets/og-mcp.png +0 -0
- package/dist/web/assets/og.png +0 -0
- package/dist/web/docs.html +13 -3
- package/dist/web/index.html +45 -10
- package/dist/web/landing.html +11 -5
- package/dist/web/legal.html +8 -4
- package/dist/web/manifest.webmanifest +31 -7
- package/dist/web/mcp.html +7 -3
- package/dist/web/server.js +118 -7
- package/dist/web/share.js +1 -1
- package/package.json +10 -10
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ npx oculon ask "why is Nvidia in the news this week?"
|
|
|
21
21
|
- **Sourced by design.** Every answer names the sources it used and whether each one was live, cached or unavailable. Nothing is presented without provenance.
|
|
22
22
|
- **Cross-source signals.** When independent sources move on the same subject, Oculon fuses them into one scored signal with the evidence behind it, and storylines are tracked across days.
|
|
23
23
|
- **Measured, not claimed.** A time machine replays past days to calibrate the radar, a first-to-know check compares Oculon against media coverage, and forecasts are timestamped on Bitcoin so they cannot be edited later.
|
|
24
|
-
- **Built for agents.** 75 MCP tools
|
|
24
|
+
- **Built for agents.** 75 MCP tools locally over stdio, and the 67 read-only ones remotely at `https://mcp.oculon.live`; the SDK and CLI return the same objects, and `--json` works on every command.
|
|
25
25
|
- **Everyday checks.** Is this message a scam? Is this link dangerous? Is this claim true? Is my car recalled? Can someone spoof my email domain? Are my dependencies safe? What should I know before I travel? Each answer names its sources, and any result can be shared as a link with a preview card.
|
|
26
26
|
- **Monitors in plain words.** "Tell me when there is an internet outage in Iran" becomes a rule that is re-checked on a schedule and reports only what changed, by email, in Telegram or in the app. Every visitor keeps their own monitors, with no account.
|
|
27
27
|
- **Everywhere people are.** A public Telegram bot ([@oculon_radar_bot](https://t.me/oculon_radar_bot)): forward it a suspicious message and it checks it. An OpenAPI spec at `/openapi.json` for ChatGPT Actions, n8n and Zapier.
|
|
@@ -29,7 +29,7 @@ npx oculon ask "why is Nvidia in the news this week?"
|
|
|
29
29
|
|
|
30
30
|
## Contents
|
|
31
31
|
|
|
32
|
-
[What it does](#what-it-does) · [Install](#install) · [CLI](#cli) · [MCP server](#mcp-server) · [Remote MCP](#remote-mcp) · [SDK](#sdk) · [Web app](#dashboard-and-schedule) · [Telegram bot](#telegram-bot) · [Configuration](#configuration) · [Deploy](#deploy) · [How it works](#how-it-works) · [Limits](#limits) · [Development](#development)
|
|
32
|
+
[What it does](#what-it-does) · [Install](#install) · [CLI](#cli) · [MCP server](#mcp-server) · [Remote MCP](#remote-mcp) · [Analyst](#oculon-analyst) · [SDK](#sdk) · [Web app](#dashboard-and-schedule) · [Telegram bot](#telegram-bot) · [Configuration](#configuration) · [Deploy](#deploy) · [How it works](#how-it-works) · [Limits](#limits) · [Development](#development)
|
|
33
33
|
|
|
34
34
|
## What it does
|
|
35
35
|
|
|
@@ -172,6 +172,19 @@ Or with any MCP client that launches stdio servers:
|
|
|
172
172
|
|
|
173
173
|
Every module is a tool (about 50, plus one per installed plugin tool; `tools/list` returns them with schemas). A few: `oculon_ask`, `oculon_radar`, `oculon_dossier`, `oculon_case_new`, `oculon_calendar`, `oculon_connect`, `oculon_markets_crosscheck`, `oculon_sanctions`, `oculon_health`, `oculon_narratives`, `oculon_ships`, `oculon_military_air`, `oculon_satellite_image` (returns the image), `oculon_forecast`, `oculon_verify_proof`, `oculon_watch_add`, `oculon_brief`, `oculon_signals`, `oculon_entity`.
|
|
174
174
|
|
|
175
|
+
## Oculon Analyst
|
|
176
|
+
|
|
177
|
+
`/ask` on any install (`https://oculon.live/ask`) is a question desk built on the same tools. It is not a chat window:
|
|
178
|
+
|
|
179
|
+
- **Ask anything.** Questions about Oculon itself are answered from its documentation, live-data questions from Oculon's tools, and everything else by searching the web and reading the best pages, preferring official and primary sources.
|
|
180
|
+
- **It plans, then checks.** The analyst splits the question into parts and shows that plan, then runs the checks for every part in parallel. The page shows each source as it is touched (data feeds with LIVE, CACHED or ERROR, plus the pages, articles and records found).
|
|
181
|
+
- **It answers with a brief.** A headline and bottom line, a short explanation for how and why questions, a 0-100 confidence with its reason, 2-6 findings that each cite numbered sources, what the data could not show, and what new evidence would change the answer. Findings can only cite sources the tools returned.
|
|
182
|
+
- **Cross-examine.** One click asks the two other models to judge each finding against the same evidence (supported, partly, unsupported) and to say what the brief missed.
|
|
183
|
+
- **Watch.** A brief can become a personal monitor that reports when the answer changes.
|
|
184
|
+
- **Pick the model:** Claude Haiku 5.5 (fast), Claude Opus 5.5 (thorough) or GPT-6.2 Astra, all through OpenRouter (`OPENROUTER_API_KEY`). Follow-up questions keep the earlier bottom lines as context; the session stays in the browser.
|
|
185
|
+
|
|
186
|
+
On a public install each visitor gets `OCULON_ANALYST_PER_HOUR` questions and cross-examinations per hour (default 40).
|
|
187
|
+
|
|
175
188
|
## Remote MCP
|
|
176
189
|
|
|
177
190
|
Oculon also runs as a remote MCP server, so an agent can use every tool with nothing installed. The endpoint speaks Streamable HTTP (stateless JSON responses):
|
|
@@ -288,7 +301,7 @@ Other deployment switches:
|
|
|
288
301
|
| `RESEND_API_KEY`, `OCULON_MAIL_FROM` | Email alerts for personal monitors (default sender `Oculon <alerts@oculon.live>`; the domain must be verified in Resend). |
|
|
289
302
|
| `OCULON_PURGE_ONCHAIN=1` | Clears data left by the paused on-chain modules each time the server starts. |
|
|
290
303
|
|
|
291
|
-
The repository includes a `Dockerfile`
|
|
304
|
+
The repository includes a `Dockerfile` (on Railway, set the service health check to `/api/meta`). Mount a persistent volume at `/data` (the image sets `OCULON_HOME=/data`), set your keys as environment variables, and point a domain at the service. Each deployment keeps its own database and its own daily budgets.
|
|
292
305
|
|
|
293
306
|
## How it works
|
|
294
307
|
|
package/dist/agent.d.ts
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { type ChatMessage } from './core/llm.js';
|
|
7
7
|
import type { Oculon } from './index.js';
|
|
8
|
-
|
|
8
|
+
import { type Tool } from './mcp.js';
|
|
9
|
+
export declare const AGENT_TOOLS: Tool[];
|
|
9
10
|
export interface AskStep {
|
|
10
11
|
tool: string;
|
|
11
12
|
args: Record<string, unknown>;
|
|
@@ -41,6 +42,29 @@ export interface AgentOptions {
|
|
|
41
42
|
maxTokens?: number;
|
|
42
43
|
/** Paid Claude first when configured; 'deep' for the most capable model. */
|
|
43
44
|
premium?: boolean | 'deep';
|
|
45
|
+
/** Use exactly this OpenRouter model for every round. */
|
|
46
|
+
route?: string;
|
|
47
|
+
/** Called before a tool runs. */
|
|
48
|
+
onToolStart?: (call: {
|
|
49
|
+
id: string;
|
|
50
|
+
tool: string;
|
|
51
|
+
args: Record<string, unknown>;
|
|
52
|
+
}) => void;
|
|
53
|
+
/** Called with the raw result; text it returns is appended to what the model sees (e.g. numbered sources). */
|
|
54
|
+
onToolResult?: (call: {
|
|
55
|
+
id: string;
|
|
56
|
+
tool: string;
|
|
57
|
+
args: Record<string, unknown>;
|
|
58
|
+
ok: boolean;
|
|
59
|
+
ms: number;
|
|
60
|
+
raw: unknown;
|
|
61
|
+
}) => string | void;
|
|
62
|
+
/** Earlier turns of a conversation, placed before the new question. */
|
|
63
|
+
history?: ChatMessage[];
|
|
64
|
+
/** Extra tools for this run only (not exposed over MCP). */
|
|
65
|
+
extraTools?: Tool[];
|
|
66
|
+
/** Text the model writes alongside its tool calls (its plan for that round). */
|
|
67
|
+
onThought?: (text: string) => void;
|
|
44
68
|
}
|
|
45
69
|
/** The tool loop shared by `ask` and case investigations. */
|
|
46
70
|
export declare function runAgent(o: Oculon, system: string, user: string, opts?: AgentOptions): Promise<AgentRun>;
|
package/dist/agent.js
CHANGED
|
@@ -47,9 +47,11 @@ export function forModel(out, max = 14_000) {
|
|
|
47
47
|
}
|
|
48
48
|
/** The tool loop shared by `ask` and case investigations. */
|
|
49
49
|
export async function runAgent(o, system, user, opts = {}) {
|
|
50
|
-
const
|
|
50
|
+
const runTools = [...(opts.extraTools ?? []), ...agentTools()];
|
|
51
|
+
const tools = runTools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.inputSchema } }));
|
|
51
52
|
const messages = [
|
|
52
53
|
{ role: 'system', content: `${system}\nToday is ${o.ctx.now().toISOString().slice(0, 10)}.` },
|
|
54
|
+
...(opts.history ?? []),
|
|
53
55
|
{ role: 'user', content: user },
|
|
54
56
|
];
|
|
55
57
|
const steps = [];
|
|
@@ -58,15 +60,17 @@ export async function runAgent(o, system, user, opts = {}) {
|
|
|
58
60
|
const maxSteps = opts.maxSteps ?? 6;
|
|
59
61
|
for (let round = 0; round < maxSteps; round++) {
|
|
60
62
|
// On the last round, withhold tools so the model must answer.
|
|
61
|
-
const r = await chat(messages, { tools: round < maxSteps - 1 ? tools : [], maxTokens: opts.maxTokens ?? 1800, premium: opts.premium ?? true, ...(opts.fetch ? { fetch: opts.fetch } : {}) });
|
|
63
|
+
const r = await chat(messages, { tools: round < maxSteps - 1 ? tools : [], maxTokens: opts.maxTokens ?? 1800, premium: opts.premium ?? true, ...(opts.route ? { route: opts.route } : {}), ...(opts.fetch ? { fetch: opts.fetch } : {}) });
|
|
62
64
|
providers.push(r.provider);
|
|
63
65
|
const calls = r.message.tool_calls ?? [];
|
|
64
66
|
if (!calls.length) {
|
|
65
67
|
return { answer: (r.message.content ?? '').trim() || '(no answer)', steps, providers, messages, urls };
|
|
66
68
|
}
|
|
67
69
|
messages.push(carryRaw(r.message, { role: 'assistant', content: r.message.content ?? '', tool_calls: calls }));
|
|
70
|
+
if (r.message.content?.trim())
|
|
71
|
+
opts.onThought?.(r.message.content.trim());
|
|
68
72
|
const results = await Promise.all(calls.map(async (c) => {
|
|
69
|
-
const tool =
|
|
73
|
+
const tool = runTools.find((t) => t.name === c.function.name);
|
|
70
74
|
let args = {};
|
|
71
75
|
try {
|
|
72
76
|
args = JSON.parse(c.function.arguments || '{}');
|
|
@@ -74,21 +78,27 @@ export async function runAgent(o, system, user, opts = {}) {
|
|
|
74
78
|
catch { }
|
|
75
79
|
const t0 = Date.now();
|
|
76
80
|
opts.onStep?.(`${c.function.name}(${JSON.stringify(args)})`);
|
|
81
|
+
opts.onToolStart?.({ id: c.id, tool: c.function.name, args });
|
|
77
82
|
let content;
|
|
78
83
|
let ok = true;
|
|
84
|
+
let raw = null;
|
|
79
85
|
if (!tool) {
|
|
80
86
|
content = `error: unknown tool ${c.function.name}`;
|
|
81
87
|
ok = false;
|
|
82
88
|
}
|
|
83
89
|
else {
|
|
84
90
|
try {
|
|
85
|
-
|
|
91
|
+
raw = await tool.run(o, args);
|
|
92
|
+
content = forModel(raw);
|
|
86
93
|
}
|
|
87
94
|
catch (e) {
|
|
88
95
|
content = `error: ${scrubSecrets(e.message)}`;
|
|
89
96
|
ok = false;
|
|
90
97
|
}
|
|
91
98
|
}
|
|
99
|
+
const extra = opts.onToolResult?.({ id: c.id, tool: c.function.name, args, ok, ms: Date.now() - t0, raw });
|
|
100
|
+
if (extra)
|
|
101
|
+
content += `\n${extra}`;
|
|
92
102
|
steps.push({ tool: c.function.name, args, ok, ms: Date.now() - t0, chars: content.length });
|
|
93
103
|
for (const u of content.match(/https?:\/\/[^\s"'<>\\]+/g) ?? [])
|
|
94
104
|
urls.add(u.replace(/[).,;]+$/, ''));
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { Oculon } from './index.js';
|
|
2
|
+
export declare const ANALYST_MODELS: {
|
|
3
|
+
readonly haiku: {
|
|
4
|
+
readonly id: 'anthropic/claude-haiku-5.5';
|
|
5
|
+
readonly label: 'Claude Haiku 5.5';
|
|
6
|
+
readonly note: 'fast';
|
|
7
|
+
};
|
|
8
|
+
readonly opus: {
|
|
9
|
+
readonly id: 'anthropic/claude-opus-5.5';
|
|
10
|
+
readonly label: 'Claude Opus 5.5';
|
|
11
|
+
readonly note: 'thorough';
|
|
12
|
+
};
|
|
13
|
+
readonly gpt: {
|
|
14
|
+
readonly id: 'openai/gpt-6.2-astra';
|
|
15
|
+
readonly label: 'GPT-6.2 Astra';
|
|
16
|
+
readonly note: 'second view';
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
export type AnalystModel = keyof typeof ANALYST_MODELS;
|
|
20
|
+
export declare const isAnalystModel: (m: unknown) => m is AnalystModel;
|
|
21
|
+
export interface Source {
|
|
22
|
+
n: number;
|
|
23
|
+
kind: 'feed' | 'link';
|
|
24
|
+
label: string;
|
|
25
|
+
url?: string;
|
|
26
|
+
host?: string;
|
|
27
|
+
status?: string;
|
|
28
|
+
tool: string;
|
|
29
|
+
}
|
|
30
|
+
export interface Finding {
|
|
31
|
+
text: string;
|
|
32
|
+
sources: number[];
|
|
33
|
+
}
|
|
34
|
+
export interface Brief {
|
|
35
|
+
headline: string;
|
|
36
|
+
bottomLine: string;
|
|
37
|
+
/** Longer explanation for how/why/steps questions, with [n] citations inline. */
|
|
38
|
+
details: string;
|
|
39
|
+
confidence: number;
|
|
40
|
+
confidenceWhy: string;
|
|
41
|
+
findings: Finding[];
|
|
42
|
+
unknowns: string[];
|
|
43
|
+
changeMyMind: string;
|
|
44
|
+
followUps: string[];
|
|
45
|
+
watch: string | null;
|
|
46
|
+
}
|
|
47
|
+
export interface AnalystEvent {
|
|
48
|
+
type: 'start' | 'plan' | 'step' | 'stepdone' | 'brief' | 'error';
|
|
49
|
+
[k: string]: unknown;
|
|
50
|
+
}
|
|
51
|
+
export interface AnalystResult {
|
|
52
|
+
id: string;
|
|
53
|
+
question: string;
|
|
54
|
+
model: AnalystModel;
|
|
55
|
+
brief: Brief;
|
|
56
|
+
sources: Source[];
|
|
57
|
+
steps: {
|
|
58
|
+
tool: string;
|
|
59
|
+
label: string;
|
|
60
|
+
ok: boolean;
|
|
61
|
+
ms: number;
|
|
62
|
+
}[];
|
|
63
|
+
ms: number;
|
|
64
|
+
}
|
|
65
|
+
export declare function searchDocs(query: string, max?: number): {
|
|
66
|
+
title: string;
|
|
67
|
+
url: string;
|
|
68
|
+
text: string;
|
|
69
|
+
}[];
|
|
70
|
+
/** "oculon_url_check" -> "URL check" */
|
|
71
|
+
export declare function toolLabel(name: string): string;
|
|
72
|
+
export interface AnalystOptions {
|
|
73
|
+
question: string;
|
|
74
|
+
model: AnalystModel;
|
|
75
|
+
/** Earlier turns: the question and the brief's bottom line, oldest first. */
|
|
76
|
+
history?: {
|
|
77
|
+
q: string;
|
|
78
|
+
a: string;
|
|
79
|
+
}[];
|
|
80
|
+
onEvent?: (e: AnalystEvent) => void;
|
|
81
|
+
}
|
|
82
|
+
export declare function analyst(o: Oculon, opts: AnalystOptions): Promise<AnalystResult>;
|
|
83
|
+
export interface Review {
|
|
84
|
+
model: AnalystModel;
|
|
85
|
+
label: string;
|
|
86
|
+
findings: {
|
|
87
|
+
i: number;
|
|
88
|
+
verdict: 'supported' | 'partly' | 'unsupported';
|
|
89
|
+
note: string;
|
|
90
|
+
}[];
|
|
91
|
+
bottomLine: 'agree' | 'partly' | 'disagree';
|
|
92
|
+
missed: string | null;
|
|
93
|
+
error?: string;
|
|
94
|
+
}
|
|
95
|
+
/** The other models re-read the same evidence and judge each finding. */
|
|
96
|
+
export declare function crossExamine(id: string): Promise<{
|
|
97
|
+
id: string;
|
|
98
|
+
reviews: Review[];
|
|
99
|
+
}>;
|
package/dist/analyst.js
ADDED
|
@@ -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
|
@@ -1986,7 +1986,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
1986
1986
|
}
|
|
1987
1987
|
catch (e) {
|
|
1988
1988
|
if (e instanceof UsageError) {
|
|
1989
|
-
out(`${c.red('usage')}: ${e.message}. See \`oculon help\`.`);
|
|
1989
|
+
out(`${c.red('usage')}: ${e.message.replace(/^usage:\s*/i, '')}. See \`oculon help\`.`);
|
|
1990
1990
|
return 2;
|
|
1991
1991
|
}
|
|
1992
1992
|
out(`${c.red('error')}: ${e.message}`);
|
package/dist/core/llm.d.ts
CHANGED
|
@@ -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([
|