All files / src types.ts

100% Statements 75/75
100% Branches 2/2
100% Functions 2/2
100% Lines 75/75

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 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505                                                              59x               59x                                                                                                                                                                                                                     59x               59x             59x                     59x             59x                 59x               59x             59x               59x                     59x                           59x                 59x   59x                                                                                                 59x                                                       59x                                                                                                                                         59x                                   59x                                   59x                   59x                       59x               59x               59x                                                                                         59x                     59x             59x         59x                                                                                           59x             59x                                                                               59x                                                                                               59x                           59x                                         59x                                   59x                 59x     59x                                                                                                   59x                                                                                                                                                         59x 59x               163x       59x               80x                                                                                                                                     59x                                         59x                     59x                       59x                   59x         59x                 59x                                                                                                                     59x                                                                                                                                                         59x                     59x                 59x                           59x                           59x               59x         59x                                                                                                                                     59x             59x                   59x         59x         59x                     59x               59x                                                 59x           59x                                 59x   59x       59x                                               59x                               59x                                           59x         59x                                                 59x                                                
import type { DownloadProgress, EnsureResult, LauncherErrorCode, Variant } from "lilbee";
 
export interface Excerpt {
    content: string;
    page_start: number | null;
    page_end: number | null;
    line_start: number | null;
    line_end: number | null;
    relevance: number;
}
 
export interface DocumentResult {
    source: string;
    content_type: string;
    excerpts: Excerpt[];
    best_relevance: number;
}
 
/** `GET /api/health`. `chat_ready`/`chat_ctx` are absent on older servers. */
export interface HealthResponse {
    status: string;
    version: string;
    /** True once the chat engine is loaded and can serve a first token. */
    chat_ready?: boolean;
    /** Per-slot context window the chat engine serves; null when not up. */
    chat_ctx?: number | null;
}
 
/** Whether a citation states a fact from the source or an inference drawn from it. */
export type ClaimType = "fact" | "inference";
 
export const CLAIM_TYPE = {
    FACT: "fact",
    INFERENCE: "inference",
} as const satisfies Record<string, ClaimType>;
 
/** How a `fetchResult` request concluded, reported to the status bar. */
export type RequestOutcome = "ok" | "auth_error" | "server_error" | "unreachable" | "starting";
 
export const REQUEST_OUTCOME = {
    OK: "ok",
    AUTH_ERROR: "auth_error",
    SERVER_ERROR: "server_error",
    UNREACHABLE: "unreachable",
    STARTING: "starting",
} as const satisfies Record<string, RequestOutcome>;
 
export interface Source {
    source: string;
    content_type: string;
    distance: number;
    chunk: string;
    page_start: number | null;
    page_end: number | null;
    line_start: number | null;
    line_end: number | null;
    chunk_type?: "raw" | "wiki";
    claim_type?: ClaimType;
    /**
     * Relative path within the vault when the server is managed and
     * `documents_dir` is inside the user's vault. `null` for external servers
     * where the file is not accessible as a vault-relative path.
     */
    vault_path?: string | null;
}
 
/**
 * Returned by `GET /api/source?source=...`. When `raw=1` the server streams
 * bytes with the original `Content-Type`; this shape is used for the JSON
 * response only.
 */
export interface SourceContent {
    markdown: string;
    content_type: string;
    crawled_at?: string;
    title?: string;
}
 
export interface ModelInfo {
    name: string;
    size_gb: number;
    min_ram_gb: number;
    description: string;
    installed: boolean;
    source?: string;
}
 
export interface ModelCatalog {
    active: string;
    catalog: ModelInfo[];
    installed: string[];
}
 
export interface ModelsResponse {
    chat: ModelCatalog;
    embedding?: ModelCatalog;
    vision?: ModelCatalog;
    reranker?: ModelCatalog;
}
 
export interface ConfigResponse {
    reranker_model: string | null;
    rerank_candidates: number;
    vision_model: string | null;
    rag_system_prompt?: string;
    general_system_prompt?: string;
    chat_mode?: ChatMode;
    embedding_model?: string;
    wiki?: boolean;
    worker_pool_call_timeout_s?: number;
    worker_pool_eager_start?: boolean;
    worker_pool_max_idle_s?: number;
    vision_load_budget_s?: number;
    chunk_size?: number;
    chunk_overlap?: number;
    max_chunks_per_file?: number;
    tesseract_timeout?: number;
    max_tokens?: number;
    show_reasoning?: boolean;
    chat_compaction?: boolean;
    max_reasoning_chars?: number;
    model_keep_alive?: string;
    gpu_memory_fraction?: number;
    // Fleet / GPU placement knobs (lilbee feat/local-model-api). Replica counts
    // of 0 mean "auto" (one per GPU). `placement` is the manual spec JSON when
    // set; it is read-only here — change it through the placement endpoints, not
    // a generic config PATCH.
    embed_replicas?: number;
    vision_replicas?: number;
    flash_attention?: boolean | null;
    kv_cache_type?: KvCacheType;
    n_gpu_layers?: number | null;
    gpu_devices?: string | null;
    placement?: string | null;
    candidate_multiplier?: number;
    max_distance?: number;
    min_relevance_score?: number;
    max_context_sources?: number;
    diversity_max_per_source?: number;
    mmr_lambda?: number;
    crawl_render_mode?: CrawlRenderMode;
    [key: string]: unknown;
}
 
export type CrawlRenderMode = "http" | "browser";
 
export const CRAWL_RENDER_MODE = {
    HTTP: "http",
    BROWSER: "browser",
} as const satisfies Record<string, CrawlRenderMode>;
 
/** KV-cache element type for the chat fleet. Mirrors the server's KvCacheType. */
export type KvCacheType = "f16" | "f32" | "q8_0" | "q4_0";
 
export const KV_CACHE_TYPE = {
    F16: "f16",
    F32: "f32",
    Q8_0: "q8_0",
    Q4_0: "q4_0",
} as const satisfies Record<string, KvCacheType>;
 
export const CONFIG_KEY = {
    RAG_SYSTEM_PROMPT: "rag_system_prompt",
    GENERAL_SYSTEM_PROMPT: "general_system_prompt",
    CHAT_MODE: "chat_mode",
    SHOW_REASONING: "show_reasoning",
    CHAT_COMPACTION: "chat_compaction",
    CRAWL_RENDER_MODE: "crawl_render_mode",
} as const;
 
