peppa/packages/bugsink/src/index.ts
Асель 8dc82859c7 PEP-36 stage 1: run Peppa with Node 26 type stripping instead of tsx
- tsconfig: erasableSyntaxOnly + verbatimModuleSyntax; parameter properties
  rewritten (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError,
  TelegramApi, MockGitea)
- bin wrappers (peppa, peppa-mcp, peppa-hook, peppa-bot, testkit mocks,
  peppa-dev): `node --import scripts/lib/require-node.mjs` (clear error on
  Node < 26, PEPPA_NODE overrides the binary); package scripts and tests on
  `node` / `node --test`; tsx removed
- install-launchd.sh pins PEPPA_NODE (checked absolute path) in the plists
- fix a race the faster hooks exposed: the prompt hook answered every pending
  question, including a PM question raised after Peppa itself pasted text
  into the terminal; sendToSession now logs `input_sent` and the hook only
  answers questions older than that input
- change pep-36-lightweight-stack: stage 1 done, hook start numbers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:51:22 +05:00

233 lines
8.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Bugsink adapter (PEP-58): REST API client (/api/canonical/0/, Bugsink 2.6) and the
// custom-webhook alert payload. No database here — Peppa's incident logic lives in core/runner.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const run = promisify(execFile);
/** An issue as Bugsink's API and its custom webhook serialize it (subset we use). */
export interface BugsinkIssueJson {
id: string;
friendly_id?: string;
project: number;
first_seen: string;
last_seen: string;
digested_event_count: number;
calculated_type: string;
calculated_value: string;
transaction?: string;
is_resolved: boolean;
is_muted?: boolean;
events_at?: string[];
// Webhook-only convenience fields.
title?: string;
project_name?: string;
url?: string;
alert_reason?: "NEW" | "REGRESSED" | "UNMUTED" | "TEST" | string;
}
interface Frame {
filename?: string;
abs_path?: string;
module?: string;
function?: string;
lineno?: number;
in_app?: boolean;
}
/** Event detail: `data` is the Sentry event payload. */
export interface BugsinkEventJson {
id: string;
issue: string;
timestamp: string;
data: {
environment?: string;
release?: string;
level?: string;
platform?: string;
exception?: { values?: Array<{ type?: string; value?: string; stacktrace?: { frames?: Frame[] } }> };
tags?: Record<string, string> | Array<[string, string]>;
};
}
/** What Peppa needs to know about an issue, whichever way it arrived. */
export interface BugsinkIssue {
issueId: string;
friendlyId: string | null;
bugsinkProjectId: number;
title: string;
culprit: string | null;
level: string | null;
environment: string | null;
release: string | null;
events: number;
firstSeen: Date;
lastSeen: Date;
url: string | null;
/** Top of the stack, innermost frame first, without locals. */
stack: string | null;
isResolved: boolean;
/** Why we got it: webhook alert reason, or POLL. */
reason: "NEW" | "REGRESSED" | "UNMUTED" | "POLL";
}
const STACK_LINES = 30;
function frameLine(f: Frame): string {
const where = f.filename ?? f.abs_path ?? f.module ?? "?";
return `${where}${f.lineno != null ? `:${f.lineno}` : ""} in ${f.function ?? "?"}${f.in_app === false ? "" : " [app]"}`;
}
function frames(e: BugsinkEventJson | null): Frame[] {
const values = e?.data.exception?.values ?? [];
// Sentry lists the outermost exception first and frames outermost first.
const last = values[values.length - 1];
return [...(last?.stacktrace?.frames ?? [])].reverse();
}
/** Where it broke: the innermost in-app frame ("billing/charge.ts"), else the innermost one. */
export function culpritOf(e: BugsinkEventJson | null, transaction?: string): string | null {
const fs = frames(e);
const f = fs.find((x) => x.in_app) ?? fs[0];
return f?.filename ?? f?.module ?? f?.abs_path ?? (transaction || null);
}
export function stackOf(e: BugsinkEventJson | null): string | null {
const fs = frames(e);
return fs.length ? fs.slice(0, STACK_LINES).map(frameLine).join("\n") : null;
}
/** Normalizes an API/webhook issue plus (optionally) its latest event. */
export function issueFromEvent(i: BugsinkIssueJson, e: BugsinkEventJson | null, reason: BugsinkIssue["reason"]): BugsinkIssue {
const title = i.title ?? `${i.calculated_type}: ${i.calculated_value}`;
return {
issueId: i.id,
friendlyId: i.friendly_id ?? null,
bugsinkProjectId: Number(i.project),
title,
culprit: culpritOf(e, i.transaction),
level: e?.data.level ?? null,
environment: e?.data.environment ?? null,
release: e?.data.release ?? i.events_at?.at(-1) ?? null,
events: i.digested_event_count,
firstSeen: new Date(i.first_seen),
lastSeen: new Date(i.last_seen),
url: i.url ?? null,
stack: stackOf(e),
isResolved: i.is_resolved,
reason,
};
}
/** Validates the custom-webhook body; null for anything that isn't an issue alert (e.g. TEST). */
export function parseWebhook(body: unknown): BugsinkIssueJson | null {
if (!body || typeof body !== "object") return null;
const b = body as Partial<BugsinkIssueJson>;
if (typeof b.id !== "string" || b.project == null || typeof b.last_seen !== "string" || typeof b.calculated_type !== "string") return null;
if (b.alert_reason === "TEST") return null;
return b as BugsinkIssueJson;
}
export class BugsinkError extends Error {
readonly status?: number;
constructor(message: string, status?: number) {
super(message);
this.status = status;
}
}
export interface BugsinkConfig {
/** Internal API base, e.g. http://127.0.0.1:3180 */
url: string;
token: string;
/** Team UUID that new projects go into. */
teamId?: string;
/** Public base URL for issue links (defaults to url). */
publicUrl?: string;
/** Docker container to configure alert webhooks in (the API has no endpoint for that). */
container?: string;
}
export type BugsinkClient = ReturnType<typeof createBugsinkClient>;
export function createBugsinkClient(c: BugsinkConfig) {
const base = `${c.url.replace(/\/$/, "")}/api/canonical/0`;
const publicUrl = (c.publicUrl ?? c.url).replace(/\/$/, "");
async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
let res: Response;
try {
res = await fetch(`${base}${path}`, {
method,
headers: { authorization: `Bearer ${c.token}`, ...(body ? { "content-type": "application/json" } : {}) },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(15_000),
});
} catch (e) {
throw new BugsinkError(`Bugsink недоступен: ${(e as Error).message}`);
}
if (!res.ok) throw new BugsinkError(`Bugsink ${method} ${path}: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
return (await res.json()) as T;
}
return {
publicUrl,
issueUrl: (issueId: string) => `${publicUrl}/issues/issue/${issueId}/event/last/`,
async createProject(name: string): Promise<{ id: number; dsn: string }> {
if (!c.teamId) throw new BugsinkError("BUGSINK_TEAM_ID не задан");
const created = await call<{ id: string | number }>("POST", "/projects/", { team: c.teamId, name });
const p = await call<{ id: number; dsn: string }>("GET", `/projects/${created.id}/`);
return { id: Number(p.id), dsn: p.dsn };
},
/** Most recently seen issues of a project (first page). */
async listIssues(projectId: number): Promise<BugsinkIssueJson[]> {
const r = await call<{ results: BugsinkIssueJson[] }>("GET", `/issues/?project=${projectId}&sort=last_seen&order=desc`);
return r.results;
},
getIssue: (issueId: string) => call<BugsinkIssueJson>("GET", `/issues/${issueId}/`),
async latestEvent(issueId: string): Promise<BugsinkEventJson | null> {
const r = await call<{ results: Array<{ id: string }> }>("GET", `/events/?issue=${issueId}&order=desc`);
const first = r.results[0];
return first ? call<BugsinkEventJson>("GET", `/events/${first.id}/`) : null;
},
resolveIssue: (issueId: string) => call<BugsinkIssueJson>("POST", `/issues/${issueId}/resolve/`),
/** Points the project's alerts (new / regressed / unmuted) at Peppa's webhook URL. */
async setAlertWebhook(projectId: number, webhookUrl: string): Promise<void> {
if (!c.container) throw new BugsinkError("API Bugsink не умеет настраивать алерты: добавьте Custom webhook вручную");
const py = [
"import json, sys",
"from alerts.models import MessagingServiceConfig",
"from projects.models import Project",
`p = Project.objects.get(id=${Number(projectId)})`,
`cfg = json.dumps({"webhook_url": ${JSON.stringify(webhookUrl)}})`,
"m = MessagingServiceConfig.objects.filter(project=p, display_name='Peppa').first()",
"m = m or MessagingServiceConfig(project=p, display_name='Peppa', kind='custom')",
"m.kind = 'custom'; m.config = cfg; m.save(); print('ok')",
].join("\n");
try {
await run("docker", ["exec", c.container, "bugsink-manage", "shell", "-c", py], { timeout: 60_000 });
} catch (e) {
throw new BugsinkError(`Не удалось настроить вебхук в Bugsink: ${(e as Error).message.slice(0, 200)}`);
}
},
};
}
/** The client configured in Peppa's env (BUGSINK_URL, BUGSINK_TOKEN…), or null. */
export function bugsinkFromEnv(env: NodeJS.ProcessEnv = process.env): BugsinkClient | null {
if (!env.BUGSINK_URL || !env.BUGSINK_TOKEN) return null;
return createBugsinkClient({
url: env.BUGSINK_URL,
token: env.BUGSINK_TOKEN,
teamId: env.BUGSINK_TEAM_ID,
publicUrl: env.BUGSINK_PUBLIC_URL,
container: env.BUGSINK_CONTAINER,
});
}