All files / src api.ts

100% Statements 451/451
100% Branches 232/232
100% Functions 128/128
100% Lines 392/392

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 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376                                                                                                                                                                                  55x 55x 55x 55x             55x 55x                     19x 19x 19x                     10x 10x                         9x 9x 9x                   7x 7x       55x 55x       8x 8x 8x   3x           208x         122x 98x 98x         12x 12x         37x 37x       55x       339x 212x 212x 212x   422x 421x 213x   1x   212x       212x 422x 421x 213x                     73x               104x 104x       242x 42x 42x   200x 50x 50x   150x         215x 215x 215x 215x 215x 215x 49x 49x   2x           642x 642x 642x 642x     642x     642x       33x       26x         31x       508x           21x                       25x 25x 25x 25x       10x   15x   25x         833x 43x       11x 7x 7x 5x 5x       489x 5x 5x 5x   484x 38x 38x 35x   446x               119x 119x 84x 84x   33x                                         518x 518x 518x 7x     7x 152x   7x 4x 4x     514x 3x   514x   514x 514x 538x 24x   532x           532x               538x 538x 538x 6x 526x 422x 422x   532x 532x 501x 5x 5x   496x       7x 7x 7x   489x 446x 446x   532x     81x 81x 7x   74x 5x 5x   69x 3x 3x   66x   37x 37x                   29x 2x   27x 2x       30x 30x       32x       7x         20x 20x   19x 19x   1x   19x 19x       8x 5x 5x   3x       19x   7x   4x   3x   5x         7x 6x 6x       7x 7x 7x       5x 5x       10x 10x 10x 10x 10x       6x 6x 5x       4x 4x         5x 5x         4x         4x                 5x 5x               5x         7x         6x       4x         4x       5x       5x       4x 4x 4x       5x         5x       4x         4x       5x       5x                         16x 16x 16x   16x 16x 16x 16x                 15x                 6x 6x 6x                 6x                         4x 4x 4x                 4x         30x 30x 30x 30x                 30x                 5x 5x 5x 5x 5x 5x                 5x         2x         2x           12x 6x       5x                   5x       9x                                   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x           8x 8x 8x 8x 8x       4x         4x             5x             13x 13x 13x 13x 13x 13x     7x       4x         4x         5x 5x 5x     5x         4x 4x                   4x                       11x 11x   11x 11x 11x 11x 11x                   11x       5x         5x       13x 11x         3x 3x         5x         5x                 4x         4x       5x         9x       4x         4x         4x         4x       4x             4x       4x       5x 5x       4x                 4x               39x         54x 54x 48x         23x 23x 14x   9x 3x         4x 4x       5x         5x       5x               8x               6x                   3x         3x         5x         5x         7x                 5x                   5x                 4x               6x             6x             3x           3x 3x                     5x                                               7x         7x       5x     5x       5x     5x       4x       4x                         5x               5x               7x 7x     6x                 8x 8x           3x 3x       4x     4x       4x       4x       4x       4x                 4x       4x       105x 1x   104x 104x 104x 104x   104x 104x 185x 185x 82x 82x   82x 82x 139x 139x         103x 103x 103x       104x        
import {
    CAPABILITY,
    CRAWLER_STATUS_FIELD,
    bearerHeaders,
    JSON_HEADERS,
    OCTET_STREAM_HEADERS,
    REQUEST_OUTCOME,
    SEARCH_CHUNK_TYPE,
    SERVER_STATUS_PREFIX,
    SSE_EVENT,
    ERROR_NAME,
    HTTP_STATUS,
} from "./types";
import { ok, err, Result } from "./result";
import { attachmentFileName } from "./utils/attachment";
import { withIdleTimeout } from "./utils/idle";
 