export type ChatMode = "search" | "chat";
 
export const CHAT_MODE = {
    SEARCH: "search",
    CHAT: "chat",
} as const satisfies Record<string, ChatMode>;
 
export type CatalogSource = "native" | "frontier" | "ollama" | "lm_studio";
 
export const CATALOG_SOURCE = {
    NATIVE: "native",
    FRONTIER: "frontier",
    OLLAMA: "ollama",
    LM_STUDIO: "lm_studio",
} as const satisfies Record<string, CatalogSource>;
 
/** Sources rendered in the shared "hosted" area: selectable, no download.
 * Frontier (cloud API key) plus the local servers (Ollama, LM Studio). */
export const HOSTED_SOURCES: ReadonlySet<CatalogSource> = new Set<CatalogSource>([
    CATALOG_SOURCE.FRONTIER,
    CATALOG_SOURCE.OLLAMA,
    CATALOG_SOURCE.LM_STUDIO,
]);
 
export type KeyStatus = "ready" | "missing_key";
 
export const KEY_STATUS = {
    READY: "ready",
    MISSING_KEY: "missing_key",
} as const satisfies Record<string, KeyStatus>;
 
export type Capability = "api_keys" | "crawling" | "wiki";
 
export const CAPABILITY = {
    API_KEYS: "api_keys",
    CRAWLING: "crawling",
    WIKI: "wiki",
} as const satisfies Record<string, Capability>;
 
export type CatalogTab = "discover" | "chat" | "embed" | "vision" | "rerank" | "library";
 
export const CATALOG_TAB = {
    DISCOVER: "discover",
    CHAT: "chat",
    EMBED: "embed",
    VISION: "vision",
    RERANK: "rerank",
    LIBRARY: "library",
} as const satisfies Record<string, CatalogTab>;
 
export type HardwareFit = "fits" | "tight" | "wont_run";
 
export const HARDWARE_FIT = {
    FITS: "fits",
    TIGHT: "tight",
    WONT_RUN: "wont_run",
} as const satisfies Record<string, HardwareFit>;
 
/**
 * Whether the connected lilbee server can run a catalog model, derived from its
 * architecture. `supported` is the common case (no badge); `unsupported` means
 * the server's runtime can't load it (gate the download); `unknown` means the
 * server couldn't classify the architecture (surface it, but don't block).
 */
export type ModelCompat = "supported" | "unsupported" | "unknown";
 
export const MODEL_COMPAT = {
    SUPPORTED: "supported",
    UNSUPPORTED: "unsupported",
    UNKNOWN: "unknown",
} as const satisfies Record<string, ModelCompat>;
 
export type DiscoverRail = "for_you" | "your_collection" | "fresh";
 
/** Vault folder that holds the managed documents when content is stored in the vault. */
export const MANAGED_DOCS_PREFIX = "lilbee/";
 
export const DISCOVER_RAIL = {
    FOR_YOU: "for_you",
    YOUR_COLLECTION: "your_collection",
    FRESH: "fresh",
} as const satisfies Record<string, DiscoverRail>;
 
export interface StatusResponse {
    config: Record<string, string>;
    document_count: number;
    /** Held-out files, capped by the server; `skipped_total` is the real count. */
    skipped?: SkippedSource[];
    skipped_total?: number;
    sources: { filename: string; chunk_count: number }[];
    total_chunks: number;
    wiki?: {
        enabled: boolean;
        page_count: number;
        draft_count: number;
        last_lint: string | null;
    };
}
 
/** A file a skip marker holds out of the index, with the reason the server recorded. */
export interface SkippedSource {
    filename: string;
    reason: string;
}
 
export interface SyncDone {
    added: string[];
    updated: string[];
    removed: string[];
    unchanged: number;
    failed: string[];
    skipped: string[];
    held_out: SkippedSource[];
}
 
/** Recovery options for a sync. Both default off (a plain incremental sync). */
export interface SyncOptions {
    /** Drop the whole index and re-embed every document from scratch. */
    forceRebuild?: boolean;
    /** Clear skip markers so files skipped on a previous sync are retried. */
    retrySkipped?: boolean;
}
 
/** Who asked for a sync. Only a user-initiated one reports that a sync is already pending. */
export type SyncTrigger = "user" | "automatic";
 
export const SYNC_TRIGGER = {
    USER: "user",
    AUTOMATIC: "automatic",
} as const satisfies Record<string, SyncTrigger>;
 
export interface GenerationOptions {
    temperature?: number;
    top_p?: number;
    top_k?: number;
    repeat_penalty?: number;
    num_ctx?: number;
    seed?: number;
}
 
/** Object-shaped `data` may carry an optional `banner` string the chat view renders above the answer bubble. */
export interface SSEEvent {
    event: string;
    data: unknown;
}
 
export interface Message {
    role: "user" | "assistant" | "system";
    content: string;
}
 
/** Author of a persisted chat turn. Narrower than `Message.role`: the store has no system turns. */
export type SessionRole = "user" | "assistant";
 
export const SESSION_ROLE = {
    USER: "user",
    ASSISTANT: "assistant",
} as const satisfies Record<string, SessionRole>;
 
/** A session's metadata, without its transcript. Body of each `GET /api/sessions` row. */
export interface SessionMeta {
    id: string;
    title: string;
    created_at: string;
    updated_at: string;
    model_ref: string;
    scope: string;
    message_count: number;
    /** Owning surface (`tui`/`http`/`cli`); the list route only returns these human origins. */
    origin: string;
}
 
/** One persisted turn. `sources` are bare source paths, not the richer `Source` chat streams carry. */
export interface SessionMessageItem {
    role: SessionRole;
    content: string;
    sources: string[];
    ts: string;
}
 
/** Body of `GET /api/sessions/{id}`, and of create/append. `summary` is `""` until compaction has folded turns away. */
export interface SessionDetail {
    meta: SessionMeta;
    messages: SessionMessageItem[];
    summary: string;
}
 
export interface SessionListResponse {
    sessions: SessionMeta[];
}
 
/** Data of a `compacting` SSE event: batch progress while the server condenses. */
export interface CompactingEventData {
    batch?: number;
    batches?: number;
}
 
