@obzerver/server 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ai.d.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { type Db } from './db.js';
2
+ export type AiProvider = 'anthropic' | 'openai';
3
+ export interface AiConfig {
4
+ provider: AiProvider;
5
+ apiKey: string;
6
+ model: string;
7
+ baseUrl: string | null;
8
+ source: 'env' | 'settings';
9
+ }
10
+ export declare const DEFAULT_MODELS: Record<AiProvider, string>;
11
+ export declare class AiError extends Error {
12
+ readonly status: number;
13
+ constructor(message: string, status?: number);
14
+ }
15
+ export declare function aiConfig(root: Db): AiConfig | null;
16
+ export declare function publicAiConfig(root: Db): {
17
+ configured: boolean;
18
+ provider: AiProvider;
19
+ model: string;
20
+ baseUrl: string | null;
21
+ apiKey: string;
22
+ source: "env" | "settings";
23
+ } | {
24
+ configured: boolean;
25
+ provider?: undefined;
26
+ model?: undefined;
27
+ baseUrl?: undefined;
28
+ apiKey?: undefined;
29
+ source?: undefined;
30
+ };
31
+ export interface AiInput {
32
+ provider?: AiProvider;
33
+ apiKey?: string;
34
+ model?: string;
35
+ baseUrl?: string | null;
36
+ }
37
+ /** Resolve form input against the stored config (a masked key means "keep the stored one"). */
38
+ export declare function configFromInput(root: Db, input: AiInput): Omit<AiConfig, 'source'>;
39
+ export declare function saveAiConfig(root: Db, input: AiInput | null): void;
40
+ /** Check the key and model with a one-word reply. */
41
+ export declare function testAi(cfg: AiConfig): Promise<string>;
42
+ export declare const LINK_KINDS: readonly ["execution", "trace", "error", "operation", "release", "issue"];
43
+ type LinkKind = typeof LINK_KINDS[number];
44
+ export interface AnswerLink {
45
+ kind: LinkKind;
46
+ ref: string;
47
+ label: string;
48
+ service?: string;
49
+ opKind?: 'http' | 'job';
50
+ }
51
+ export interface Answer {
52
+ summary: string;
53
+ timeRange: {
54
+ from: number;
55
+ to: number;
56
+ minutes: number;
57
+ } | null;
58
+ sources: Array<{
59
+ tool: string;
60
+ calls: number;
61
+ }>;
62
+ evidence: Array<{
63
+ claim: string;
64
+ value: string;
65
+ tool: string;
66
+ }>;
67
+ links: AnswerLink[];
68
+ confidence: 'high' | 'medium' | 'low';
69
+ confidenceReason: string;
70
+ followUps: string[];
71
+ /** What the server changed while checking the answer. */
72
+ checks: string[];
73
+ model: string;
74
+ }
75
+ export declare function verifyAnswer(raw: Record<string, any>, ctx: {
76
+ called: Map<string, number>;
77
+ corpus: string;
78
+ windows: number[];
79
+ now: number;
80
+ model: string;
81
+ }): Answer;
82
+ export type AiEvent = {
83
+ type: 'step';
84
+ id: string;
85
+ tool: string;
86
+ input: Record<string, unknown>;
87
+ } | {
88
+ type: 'step_done';
89
+ id: string;
90
+ ok: boolean;
91
+ summary: string;
92
+ ms: number;
93
+ } | {
94
+ type: 'note';
95
+ text: string;
96
+ } | {
97
+ type: 'answer';
98
+ answer: Answer;
99
+ } | {
100
+ type: 'error';
101
+ message: string;
102
+ };
103
+ export interface ChatTurn {
104
+ role: 'user' | 'assistant';
105
+ text: string;
106
+ }
107
+ /** Run one question to a verified answer, emitting progress. Tools run against `db` (the current project). */
108
+ export declare function ask(db: Db, cfg: AiConfig, opts: {
109
+ project: string;
110
+ question: string;
111
+ history?: ChatTurn[];
112
+ emit: (e: AiEvent) => void;
113
+ signal?: AbortSignal;
114
+ now?: number;
115
+ }): Promise<Answer | null>;
116
+ export {};
package/dist/ai.js ADDED
@@ -0,0 +1,365 @@
1
+ // Ask Obzeri: a chat assistant in the dashboard that answers from telemetry only.
2
+ //
3
+ // The model never sees the database. It can only call the same read-only tools the MCP server
4
+ // exposes, against the current project, and it must finish with a structured `answer`. The server
5
+ // then checks that answer against what the tools actually returned before anyone sees it:
6
+ // - sources and the time range come from the tool calls that really ran, not from the model
7
+ // - a link is kept only if its id appeared in a tool result (no invented trace or execution ids)
8
+ // - evidence must cite a tool that ran
9
+ // - confidence is lowered when the answer read no data or something had to be dropped
10
+ import { getSetting, setSetting } from './db.js';
11
+ import { MCP_TOOLS } from './mcp.js';
12
+ import * as Q from './queries.js';
13
+ export const DEFAULT_MODELS = { anthropic: 'claude-sonnet-5-5', openai: '' };
14
+ const MAX_STEPS = 10;
15
+ const MAX_TOOL_CHARS = 12000;
16
+ export class AiError extends Error {
17
+ status;
18
+ constructor(message, status = 502) {
19
+ super(message);
20
+ this.status = status;
21
+ }
22
+ }
23
+ const env = (k) => process.env[k]?.trim() || undefined;
24
+ // ---------------------------------------------------------------- settings (server-wide)
25
+ export function aiConfig(root) {
26
+ const provider = env('OBZERVER_AI_PROVIDER');
27
+ const envKey = env('OBZERVER_AI_API_KEY') || (provider === 'openai' ? env('OPENAI_API_KEY') : env('ANTHROPIC_API_KEY'));
28
+ if (provider === 'anthropic' || provider === 'openai') {
29
+ const baseUrl = env('OBZERVER_AI_BASE_URL') || null;
30
+ // Local OpenAI-compatible servers (Ollama, LM Studio) need no key.
31
+ if (envKey || (provider === 'openai' && baseUrl)) {
32
+ return { provider, apiKey: envKey || '', model: env('OBZERVER_AI_MODEL') || DEFAULT_MODELS[provider], baseUrl, source: 'env' };
33
+ }
34
+ }
35
+ try {
36
+ const s = JSON.parse(getSetting(root, 'ai') || 'null');
37
+ return s ? { ...s, source: 'settings' } : null;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ const mask = (k) => (k.length >= 16 ? `••••${k.slice(-4)}` : k ? '••••' : '');
44
+ export function publicAiConfig(root) {
45
+ const c = aiConfig(root);
46
+ return c ? { configured: !!c.model, provider: c.provider, model: c.model, baseUrl: c.baseUrl, apiKey: mask(c.apiKey), source: c.source } : { configured: false };
47
+ }
48
+ /** Resolve form input against the stored config (a masked key means "keep the stored one"). */
49
+ export function configFromInput(root, input) {
50
+ const cur = aiConfig(root);
51
+ const provider = input.provider ?? cur?.provider;
52
+ if (provider !== 'anthropic' && provider !== 'openai')
53
+ throw new AiError('Pick a provider: anthropic or openai', 400);
54
+ const apiKey = input.apiKey === undefined || input.apiKey.includes('••••') ? (cur?.provider === provider ? cur.apiKey : '') : input.apiKey.trim();
55
+ const baseUrl = (input.baseUrl === undefined ? (cur?.provider === provider ? cur.baseUrl : null) : input.baseUrl)?.trim().replace(/\/$/, '') || null;
56
+ const model = (input.model ?? '').trim() || (cur?.provider === provider ? cur.model : '') || DEFAULT_MODELS[provider];
57
+ if (!model)
58
+ throw new AiError('Enter the model name', 400);
59
+ if (!apiKey && !(provider === 'openai' && baseUrl))
60
+ throw new AiError('Enter an API key', 400);
61
+ if (baseUrl && !/^https?:\/\//.test(baseUrl))
62
+ throw new AiError('Base URL must start with http:// or https://', 400);
63
+ return { provider, apiKey, model, baseUrl };
64
+ }
65
+ export function saveAiConfig(root, input) {
66
+ if (input === null) {
67
+ setSetting(root, 'ai', 'null');
68
+ return;
69
+ }
70
+ setSetting(root, 'ai', JSON.stringify(configFromInput(root, input)));
71
+ }
72
+ async function post(url, headers, body, signal) {
73
+ let res;
74
+ try {
75
+ res = await fetch(url, {
76
+ method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body),
77
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(90000)]) : AbortSignal.timeout(90000),
78
+ });
79
+ }
80
+ catch (e) {
81
+ if (signal?.aborted)
82
+ throw new AiError('Stopped', 499);
83
+ throw new AiError(`Could not reach the AI provider: ${e.message}`);
84
+ }
85
+ const text = await res.text();
86
+ let json = null;
87
+ try {
88
+ json = JSON.parse(text);
89
+ }
90
+ catch { /* not JSON */ }
91
+ if (!res.ok) {
92
+ const msg = json?.error?.message || json?.error || json?.message || text.slice(0, 200) || res.statusText;
93
+ throw new AiError(`AI provider returned ${res.status}: ${typeof msg === 'string' ? msg : JSON.stringify(msg)}`, res.status === 401 || res.status === 403 ? 400 : 502);
94
+ }
95
+ return json;
96
+ }
97
+ async function callAnthropic(cfg, system, msgs, tools, signal) {
98
+ const messages = msgs.map((m) => ({
99
+ role: m.role,
100
+ content: m.content.map((p) => p.type === 'text' ? { type: 'text', text: p.text }
101
+ : p.type === 'tool_call' ? { type: 'tool_use', id: p.id, name: p.name, input: p.input }
102
+ : { type: 'tool_result', tool_use_id: p.id, content: p.content, is_error: p.isError }),
103
+ }));
104
+ const r = await post(`${cfg.baseUrl || 'https://api.anthropic.com'}/v1/messages`, { 'x-api-key': cfg.apiKey, 'anthropic-version': '2023-06-01' }, { model: cfg.model, max_tokens: 4096, system, messages, tools: tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema })) }, signal);
105
+ const parts = (r.content || []).map((b) => b.type === 'tool_use'
106
+ ? { type: 'tool_call', id: b.id, name: b.name, input: b.input || {} }
107
+ : { type: 'text', text: b.text || '' });
108
+ return { parts, stop: r.stop_reason === 'tool_use' ? 'tool' : 'end' };
109
+ }
110
+ async function callOpenAi(cfg, system, msgs, tools, signal) {
111
+ const messages = [{ role: 'system', content: system }];
112
+ for (const m of msgs) {
113
+ if (m.role === 'assistant') {
114
+ const text = m.content.filter((p) => p.type === 'text').map((p) => p.text).join('\n');
115
+ const calls = m.content.filter((p) => p.type === 'tool_call');
116
+ messages.push({ role: 'assistant', content: text || null, ...(calls.length ? { tool_calls: calls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.input) } })) } : {}) });
117
+ }
118
+ else {
119
+ for (const p of m.content) {
120
+ if (p.type === 'tool_result')
121
+ messages.push({ role: 'tool', tool_call_id: p.id, content: p.content });
122
+ else if (p.type === 'text')
123
+ messages.push({ role: 'user', content: p.text });
124
+ }
125
+ }
126
+ }
127
+ const r = await post(`${cfg.baseUrl || 'https://api.openai.com/v1'}/chat/completions`, cfg.apiKey ? { authorization: `Bearer ${cfg.apiKey}` } : {}, { model: cfg.model, messages, tools: tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.inputSchema } })), tool_choice: 'auto' }, signal);
128
+ const msg = r.choices?.[0]?.message || {};
129
+ const parts = [];
130
+ if (msg.content)
131
+ parts.push({ type: 'text', text: msg.content });
132
+ for (const c of msg.tool_calls || []) {
133
+ let input = {};
134
+ try {
135
+ input = JSON.parse(c.function?.arguments || '{}');
136
+ }
137
+ catch { /* model sent bad JSON: run with no args */ }
138
+ parts.push({ type: 'tool_call', id: c.id, name: c.function?.name, input });
139
+ }
140
+ return { parts, stop: parts.some((p) => p.type === 'tool_call') ? 'tool' : 'end' };
141
+ }
142
+ const callModel = (cfg, system, msgs, tools, signal) => (cfg.provider === 'anthropic' ? callAnthropic : callOpenAi)(cfg, system, msgs, tools, signal);
143
+ /** Check the key and model with a one-word reply. */
144
+ export async function testAi(cfg) {
145
+ const turn = await callModel(cfg, 'Reply with exactly: OK', [{ role: 'user', content: [{ type: 'text', text: 'Ping' }] }], []);
146
+ const text = turn.parts.filter((p) => p.type === 'text').map((p) => p.text).join('').trim();
147
+ return `${cfg.model} answered: ${text.slice(0, 40) || '(empty)'}`;
148
+ }
149
+ // ---------------------------------------------------------------- the structured answer
150
+ export const LINK_KINDS = ['execution', 'trace', 'error', 'operation', 'release', 'issue'];
151
+ const ANSWER_TOOL = {
152
+ name: 'answer',
153
+ description: 'Give the final answer. Call this exactly once, after reading the data you need. Every claim must come from tool results in this conversation.',
154
+ inputSchema: {
155
+ type: 'object',
156
+ required: ['summary', 'evidence', 'links', 'confidence', 'confidenceReason'],
157
+ properties: {
158
+ summary: { type: 'string', description: "The answer in Markdown, in the user's language. Lead with the conclusion. Name routes, versions and numbers exactly as the tools returned them." },
159
+ evidence: {
160
+ type: 'array', description: 'The specific readings the answer rests on (2-6 items).',
161
+ items: { type: 'object', required: ['claim', 'value', 'tool'], properties: {
162
+ claim: { type: 'string', description: 'What the reading shows, in the user\'s language' },
163
+ value: { type: 'string', description: 'The number or fact as the tool returned it, e.g. "p95 1,240 ms (was 310 ms)"' },
164
+ tool: { type: 'string', description: 'The tool that returned it' },
165
+ } },
166
+ },
167
+ links: {
168
+ type: 'array', description: 'Things to open in the dashboard. Use only ids that appear in tool results.',
169
+ items: { type: 'object', required: ['kind', 'ref', 'label'], properties: {
170
+ kind: { type: 'string', enum: [...LINK_KINDS] },
171
+ ref: { type: 'string', description: 'execution: numeric id · trace: 32-hex trace id · error: fingerprint · operation: route or job name · release: version · issue: numeric id' },
172
+ service: { type: 'string', description: 'Service id (required for operation and release)' },
173
+ opKind: { type: 'string', enum: ['http', 'job'], description: 'For operation links' },
174
+ label: { type: 'string' },
175
+ } },
176
+ },
177
+ confidence: { type: 'string', enum: ['high', 'medium', 'low'] },
178
+ confidenceReason: { type: 'string', description: 'Why this confidence: sample size, how direct the evidence is, what could not be checked' },
179
+ followUps: { type: 'array', items: { type: 'string' }, description: '2-3 short follow-up questions the user might ask next, in their language' },
180
+ },
181
+ },
182
+ };
183
+ /** Is `ref` present in what the tools returned? Numbers must appear as JSON values, strings as substrings. */
184
+ function seenIn(corpus, ref, kind) {
185
+ if (!ref)
186
+ return false;
187
+ if (kind === 'execution' || kind === 'issue')
188
+ return /^\d+$/.test(ref) && new RegExp(`"id":\\s*${ref}(?![\\d])`).test(corpus);
189
+ return corpus.includes(ref.length > 200 ? ref.slice(0, 200) : ref);
190
+ }
191
+ const LEVELS = ['low', 'medium', 'high'];
192
+ const lower = (c) => LEVELS[Math.max(0, LEVELS.indexOf(c) - 1)];
193
+ export function verifyAnswer(raw, ctx) {
194
+ const checks = [];
195
+ const dataTools = [...ctx.called.keys()];
196
+ let confidence = LEVELS.includes(raw.confidence) ? raw.confidence : 'low';
197
+ let confidenceReason = String(raw.confidenceReason || '').trim();
198
+ const evidence = (Array.isArray(raw.evidence) ? raw.evidence : []).filter((e) => e && e.claim && e.value)
199
+ .map((e) => ({ claim: String(e.claim), value: String(e.value), tool: String(e.tool || '') }));
200
+ const keptEvidence = evidence.filter((e) => ctx.called.has(e.tool));
201
+ if (keptEvidence.length < evidence.length)
202
+ checks.push(`Dropped ${evidence.length - keptEvidence.length} evidence item(s) that cited a tool that never ran.`);
203
+ const links = [];
204
+ let dropped = 0;
205
+ for (const l of Array.isArray(raw.links) ? raw.links : []) {
206
+ const kind = l?.kind;
207
+ const ref = String(l?.ref ?? '').trim();
208
+ if (!LINK_KINDS.includes(kind) || !seenIn(ctx.corpus, ref, kind)) {
209
+ dropped++;
210
+ continue;
211
+ }
212
+ if ((kind === 'operation' || kind === 'release') && !(l.service && ctx.corpus.includes(String(l.service)))) {
213
+ dropped++;
214
+ continue;
215
+ }
216
+ if (links.some((x) => x.kind === kind && x.ref === ref))
217
+ continue;
218
+ links.push({ kind, ref, label: String(l.label || ref).slice(0, 120), ...(l.service ? { service: String(l.service) } : {}), ...(kind === 'operation' ? { opKind: l.opKind === 'job' ? 'job' : 'http' } : {}) });
219
+ }
220
+ if (dropped)
221
+ checks.push(`Removed ${dropped} link(s) whose ids did not appear in any tool result.`);
222
+ if (!dataTools.length) {
223
+ confidence = 'low';
224
+ confidenceReason = 'No telemetry was read for this answer.';
225
+ checks.push('The answer did not read any data.');
226
+ }
227
+ else if (dropped || keptEvidence.length < evidence.length) {
228
+ const was = confidence;
229
+ confidence = lower(confidence);
230
+ if (was !== confidence)
231
+ checks.push(`Confidence lowered from ${was} to ${confidence} because parts of the answer could not be verified.`);
232
+ }
233
+ if (dataTools.length && !keptEvidence.length && confidence === 'high') {
234
+ confidence = 'medium';
235
+ checks.push('Confidence lowered to medium: no evidence was given.');
236
+ }
237
+ const minutes = ctx.windows.length ? Math.max(...ctx.windows) : 0;
238
+ return {
239
+ summary: String(raw.summary || '').trim() || '(no summary)',
240
+ timeRange: minutes ? { from: ctx.now - minutes * 60000, to: ctx.now, minutes } : null,
241
+ sources: dataTools.map((tool) => ({ tool, calls: ctx.called.get(tool) })),
242
+ evidence: keptEvidence.slice(0, 8),
243
+ links: links.slice(0, 12),
244
+ confidence,
245
+ confidenceReason: confidenceReason || 'Not given.',
246
+ followUps: (Array.isArray(raw.followUps) ? raw.followUps : []).map(String).filter(Boolean).slice(0, 3),
247
+ checks,
248
+ model: ctx.model,
249
+ };
250
+ }
251
+ function systemPrompt(db, project, now) {
252
+ let apps = '';
253
+ try {
254
+ apps = Q.meta(db).services.map((s) => s.id).join(', ');
255
+ }
256
+ catch { /* empty project */ }
257
+ return [
258
+ 'You are Obzeri, the assistant inside Obzerver, an observability dashboard for Node.js Express and Fastify services.',
259
+ `Project: ${project}. Applications: ${apps || 'none have reported data yet'}. Current time: ${new Date(now).toISOString()}.`,
260
+ '',
261
+ 'How to work:',
262
+ '- Answer only from the tools. Never invent numbers, routes, versions, ids or causes. If the tools do not show it, say so plainly.',
263
+ '- Translate the question into tool calls. Pick windows deliberately with `minutes`: "since yesterday" = 1440 (compare with the previous 1440 when asked what changed), "this week" = 10080, "this month" = 43200.',
264
+ '- Before calling anything slow, busy, rare or unusual, check what is normal with get_baseline (same hour in earlier weeks). Raw data is only kept for days; for anything older than that, or "this month / since the last releases / which version was most stable", use get_history. Say which basis (week/day) a "normal" comes from, and say so plainly when there is not enough history yet.',
265
+ '- Comparisons need two readings (e.g. this week vs the week before: minutes 10080 now, and the trend tools). Correlation questions need both series over the same window; say clearly that co-occurrence is not proof of cause.',
266
+ '- Prefer few, targeted calls: overview → the relevant list → the detail of the top items. Stop when you can answer.',
267
+ '- For "find problems I have not noticed": check error groups (new and growing), slowest and most failing operations, N+1 and slow queries, release verdicts, firing alerts and SLO budgets; report what is unusual with evidence.',
268
+ '- Finish by calling the `answer` tool exactly once. Write the summary in the language of the user\'s question (Hebrew questions get Hebrew answers). Put numbers in evidence exactly as the tools returned them.',
269
+ '- Links: use only execution ids, trace ids, fingerprints, route names and versions that appear in tool results. Include the most useful executions or traces when you looked at them.',
270
+ '- Confidence: high = direct evidence with enough data; medium = indirect or small sample; low = little data or the question could not really be answered.',
271
+ ].join('\n');
272
+ }
273
+ const summarize = (out) => {
274
+ if (Array.isArray(out))
275
+ return `${out.length} row${out.length === 1 ? '' : 's'}`;
276
+ if (out && typeof out === 'object')
277
+ return `${Object.keys(out).length} fields`;
278
+ return 'done';
279
+ };
280
+ /** Run one question to a verified answer, emitting progress. Tools run against `db` (the current project). */
281
+ export async function ask(db, cfg, opts) {
282
+ const now = opts.now ?? Date.now();
283
+ const tools = [...MCP_TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })), ANSWER_TOOL];
284
+ const msgs = [];
285
+ for (const h of (opts.history || []).slice(-8)) {
286
+ if (!h.text?.trim())
287
+ continue;
288
+ const role = h.role === 'assistant' ? 'assistant' : 'user';
289
+ // Keep strict user/assistant alternation for the providers.
290
+ if (msgs.length && msgs[msgs.length - 1].role === role)
291
+ msgs[msgs.length - 1].content.push({ type: 'text', text: h.text });
292
+ else
293
+ msgs.push({ role, content: [{ type: 'text', text: h.text }] });
294
+ }
295
+ if (msgs.length && msgs[0].role === 'assistant')
296
+ msgs.shift();
297
+ if (msgs.length && msgs[msgs.length - 1].role === 'user')
298
+ msgs.pop();
299
+ msgs.push({ role: 'user', content: [{ type: 'text', text: opts.question }] });
300
+ const called = new Map();
301
+ const windows = [];
302
+ let corpus = '';
303
+ let nudged = false;
304
+ const system = systemPrompt(db, opts.project, now);
305
+ for (let step = 0; step < MAX_STEPS; step++) {
306
+ if (opts.signal?.aborted)
307
+ return null;
308
+ const turn = await callModel(cfg, system, msgs, step === MAX_STEPS - 1 ? [ANSWER_TOOL] : tools, opts.signal);
309
+ msgs.push({ role: 'assistant', content: turn.parts });
310
+ const calls = turn.parts.filter((p) => p.type === 'tool_call');
311
+ const final = calls.find((c) => c.name === 'answer');
312
+ if (final) {
313
+ const answer = verifyAnswer(final.input, { called, corpus, windows, now, model: cfg.model });
314
+ opts.emit({ type: 'answer', answer });
315
+ return answer;
316
+ }
317
+ if (!calls.length) {
318
+ // The model answered in prose. Ask once for the structured answer; otherwise wrap the prose.
319
+ const text = turn.parts.filter((p) => p.type === 'text').map((p) => p.text).join('\n').trim();
320
+ if (!nudged) {
321
+ nudged = true;
322
+ msgs.push({ role: 'user', content: [{ type: 'text', text: 'Now call the `answer` tool with your findings (summary, evidence, links, confidence).' }] });
323
+ continue;
324
+ }
325
+ const answer = verifyAnswer({ summary: text, evidence: [], links: [], confidence: 'low', confidenceReason: 'The model did not return a structured answer.' }, { called, corpus, windows, now, model: cfg.model });
326
+ opts.emit({ type: 'answer', answer });
327
+ return answer;
328
+ }
329
+ for (const t of turn.parts)
330
+ if (t.type === 'text' && t.text.trim())
331
+ opts.emit({ type: 'note', text: t.text.trim() });
332
+ const results = [];
333
+ for (const c of calls) {
334
+ const tool = MCP_TOOLS.find((t) => t.name === c.name);
335
+ opts.emit({ type: 'step', id: c.id, tool: c.name, input: c.input });
336
+ const t0 = Date.now();
337
+ if (!tool) {
338
+ results.push({ type: 'tool_result', id: c.id, content: `Unknown tool ${c.name}`, isError: true });
339
+ opts.emit({ type: 'step_done', id: c.id, ok: false, summary: 'unknown tool', ms: 0 });
340
+ continue;
341
+ }
342
+ try {
343
+ const out = tool.run(db, c.input || {});
344
+ let text = typeof out === 'string' ? out : JSON.stringify(out ?? null);
345
+ if (text.length > MAX_TOOL_CHARS)
346
+ text = `${text.slice(0, MAX_TOOL_CHARS)}\n…(truncated: narrow the query with service, limit or a shorter window)`;
347
+ corpus += `\n${text}`;
348
+ called.set(c.name, (called.get(c.name) ?? 0) + 1);
349
+ // History tools look further back than `minutes`: get_history by `days`, baselines over the last 8 weeks.
350
+ windows.push(c.name === 'get_history' ? (Number(c.input?.days) || 30) * 1440 : c.name === 'get_baseline' ? 8 * 10080
351
+ : Number(c.input?.minutes) > 0 ? Number(c.input.minutes) : 60);
352
+ results.push({ type: 'tool_result', id: c.id, content: text, isError: false });
353
+ opts.emit({ type: 'step_done', id: c.id, ok: true, summary: summarize(out), ms: Date.now() - t0 });
354
+ }
355
+ catch (e) {
356
+ results.push({ type: 'tool_result', id: c.id, content: `Error: ${e.message}`, isError: true });
357
+ opts.emit({ type: 'step_done', id: c.id, ok: false, summary: e.message.slice(0, 120), ms: Date.now() - t0 });
358
+ }
359
+ }
360
+ msgs.push({ role: 'user', content: results });
361
+ }
362
+ opts.emit({ type: 'error', message: 'The assistant used all its steps without answering. Try a narrower question.' });
363
+ return null;
364
+ }
365
+ //# sourceMappingURL=ai.js.map
package/dist/ai.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai.js","sourceRoot":"","sources":["../src/ai.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,EAAE;AACF,8FAA8F;AAC9F,kGAAkG;AAClG,0FAA0F;AAC1F,8FAA8F;AAC9F,mGAAmG;AACnG,yCAAyC;AACzC,wFAAwF;AACxF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAW,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAa,MAAM,UAAU,CAAC;AAChD,OAAO,KAAK,CAAC,MAAM,cAAc,CAAC;AAKlC,MAAM,CAAC,MAAM,cAAc,GAA+B,EAAE,SAAS,EAAE,mBAAmB,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC;AACzG,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,MAAM,cAAc,GAAG,KAAK,CAAC;AAE7B,MAAM,OAAO,OAAQ,SAAQ,KAAK;IACM;IAAtC,YAAY,OAAe,EAAW,SAAS,GAAG;QAAI,KAAK,CAAC,OAAO,CAAC,CAAC;QAA/B,WAAM,GAAN,MAAM,CAAM;IAAoB,CAAC;CACxE;AAED,MAAM,GAAG,GAAG,CAAC,CAAS,EAAsB,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;AAEnF,0FAA0F;AAE1F,MAAM,UAAU,QAAQ,CAAC,IAAQ;IAC/B,MAAM,QAAQ,GAAG,GAAG,CAAC,sBAAsB,CAA2B,CAAC;IACvE,MAAM,MAAM,GAAG,GAAG,CAAC,qBAAqB,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC,CAAC;IACxH,IAAI,QAAQ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C,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC;YAC1H,CAAC;QACH,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;IAChD,CAAC;IACD,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,8EAA8E,EAAE,CAAC,CAAC;IACtH,OAAO,IAAI,CAAC;AACd,CAAC"}
package/dist/alerts.d.ts CHANGED
@@ -10,6 +10,8 @@ export declare const RULE_TYPES: Record<RuleType, {
10
10
  export declare const isRuleType: (t: unknown) => t is RuleType;
11
11
  export interface RuleParams {
12
12
  mode?: 'threshold' | 'anomaly';
13
+ /** Anomaly mode only: also require the value to be unusual for this hour of the week (default true). */
14
+ seasonal?: boolean;
13
15
  threshold?: number;
14
16
  op?: '>' | '<';
15
17
  windowMin?: number;
@@ -53,6 +55,12 @@ export interface Delivery {
53
55
  error?: string;
54
56
  }
55
57
  export declare const toRule: (r: Row) => Rule;
58
+ /** The normal range for this rule's metric at this hour, learned from earlier weeks or days; null without enough history. */
59
+ export declare function seasonalRange(db: Db, type: RuleType, p: RuleParams, at: number): {
60
+ expected: number;
61
+ high: number;
62
+ description: string;
63
+ } | null;
56
64
  export interface Alerts {
57
65
  evaluate(now?: number): Promise<void>;
58
66
  onNewErrorGroup(g: NewErrorGroup): Promise<void>;
package/dist/alerts.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { withProject } from './projects.js';
2
2
  import { percentile } from './queries.js';
3
+ import { baseline } from './history.js';
3
4
  import { alertEmail, parseRecipients, sendMail } from './mailer.js';
4
5
  import { BURN_ALERTS, burnRate, toSlo } from './slos.js';
5
6
  export const RULE_TYPES = {
@@ -43,6 +44,21 @@ function scopeSql(p) {
43
44
  }
44
45
  return { sql: cond.length ? ` AND ${cond.join(' AND ')}` : '', args };
45
46
  }
47
+ const SEASONAL = {
48
+ error_rate: ['http', 'failureRate', 1], p95_latency: ['http', 'p95', 1], avg_latency: ['http', 'avg', 1],
49
+ throughput: ['http', 'callsPerHour', 1 / 60], job_failure_rate: ['job', 'failureRate', 1], job_queue_wait: ['job', 'queueWaitP95', 1],
50
+ };
51
+ /** The normal range for this rule's metric at this hour, learned from earlier weeks or days; null without enough history. */
52
+ export function seasonalRange(db, type, p, at) {
53
+ const m = SEASONAL[type];
54
+ if (!m || p.seasonal === false)
55
+ return null;
56
+ const b = baseline(db, { series: 'op', kind: m[0], service: p.service || null, name: p.route || null }, at);
57
+ const r = b[m[1]];
58
+ if (!b.basis || !r)
59
+ return null;
60
+ return { expected: r.expected * m[2], high: r.high * m[2], description: b.description };
61
+ }
46
62
  /** The rule's metric for the window ending at `to`, or null if there is nothing to judge. */
47
63
  function measure(db, type, p, to) {
48
64
  const windowMs = (Number(p.windowMin) || 10) * 60000;
@@ -222,6 +238,7 @@ export function createAlerts(db, { publicUrl, log, onIssueOpened, mailDb } = {})
222
238
  const value = m.value;
223
239
  const minN = Number(p.minRequests) || 0;
224
240
  let fire = false;
241
+ let note = '';
225
242
  if (p.mode === 'anomaly') {
226
243
  // Compare against the same metric over the preceding 12 windows.
227
244
  const windowMs = (Number(p.windowMin) || 15) * 60000;
@@ -235,6 +252,12 @@ export function createAlerts(db, { publicUrl, log, onIssueOpened, mailDb } = {})
235
252
  const sd = hist.length > 1 ? Math.sqrt(hist.reduce((a, b) => a + (b - mean) ** 2, 0) / (hist.length - 1)) : 0;
236
253
  const floor = Number(p.threshold) || 0; // minimum absolute value worth alerting on
237
254
  fire = m.n >= minN && value > floor && value > mean + 3 * Math.max(sd, mean * 0.1, 0.5) && (rule.type !== 'error_rate' || (m.extra || 0) >= 5);
255
+ // A jump that happens at this hour every week (the 09:00 rush) is not an anomaly.
256
+ const season = fire ? seasonalRange(db, rule.type, p, now) : null;
257
+ if (season && value <= season.high)
258
+ fire = false;
259
+ if (season)
260
+ note = ` (usual for this hour: ~${Math.round(season.expected * 100) / 100}, normal up to ${Math.round(season.high * 100) / 100}; ${season.description})`;
238
261
  }
239
262
  else if (rule.type === 'silence' || rule.type === 'job_silence') {
240
263
  fire = value >= (Number(p.windowMin) || 15);
@@ -249,7 +272,7 @@ export function createAlerts(db, { publicUrl, log, onIssueOpened, mailDb } = {})
249
272
  fire = false;
250
273
  db.run('UPDATE alert_rules SET last_eval = ?, last_value = ? WHERE id = ?', now, value, rule.id);
251
274
  if (fire && rule.state !== 'firing')
252
- await transition(rule, 'firing', value, describe(rule, value));
275
+ await transition(rule, 'firing', value, describe(rule, value) + note);
253
276
  else if (!fire && rule.state === 'firing')
254
277
  await transition(rule, 'resolved', value, `${describe(rule, value)} — back to normal`);
255
278
  }