import type {
    AgentClient,
    AgentConfigIndexResponse,
    AgentConfigResponse,
    Capability,
    CatalogResponse,
    ConfigResponse,
    ConfigSchemaResponse,
    ConfigSourcesResponse,
    ActiveProfileResponse,
    AnalyzeOptions,
    AnalyzeStateResponse,
    ExportedProfile,
    ProfileApplyResponse,
    ProfileDiffResponse,
    ProfileDiscardResponse,
    ProfileEntry,
    ProfileFolder,
    ProfileListResponse,
    ProfileLocationResponse,
    ProfileSaveResponse,
    ProfileValidationResponse,
    CrawlerStatusField,
    CrawlerStatusResponse,
    ConfigUpdateResponse,
    ConversationState,
    CrawlLogin,
    CrawlRenderMode,
    DatasetFormat,
    DocumentResult,
    DocumentsResponse,
    GenerationOptions,
    HealthResponse,
    InstalledResponse,
    PlacementResponse,
    PlacementSpec,
    MemoryFlagsResponse,
    MemoryItem,
    MemoryKind,
    MemoryListResponse,
    MemoryRemoveResponse,
    Message,
    ModelShowResponse,
    SessionDeleteResponse,
    SessionDetail,
    SessionExport,
    SessionListResponse,
    SessionMeta,
    SessionRenameResponse,
    SessionRole,
    SessionSourceRefInput,
    RememberResponse,
    ModelsResponse,
    ModelTask,
    RequestOutcome,
    SearchChunkType,
    SourceContent,
    SSEEvent,
    SetModelResponse,
    StatusResponse,
    WikiStatusResponse,
    SyncOptions,
    LintResult,
    DraftAcceptResponse,
    DraftInfoResponse,
    DraftRejectResponse,
    WikiCitationChain,
    WikiPage,
    WikiPageDetail,
    WikiStub,
    WikiPruneResult,
} from "./types";
const DEFAULT_TIMEOUT_MS = 15_000;
const CONTENT_DISPOSITION = "Content-Disposition";
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;
    }
}
 
/**
 * Thrown when the server answers 503 while it upgrades an older library in place.
 * Never retried: the upgrade runs for a while and `/api/health` reports its progress.
 */
export class LibraryUpgradingError extends Error {
    constructor() {
        super("lilbee is upgrading the library");
        this.name = ERROR_NAME.LIBRARY_UPGRADING;
    }
}
 
const HTTP_SERVER_ERROR = 500;
const HTTP_SERVICE_UNAVAILABLE = 503;
 
/** True when a 503 body is the object the server sends while it upgrades, which always carries `upgrade`. */
function isUpgradeBody(text: string): boolean {
    try {
        const body: unknown = JSON.parse(text);
        return typeof body === "object" && body !== null && "upgrade" in body;
    } catch {
        return false;
    }
}
 
/** True when the error carries the status line `assertOk` writes, so the server answered. */
export function hasStatusLine(error: unknown): error is Error {
    return error instanceof Error && error.message.startsWith(SERVER_STATUS_PREFIX);
}
 
/** The status in that line, or null when it carries no number to read. */
function httpStatusOf(error: unknown): number | null {
    if (!hasStatusLine(error)) return null;
    const status = parseInt(error.message.slice(SERVER_STATUS_PREFIX.length + 1), 10);
    return Number.isNaN(status) ? null : status;
}
 
/** True when the server rejected the request itself, so re-sending it unchanged will not help. */
export function isClientError(error: unknown): boolean {
    const status = httpStatusOf(error);
    return status !== null && status < HTTP_SERVER_ERROR;
}
 
/** True when the server failed rather than refused. An unreadable status is not a failure. */
function isServerError(error: unknown): boolean {
    const status = httpStatusOf(error);
    return status !== null && status >= HTTP_SERVER_ERROR;
}
 
/** Statuses a `Response` cannot be built with a body for; Chromium can still hand them a non-null empty one. */
const NULL_BODY_STATUSES: ReadonlySet<number> = new Set([204, 205, 304]);
 
/** `res` with its body read through a stream that fails once `idleMs` pass without a byte. */
function idleBoundedBody(res: Response, idleMs: number, abort: () => void): Response {
    if (!res.body || NULL_BODY_STATUSES.has(res.status)) return res;
    const reader = res.body.getReader();
    const chunks = withIdleTimeout(readChunks(reader), idleMs, abort);
    const body = new ReadableStream<Uint8Array>({
        async pull(stream) {
            const next = await chunks.next();
            if (next.done) stream.close();
            else stream.enqueue(next.value);
        },
        cancel: (reason) => reader.cancel(reason),
    });
    return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
}
 