/** Data of a `compaction` SSE event: what a chat turn folded away before answering. */
export interface CompactionEventData {
    summary: string;
    condensed: number;
    /** Turns dropped with no notes; shown plainly rather than hidden. */
    stranded: number;
}
 
/** Conversation state a chat stream carries so the server can window and compact it. */
export interface ConversationState {
    summary: string;
    sessionId: string | null;
}
 
export interface SessionRenameResponse {
    id: string;
    title: string;
}
 
export interface SessionDeleteResponse {
    id: string;
    deleted: boolean;
}
 
export type ServerState = "stopped" | "downloading" | "starting" | "ready" | "error";
 
export const SERVER_STATE = {
    STOPPED: "stopped",
    DOWNLOADING: "downloading",
    STARTING: "starting",
    READY: "ready",
    ERROR: "error",
} as const satisfies Record<string, ServerState>;
 
/**
 * Progress phases emitted by the managed-server start flow to any observer that
 * passes an `onProgress` handler — currently the setup wizard, which shows
 * binary-download and server-startup state inline while the user waits on the
 * Server step. Lives here (not in main.ts) so leaf views can import the
 * constant without pulling in the plugin entry point and risking a circular
 * value import.
 */
export type ManagedServerProgressPhase = "downloading" | "starting" | "ready" | "error";
 
export const MANAGED_PHASE = {
    DOWNLOADING: "downloading",
    STARTING: "starting",
    READY: "ready",
    ERROR: "error",
} as const satisfies Record<string, ManagedServerProgressPhase>;
 
export interface ManagedServerProgress {
    phase: ManagedServerProgressPhase;
    message: string;
    /** 0-100 while the server binary downloads; absent when the size is unknown. */
    percent?: number;
}
 
export type ManagedServerProgressHandler = (event: ManagedServerProgress) => void;
 
export type ServerMode = "managed" | "external";
 
export const SERVER_MODE = {
    MANAGED: "managed",
    EXTERNAL: "external",
} as const satisfies Record<string, ServerMode>;
 
/** Three-way result of the managed-mode consent modal. */
export type ManagedConsentResultKind = "download" | "external" | "cancel";
 
export type ManagedConsentResult = { kind: "download" } | { kind: "external" } | { kind: "cancel" };
 
export const MANAGED_CONSENT_RESULT = {
    DOWNLOAD: "download",
    EXTERNAL: "external",
    CANCEL: "cancel",
} as const satisfies Record<string, ManagedConsentResultKind>;
 
/** Outcome of the consent-then-start gate the plugin runs before a managed binary download. */
export type SetupOutcomeKind = "started" | "switched-to-external" | "canceled";
 
export type SetupOutcome =
    { kind: "started"; mode: ServerMode } | { kind: "switched-to-external" } | { kind: "canceled" };
 
export const SETUP_OUTCOME = {
    STARTED: "started",
    SWITCHED_TO_EXTERNAL: "switched-to-external",
    CANCELED: "canceled",
} as const satisfies Record<string, SetupOutcomeKind>;
 
export type SearchChunkType = "all" | "wiki" | "raw";
 
export const SEARCH_CHUNK_TYPE = {
    ALL: "all",
    WIKI: "wiki",
    RAW: "raw",
} as const satisfies Record<string, SearchChunkType>;
 
export type MemoryKind = "fact" | "preference";
 
export const MEMORY_KIND = {
    FACT: "fact",
    PREFERENCE: "preference",
} as const satisfies Record<string, MemoryKind>;
 
export interface MemoryItem {
    id: string;
    kind: MemoryKind;
    shared: boolean;
    text: string;
}
 
export interface MemoryListResponse {
    memories: MemoryItem[];
}
 
export interface RememberResponse {
    id: string;
    kind: MemoryKind;
}
 
export interface MemoryFlagsResponse {
    id: string;
    updated: boolean;
}
 
export interface MemoryRemoveResponse {
    id: string;
    /** False when the id was unknown (the server no longer raises on a miss). */
    deleted: boolean;
}
 
export interface MemoryExtractedItem {
    id: string;
    kind: MemoryKind;
    text: string;
}
 
/** Payload of the `memory_extracted` SSE event the server emits after an auto-extract chat turn. */
export interface MemoryExtractedData {
    count: number;
    items: MemoryExtractedItem[];
}
 
/** Server config keys for the memory subsystem (read/written via /api/config). */
export const MEMORY_CONFIG_KEY = {
    ENABLED: "memory_enabled",
    AUTO_EXTRACT: "memory_auto_extract",
} as const;
 
// ---------------------------------------------------------------------------
// Agent integration (`GET /api/agent-config`)
 
/** An AI coding client lilbee can write a config for. */
export type AgentClient = "claude" | "hermes" | "opencode";
 
export const AGENT_CLIENT = {
    CLAUDE: "claude",
    HERMES: "hermes",
    OPENCODE: "opencode",
} as const satisfies Record<string, AgentClient>;
 
/** Declaration order of the server's index response; drives the settings badge list. */
export const AGENT_CLIENTS: readonly AgentClient[] = [AGENT_CLIENT.CLAUDE, AGENT_CLIENT.HERMES, AGENT_CLIENT.OPENCODE];
 
/** The client the user paired with, or "none" while nothing is wired. */
export type AgentSelection = AgentClient | "none";
 
export const AGENT_SELECTION = {
    NONE: "none",
    CLAUDE: "claude",
    HERMES: "hermes",
    OPENCODE: "opencode",
} as const satisfies Record<string, AgentSelection>;
 
/** Which lilbee surface a client's config wires it up to. */
export type AgentSurface = "model_provider" | "mcp";
 
/** The serialization a client's own config file is written in. */
export type AgentConfigFormat = "json" | "yaml";
 
export interface AgentClientDetection {
    client: AgentClient;
    cli_detected: boolean;
    cli_path: string | null;
}
 
export interface AgentConfigIndexResponse {
    clients: AgentClientDetection[];
}
 
/**
 * `GET /api/agent-config/{client}`. `config` carries the block for a JSON
 * client and `content` the rendered text for a YAML one. `stdio_config` is the
 * alternative block for a client that can also run lilbee as a subprocess.
 */
export interface AgentConfigResponse {
    client: AgentClient;
    format: AgentConfigFormat;
    surfaces: AgentSurface[];
    config?: Record<string, unknown> | null;
    content?: string | null;
    stdio_config?: Record<string, unknown> | null;
}
 
