All files / src api.ts

100% Statements 338/338
100% Branches 171/171
100% Functions 85/85
100% Lines 295/295

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 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025                                                                                                                            39x 39x 39x             39x 39x                     18x 18x 18x                     9x 9x                         9x 9x 9x                     24x       429x 429x 429x 429x     429x     429x       19x       12x         13x       323x           7x                       19x 19x 19x 19x       10x   9x   19x         563x 43x       11x 7x 7x 5x 5x       307x 5x 5x 5x   302x 18x 18x   284x               97x 97x 66x 66x   29x                                     332x 332x 332x 6x 6x 149x   6x 3x 3x     329x 3x   329x   329x 329x 353x 24x   347x           347x               353x 4x 343x 271x 271x 271x   347x 347x 319x 5x 5x   314x       7x 7x 7x   307x 284x 284x   347x     58x 58x 7x   51x 5x 5x   46x       18x 18x 18x                   28x 1x   27x 2x       30x 30x       29x       6x         16x 16x   15x 15x   1x   15x 15x       7x 4x 4x   3x       15x   7x   3x   5x         7x 6x 6x       3x 3x 3x       5x 5x       10x 10x 10x 10x 10x       4x 4x 4x       3x 3x         3x         3x                 4x               4x       3x         3x       4x       4x       4x 4x 4x       4x         4x       3x         3x       4x       4x                         15x 15x 15x   15x 15x 15x 15x                 14x                 6x 6x 6x                 6x                         3x 3x 3x                 3x       21x 21x 21x 21x                 21x       11x 5x       4x                   4x       8x                                 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x       7x 7x 7x 7x 7x       3x         3x             4x             6x 6x 6x 6x 6x 6x     6x       3x         3x         4x 4x 4x     4x         3x 3x                   3x                     8x 8x   8x 8x 8x 8x                   8x       12x 10x       4x 4x       4x         4x       4x               7x               5x                 4x         4x         4x         4x                   4x                 3x               5x             5x           3x 3x                     5x 5x     3x   2x 1x                                         6x         6x       4x     4x       4x     4x       3x       3x                         4x               4x               6x 6x     5x                 4x 4x           3x 3x       3x     3x       3x       3x       3x       3x                 3x       3x       73x 1x   72x 72x 72x 72x   72x 106x 106x 34x   34x   34x   34x 102x 30x 72x 35x 35x 35x   1x   35x            
import {
    CAPABILITY,
    bearerHeaders,
    JSON_HEADERS,
    OCTET_STREAM_HEADERS,
    REQUEST_OUTCOME,
    SEARCH_CHUNK_TYPE,
    SSE_EVENT,
    ERROR_NAME,
} from "./types";
import { ok, err, Result } from "./result";
 
import type {
    AgentClient,
    AgentConfigIndexResponse,
    AgentConfigResponse,
    Capability,
    CatalogResponse,
    ConfigResponse,
    ConfigUpdateResponse,
    ConversationState,
    CrawlRenderMode,
    DatasetFormat,
    DocumentResult,
    DocumentsResponse,
    GenerationOptions,
    HealthResponse,
    InstalledResponse,
    PlacementResponse,
    PlacementSpec,
    MemoryFlagsResponse,
    MemoryItem,
    MemoryKind,
    MemoryListResponse,
    MemoryRemoveResponse,
    Message,
    ModelShowResponse,
    SessionDeleteResponse,
    SessionDetail,
    SessionListResponse,
    SessionMeta,
    SessionRenameResponse,
    SessionRole,
    RememberResponse,
    ModelsResponse,
    ModelTask,
    RequestOutcome,
    SearchChunkType,
    SourceContent,
    SSEEvent,
    StatusResponse,
    SyncOptions,
    LintResult,
    DraftAcceptResponse,
    DraftInfoResponse,
    DraftRejectResponse,
    WikiCitationChain,
    WikiPage,
    WikiPageDetail,
    WikiStub,
    WikiPruneResult,
} from "./types";
const DEFAULT_TIMEOUT_MS = 15_000;
const RETRY_COUNT = 2;
const RETRY_BACKOFF_MS = 500;
// In managed mode, the plugin's onload doesn't configure the API until
// startManagedServer finishes (binary download + server boot). A caller
// firing a chat or catalog request in that window would otherwise see
// "Server is still starting up" with no recovery. Poll for the URL
// instead of bailing immediately; if it never lands, the throw still
// happens, just deferred.
const STARTUP_WAIT_MS = 12_000;
const STARTUP_POLL_INTERVAL_MS = 250;
 