async function* readChunks(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncGenerator<Uint8Array, void> {
    while (true) {
        const { done, value } = await reader.read();
        if (done) return;
        yield value;
    }
}
 
/**
 * 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 httpStatusOf(error) === status;
}
 
/**
 * Accumulates SSE lines into frames. A frame is the `event:` name plus every
 * `data:` line before the blank line that ends it.
 */
class SseFrames {
    private event: string = SSE_EVENT.MESSAGE;
    private data: string[] = [];
 
    /** Feed one line. Returns the frame it completed, or null. */
    accept(line: string): SSEEvent | null {
        if (line.startsWith("event:")) {
            this.event = (line.startsWith("event: ") ? line.slice(7) : line.slice(6)).trim();
            return null;
        }
        if (line.startsWith("data:")) {
            this.data.push(line.startsWith("data: ") ? line.slice(6) : line.slice(5));
            return null;
        }
        return line.trim() === "" ? this.take() : null;
    }
 
    /** The accumulated frame, or null when there is none. Resets either way. */
    take(): SSEEvent | null {
        const event = this.event;
        const raw = this.data.join("\n");
        const had = this.data.length > 0;
        this.event = SSE_EVENT.MESSAGE;
        this.data = [];
        if (!had) return null;
        try {
            return { event, data: JSON.parse(raw) };
        } catch {
            return { event, data: raw };
        }
    }
}
 
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(() => "");
            if (res.status === HTTP_SERVICE_UNAVAILABLE && isUpgradeBody(text)) throw new LibraryUpgradingError();
            throw new Error(`${SERVER_STATUS_PREFIX} ${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.
     * The timeout bounds the wait for the response headers and, after an ok
     * response, every gap between bytes of its body.
     * 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;
            // A caller's signal bounds the whole call, this wait included. Without
            // that, a 12 s wait for a host runs before the signal is ever consulted.
            while (!this.baseUrl && Date.now() < deadline && !opts?.signal?.aborted) {
                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;
                const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
                const controller = opts?.signal || opts?.stream ? null : new AbortController();
                if (opts?.signal) {
                    fetchInit.signal = opts.signal;
                } else if (controller) {
                    fetchInit.signal = controller.signal;
                    timer = window.setTimeout(() => controller.abort(), timeoutMs);
                }
                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 controller ? idleBoundedBody(okRes, timeoutMs, () => controller.abort()) : 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 LibraryUpgradingError) {
                    this.recordOutcome(REQUEST_OUTCOME.UPGRADING);
                    throw err;
                }
                if (hasStatusLine(err)) {
                    // A 4xx is the caller's to handle, not a global server fault; only a 5xx is.
                    this.recordOutcome(isServerError(err) ? 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.probeProvidersInstalled();
            case CAPABILITY.CRAWLING:
                return this.probeCrawlerInstalled(CRAWLER_STATUS_FIELD.PACKAGE);
            case CAPABILITY.CRAWLING_BROWSER:
                return this.probeCrawlerInstalled(CRAWLER_STATUS_FIELD.WITH_BROWSER);
            case CAPABILITY.WIKI:
                return this.probeWikiEnabled();
        }
    }
 
    private async probeProvidersInstalled(): 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(field: CrawlerStatusField): Promise<boolean> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/setup/crawler/status`);
        const body = (await res.json()) as CrawlerStatusResponse;
        return body[field] === 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 session as a markdown document (front matter, one section per turn, numbered sources) and its file name. */
    async getSessionMarkdown(sessionId: string): Promise<SessionExport> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}/markdown`);
        return { markdown: await res.text(), fileName: attachmentFileName(res.headers.get(CONTENT_DISPOSITION)) };
    }
 
    /** 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,
        sourceRefs: readonly SessionSourceRefInput[] = [],
    ): Promise<SessionDetail> {
        const source_refs = sourceRefs.map(({ source, citation_number }) => ({ source, citation_number }));
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify({ role, content, source_refs }),
            },
        );
        return (await res.json()) as SessionDetail;
    }
 
    /** Copies the first `messageCount` messages (all when omitted) into a new session and returns it. */
    async forkSession(sessionId: string, messageCount?: number): Promise<SessionDetail> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/sessions/${encodeURIComponent(sessionId)}/fork`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ message_count: messageCount ?? null }),
        });
        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);
    }
 
    /** Streams a sync. Always prunes the sources a .lilbeeignore excludes. */
    async *syncStream(signal?: AbortSignal, options?: SyncOptions): AsyncGenerator<SSEEvent, void> {
        const body: Record<string, unknown> = { prune_ignored: true };
        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);
    }
 
    /** Streams an analyze run: `analyze` progress frames, then `done` with the report or `error`. */
    async *analyzeStream(
        directory?: string | null,
        options?: AnalyzeOptions,
        signal?: AbortSignal,
    ): AsyncGenerator<SSEEvent, void> {
        const body: Record<string, unknown> = {};
        if (directory !== undefined) body.directory = directory;
        if (options?.apply) body.apply = true;
        if (options?.save !== undefined && options.save !== null) body.save = options.save;
        if (options?.target) body.target = options.target;
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/analyze`,
            {
                method: "POST",
                headers: { ...JSON_HEADERS, ...this.authHeaders() },
                body: JSON.stringify(body),
            },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    /** The project's analyze tip state, or null on a server that predates analyze. */
    async analyzeState(): Promise<AnalyzeStateResponse | null> {
        return this.jsonOrNullWhenMissing<AnalyzeStateResponse>(`${this.baseUrl}/api/analyze/state`);
    }
 
    /** Hide the analyze tip for this project; null on a server that predates analyze. */
    async dismissAnalyzeTip(): Promise<AnalyzeStateResponse | null> {
        return this.jsonOrNullWhenMissing<AnalyzeStateResponse>(`${this.baseUrl}/api/analyze/dismiss`, {
            method: "POST",
        });
    }
 
    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<SetModelResponse, Error>> {
        return this.fetchResult<SetModelResponse>(`${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;
        signal?: AbortSignal;
    }): 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}`, undefined, {
            signal: params?.signal,
        });
    }
 
    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: string[]; 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: string[]; 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,
        login?: CrawlLogin,
    ): 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;
        if (login !== undefined) body.login = login;
        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 *setupCrawler(signal?: AbortSignal): AsyncGenerator<SSEEvent, void> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/setup/crawler`,
            { method: "POST", 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;
    }
 
    /** The values the server accepts per setting. Absent before the server grew the route. */
    async configSchema(): Promise<ConfigSchemaResponse> {
        const res = await this.fetchWithRetry(`${this.baseUrl}/api/config/schema`);
        return (await res.json()) as ConfigSchemaResponse;
    }
 
    /** The layer that supplies each setting; null on a server without the route. */
    async configSources(): Promise<ConfigSourcesResponse | null> {
        return this.jsonOrNullWhenMissing<ConfigSourcesResponse>(`${this.baseUrl}/api/config/sources`);
    }
 
    /** Remove the user's value for each key so it falls back to the next source; null on a server without the route. */
    async resetConfig(keys: string[]): Promise<ConfigUpdateResponse | null> {
        return this.jsonOrNullWhenMissing<ConfigUpdateResponse>(`${this.baseUrl}/api/config/reset`, {
            method: "POST",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ keys }),
        });
    }
 
    /** Every profile, highest precedence first; null on a server without profiles. */
    async listProfiles(): Promise<ProfileListResponse | null> {
        return this.jsonOrNullWhenMissing<ProfileListResponse>(`${this.baseUrl}/api/profiles`);
    }
 
    /** The project's applied profile and the state of its file. */
    async activeProfile(): Promise<ActiveProfileResponse> {
        return this.profileJson<ActiveProfileResponse>("/api/profiles/active");
    }
 
    async getProfile(name: string): Promise<ProfileEntry> {
        return this.profileJson<ProfileEntry>(this.profilePath(name));
    }
 
    /** What applying the profile changes and which of the user's values it keeps. */
    async profileDiff(name: string): Promise<ProfileDiffResponse> {
        return this.profileJson<ProfileDiffResponse>(this.profilePath(name, "/diff"));
    }
 
    async applyProfile(name: string): Promise<ProfileApplyResponse> {
        return this.profileJson<ProfileApplyResponse>(this.profilePath(name, "/apply"), "POST");
    }
 
    /** Save the project's settings as a new profile and switch the project to it. */
    async saveProfile(name: string, target: ProfileFolder): Promise<ProfileSaveResponse> {
        return this.profileJson<ProfileSaveResponse>("/api/profiles", "POST", { name, target });
    }
 
    /** Write the project's settings into its profile, which *name* must pick. */
    async updateProfile(name: string): Promise<ProfileSaveResponse> {
        return this.profileJson<ProfileSaveResponse>(this.profilePath(name), "PUT");
    }
 
    /** Remove the user's values of profile settings so the profile's values show through. */
    async discardProfileChanges(): Promise<ProfileDiscardResponse> {
        return this.profileJson<ProfileDiscardResponse>("/api/profiles/discard", "POST");
    }
 
    async duplicateProfile(name: string, newName: string, target: ProfileFolder): Promise<ProfileLocationResponse> {
        return this.profileJson<ProfileLocationResponse>(this.profilePath(name, "/duplicate"), "POST", {
            new_name: newName,
            target,
        });
    }
 
    async renameProfile(name: string, newName: string): Promise<ProfileLocationResponse> {
        return this.profileJson<ProfileLocationResponse>(this.profilePath(name), "PATCH", { new_name: newName });
    }
 
    async deleteProfile(name: string): Promise<ProfileLocationResponse> {
        return this.profileJson<ProfileLocationResponse>(this.profilePath(name), "DELETE");
    }
 
    async exportProfile(name: string): Promise<ExportedProfile> {
        const res = await this.fetchWithRetry(`${this.baseUrl}${this.profilePath(name, "/export")}`);
        return { content: await res.text(), filename: attachmentFileName(res.headers.get(CONTENT_DISPOSITION)) };
    }
 
    async importProfile(content: string, filename: string, target: ProfileFolder): Promise<ProfileLocationResponse> {
        return this.profileJson<ProfileLocationResponse>("/api/profiles/import", "POST", { content, filename, target });
    }
 
    /** Every problem with a profile file's text, as a profile in *folder*. */
    async validateProfile(
        content: string,
        filename: string,
        folder: ProfileFolder,
    ): Promise<ProfileValidationResponse> {
        return this.profileJson<ProfileValidationResponse>("/api/profiles/validate", "POST", {
            content,
            filename,
            folder,
        });
    }
 
    private profilePath(name: string, suffix = ""): string {
        return `/api/profiles/${encodeURIComponent(name)}${suffix}`;
    }
 
    private async profileJson<T>(path: string, method = "GET", body?: Record<string, unknown>): Promise<T> {
        const init: RequestInit =
            body === undefined ? { method } : { method, headers: JSON_HEADERS, body: JSON.stringify(body) };
        const res = await this.fetchWithRetry(`${this.baseUrl}${path}`, init);
        return (await res.json()) as T;
    }
 
    /** The JSON body, or null when the server answers 404 because it predates the route. */
    private async jsonOrNullWhenMissing<T>(url: string, init?: RequestInit): Promise<T | null> {
        try {
            const res = await this.fetchWithRetry(url, init);
            return (await res.json()) as T;
        } catch (e) {
            if (e instanceof Error && isHttpStatus(e, HTTP_STATUS.NOT_FOUND)) return null;
            throw e;
        }
    }
 
    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<SetModelResponse, Error>> {
        return this.fetchResult<SetModelResponse>(`${this.baseUrl}/api/models/embedding`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    async setRerankerModel(model: string): Promise<Result<SetModelResponse, Error>> {
        return this.fetchResult<SetModelResponse>(`${this.baseUrl}/api/models/reranker`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    async setVisionModel(model: string): Promise<Result<SetModelResponse, Error>> {
        return this.fetchResult<SetModelResponse>(`${this.baseUrl}/api/models/vision`, {
            method: "PUT",
            headers: { ...JSON_HEADERS, ...this.authHeaders() },
            body: JSON.stringify({ model }),
        });
    }
 
    /** Chat-model cold-load progress, streamed as SSE until the engine is ready
     *  or fails. Each `warm` event carries a `WarmProgress` snapshot. */
    async *warmStream(signal?: AbortSignal): AsyncGenerator<SSEEvent, void> {
        const res = await this.fetchWithRetry(
            `${this.baseUrl}/api/warm/stream`,
            { headers: this.authHeaders() },
            { stream: true, signal },
        );
        yield* this.parseSSE(res);
    }
 
    /** 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(opts?: { signal?: AbortSignal }): Promise<Result<PlacementResponse, Error>> {
        return this.fetchResult<PlacementResponse>(
            `${this.baseUrl}/api/placement`,
            { headers: this.authHeaders() },
            opts,
        );
    }
 
    /** 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(),
        });
    }
 
    /** Wiki counters. `/api/status` carries none, so they come from here. */
    async wikiStatus(): Promise<Result<WikiStatusResponse, Error>> {
        return this.fetchResult<WikiStatusResponse>(`${this.baseUrl}/api/wiki/status`, {
            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[]> {
        return (
            (await this.jsonOrNullWhenMissing<WikiStub[]>(`${this.baseUrl}/api/wiki/stubs`, {
                headers: this.authHeaders(),
            })) ?? []
        );
    }
 
    /**
     * 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();
        const frames = new SseFrames();
        let buffer = "";
 
        try {
            for (;;) {
                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) {
                    const event = frames.accept(line);
                    if (event) yield event;
                }
            }
            // A stream that closes without its trailing blank line still holds a
            // frame, usually the terminating `done`.
            frames.accept(buffer);
            const tail = frames.take();
            if (tail) yield tail;
        } finally {
            // A consumer that stops early would otherwise leave the body unread
            // and the socket open until the server finished sending.
            await reader.cancel().catch(() => undefined);
        }
    }
}