/** Which agent lilbee keeps wired, and whether it rewrites the config each boot. */
export interface AgentIntegrationSettings {
    agent: AgentSelection;
    /** Rewrite the agent's config on every server boot, so its token and port stay current. */
    keepConfigFresh: boolean;
    /** Set once the first-use picker has been answered or dismissed. */
    pickerShown: boolean;
}
 
export const DEFAULT_AGENT_INTEGRATION: AgentIntegrationSettings = {
    agent: "none",
    keepConfigFresh: true,
    pickerShown: false,
};
 
/** Below this the agent runs out of room mid-task, so the settings row warns. */
export const AGENT_MIN_CONTEXT_TOKENS = 20_000;
 
export interface LilbeeSettings {
    serverUrl: string;
    topK: number;
    serverMode: ServerMode;
    ragSystemPrompt: string;
    generalSystemPrompt: string;
    setupCompleted: boolean;
    wikiEnabled: boolean;
    searchChunkType: SearchChunkType;
    wikiSyncToVault: boolean;
    wikiVaultFolder: string;
    manualToken: string;
    /**
     * Store lilbee's managed content (crawls, imported files) inside the vault
     * instead of the server's data directory. Only honoured in managed mode —
     * external servers keep their own documents_dir.
     */
    storeContentInVault: boolean;
    lastCatalogTab: CatalogTab;
    /**
     * Filesystem root that holds the shared lilbee binary, models cache, and
     * per-vault data directories. Empty string means "use platform default"
     * (resolved via getDefaultLilbeeDataRoot). Set explicitly to point the
     * plugin at a different location (e.g. an external SSD).
     */
    sharedRoot: string;
    /** Set once the plugin has applied its one-time `show_reasoning` on-by-default. */
    reasoningDefaulted: boolean;
    /**
     * Offer in-development (`.dev`) server builds in the version picker and make
     * them the auto-install/update target. Off by default: the plugin tracks the
     * latest stable release unless the user opts in.
     */
    includeDevBuilds: boolean;
    /** Which coding agent lilbee keeps wired to this vault. */
    agentIntegration: AgentIntegrationSettings;
}
 
export const DEFAULT_SETTINGS: LilbeeSettings = {
    serverUrl: "http://127.0.0.1:7433",
    // Match the server's default retrieval depth (core config top_k = 12) so the
    // plugin and a bare `lilbee serve` behave identically out of the box.
    topK: 12,
    serverMode: "managed",
    ragSystemPrompt: "",
    generalSystemPrompt: "",
    setupCompleted: false,
    wikiEnabled: false,
    searchChunkType: SEARCH_CHUNK_TYPE.ALL,
    // On, but only reached once the wiki itself is enabled (which is opt-in).
    // A wiki you cannot open in the vault is most of the point missing: these
    // pages carry [[wikilinks]], so as vault notes they get Obsidian's graph,
    // backlinks and click-through for free.
    wikiSyncToVault: true,
    wikiVaultFolder: "lilbee-wiki",
    manualToken: "",
    storeContentInVault: true,
    lastCatalogTab: "discover",
    sharedRoot: "",
    reasoningDefaulted: false,
    includeDevBuilds: false,
    agentIntegration: { ...DEFAULT_AGENT_INTEGRATION },
};
 
/**
 * Cross-vault state that lives in `<shared-root>/config.json`. These fields
 * used to be per-vault but the binary and the HuggingFace cache they describe
 * are shared, so they must agree across all vaults using this shared root.
 */
export interface SharedConfig {
    lilbeeVersion: string;
    /** Which server build is installed. Empty when unknown (e.g. installed before variant tracking). */
    lilbeeVariant: ServerVariant | "";
    /** The GPU probe that chose `lilbeeVariant`. Null when the install predates detection tracking. */
    lilbeeDetection: GpuDetection | null;
    hfToken: string;
    /** Plugin version that last ran the automatic server-update check. */
    lastUpdateCheckPluginVersion: string;
    /** Install the latest server release when the plugin updates. Turned off automatically by an explicit non-latest install. */
    serverAutoUpdate: boolean;
    /** The user removed the managed server; never download it again until they ask. */
    serverUninstalled: boolean;
    /** Show a reminder on launch while a newer server release exists and automatic updates are off. */
    serverUpdateReminder: boolean;
}
 
export const DEFAULT_SHARED_CONFIG: SharedConfig = {
    lilbeeVersion: "",
    lilbeeVariant: "",
    lilbeeDetection: null,
    hfToken: "",
    lastUpdateCheckPluginVersion: "",
    serverAutoUpdate: true,
    serverUninstalled: false,
    serverUpdateReminder: true,
};
 
/** What a managed-mode uninstall deletes. Documents in the vault are never a target. */
export type UninstallTargetKind = "binary" | "models" | "index" | "cache";
 
export const UNINSTALL_TARGET = {
    BINARY: "binary",
    MODELS: "models",
    INDEX: "index",
    CACHE: "cache",
} as const satisfies Record<string, UninstallTargetKind>;
 
export interface UninstallTarget {
    kind: UninstallTargetKind;
    path: string;
    bytes: number;
}
 
export interface UninstallPlan {
    targets: UninstallTarget[];
    totalBytes: number;
}
 
/** How the selected server version relates to the installed one. */
export type VersionAction = "install" | "reinstall" | "update" | "downgrade";
 
export const VERSION_ACTION = {
    INSTALL: "install",
    REINSTALL: "reinstall",
    UPDATE: "update",
    DOWNGRADE: "downgrade",
} as const satisfies Record<string, VersionAction>;
 
/** One row in `<shared-root>/registry.json` — one per Obsidian vault. */
export interface VaultRegistryEntry {
    id: string;
    displayName: string;
    dataDir: string;
    obsidianVaultPath: string;
    addedAt: number;
    lastActiveAt: number;
}
 
/** Names of files/dirs the plugin writes inside the shared root. */
export const SHARED_PATH = {
    BIN: "bin",
    MODELS: "models",
    VAULTS: "vaults",
    CONFIG: "config.json",
    REGISTRY: "registry.json",
} as const;
 
/** Subdirectory of a vault data dir where all log files land. */
export const LOGS_DIR = "logs";
 
