All files / src api.ts

100% Statements 573/573
100% Branches 198/198
100% Functions 66/66
100% Lines 573/573

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 7221x                                                                 1x 1x 1x               1x 15x 15x 15x 15x 15x 15x 15x             1x 1x 5x 5x 5x 1x               1x 9x 9x 9x 9x 9x 9x 9x       1x 227x 227x 227x 227x   227x 227x 227x 227x 227x 227x   227x 16x 16x   227x 10x 10x     227x 8x 8x   227x 159x 159x       227x 2x 2x   227x 100x 8x 100x   227x 10x 7x 10x 5x 5x 10x   227x 5x 5x 5x 1x 1x 5x 5x   227x 146x 5x 5x 5x 5x 146x 14x 14x 14x 127x 146x   227x 49x 49x 49x 49x 49x 49x 25x 25x 49x 24x 24x 49x               227x 161x 161x 161x 161x 161x 3x 3x 3x 158x 158x 158x 161x 172x 14x 14x 172x 172x 172x 172x 1x 172x 128x 128x 128x 128x 172x 172x 172x 5x 5x 5x 5x 172x       6x 6x 6x 6x 146x 127x 127x 172x 172x 172x 172x 40x 40x 6x 6x 40x 5x 5x 5x 40x 14x 14x 14x 40x 2x 2x 40x 172x 18x 18x 161x   227x 23x 23x   227x 3x 3x     227x 13x 13x 12x 12x 12x 13x 1x 1x 12x 12x 13x   227x 4x 1x 1x 1x 3x 4x   227x 12x 12x 6x 12x 2x 12x 4x 12x 12x   227x 6x 5x 6x 6x   227x 2x 2x 2x 2x   227x 4x 4x 4x   227x 8x 8x 8x 8x 8x 8x   227x 7x 7x 7x 7x 7x 3x 7x   227x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 10x 11x   227x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   227x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x   227x 1x 1x 1x   227x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   227x 6x 6x 6x 6x 6x 6x   227x               5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   227x 4x 4x 4x 4x 4x 4x   227x 1x 1x 1x 1x 1x 1x 1x   227x 2x 2x 2x 2x 2x 2x 2x 2x   227x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   227x 1x 1x 1x 1x 1x 1x 1x   227x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   227x 6x 6x 6x   227x 1x 1x 1x   227x 2x 2x 2x 2x 2x 2x 2x   227x 2x 2x 2x 2x 2x 2x   227x 5x 5x 5x 5x 5x 5x   227x 3x 3x 3x 3x 3x 3x   227x 1x 1x 1x   227x 2x 2x 2x 2x 2x   227x 2x 2x 2x 2x 2x   227x 1x 1x 1x 1x 1x 1x   227x 1x 1x 1x 1x 1x 1x   227x 2x 2x 2x 2x 1x 2x   227x 1x 1x 1x 1x 1x 1x   227x 2x 2x 2x 2x 2x   227x 2x 2x 2x 2x 2x 2x           227x 4x 4x 4x 4x 3x 4x             227x 2x 2x 2x 2x 2x   227x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   227x 1x 1x 1x   227x 1x 1x 1x 1x 1x   227x 1x 1x 1x 1x 1x 1x   227x 1x 1x 1x 1x 1x 1x   227x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   227x 42x 1x 1x 41x 41x 41x 41x   42x 63x 63x 22x   22x   22x   63x 66x 18x 66x 23x 23x 23x 23x 1x 1x 23x 23x 66x 22x 42x 227x  
import { CAPABILITY, JSON_HEADERS, SEARCH_CHUNK_TYPE, SSE_EVENT, ERROR_NAME } from "./types";
import { ok, err, Result } from "neverthrow";
 
import type {
    AskResponse,
    Capability,
    CatalogResponse,
    ConfigResponse,
    ConfigUpdateResponse,
    DocumentResult,
    DocumentsResponse,
    GenerationOptions,
    InstalledResponse,
    Message,
    ModelShowResponse,
    ModelsResponse,
    ModelTask,
    SearchChunkType,
    SourceContent,
    SSEEvent,
    StatusResponse,
    SyncOptions,
    LintResult,
    DraftAcceptResponse,
    DraftInfoResponse,
    DraftRejectResponse,
    WikiBuildResult,
    WikiCitationChain,
    WikiPage,
    WikiPageDetail,
    WikiStatusResult,
    WikiSynthesizeResult,
} from "./types";
const DEFAULT_TIMEOUT_MS = 15_000;
const RETRY_COUNT = 2;
const RETRY_BACKOFF_MS = 500;
 