/**
 * 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;
    }
}
 
/**
 * True when a `fetchResult` error came from a specific HTTP status. `assertOk`
 * formats non-ok responses as `Server responded <status>: <body>`, so callers
 * (e.g. the placement view distinguishing a 409 "apply not enabled" from a real
 * failure) can branch on the status without a bespoke error type per route.
 */
export function isHttpStatus(error: Error, status: number): boolean {
    return error.message.startsWith(`Server responded ${status}`);
}
 
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;
    }
 
    /** Reachability probe for an arbitrary URL. True on an ok response, false on
     * any error or timeout. Keeps browser fetch inside this module.
     *
     * *token* is explicit rather than optional: the server authenticates every
     * route, so a bare probe of a healthy server comes back 401 and reads as
     * unreachable. Pass null only when there is genuinely no token to send —
     * making it a required argument keeps a future caller from defaulting its
     * way back into that bug. */
    static async probe(url: string, timeoutMs: number, token: string | null): Promise<boolean> {
        const controller = new AbortController();
        const timer = window.setTimeout(() => controller.abort(), timeoutMs);
        try {
            const res = await window.fetch(url, {
                signal: controller.signal,
                ...(token ? { headers: bearerHeaders(token) } : {}),
            });
            return res.ok;
        } catch {
            return false;
        } finally {
            window.clearTimeout(timer);
        }
    }
 
    private authHeaders(): Record<string, string> {
        if (!this.token) return {};
        return bearerHeaders(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 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; timeoutMs?: number },
    ): 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; timeoutMs?: number },
    ): Promise<Response> {
        // Detect a URL that was pre-interpolated with an empty baseUrl
        // (callers do `${this.baseUrl}/api/...` — when baseUrl is "" the
        // result starts with "/api/..."). After the startup wait below
        // we rebuild it with the real host.
        const isRelative = !/^https?:\/\//i.test(url);
        const path = isRelative ? (url.startsWith("/") ? url : `/${url}`) : null;
        if (!this.baseUrl) {
            const deadline = Date.now() + STARTUP_WAIT_MS;
            while (!this.baseUrl && Date.now() < deadline) {
                await new Promise((r) => window.setTimeout(r, STARTUP_POLL_INTERVAL_MS));
            }
            if (!this.baseUrl) {
                this.recordOutcome(REQUEST_OUTCOME.STARTING);
                throw new ServerStartingError();
            }
        }
        if (path !== null) {
            url = `${this.baseUrl}${path}`;
        }
        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) => window.setTimeout(r, RETRY_BACKOFF_MS * attempt));
            }
            try {
                // Auth is attached here rather than at each call site: the
                // server authenticates every route, and a caller that forgot
                // the header would see a 401 that reads as an unreachable or
                // broken server. Re-read per attempt so the retry below picks
                // up a token refreshed after a 401 with no extra bookkeeping.
                const fetchInit: RequestInit = {
                    ...init,
                    headers: {
                        ...(init?.headers ?? {}),
                        ...this.authHeaders(),
                    },
                };
                let timer: number | undefined;
                if (opts?.signal) {
                    fetchInit.signal = opts.signal;
                } else if (!opts?.stream) {
                    const controller = new AbortController();
                    fetchInit.signal = controller.signal;
                    timer = window.setTimeout(() => controller.abort(), opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS);
                }
                try {
                    const res = await window.fetch(url, fetchInit);
                    if ((res.status === 401 || res.status === 403) && !authRetried && this.refreshTokenFromProvider()) {
                        authRetried = true;
                        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(REQUEST_OUTCOME.AUTH_ERROR);
                        throw new SessionTokenError(res.status, text);
                    }
                    const okRes = await this.assertOk(res);
                    this.recordOutcome(REQUEST_OUTCOME.OK);
                    return okRes;
                } finally {
                    if (timer !== undefined) window.clearTimeout(timer);
                }
            } catch (err) {
                lastError = err;
                if (err instanceof SessionTokenError) {
                    throw err;
                }
                if (err instanceof RateLimitedError) {
                    this.recordOutcome(REQUEST_OUTCOME.SERVER_ERROR);
                    throw err;
                }
                if (err instanceof Error && err.message.startsWith("Server responded")) {
                    // A 4xx is a reachable server rejecting this request (validation,
                    // not-found, conflict) that the caller handles — don't flag a
                    // global server error. Only 5xx flips the status to error.
                    const status = parseInt(err.message.slice("Server responded ".length), 10);
                    this.recordOutcome(status >= 500 ? REQUEST_OUTCOME.SERVER_ERROR : REQUEST_OUTCOME.OK);
                    throw err;
                }
                // An abort is the caller's decision, never a server fault. The
                // signal is the witness, not the error: Chromium reports an
                // aborted fetch as AbortError from some paths and as
                // TypeError("Failed to fetch") from others, and the latter is
                // indistinguishable from a refused connection by message. Left
                // to the name check alone, pressing Stop mid-stream retried the
                // request and then recorded "unreachable", which degraded the
                // whole plugin until a health probe cleared it.
                if (opts?.signal?.aborted) {
                    throw err;
                }
                if (err instanceof Error && err.name === ERROR_NAME.ABORT_ERROR) {
                    throw err;
                }
            }
        }
        this.recordOutcome(REQUEST_OUTCOME.UNREACHABLE);
        throw lastError;
    }
 
    async health(): Promise<Result<HealthResponse, 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 (await res.json()) as DocumentResult[];
    }
 
    async listSessions(): Promise<SessionMeta[]> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions`);
        const data = (await res.json()) as SessionListResponse;
        return data.sessions;
    }
 
    async getSession(sessionId: string): Promise<SessionDetail> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}`);
        return (await res.json()) as SessionDetail;
    }
 
    /** The server takes no title here; `renameSession` is the only HTTP title write. */
    async createSession(modelRef: string, scope: string): Promise<SessionDetail> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model_ref: modelRef, scope }),
        });
        return (await res.json()) as SessionDetail;
    }
 
    async appendSessionMessage(
        sessionId: string,
        role: SessionRole,
        content: string,
        sources: string[] = [],
    ): Promise<SessionDetail> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify({ role, content, sources }),
            },
        );
        return (await res.json()) as SessionDetail;
    }
 
    async renameSession(sessionId: string, title: string): Promise<SessionRenameResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}`, {
            method: "PATCH",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ title }),
        });
        return (await res.json()) as SessionRenameResponse;
    }
 
    async deleteSession(sessionId: string): Promise<SessionDeleteResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}`, {
            method: "DELETE",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
        });
        return (await res.json()) as SessionDeleteResponse;
    }
 
    async listMemories(): Promise<MemoryItem[]> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/memories`);
        const data = (await res.json()) as MemoryListResponse;
        return data.memories;
    }
 
    async remember(text: string, kind: MemoryKind, shared = false): Promise<RememberResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/memories`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ text, kind, shared }),
        });
        return (await res.json()) as RememberResponse;
    }
 
    async setMemoryShared(id: string, shared: boolean): Promise<MemoryFlagsResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/memories/${encodeURIComponent(id)}`, {
            method: "PATCH",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ shared }),
        });
        return (await res.json()) as MemoryFlagsResponse;
    }
 
    async forgetMemory(id: string): Promise<MemoryRemoveResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/memories/${encodeURIComponent(id)}`, {
            method: "DELETE",
            headers: { ...this.authHeaders() },
        });
        return (await res.json()) as MemoryRemoveResponse;
    }
 
    async *chatStream(
        question: string,
        history: Message[],
        topK?: number,
        signal?: AbortSignal,
        options?: GenerationOptions,
        chunkType?: SearchChunkType,
        conversation?: ConversationState,
    ): AsyncGenerator<SSEEvent, void> {
        // Omitted top_k uses the server's configured default; an explicit 0 disables retrieval.
        const body: Record<string, unknown> = { question, history };
        if (topK !== undefined) body.top_k = topK;
        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;
        if (conversation?.summary) body.summary = conversation.summary;
        if (conversation?.sessionId) body.session_id = conversation.sessionId;
        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,
        signal?: AbortSignal,
        ocrTimeout?: number | null,
    ): AsyncGenerator<SSEEvent, void> {
        const body: Record<string, unknown> = { paths, force };
        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);
    }
 
    /**
     * Upload file CONTENT to /api/add/upload and stream ingest progress. Used
     * when the server is remote (external mode): the plugin can't hand it a
     * server-readable path, so it sends the bytes straight from the vault.
     * FormData sets its own multipart Content-Type, so no JSON header here.
     */
    async *uploadFiles(
        files: { name: string; data: ArrayBuffer }[],
        signal?: AbortSignal,
    ): AsyncGenerator<SSEEvent, void> {
        const form = new FormData();
        for (const file of files) form.append("data", new Blob([file.data]), file.name);
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/add/upload`,
            {
                method: "POST",
                headers: { ...this.authHeaders() },
                body: form,
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async *syncStream(signal?: AbortSignal, options?: SyncOptions): AsyncGenerator<SSEEvent, void> {
        const body: Record<string, unknown> = {};
        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 (await res.json()) as ModelsResponse;
    }
 
    async *pullModel(model: string, source = "native", signal?: AbortSignal): AsyncGenerator<SSEEvent, void> {
        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;
        installed?: 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?.installed !== undefined) qs.set("installed", String(params.installed));
        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 (await res.json()) as InstalledResponse;
    }
 
    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 (await res.json()) as ModelShowResponse;
    }
 
    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 (await res.json()) as DocumentsResponse;
    }
 
    async removeDocuments(names: string[]): 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 }),
        });
        return (await res.json()) as { removed: number; not_found: string[] };
    }
 
    /** Download the per-page text dataset as raw bytes (parquet or jsonl). */
    async exportDataset(format: DatasetFormat, source?: string): Promise<ArrayBuffer> {
        const qs = new URLSearchParams({ format });
        if (source) qs.set("source", source);
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/export?${qs}`, {
            headers: this.authHeaders(),
        });
        return res.arrayBuffer();
    }
 
    /** Upload a per-page text dataset; the server re-embeds it and streams SSE progress. */
    async *importDataset(data: ArrayBuffer | Uint8Array, format: DatasetFormat): AsyncGenerator<SSEEvent, void> {
        const qs = new URLSearchParams({ format });
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/import?${qs}`,
            {
                method: "POST",
                headers: { ...OCTET_STREAM_HEADERS, ...this.authHeaders() },
                // Raw bytes — an ArrayBufferView is a valid fetch body at this serialization boundary.
                body: data as BodyInit,
            },
            { stream: true },
        );
        yield* this.parseSSE(res);
    }
 
    async *crawl(
        url: string,
        depth?: number | null,
        maxPages?: number | null,
        signal?: AbortSignal,
        renderMode?: CrawlRenderMode,
        includeSubdomains?: boolean,
    ): AsyncGenerator<SSEEvent, void> {
        const body: Record<string, unknown> = { url };
        if (depth !== undefined) body.depth = depth;
        // max_pages of 0 means "unlimited" on the server, so pass it through.
        if (maxPages !== undefined) body.max_pages = maxPages;
        if (renderMode !== undefined) body.render_mode = renderMode;
        if (includeSubdomains !== undefined) body.include_subdomains = includeSubdomains;
        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 (await res.json()) as ConfigResponse;
    }
 
    async configDefaults(): Promise<Record<string, unknown>> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/config/defaults`);
        return (await res.json()) as Record<string, unknown>;
    }
 
    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 (await res.json()) as ConfigUpdateResponse;
    }
 
    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 }),
        });
    }
 
    /** Live per-GPU utilization + free memory, streamed as SSE until aborted. */
    async *gpuStatsStream(signal?: AbortSignal): AsyncGenerator<SSEEvent, void> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/gpus/stream`,
            { headers: this.authHeaders() },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    /** The current effective placement (auto plan or active manual spec). */
    async placement(): Promise<Result<PlacementResponse, Error>> {
        return this.fetchResult<PlacementResponse>(`${this.baseUrl}/api/placement`, { headers: this.authHeaders() });
    }
 
    /** Dry-run a candidate spec (or auto when null); reports fit without persisting. */
    async placementPreview(spec: PlacementSpec | null): Promise<Result<PlacementResponse, Error>> {
        return this.fetchResult<PlacementResponse>(`${this.baseUrl}/api/placement/preview`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ spec }),
        });
    }
 
    /** Apply a manual spec: persists it and rebuilds the fleet. Returns 409 when
     * the server has not enabled HTTP placement (older or shared deployments). */
    async applyPlacement(spec: PlacementSpec): Promise<Result<PlacementResponse, Error>> {
        return this.fetchResult<PlacementResponse>(`${this.baseUrl}/api/placement`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ spec }),
        });
    }
 
    /** Clear the manual spec, returning to auto placement (rebuilds the fleet). */
    async clearPlacement(): Promise<Result<PlacementResponse, Error>> {
        return this.fetchResult<PlacementResponse>(`${this.baseUrl}/api/placement`, {
            method: "DELETE",
            headers: this.authHeaders(),
        });
    }
 
    /** Which agent CLIs the server can see on the machine it runs on. */
    async getAgentConfigIndex(): Promise<Result<AgentConfigIndexResponse, Error>> {
        return this.fetchResult<AgentConfigIndexResponse>(`${this.baseUrl}/api/agent-config`, {
            headers: this.authHeaders(),
        });
    }
 
    /** One client's config document, built against this server's live URL and token. */
    async getAgentConfig(client: AgentClient): Promise<Result<AgentConfigResponse, Error>> {
        return this.fetchResult<AgentConfigResponse>(`${this.baseUrl}/api/agent-config/${encodeURIComponent(client)}`, {
            headers: this.authHeaders(),
        });
    }
 
    async wikiList(): Promise<WikiPage[]> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki`, { headers: this.authHeaders() });
        return (await res.json()) as WikiPage[];
    }
 
    /**
     * The subjects the corpus names that have no page yet.
     *
     * Returns `[]` on 404 rather than throwing: the route arrived after the
     * plugin shipped, so an older server simply has no stubs to offer and the
     * browse list should render its written pages as before instead of failing.
     */
    async wikiStubs(): Promise<WikiStub[]> {
        try {
            const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/stubs`, {
                headers: this.authHeaders(),
            });
            return (await res.json()) as WikiStub[];
        } catch (e) {
            if (e instanceof Error && isHttpStatus(e, 404)) return [];
            throw e;
        }
    }
 
    /**
     * Write one indexed page. Costs a single LLM call and is GPU-heavy.
     *
     * Not a stream, but nothing like a normal request either: the server holds
     * the connection for the whole generation, which is minutes on a large
     * model. The default 15s timeout aborted every call before the page could
     * land, so this one names its own.
     */
    /**
     * Write one indexed page, streaming progress.
     *
     * The server holds this open for a whole model call, so it streams like the
     * wiki build rather than answering with a body: wiki_phase, heartbeats
     * while the GPU works, wiki_page, then done. The done event carries the
     * slug the read route accepts — the bare slug the caller sends is 404 there.
     */
    async *wikiGenerate(slug: string, signal?: AbortSignal): AsyncGenerator<SSEEvent, void> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/wiki/generate/${encodeURIComponent(slug)}`,
            { method: "POST", headers: this.authHeaders() },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    async wikiPage(slug: string): Promise<WikiPageDetail> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/${encodeURIComponent(slug)}`, {
            headers: this.authHeaders(),
        });
        return (await res.json()) as WikiPageDetail;
    }
 
    async wikiCitations(slug: string): Promise<WikiCitationChain> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/${encodeURIComponent(slug)}/citations`, {
            headers: this.authHeaders(),
        });
        return (await res.json()) as WikiCitationChain;
    }
 
    async wikiLint(): Promise<LintResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/lint`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return (await res.json()) as LintResult;
    }
 
    /**
     * Refresh the wiki across every ingested source, streaming progress.
     *
     * A build issues per-source LLM calls and embeddings and can run for a long
     * time, so the server streams `wiki_phase` / `wiki_page` events and closes
     * with a `done` event carrying a {@link WikiBuildResult}. Aborting the
     * signal stops the run at the next source boundary and releases the
     * server's build mutex.
     */
    async *wikiUpdate(signal?: AbortSignal): AsyncGenerator<SSEEvent, void> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/wiki/update`,
            {
                method: "PATCH",
                headers: this.authHeaders(),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    /**
     * 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 (await res.json()) as SourceContent;
    }
 
    /**
     * 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 wikiDrafts(): Promise<DraftInfoResponse[]> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts`, { headers: this.authHeaders() });
        return (await res.json()) as DraftInfoResponse[];
    }
 
    async wikiDraftDiff(slug: string): Promise<string> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts/diff/${encodeURIComponent(slug)}`, {
            headers: this.authHeaders(),
        });
        return res.text();
    }
 
    async wikiDraftAccept(slug: string): Promise<DraftAcceptResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts/accept/${encodeURIComponent(slug)}`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return (await res.json()) as DraftAcceptResponse;
    }
 
    async wikiDraftReject(slug: string): Promise<DraftRejectResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/drafts/${encodeURIComponent(slug)}`, {
            method: "DELETE",
            headers: this.authHeaders(),
        });
        return (await res.json()) as DraftRejectResponse;
    }
 
    /**
     * Prune stale and orphaned wiki pages. The server walks the tree and the
     * store off its event loop and answers once with the whole report, so this
     * is a single request rather than a progress stream.
     */
    async wikiPrune(): Promise<WikiPruneResult> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/wiki/prune`, {
            method: "POST",
            headers: this.authHeaders(),
        });
        return (await res.json()) as WikiPruneResult;
    }
 
    private async *parseSSE(response: Response): AsyncGenerator<SSEEvent, void> {
        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;
                }
            }
        }
    }
}