/** Log file names the diagnostics bundle knows about. */
export const LOG_FILE = {
    SERVER: "server.log",
    FAULT: "server-fault.log",
    SPAWN_CRASH: "spawn-crash.log",
    SERVER_STDIO: "server-stdio.log",
    PLUGIN: "plugin.log",
} as const;
 
/** One captured plugin-side error or lifecycle event. */
export interface JournalEntry {
    timestamp: string;
    label: string;
    message: string;
    stack: string | null;
}
 
/** One file gathered (or missed) by the diagnostics collector. */
export interface CollectedFile {
    /** Path inside the zip, e.g. "logs/worker-chat.log". */
    name: string;
    /** File bytes after tail-capping and redaction; null when the file was missed. */
    data: Uint8Array | null;
    /** Manifest note, e.g. "not found" or "truncated to last 1 MiB". Null when collected whole. */
    note: string | null;
}
 
/** Everything the collector gathered, ready to zip. */
export interface DiagnosticsBundle {
    files: CollectedFile[];
    summaryMarkdown: string;
}
 
/** Inputs the collector reads from the live plugin. */
export interface DiagnosticsContext {
    dataDir: string | null;
    sharedRoot: string | null;
    settings: LilbeeSettings;
    journalEntries: readonly JournalEntry[];
    pluginVersion: string;
    serverVersion: string;
    /** Which server build is installed. Empty when nothing has recorded one. */
    serverVariant: ServerVariant | "";
    /** The GPU probe that chose the installed build, or null when none was recorded. */
    gpuDetection: GpuDetection | null;
    serverState: ServerState;
    serverUrl: string;
    lastOutput: string;
}
 
/** SSE event type constants — shared across chat, sync, and model pull streams. */
export const SSE_EVENT = {
    TOKEN: "token",
    REASONING: "reasoning",
    SOURCES: "sources",
    DONE: "done",
    ERROR: "error",
    COMPACTING: "compacting",
    COMPACTION: "compaction",
    WARMING: "warming",
    PROGRESS: "progress",
    MESSAGE: "message",
    FILE_START: "file_start",
    EXTRACT: "extract",
    EMBED: "embed",
    FILE_DONE: "file_done",
    PULL: "pull",
    CRAWL_START: "crawl_start",
    CRAWL_PAGE: "crawl_page",
    CRAWL_DONE: "crawl_done",
    CRAWL_ERROR: "crawl_error",
    WIKI_PHASE: "wiki_phase",
    WIKI_PAGE: "wiki_page",
    SETUP_START: "setup_start",
    SETUP_PROGRESS: "setup_progress",
    SETUP_DONE: "setup_done",
    ALREADY_INGESTING: "already_ingesting",
    BATCH_PROGRESS: "batch_progress",
    MEMORY_EXTRACTED: "memory_extracted",
    GPU_STATS: "gpu_stats",
} as const;
 
/** Stage of a wiki build or synthesis run. */
export type WikiPhase = "extract" | "generate" | "index";
 
/**
 * `wiki_phase` event: the run entered a new stage. `total` is the number of
 * units the phase will process (sources for a build, clusters for synthesis),
 * and 0 where the phase has no unit count.
 */
export interface WikiPhasePayload {
    phase: WikiPhase;
    total: number;
}
 
/** `wiki_page` event: one source (build) or cluster (synthesis) was written. */
export interface WikiPagePayload {
    label: string;
    pages: number;
    current: number;
    total: number;
}
 
export interface SetupStartPayload {
    component: string;
    size_estimate_bytes: number | null;
}
 
export interface SetupProgressPayload {
    component: string;
    downloaded_bytes: number;
    total_bytes: number | null;
    detail: string;
}
 
export interface SetupDonePayload {
    component: string;
    success: boolean;
    error: string | null;
}
 
export interface BatchProgressPayload {
    file: string;
    status: string;
    current: number;
    total: number;
}
 
export const JSON_HEADERS = { "Content-Type": "application/json" } as const;
export const OCTET_STREAM_HEADERS = { "Content-Type": "application/octet-stream" } as const;
 
/**
 * Authorization header carrying a lilbee session token. The server
 * authenticates every route, `/api/health` included, so a request sent without
 * this comes back 401 — which a probe reads as "dead" rather than "unauthorized".
 */
export function bearerHeaders(token: string): Record<string, string> {
    return { Authorization: `Bearer ${token}` };
}
 
/** MIME content types referenced across click dispatch + preview rendering. */
export const CONTENT_TYPE = {
    PDF: "application/pdf",
    PDF_SHORT: "pdf",
    MARKDOWN: "text/markdown",
    HTML: "text/html",
} as const;
 
export function isPdfContentType(value: string | null | undefined): boolean {
    return value === CONTENT_TYPE.PDF || value === CONTENT_TYPE.PDF_SHORT;
}
 
export interface SizeVariant {
    size_label: string;
    params: string;
    size_gb: number;
    ref: string;
}
 
export interface CatalogEntry {
    hf_repo: string;
    gguf_filename: string;
    display_name: string;
    size_gb: number;
    min_ram_gb: number;
    description: string;
    quality_tier: string;
    installed: boolean;
    source: CatalogSource;
    task: ModelTask;
    featured: boolean;
    downloads: number;
    param_count: string;
    fit?: HardwareFit | null;
    compat?: ModelCompat | null;
    architecture?: string | null;
    size_variants?: SizeVariant[] | null;
    /** Hosted rows (frontier + local servers) carry their serving provider. */
    provider?: string;
    /** Set on frontier rows; `null` for local servers (no API key), absent on older servers. */
    key_status?: KeyStatus | null;
}
 
export interface CatalogResponse {
    total: number;
    limit: number;
    offset: number;
    models: CatalogEntry[];
    has_more: boolean;
}
 
export interface InstalledModel {
    name: string;
    source: string;
}
 
export interface InstalledResponse {
    models: InstalledModel[];
}
 
export interface DocumentEntry {
    filename: string;
    chunk_count: number;
    ingested_at: string;
}
 
export interface DocumentsResponse {
    documents: DocumentEntry[];
    total: number;
    limit: number;
    offset: number;
    has_more: boolean;
}
 
export type DatasetFormat = "parquet" | "jsonl";
 
export const DATASET_FORMAT = {
    PARQUET: "parquet",
    JSONL: "jsonl",
} as const satisfies Record<string, DatasetFormat>;
 