/**
 * Thrown when the server rejects a request with 401 / 403 after the plugin's
 * auto-retry + token-refresh has failed. Signals that the stored session token
 * (manualToken or auto-discovered) is stale and the user needs to paste a new
 * one in Settings → Session token. Catchers should surface a targeted notice.
 */
export class SessionTokenError extends Error {
    readonly status: number;
    constructor(status: number, body: string) {
        super(`Session token invalid (HTTP ${status}): ${body}`);
        this.name = ERROR_NAME.SESSION_TOKEN;
        this.status = status;
    }
}
 
/**
 * Thrown when a request is attempted before the managed server has reported
 * its random listen port. Lets callers (settings UI, status bar) render a
 * "starting…" state instead of firing requests at the default port.
 */
export class ServerStartingError extends Error {
    constructor() {
        super("Server is still starting up");
        this.name = ERROR_NAME.SERVER_STARTING;
    }
}
 
/**
 * Thrown when the server returns HTTP 429 (e.g. a streaming endpoint already
 * has a stream in flight from another client). Carries the optional Retry-After
 * value in seconds so callers can include it in user copy. Never auto-retried —
 * the bead contract is "surface gracefully, do not silently retry-loop".
 */
export class RateLimitedError extends Error {
    readonly retryAfterSeconds: number | null;
    constructor(retryAfterSeconds: number | null = null) {
        super("lilbee is busy with another request");
        this.name = ERROR_NAME.RATE_LIMITED;
        this.retryAfterSeconds = retryAfterSeconds;
    }
}
 
export type RequestOutcome = "ok" | "auth_error" | "server_error" | "unreachable" | "starting";
 
export class LilbeeClient {
    private token: string | null = null;
    private tokenProvider: (() => string | null) | null = null;
    private outcomeCb: ((o: RequestOutcome) => void) | null = null;
    private capabilityCache: Map<Capability, boolean> = new Map();
 
    constructor(
        private baseUrl: string,
        token?: string,
    ) {
        if (token) this.token = token;
    }
 
    setToken(token: string | null): void {
        this.token = token;
    }
 
    setTokenProvider(provider: (() => string | null) | null): void {
        this.tokenProvider = provider;
    }
 
    /** Subscribe to the outcome of every ``fetchWithRetry`` call. */
    setOutcomeCallback(cb: ((o: RequestOutcome) => void) | null): void {
        this.outcomeCb = cb;
    }
 
    private recordOutcome(outcome: RequestOutcome): void {
        this.outcomeCb?.(outcome);
    }
 
    /** Repoint the client at a new base URL in place — lets the wizard update
     * the target server without tearing down the existing client instance. */
    setBaseUrl(url: string): void {
        this.baseUrl = url;
    }
 
    private authHeaders(): Record<string, string> {
        if (!this.token) return {};
        return { Authorization: `Bearer ${this.token}` };
    }
 
    private refreshTokenFromProvider(): boolean {
        if (!this.tokenProvider) return false;
        const next = this.tokenProvider();
        if (next === null || next === this.token) return false;
        this.token = next;
        return true;
    }
 
    private applyRefreshedToken(init: RequestInit | undefined): RequestInit {
        const base = { ...init };
        const existing = (base.headers ?? {}) as Record<string, string>;
        if (existing.Authorization) {
            base.headers = { ...existing, Authorization: `Bearer ${this.token}` };
        }
        return base;
    }
 
    private async assertOk(res: Response): Promise<Response> {
        if (res.status === 429) {
            const header = res.headers.get("Retry-After");
            const seconds = header ? parseInt(header, 10) : NaN;
            throw new RateLimitedError(Number.isFinite(seconds) ? seconds : null);
        }
        if (!res.ok) {
            const text = await res.text().catch(() => "");
            throw new Error(`Server responded ${res.status}: ${text}`);
        }
        return res;
    }
 
    private async fetchResult<T>(
        url: string,
        init?: RequestInit,
        opts?: { stream?: boolean; signal?: AbortSignal },
    ): Promise<Result<T, Error>> {
        try {
            const res = await this.fetchWithRetry(url, init, opts);
            const value = (await res.json()) as T;
            return ok(value);
        } catch (e) {
            return err(e instanceof Error ? e : new Error(String(e)));
        }
    }
 