export interface DatasetImportResponse {
    sources: string[];
    pages: number;
    chunks: number;
}
 
export interface ConfigUpdateResponse {
    updated: string[];
    reindex_required: boolean;
}
 
export interface EmbeddingModelResponse {
    model: string;
}
 
/** Table extraction backends the server accepts for `table_model`. */
export const TABLE_MODEL = {
    DISABLED: "disabled",
    TATR: "tatr",
    SLANET_AUTO: "slanet_auto",
    SLANET_PLUS: "slanet_plus",
    SLANET_WIRED: "slanet_wired",
    SLANET_WIRELESS: "slanet_wireless",
} as const;
 
export type TableModel = (typeof TABLE_MODEL)[keyof typeof TABLE_MODEL];
 
export const WIKI_PAGE_TYPE = {
    SUMMARY: "summary",
    SYNTHESIS: "synthesis",
    CONCEPT: "concept",
    ENTITY: "entity",
    DRAFT: "draft",
    ARCHIVE: "archive",
} as const;
 
export type WikiPageType = (typeof WIKI_PAGE_TYPE)[keyof typeof WIKI_PAGE_TYPE];
 
/** Wiki pages that count as "published" — sidebar lists them, vault sync writes them. */
export const PUBLISHED_WIKI_PAGE_TYPES: ReadonlySet<WikiPageType> = new Set([
    WIKI_PAGE_TYPE.SUMMARY,
    WIKI_PAGE_TYPE.SYNTHESIS,
    WIKI_PAGE_TYPE.CONCEPT,
    WIKI_PAGE_TYPE.ENTITY,
]);
 
/** Subset of published types grouped under "Concepts" in the sidebar. */
/** Concept-flavoured pages only. Entities are listed separately: fifty proper
 * nouns under a heading reading "Concepts" is not what the server means. */
export const CONCEPT_ONLY_WIKI_PAGE_TYPES: ReadonlySet<WikiPageType> = new Set([
    WIKI_PAGE_TYPE.SYNTHESIS,
    WIKI_PAGE_TYPE.CONCEPT,
]);
 
export const CONCEPT_WIKI_PAGE_TYPES: ReadonlySet<WikiPageType> = new Set([
    WIKI_PAGE_TYPE.SYNTHESIS,
    WIKI_PAGE_TYPE.CONCEPT,
    WIKI_PAGE_TYPE.ENTITY,
]);
 
/** Whether an indexed subject is an LLM-curated concept or a proper-noun entity. */
export type WikiStubKind = "concept" | "entity";
 
export const WIKI_STUB_KIND = {
    CONCEPT: "concept",
    ENTITY: "entity",
} as const satisfies Record<string, WikiStubKind>;
 
/**
 * A subject the corpus names that has no page yet, from `GET /api/wiki/stubs`.
 *
 * Naming every entity costs no LLM call, so the browse list can show every page
 * the wiki *could* have as soon as a sync finishes; a body is written only when
 * someone asks for that page. `slug` is what `POST /api/wiki/generate/{slug}`
 * takes.
 */
export interface WikiStub {
    slug: string;
    label: string;
    kind: WikiStubKind;
    type_hint: string;
    mentions: number;
    sources: string[];
}
 
/** Result of generating one indexed page. */
export interface WikiGenerateResult {
    slug: string;
    path: string;
}
 
export interface WikiPage {
    slug: string;
    title: string;
    page_type: WikiPageType;
    source_count: number;
    created_at: string | null;
}
 
export interface WikiPageDetail extends WikiPage {
    content: string;
}
 
export interface WikiCitation {
    citation_key: string;
    claim_type: ClaimType;
    source_filename: string;
    source_hash: string;
    page_start: number | null;
    page_end: number | null;
    line_start: number | null;
    line_end: number | null;
    excerpt: string;
    created_at: string;
}
 
export interface WikiCitationChain {
    wiki_page: string;
    citations: WikiCitation[];
}
 
export type DraftPendingKind = "drift" | "parse" | "collision" | "low_faithfulness" | "bad_title";
export const DRAFT_PENDING_KIND = {
    DRIFT: "drift",
    PARSE: "parse",
    COLLISION: "collision",
    LOW_FAITHFULNESS: "low_faithfulness",
    BAD_TITLE: "bad_title",
} as const satisfies Record<string, DraftPendingKind>;
 
export interface DraftInfoResponse {
    slug: string;
    path: string;
    drift_ratio: number | null;
    faithfulness_score: number | null;
    bad_title: boolean;
    published_path: string | null;
    published_exists: boolean;
    pending_kind: DraftPendingKind | null;
    mtime: number;
}
 
export interface DraftAcceptResponse {
    slug: string;
    moved_to: string;
    reindexed_chunks: number;
}
 
export interface DraftRejectResponse {
    slug: string;
}
 
export interface LintIssue {
    wiki_page: string;
    citation_key: string;
    status: "valid" | "stale_hash" | "source_deleted" | "excerpt_missing" | "model_changed";
    detail: string;
}
 
/** Result of a wiki lint run, whole-wiki or single-page. */
export interface LintResult {
    issues: LintIssue[];
    total: number;
    errors: number;
    warnings: number;
}
 
/**
 * Summary of a wiki build/update, delivered as the `done` event of the
 * `PATCH /api/wiki/update` stream.
 */
export interface WikiBuildResult {
    paths: string[];
    entities: number;
    count: number;
}
 
/** A single action taken by a prune run. */
export interface WikiPruneRecord {
    wiki_source: string;
    action: string;
    reason: string;
}
 
/** Result of pruning stale and orphaned wiki pages. */
export interface WikiPruneResult {
    records: WikiPruneRecord[];
    archived: number;
    flagged: number;
    reconciled: number;
}
 
/** Obsidian's DataAdapter has these methods but the type declarations are incomplete. */
export interface VaultAdapter {
    getBasePath(): string;
}
 
export type TaskStatus = "queued" | "active" | "done" | "failed" | "cancelled" | "waiting";
 
export const TASK_STATUS = {
    QUEUED: "queued",
    ACTIVE: "active",
    DONE: "done",
    FAILED: "failed",
    CANCELLED: "cancelled",
    WAITING: "waiting",
} as const satisfies Record<string, TaskStatus>;
 
export type DotState = "primary" | "success" | "error" | "muted";
 
export const DOT_STATE = {
    PRIMARY: "primary",
    SUCCESS: "success",
    ERROR: "error",
    MUTED: "muted",
} as const satisfies Record<string, DotState>;
 
export type TaskType = "sync" | "add" | "pull" | "crawl" | "download" | "wiki" | "delete" | "setup" | "import";
 
export const TASK_TYPE = {
    SYNC: "sync",
    ADD: "add",
    PULL: "pull",
    CRAWL: "crawl",
    DOWNLOAD: "download",
    WIKI: "wiki",
    DELETE: "delete",
    SETUP: "setup",
    IMPORT: "import",
} as const satisfies Record<string, TaskType>;
 
export type ModelTask = "chat" | "vision" | "embedding" | "rerank";
 
export const MODEL_TASK = {
    CHAT: "chat",
    VISION: "vision",
    EMBEDDING: "embedding",
    RERANK: "rerank",
} as const satisfies Record<string, ModelTask>;
 
// ---------------------------------------------------------------------------
// GPU placement / fleet (lilbee feat/local-model-api)
// ---------------------------------------------------------------------------
 
/** A worker role in the model fleet. Mirrors the server's WorkerRole. */
export type WorkerRole = "chat" | "embed" | "rerank" | "vision";
 
export const WORKER_ROLE = {
    CHAT: "chat",
    EMBED: "embed",
    RERANK: "rerank",
    VISION: "vision",
} as const satisfies Record<string, WorkerRole>;
 
/** Roles whose replica count is user-tunable; the others are always single. */
export const REPLICA_ROLES: ReadonlySet<WorkerRole> = new Set<WorkerRole>([WORKER_ROLE.EMBED, WORKER_ROLE.VISION]);
 
/** Whether placement is auto (planner-chosen) or a manual pinned spec. */
export type PlacementMode = "auto" | "manual";
 
export const PLACEMENT_MODE = {
    AUTO: "auto",
    MANUAL: "manual",
} as const satisfies Record<string, PlacementMode>;
 
/** One detected GPU. Mirrors the server's GpuInfoResponse. */
export interface GpuInfo {
    index: number;
    backend: string;
    label: string;
    name: string;
    total_bytes: number;
    free_bytes: number;
}
 
/** A live per-GPU activity snapshot from the GET /api/gpus/stream SSE stream.
 * `utilization_pct` is compute load (0-100), or null for backends that can't
 * report it; `free_bytes` moves as models load and ingest runs. */
export interface GpuStat {
    index: number;
    utilization_pct: number | null;
    free_bytes: number;
    total_bytes: number;
}
 
/** Server-issued hint when GPU monitoring is degraded (e.g. Intel hosts without intel_gpu_top). */
export type GpuNotice = string | null;
 
/** Payload of a `gpu_stats` SSE event. `notice` is omitted on healthy hosts. */
export interface GpuStatsPayload {
    gpus: GpuStat[];
    notice?: GpuNotice;
}
 
/** Where one role's model is placed in the resolved plan. Mirrors RolePlacementResponse. */
export interface RolePlacement {
    role: WorkerRole;
    model: string;
    devices: number[];
    tensor_split: number[] | null;
    replicas: number;
    /** Estimated memory footprint of the role's model; absent on older servers. */
    vram_bytes?: number | null;
}
 
/** `GET /api/placement`, `POST /api/placement/preview`, and the apply response. */
export interface PlacementResponse {
    gpus: GpuInfo[];
    roles: RolePlacement[];
    /** Roles that cannot fit the current hardware under this plan. */
    unplaceable: string[];
    manual: boolean;
    spec_json: string | null;
    /** Host-level fix instruction, present only when GPU monitoring is degraded. */
    notice?: GpuNotice;
}
 
/** One role entry in a manual placement spec. */
export interface PlacementRoleSpec {
    devices: number[];
    tensor_split?: number[];
    replicas?: number;
}
 
/** A manual placement spec: role to pinning. Sent to preview and apply. */
export type PlacementSpec = Partial<Record<WorkerRole, PlacementRoleSpec>>;
 
export const ERROR_NAME = {
    ABORT_ERROR: "AbortError",
    SESSION_TOKEN: "SessionTokenError",
    SERVER_STARTING: "ServerStartingError",
    RATE_LIMITED: "RateLimitedError",
} as const;
 
export const WIZARD_STEP = {
    WELCOME: 0,
    SERVER_MODE: 1,
    MODEL_PICKER: 2,
    EMBEDDING_PICKER: 3,
    SYNC: 4,
    WIKI: 5,
    DONE: 6,
} as const satisfies Record<string, number>;
 
export const DOWNLOAD_PANEL = {
    MAX_VISIBLE: 5,
    DISMISS_DELAY_MS: 1500,
} as const;
 
export const TASK_QUEUE = {
    MAX_CONCURRENT_BACKGROUND: 2,
    MAX_QUEUED_PER_TYPE: 5,
} as const;
 
export const BACKGROUND_TASK_TYPES: ReadonlySet<TaskType> = new Set<TaskType>([
    TASK_TYPE.SYNC,
    TASK_TYPE.ADD,
    TASK_TYPE.PULL,
    TASK_TYPE.CRAWL,
    TASK_TYPE.DOWNLOAD,
    TASK_TYPE.WIKI,
    TASK_TYPE.DELETE,
    TASK_TYPE.IMPORT,
]);
 
export const PLATFORM = {
    DARWIN: "darwin",
    LINUX: "linux",
    WIN32: "win32",
} as const;
 
/** Which lilbee server build is installed: the default (Vulkan/CPU) build, a vendor build, or a compat build for CPUs without AVX2. */
export type ServerVariant = Variant;
export const SERVER_VARIANT = {
    DEFAULT: "default",
    CU121: "cu121",
    CU124: "cu124",
    CU125: "cu125",
    ROCM: "rocm",
    COMPAT: "compat",
    COMPAT_CU124: "compat-cu124",
    COMPAT_ROCM: "compat-rocm",
} as const satisfies Record<string, ServerVariant>;
 