    /**
     * Fetch with automatic retry on network errors and a default timeout.
     * Does NOT retry on HTTP error responses (4xx/5xx) — only on fetch failures
     * (e.g. connection refused, DNS failure, timeout).
     * SSE streams should pass `stream: true` to skip the timeout.
     */
    async fetchWithRetry(
        url: string,
        init?: RequestInit,
        opts?: { stream?: boolean; signal?: AbortSignal },
    ): Promise<Response> {
        if (!this.baseUrl) {
            this.recordOutcome("starting");
            throw new ServerStartingError();
        }
        const maxAttempts = RETRY_COUNT + 1;
        let lastError: unknown;
        let authRetried = false;
        for (let attempt = 0; attempt < maxAttempts; attempt++) {
            if (attempt > 0) {
                await new Promise((r) => setTimeout(r, RETRY_BACKOFF_MS * attempt));
            }
            try {
                const fetchInit = { ...init };
                let timer: ReturnType<typeof setTimeout> | undefined;
                if (opts?.signal) {
                    fetchInit.signal = opts.signal;
                } else if (!opts?.stream) {
                    const controller = new AbortController();
                    fetchInit.signal = controller.signal;
                    timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
                }
                try {
                    const res = await globalThis.fetch(url, fetchInit);
                    if ((res.status === 401 || res.status === 403) && !authRetried && this.refreshTokenFromProvider()) {
                        authRetried = true;
                        init = this.applyRefreshedToken(init);
                        continue;
                    }
                    if (res.status === 401 || res.status === 403) {
                        // Either no provider, provider returned the same token, or refreshed
                        // token still failed. The stored session token is stale — surface a
                        // typed error so the UI can tell the user what to do.
                        const text = await res.text().catch(() => "");
                        this.recordOutcome("auth_error");
                        throw new SessionTokenError(res.status, text);
                    }
                    const okRes = await this.assertOk(res);
                    this.recordOutcome("ok");
                    return okRes;
                } finally {
                    if (timer !== undefined) clearTimeout(timer);
                }
            } catch (err) {
                lastError = err;
                if (err instanceof SessionTokenError) {
                    throw err;
                }
                if (err instanceof RateLimitedError) {
                    this.recordOutcome("server_error");
                    throw err;
                }
                if (err instanceof Error && err.message.startsWith("Server responded")) {
                    this.recordOutcome("server_error");
                    throw err;
                }
                if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
                    throw err;
                }
            }
        }
        this.recordOutcome("unreachable");
        throw lastError;
    }
 
    async health(): Promise<Result<{ status: string; version: string }, Error>> {
        return this.fetchResult(`${this.baseUrl}/api/health`);
    }
 
    async status(): Promise<Result<StatusResponse, Error>> {
        return this.fetchResult(`${this.baseUrl}/api/status`);
    }
 
    /** Cached per session; fail-open on probe error (showing a section that won't work degrades better than hiding one the user needs). */
    async getCapability(cap: Capability): Promise<boolean> {
        const cached = this.capabilityCache.get(cap);
        if (cached !== undefined) return cached;
        let value: boolean;
        try {
            value = await this.probeCapability(cap);
        } catch {
            value = true;
        }
        this.capabilityCache.set(cap, value);
        return value;
    }
 
    invalidateCapability(cap?: Capability): void {
        if (cap === undefined) {
            this.capabilityCache.clear();
            return;
        }
        this.capabilityCache.delete(cap);
    }
 
    private async probeCapability(cap: Capability): Promise<boolean> {
        switch (cap) {
            case CAPABILITY.API_KEYS:
                return this.probeLitellmInstalled();
            case CAPABILITY.CRAWLING:
                return this.probeCrawlerInstalled();
            case CAPABILITY.WIKI:
                return this.probeWikiEnabled();
        }
    }
 
    private async probeLitellmInstalled(): Promise<boolean> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models/external`);
        const body = (await res.json()) as { models?: unknown; error?: unknown };
        return body.error === null || body.error === undefined;
    }
 
    private async probeCrawlerInstalled(): Promise<boolean> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/setup/crawler/status`);
        const body = (await res.json()) as { package_installed?: boolean };
        return body.package_installed === true;
    }
 
    private async probeWikiEnabled(): Promise<boolean> {
        const cfg = await this.config();
        return cfg.wiki === true;
    }
 
    async search(query: string, topK?: number, chunkType?: SearchChunkType): Promise<DocumentResult[]> {
        const params = new URLSearchParams({ q: query });
        if (topK !== undefined) params.set("top_k", String(topK));
        if (chunkType && chunkType !== SEARCH_CHUNK_TYPE.ALL) params.set("chunk_type", chunkType);
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/search?${params}`);
        return res.json();
    }
 
    async chat(question: string, history: Message[], topK?: number): Promise<AskResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/chat`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ question, history, top_k: topK ?? 0 }),
        });
        return res.json();
    }
 
    async *chatStream(
        question: string,
        history: Message[],
        topK?: number,
        signal?: AbortSignal,
        options?: GenerationOptions,
        chunkType?: SearchChunkType,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = { question, history, top_k: topK ?? 0 };
        if (options && Object.keys(options).length > 0) body.options = options;
        // "all" is the UI-side label for no filter; the field is omitted on the wire.
        if (chunkType && chunkType !== SEARCH_CHUNK_TYPE.ALL) body.chunk_type = chunkType;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/chat/stream`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async *addFiles(
        paths: string[],
        force = false,
        enableOcr?: boolean | null,
        signal?: AbortSignal,
        ocrTimeout?: number | null,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = { paths, force };
        if (enableOcr !== undefined && enableOcr !== null) body.enable_ocr = enableOcr;
        if (ocrTimeout !== undefined && ocrTimeout !== null) body.ocr_timeout = ocrTimeout;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/add`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async *syncStream(
        enableOcr?: boolean | null,
        signal?: AbortSignal,
        options?: SyncOptions,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = {};
        if (enableOcr !== undefined && enableOcr !== null) body.enable_ocr = enableOcr;
        if (options?.forceRebuild) body.force_rebuild = true;
        if (options?.retrySkipped) body.retry_skipped = true;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/sync`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async listModels(): Promise<ModelsResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models`);
        return res.json();
    }
 
    async *pullModel(model: string, source = "native", signal?: AbortSignal): AsyncGenerator<SSEEvent> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/models/pull`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify({ model, source }),
                signal,
            },
            { stream: true },
        );
        yield* this.parseSSE(res);
    }
 
    async setChatModel(model: string): Promise<Result<void, Error>> {
        return this.fetchResult<void>(`${this.baseUrl}/api/models/chat`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    async catalog(params?: {
        task?: ModelTask;
        search?: string;
        size?: "small" | "medium" | "large";
        sort?: "featured" | "downloads" | "name" | "size_asc" | "size_desc";
        featured?: boolean;
        limit?: number;
        offset?: number;
    }): Promise<Result<CatalogResponse, Error>> {
        const qs = new URLSearchParams();
        if (params?.task) qs.set("task", params.task);
        if (params?.search) qs.set("search", params.search);
        if (params?.size) qs.set("size", params.size);
        if (params?.sort) qs.set("sort", params.sort);
        if (params?.featured !== undefined) qs.set("featured", String(params.featured));
        if (params?.limit !== undefined) qs.set("limit", String(params.limit));
        if (params?.offset !== undefined) qs.set("offset", String(params.offset));
        const suffix = qs.toString() ? `?${qs}` : "";
        return this.fetchResult<CatalogResponse>(`${this.baseUrl}/api/models/catalog${suffix}`);
    }
 
    async installedModels(params?: { task?: ModelTask }): Promise<InstalledResponse> {
        const qs = new URLSearchParams();
        if (params?.task) qs.set("task", params.task);
        const suffix = qs.toString() ? `?${qs}` : "";
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models/installed${suffix}`);
        return res.json();
    }
 
    async showModel(model: string): Promise<ModelShowResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/models/show`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
        return res.json();
    }
 
    async deleteModel(
        model: string,
        source = "native",
    ): Promise<Result<{ deleted: boolean; model: string; freed_gb: number }, Error>> {
        return this.fetchResult(`${this.baseUrl}/api/models/${encodeURIComponent(model)}?source=${source}`, {
            method: "DELETE",
            headers: this.authHeaders(),
        });
    }
 
    async listDocuments(search?: string, limit?: number, offset?: number): Promise<DocumentsResponse> {
        const qs = new URLSearchParams();
        if (search) qs.set("search", search);
        if (limit !== undefined) qs.set("limit", String(limit));
        if (offset !== undefined) qs.set("offset", String(offset));
        const suffix = qs.toString() ? `?${qs}` : "";
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/documents${suffix}`, {
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async removeDocuments(names: string[], deleteFiles = false): Promise<{ removed: number; not_found: string[] }> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/documents/remove`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ names, delete_files: deleteFiles }),
        });
        return res.json();
    }
 
    async *crawl(
        url: string,
        depth?: number | null,
        maxPages?: number | null,
        signal?: AbortSignal,
    ): AsyncGenerator<SSEEvent> {
        const body: Record<string, unknown> = { url };
        if (depth !== undefined) body.depth = depth;
        if (maxPages !== undefined) body.max_pages = maxPages;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/crawl`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify(body),
                signal,
            },
            { stream: true },
        );
        yield* this.parseSSE(res);
    }
 
    async config(): Promise<ConfigResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/config`);
        return res.json();
    }
 
    async configDefaults(): Promise<Record<string, unknown>> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/config/defaults`);
        return res.json();
    }
 
    async updateConfig(updates: Record<string, unknown>): Promise<ConfigUpdateResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/config`, {
            method: "PATCH",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify(updates),
        });
        return res.json();
    }
 
    async setEmbeddingModel(model: string): Promise<Result<void, Error>> {
        return this.fetchResult<void>(`${this.baseUrl}/api/models/embedding`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    async setRerankerModel(model: string): Promise<Result<void, Error>> {
        return this.fetchResult<void>(`${this.baseUrl}/api/models/reranker`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    async setVisionModel(model: string): Promise<Result<void, Error>> {
        return this.fetchResult<void>(`${this.baseUrl}/api/models/vision`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    async wikiList(): Promise<WikiPage[]> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki`, { headers: this.authHeaders() });
        return res.json();
    }
 
    async wikiPage(slug: string): Promise<WikiPageDetail> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/${encodeURIComponent(slug)}`, {
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiCitations(slug: string): Promise<WikiCitationChain> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/${encodeURIComponent(slug)}/citations`, {
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiCitationsForSource(filename: string): Promise<WikiCitationChain[]> {
        const params = new URLSearchParams({ source: filename });
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/citations?${params}`, {
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiLint(): Promise<LintResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/lint`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiBuild(): Promise<WikiBuildResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/build`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiUpdate(): Promise<WikiBuildResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/update`, {
            method: "PATCH",
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiStatus(): Promise<WikiStatusResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/status`, {
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiSynthesize(): Promise<WikiSynthesizeResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/synthesize`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    /**
     * Fetch the rendered text of a source file (markdown / html / plaintext)
     * as JSON. Used by the preview modal when the file is not in the vault.
     */
    async getSource(source: string): Promise<SourceContent> {
        const params = new URLSearchParams({ source });
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/source?${params}`, {
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    /**
     * Fetch the raw bytes of a source file with its original Content-Type.
     * Returns the raw Response so callers can read `arrayBuffer()` or stream
     * it into an `<object>` tag (e.g. PDFs in the preview modal).
     */
    async getSourceRaw(source: string): Promise<Response> {
        const params = new URLSearchParams({ source, raw: "1" });
        return this.fetchWithRetry(`${this.baseUrl}/api/source?${params}`, {
            headers: this.authHeaders(),
        });
    }
 
    async *wikiGenerate(source: string, signal?: AbortSignal): AsyncGenerator<SSEEvent> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/wiki/generate`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify({ source }),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async wikiDrafts(): Promise<DraftInfoResponse[]> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts`, { headers: this.authHeaders() });
        return res.json();
    }
 
    async wikiDraftDiff(slug: string): Promise<string> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts/${encodeURIComponent(slug)}/diff`, {
            headers: this.authHeaders(),
        });
        return res.text();
    }
 
    async wikiDraftAccept(slug: string): Promise<DraftAcceptResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts/${encodeURIComponent(slug)}/accept`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async wikiDraftReject(slug: string): Promise<DraftRejectResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts/${encodeURIComponent(slug)}`, {
            method: "DELETE",
            headers: this.authHeaders(),
        });
        return res.json();
    }
 
    async *wikiPrune(signal?: AbortSignal): AsyncGenerator<SSEEvent> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/wiki/prune`,
            {
                method: "POST",
                headers: this.authHeaders(),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    private async *parseSSE(response: Response): AsyncGenerator<SSEEvent> {
        if (!response.body) {
            throw new Error("Response body is null");
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";
        let currentEvent: string = SSE_EVENT.MESSAGE;
 
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });
 
            const lines = buffer.split("\n");
            // split() always returns at least one element, so pop() is never undefined
            buffer = lines.pop()!;
 
            for (const line of lines) {
                if (line.startsWith("event:")) {
                    currentEvent = (line.startsWith("event: ") ? line.slice(7) : line.slice(6)).trim();
                } else if (line.startsWith("data:")) {
                    const raw = line.startsWith("data: ") ? line.slice(6) : line.slice(5);
                    try {
                        yield { event: currentEvent, data: JSON.parse(raw) };
                    } catch {
                        yield { event: currentEvent, data: raw };
                    }
                    currentEvent = SSE_EVENT.MESSAGE;
                }
            }
        }
    }
}