/** What the plugin asks of the server binary: which build to make available and how to report on it. */
export interface EnsureRequest {
    includeDev: boolean;
    /** An exact release tag to install; default: the installed binary, else the latest release. */
    release?: string;
    /** Download even when the release is already installed. */
    force?: boolean;
    onProgress?: (progress: DownloadProgress) => void;
    /** macOS: the quarantine attribute could not be cleared, so Gatekeeper will block the binary. */
    onQuarantineFailed?: () => void;
    signal?: AbortSignal;
}
 
/** Where an ensured server binary came from. */
export const ENSURE_SOURCE = {
    CACHE: "cache",
    DOWNLOAD: "download",
} as const satisfies Record<string, EnsureResult["source"]>;
 
/** Why the launcher failed a release query or a download. */
export const LAUNCHER_ERROR_CODE = {
    RATE_LIMITED: "rate-limited",
    HTTP: "http",
    NO_RELEASE: "no-release",
    NO_SPACE: "no-space",
    STALLED: "stalled",
    NO_DIGEST: "no-digest",
    DIGEST_MISMATCH: "digest-mismatch",
} as const satisfies Record<string, LauncherErrorCode>;
 
/** The release and build a flat pre-launcher install was moved under. */
export interface MigratedBinary {
    release: string;
    variant: ServerVariant;
}
 
/** GitHub "owner/repo" of the lilbee server. */
export const LILBEE_GITHUB_REPO = "tobocop2/lilbee";
/** Lowest CUDA driver ceiling (major*100 + minor) that any lilbee CUDA build supports. */
export const CUDA_MIN_CEILING = 1201;
 
/** How the `nvidia-smi` probe ended. */
export type NvidiaProbeStatus = "skipped" | "missing" | "sandboxed" | "unreadable" | "detected";
export const NVIDIA_PROBE_STATUS = {
    /** macOS: lilbee ships one build there, so nothing is probed. */
    SKIPPED: "skipped",
    /** `nvidia-smi` is absent or exited non-zero at every location tried. */
    MISSING: "missing",
    /** Linux: the kernel module is loaded but no `nvidia-smi` is reachable (Flatpak, Snap). */
    SANDBOXED: "sandboxed",
    /** `nvidia-smi` ran but its output names no CUDA version. */
    UNREADABLE: "unreadable",
    /** The driver named the newest CUDA version it supports. */
    DETECTED: "detected",
} as const satisfies Record<string, NvidiaProbeStatus>;
 
/** What the `nvidia-smi` probe found, and why it ended there. */
export type NvidiaProbe =
    | { status: "skipped" }
    | { status: "missing"; error: string }
    | { status: "sandboxed" }
    | { status: "unreadable" }
    /** The driver's maximum CUDA version as major*100+minor (12.4 -> 1204). */
    | { status: "detected"; cudaCeiling: number };
 
/** Why the plugin picked the server build it did. Recorded at every install and update check. */
export type AmdProbeStatus = "skipped" | "missing" | "sandboxed" | "unreadable" | "detected" | "unsupported";
export const AMD_PROBE_STATUS = {
    /** lilbee ships a ROCm build for Linux only, so other platforms probe nothing. */
    SKIPPED: "skipped",
    /** No amdgpu module and no compute device. */
    MISSING: "missing",
    /** The amdgpu module is loaded but `/dev/kfd` is not visible (Flatpak, Snap). */
    SANDBOXED: "sandboxed",
    /** `/dev/kfd` is present but its topology could not be read. */
    UNREADABLE: "unreadable",
    /** The driver named the gfx targets and the ROCm build serves them. */
    DETECTED: "detected",
    /** The driver named the gfx targets but the release's ROCm build cannot serve them. */
    UNSUPPORTED: "unsupported",
} as const satisfies Record<string, AmdProbeStatus>;
 
export type RocmRefusal = "no-asset" | "no-manifest" | "missing-kernels";
export const ROCM_REFUSAL = {
    NO_ASSET: "no-asset",
    NO_MANIFEST: "no-manifest",
    MISSING_KERNELS: "missing-kernels",
} as const satisfies Record<string, RocmRefusal>;
 
export type AmdProbe =
    | { status: "skipped" }
    | { status: "missing" }
    | { status: "sandboxed" }
    | { status: "unreadable" }
    | { status: "detected"; gfxTargets: string[] }
    | { status: "unsupported"; gfxTargets: string[]; reason: RocmRefusal };
 
export interface GpuDetection {
    nvidia: NvidiaProbe;
    amd: AmdProbe;
    /** When the probe ran, ISO 8601. */
    detectedAt: string;
}
 
/** Source of the lilbee server binary; surfaced wherever the unsigned download is explained. */
export const LILBEE_REPO_URL = `https://github.com/${LILBEE_GITHUB_REPO}`;
 
/** Progress value for a job whose length cannot be known: the Task Centre draws
 * an indeterminate bar instead of a percentage. Use it when the work reports no
 * phases at all, rather than leaving a percentage bar sitting at zero. */
export const INDETERMINATE_PROGRESS = -1;
 
export interface TaskEntry {
    id: string;
    name: string;
    type: TaskType;
    status: TaskStatus;
    progress: number;
    detail: string;
    startedAt: number;
    completedAt: number | null;
    error: string | null;
    canCancel: boolean;
    bytesCurrent?: number;
    bytesTotal?: number;
    rateBps?: number;
    lastRateAt?: number;
    retry?: () => void | Promise<void>;
}
 
export type ModelSize = "small" | "medium" | "large";
export type ModelSort = "featured" | "downloads" | "name" | "size_asc" | "size_desc";
 
export type CatalogViewMode = "grid" | "list";
 
export const CATALOG_VIEW_MODE = {
    GRID: "grid",
    LIST: "list",
} as const satisfies Record<string, CatalogViewMode>;
 
export interface ModelShowResponse {
    architecture?: string;
    context_length?: string;
    embedding_length?: string;
    chat_template?: string;
    file_type?: string;
    parameters?: string;
    [key: string]: string | undefined;
}
 
export interface ModelCardOptions {
    onClick?: (entry: CatalogEntry) => void;
    onPull?: (entry: CatalogEntry, btn: HTMLElement) => void;
    onUse?: (entry: CatalogEntry, btn: HTMLElement) => void;
    onRemove?: (entry: CatalogEntry, btn: HTMLElement) => void;
    onInfo?: (entry: CatalogEntry) => void;
    showActions?: boolean;
    isActive?: boolean;
}