All files / api/src/connectors/libsql user-data.ts

64.05% Statements 606/946
71.42% Branches 55/77
49.18% Functions 30/61
64.05% Lines 606/946

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    1x 1x 1x                                                                                                                             1x           1x 1x 1x 1x 1x             1x 1x                                   1x 35x 35x 35x   1x   1x                       1x                         1x         1x                               1x                                         1x                                       1x         1x 4x 4x   4x 4x 4x 4x 4x 4x 4x   1x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x     1x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   1x 24x 24x 24x 24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x         1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                 1x 3x 3x 3x 3x 3x 3x 3x   3x 3x     3x 3x   3x 1x 1x   2x 2x 2x 2x 2x 2x 3x 3x     1x                                   1x                         1x         1x                                           1x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 1x 1x   1x 1x 2x 2x 2x   1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x   1x         1x                               1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   1x                             1x           1x 3x 3x     3x 3x 3x 3x   1x 1x 1x 1x 1x 1x     1x 1x 1x 1x   1x 5x 5x 5x 5x 5x 1x 1x   4x 4x 5x 5x 4x 4x 4x 5x   1x 2x 2x 2x 2x 2x 1x 1x   1x 1x 1x 1x 1x 1x 1x 2x     1x                                       1x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x     5x 5x 5x 5x 5x 5x 5x   5x 5x   1x                                         1x               1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x                                         1x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x   4x 4x   1x                                                       1x 5x 5x 5x         5x 5x 5x   5x 5x 5x 5x 5x   5x 1x 1x   4x 4x 4x   5x 5x 5x 5x 5x   5x 5x 5x       5x 5x 5x 5x   5x 5x                 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   4x 4x       4x 4x 5x       4x 4x 4x 4x 5x       4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x   4x 5x 1x 1x 1x 5x   1x             1x                 1x                   1x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   1x                           1x                                         1x 17x 17x 17x 17x 17x   17x 17x 17x 17x 17x 17x 17x     17x 17x 17x 17x 17x 17x 17x   17x 17x   1x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 1x 1x   1x 2x   1x                 1x                   1x                                         1x                                       1x                 1x 8x 8x 8x     1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x     1x 2x 2x 2x 2x 2x 2x 2x   2x 2x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import type { UserDataStorageConnector } from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import { decryptAPIKey, encryptAPIKey } from '@api/utils/api-key-encryption';
import { emitSSEEvent } from '@api/utils/sse-event-manager';
import {
  Agent as AgentSchema,
  type Feedback,
  type FeedbackCreateParams,
  type FeedbackQueryParams,
  Feedback as FeedbackSchema,
  type ImprovedResponse,
  type ImprovedResponseQueryParams,
  ImprovedResponse as ImprovedResponseSchema,
  type ImprovedResponseUpdateParams,
  type Model,
  type ModelCreateParams,
  type ModelQueryParams,
  Model as ModelSchema,
  type ModelUpdateParams,
  type Skill,
  type SkillCreateParams,
  type SkillEvent,
  type SkillEventCreateParams,
  type SkillEventQueryParams,
  SkillEvent as SkillEventSchema,
  type SkillOptimizationArm,
  type SkillOptimizationArmCreateParams,
  type SkillOptimizationArmQueryParams,
  SkillOptimizationArm as SkillOptimizationArmSchema,
  type SkillOptimizationArmUpdateParams,
  type SkillOptimizationCluster,
  type SkillOptimizationClusterCreateParams,
  type SkillOptimizationClusterQueryParams,
  SkillOptimizationCluster as SkillOptimizationClusterSchema,
  type SkillOptimizationClusterUpdateParams,
  type SkillOptimizationEvaluation,
  type SkillOptimizationEvaluationCreateParams,
  type SkillOptimizationEvaluationQueryParams,
  type SkillOptimizationEvaluationRun,
  type SkillOptimizationEvaluationRunCreateParams,
  type SkillOptimizationEvaluationRunQueryParams,
  SkillOptimizationEvaluationRun as SkillOptimizationEvaluationRunSchema,
  SkillOptimizationEvaluation as SkillOptimizationEvaluationSchema,
  type SkillOptimizationEvaluationUpdateParams,
  type SkillQueryParams,
  Skill as SkillSchema,
  type SkillUpdateParams,
  type SystemSettings,
  SystemSettings as SystemSettingsSchema,
  type SystemSettingsUpdateParams,
  type Tool,
  type ToolCreateParams,
  type ToolQueryParams,
  Tool as ToolSchema,
} from '@shared/types/data';
import type {
  Agent,
  AgentCreateParams,
  AgentQueryParams,
  AgentUpdateParams,
} from '@shared/types/data/agent';
import type {
  AIProviderConfig,
  AIProviderConfigCreateParams,
  AIProviderConfigQueryParams,
  AIProviderConfigUpdateParams,
} from '@shared/types/data/ai-provider';
import { AIProviderConfig as AIProviderConfigSchema } from '@shared/types/data/ai-provider';
import type { EvaluationScoresByTimeBucketParams } from '@shared/types/data/evaluation-runs-with-scores';
import type {
  SkillOptimizationArmStat,
  SkillOptimizationArmStatQueryParams,
} from '@shared/types/data/skill-optimization-arm-stats';
import { SkillOptimizationArmStat as SkillOptimizationArmStatSchema } from '@shared/types/data/skill-optimization-arm-stats';
import { v4 as uuidv4 } from 'uuid';
import { z } from 'zod';
import { getLibsqlClient } from './client';
import {
  deleteFrom,
  insertInto,
  parseRows,
  selectFrom,
  updateIn,
} from './query';
import { asColumns, toJsonColumn } from './rows';
import { aggregateScoresByTimeBucket } from './time-bucket';
 
/**
 * libSQL implementation of `UserDataStorageConnector`.
 *
 * Deliberately shaped like `connectors/supabase/supabase.ts` method for method,
 * so the two can be diffed when behaviour is in question. The differences are
 * confined to three places:
 *
 * 1. **Ids.** Postgres defaults `id` to `uuid_generate_v4()`. SQLite has no
 *    uuid function, so creates that do not carry an id generate one here.
 * 2. **JSON columns.** Objects and arrays are stringified going in; `query.ts`
 *    decodes them coming out.
 * 3. **Stored procedures.** The five RPCs the API calls become explicit
 *    transactions at the bottom of this file.
 */
 
/** Postgres generates ids column-side; SQLite needs them supplied. */
const withId = <T extends { id?: string }>(row: T): T & { id: string } => ({
  ...row,
  id: row.id ?? uuidv4(),
});
 
export const libsqlUserDataStorageConnector: UserDataStorageConnector = {
  // ------------------------------------------------------------- Feedback
  getFeedback: async (
    c: AppContext,
    queryParams: FeedbackQueryParams,
  ): Promise<Feedback[]> =>
    selectFrom(
      getLibsqlClient(c),
      'feedbacks',
      { id: queryParams.id, log_id: queryParams.log_id },
      z.array(FeedbackSchema),
      { limit: queryParams.limit, offset: queryParams.offset },
    ),
 
  createFeedback: async (
    c: AppContext,
    feedback: FeedbackCreateParams,
  ): Promise<Feedback> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'feedbacks',
      withId(feedback),
      z.array(FeedbackSchema),
    );
    return rows[0];
  },
 
  deleteFeedback: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'feedbacks', { id });
  },
 
  // ----------------------------------------------------- Improved Response
  getImprovedResponse: async (
    c: AppContext,
    params: ImprovedResponseQueryParams,
  ): Promise<ImprovedResponse[]> =>
    selectFrom(
      getLibsqlClient(c),
      'improved_responses',
      {
        id: params.id,
        agent_id: params.agent_id,
        skill_id: params.skill_id,
        log_id: params.log_id,
      },
      z.array(ImprovedResponseSchema),
    ),
 
  createImprovedResponse: async (
    c: AppContext,
    improvedResponse: ImprovedResponse,
  ): Promise<ImprovedResponse> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'improved_responses',
      {
        ...withId(improvedResponse),
        original_response_body: toJsonColumn(
          improvedResponse.original_response_body,
        ),
        improved_response_body: toJsonColumn(
          improvedResponse.improved_response_body,
        ),
      },
      z.array(ImprovedResponseSchema),
    );
    return rows[0];
  },
 
  updateImprovedResponse: async (
    c: AppContext,
    id: string,
    update: ImprovedResponseUpdateParams,
  ): Promise<ImprovedResponse> => {
    const rows = await updateIn(
      getLibsqlClient(c),
      'improved_responses',
      { id },
      {
        improved_response_body:
          update.improved_response_body === undefined
            ? undefined
            : toJsonColumn(update.improved_response_body),
      },
      z.array(ImprovedResponseSchema),
    );
    return rows[0];
  },
 
  deleteImprovedResponse: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'improved_responses', { id });
  },
 
  // --------------------------------------------------------------- Agents
  getAgents: async (
    c: AppContext,
    queryParams: AgentQueryParams,
  ): Promise<Agent[]> =>
    selectFrom(
      getLibsqlClient(c),
      'agents',
      { id: queryParams.id, name: queryParams.name },
      z.array(AgentSchema),
      { limit: queryParams.limit, offset: queryParams.offset },
    ),
 
  createAgent: async (
    c: AppContext,
    agent: AgentCreateParams,
  ): Promise<Agent> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'agents',
      {
        id: uuidv4(),
        name: agent.name,
        description: agent.description,
        metadata: toJsonColumn(agent.metadata ?? {}),
      },
      z.array(AgentSchema),
    );
    return rows[0];
  },
 
  updateAgent: async (
    c: AppContext,
    id: string,
    update: AgentUpdateParams,
  ): Promise<Agent> => {
    const rows = await updateIn(
      getLibsqlClient(c),
      'agents',
      { id },
      {
        description: update.description ?? undefined,
        metadata:
          update.metadata === undefined
            ? undefined
            : toJsonColumn(update.metadata),
      },
      z.array(AgentSchema),
    );
    return rows[0];
  },
 
  deleteAgent: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'agents', { id });
  },
 
  // --------------------------------------------------------------- Skills
  getSkills: async (
    c: AppContext,
    queryParams: SkillQueryParams,
  ): Promise<Skill[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skills',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        name: queryParams.name,
      },
      z.array(SkillSchema),
      { limit: queryParams.limit, offset: queryParams.offset },
    ),
 
  createSkill: async (
    c: AppContext,
    skill: SkillCreateParams,
  ): Promise<Skill> => {
    const { metadata, allowed_template_variables, optimize, ...rest } =
      skill as SkillCreateParams & Record<string, unknown>;
 
    const rows = await insertInto(
      getLibsqlClient(c),
      'skills',
      {
        ...asColumns(rest),
        id: uuidv4(),
        metadata: toJsonColumn(metadata ?? {}),
        allowed_template_variables: toJsonColumn(
          allowed_template_variables ?? [],
        ),
        optimize: optimize === undefined ? undefined : optimize ? 1 : 0,
      },
      z.array(SkillSchema),
    );
    return rows[0];
  },
 
  updateSkill: async (
    c: AppContext,
    id: string,
    update: SkillUpdateParams,
  ): Promise<Skill> => {
    const { metadata, allowed_template_variables, optimize, ...rest } =
      update as SkillUpdateParams & Record<string, unknown>;
 
    const rows = await updateIn(
      getLibsqlClient(c),
      'skills',
      { id },
      {
        ...asColumns(rest),
        metadata: metadata === undefined ? undefined : toJsonColumn(metadata),
        allowed_template_variables:
          allowed_template_variables === undefined
            ? undefined
            : toJsonColumn(allowed_template_variables),
        optimize: optimize === undefined ? undefined : optimize ? 1 : 0,
      },
      z.array(SkillSchema),
    );
    return rows[0];
  },
 
  deleteSkill: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skills', { id });
  },
 
  /** Replaces the `increment_skill_total_requests` RPC. */
  incrementSkillTotalRequests: async (
    c: AppContext,
    skillId: string,
  ): Promise<Skill> => {
    const client = getLibsqlClient(c);
    await client.execute({
      sql: 'UPDATE skills SET total_requests = total_requests + 1 WHERE id = ?',
      args: [skillId],
    });
    const rows = await selectFrom(
      client,
      'skills',
      { id: skillId },
      z.array(SkillSchema),
    );
    return rows[0];
  },
 
  /**
   * Replaces the `try_acquire_reclustering_lock` RPC.
   *
   * The conditional UPDATE is what makes this a lock: two callers racing both
   * issue it, SQLite serialises them, and only the one that finds
   * `last_clustering_at` still stale changes a row.
   */
  tryAcquireReclusteringLock: async (
    c: AppContext,
    skillId: string,
    lockThresholdMs: number,
  ): Promise<Skill | null> => {
    const client = getLibsqlClient(c);
    const now = new Date();
    const cutoff = new Date(now.getTime() - lockThresholdMs).toISOString();
 
    const result = await client.execute({
      sql: `UPDATE skills SET last_clustering_at = ?
            WHERE id = ?
              AND (last_clustering_at IS NULL OR last_clustering_at < ?)`,
      args: [now.toISOString(), skillId, cutoff],
    });
 
    if (result.rowsAffected === 0) {
      return null;
    }
 
    const rows = await selectFrom(
      client,
      'skills',
      { id: skillId },
      z.array(SkillSchema),
    );
    return rows[0] ?? null;
  },
 
  // ---------------------------------------------------------------- Tools
  getTools: async (
    c: AppContext,
    queryParams: ToolQueryParams,
  ): Promise<Tool[]> =>
    selectFrom(
      getLibsqlClient(c),
      'tools',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        hash: queryParams.hash,
        type: queryParams.type,
        name: queryParams.name,
      },
      z.array(ToolSchema),
      { limit: queryParams.limit, offset: queryParams.offset },
    ),
 
  createTool: async (c: AppContext, tool: ToolCreateParams): Promise<Tool> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'tools',
      {
        ...withId(tool as ToolCreateParams & { id?: string }),
        raw_data: toJsonColumn(tool.raw_data),
      },
      z.array(ToolSchema),
    );
    return rows[0];
  },
 
  deleteTool: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'tools', { id });
  },
 
  // ------------------------------------------------- AI Provider API Keys
  getAIProviderAPIKeys: async (
    c: AppContext,
    queryParams: AIProviderConfigQueryParams,
  ): Promise<AIProviderConfig[]> => {
    const rows = await selectFrom(
      getLibsqlClient(c),
      'ai_providers',
      {
        id: queryParams.id,
        ai_provider: queryParams.ai_provider,
        name: queryParams.name,
      },
      z.array(AIProviderConfigSchema),
      { limit: queryParams.limit, offset: queryParams.offset },
    );
 
    return rows.map((row) => ({
      ...row,
      api_key: row.api_key ? decryptAPIKey(c, row.api_key) : null,
    }));
  },
 
  getAIProviderAPIKeyById: async (
    c: AppContext,
    id: string,
  ): Promise<AIProviderConfig | null> => {
    const rows = await selectFrom(
      getLibsqlClient(c),
      'ai_providers',
      { id },
      z.array(AIProviderConfigSchema),
    );
 
    if (rows.length === 0) {
      return null;
    }
 
    return {
      ...rows[0],
      api_key: rows[0].api_key ? decryptAPIKey(c, rows[0].api_key) : null,
    };
  },
 
  createAIProvider: async (
    c: AppContext,
    apiKey: AIProviderConfigCreateParams,
  ): Promise<AIProviderConfig> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'ai_providers',
      {
        id: uuidv4(),
        ai_provider: apiKey.ai_provider,
        name: apiKey.name,
        api_key: apiKey.api_key ? encryptAPIKey(c, apiKey.api_key) : null,
        custom_fields: toJsonColumn(apiKey.custom_fields ?? {}),
      },
      z.array(AIProviderConfigSchema),
    );
 
    return {
      ...rows[0],
      api_key: rows[0].api_key ? decryptAPIKey(c, rows[0].api_key) : null,
    };
  },
 
  updateAIProvider: async (
    c: AppContext,
    id: string,
    update: AIProviderConfigUpdateParams,
  ): Promise<AIProviderConfig> => {
    const rows = await updateIn(
      getLibsqlClient(c),
      'ai_providers',
      { id },
      {
        ai_provider: update.ai_provider,
        name: update.name,
        api_key:
          update.api_key === undefined
            ? undefined
            : update.api_key
              ? encryptAPIKey(c, update.api_key)
              : null,
        custom_fields:
          update.custom_fields === undefined
            ? undefined
            : toJsonColumn(update.custom_fields),
      },
      z.array(AIProviderConfigSchema),
    );
 
    return {
      ...rows[0],
      api_key: rows[0].api_key ? decryptAPIKey(c, rows[0].api_key) : null,
    };
  },
 
  deleteAIProvider: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'ai_providers', { id });
  },
 
  // --------------------------------------------------------------- Models
  getModels: async (
    c: AppContext,
    queryParams: ModelQueryParams,
  ): Promise<Model[]> =>
    selectFrom(
      getLibsqlClient(c),
      'models',
      {
        id: queryParams.id,
        ai_provider_id: queryParams.ai_provider_id,
        model_name: queryParams.model_name,
      },
      z.array(ModelSchema),
      { limit: queryParams.limit, offset: queryParams.offset },
    ),
 
  createModel: async (
    c: AppContext,
    model: ModelCreateParams,
  ): Promise<Model> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'models',
      withId(model as ModelCreateParams & { id?: string }),
      z.array(ModelSchema),
    );
    return rows[0];
  },
 
  updateModel: async (
    c: AppContext,
    id: string,
    update: ModelUpdateParams,
  ): Promise<Model> => {
    const rows = await updateIn(
      getLibsqlClient(c),
      'models',
      { id },
      asColumns(update),
      z.array(ModelSchema),
    );
    return rows[0];
  },
 
  deleteModel: async (c: AppContext, id: string): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'models', { id });
  },
 
  // --------------------------------------------- Skill-Model Relationships
  /** PostgREST expresses this as an embedded select; here it is a plain join. */
  getSkillModels: async (c: AppContext, skillId: string): Promise<Model[]> => {
    const result = await getLibsqlClient(c).execute({
      sql: `SELECT m.* FROM skill_models sm
            JOIN models m ON m.id = sm.model_id
            WHERE sm.skill_id = ?`,
      args: [skillId],
    });
    return parseRows('models', result.rows, z.array(ModelSchema));
  },
 
  getSkillsByModelId: async (
    c: AppContext,
    modelId: string,
  ): Promise<Skill[]> => {
    const result = await getLibsqlClient(c).execute({
      sql: `SELECT s.* FROM skill_models sm
            JOIN skills s ON s.id = sm.skill_id
            WHERE sm.model_id = ?`,
      args: [modelId],
    });
    return parseRows('skills', result.rows, z.array(SkillSchema));
  },
 
  addModelsToSkill: async (
    c: AppContext,
    skillId: string,
    modelIds: string[],
  ): Promise<void> => {
    if (modelIds.length === 0) {
      return;
    }
 
    await getLibsqlClient(c).batch(
      modelIds.map((modelId) => ({
        sql: 'INSERT OR IGNORE INTO skill_models (skill_id, model_id) VALUES (?, ?)',
        args: [skillId, modelId],
      })),
      'write',
    );
  },
 
  removeModelsFromSkill: async (
    c: AppContext,
    skillId: string,
    modelIds: string[],
  ): Promise<void> => {
    if (modelIds.length === 0) {
      return;
    }
 
    await getLibsqlClient(c).batch(
      modelIds.map((modelId) => ({
        sql: 'DELETE FROM skill_models WHERE skill_id = ? AND model_id = ?',
        args: [skillId, modelId],
      })),
      'write',
    );
  },
 
  // ------------------------------------------ Skill Optimization Clusters
  getSkillOptimizationClusters: async (
    c: AppContext,
    queryParams: SkillOptimizationClusterQueryParams,
  ): Promise<SkillOptimizationCluster[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skill_optimization_clusters',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        skill_id: queryParams.skill_id,
      },
      z.array(SkillOptimizationClusterSchema),
      {
        orderBy: 'name asc',
        limit: queryParams.limit,
        offset: queryParams.offset,
      },
    ),
 
  createSkillOptimizationClusters: async (
    c: AppContext,
    params_list: SkillOptimizationClusterCreateParams[],
  ): Promise<SkillOptimizationCluster[]> => {
    const client = getLibsqlClient(c);
    const created: SkillOptimizationCluster[] = [];
 
    for (const params of params_list) {
      const rows = await insertInto(
        client,
        'skill_optimization_clusters',
        {
          ...withId(
            params as SkillOptimizationClusterCreateParams & {
              id?: string;
            },
          ),
          centroid: toJsonColumn(params.centroid),
        },
        z.array(SkillOptimizationClusterSchema),
      );
      created.push(rows[0]);
    }
 
    return created;
  },
 
  updateSkillOptimizationCluster: async (
    c: AppContext,
    id: string,
    update: SkillOptimizationClusterUpdateParams,
  ): Promise<SkillOptimizationCluster> => {
    const { centroid, ...rest } =
      update as SkillOptimizationClusterUpdateParams & Record<string, unknown>;
 
    const rows = await updateIn(
      getLibsqlClient(c),
      'skill_optimization_clusters',
      { id },
      {
        ...asColumns(rest),
        centroid: centroid === undefined ? undefined : toJsonColumn(centroid),
      },
      z.array(SkillOptimizationClusterSchema),
    );
    return rows[0];
  },
 
  deleteSkillOptimizationCluster: async (
    c: AppContext,
    id: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_clusters', { id });
  },
 
  /** Replaces the `increment_cluster_counters` RPC. */
  incrementClusterCounters: async (
    c: AppContext,
    clusterId: string,
  ): Promise<SkillOptimizationCluster> => {
    const client = getLibsqlClient(c);
    await client.execute({
      sql: `UPDATE skill_optimization_clusters
            SET total_steps = total_steps + 1,
                observability_total_requests = observability_total_requests + 1
            WHERE id = ?`,
      args: [clusterId],
    });
    const rows = await selectFrom(
      client,
      'skill_optimization_clusters',
      { id: clusterId },
      z.array(SkillOptimizationClusterSchema),
    );
    return rows[0];
  },
 
  // ---------------------------------------------- Skill Optimization Arms
  getSkillOptimizationArms: async (
    c: AppContext,
    queryParams: SkillOptimizationArmQueryParams,
  ): Promise<SkillOptimizationArm[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skill_optimization_arms',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        skill_id: queryParams.skill_id,
        cluster_id: queryParams.cluster_id,
      },
      z.array(SkillOptimizationArmSchema),
      {
        orderBy: 'created_at desc',
        limit: queryParams.limit,
        offset: queryParams.offset,
      },
    ),
 
  createSkillOptimizationArms: async (
    c: AppContext,
    params_list: SkillOptimizationArmCreateParams[],
  ): Promise<SkillOptimizationArm[]> => {
    const client = getLibsqlClient(c);
    const created: SkillOptimizationArm[] = [];
 
    for (const params of params_list) {
      const rows = await insertInto(
        client,
        'skill_optimization_arms',
        {
          ...withId(
            params as SkillOptimizationArmCreateParams & {
              id?: string;
            },
          ),
          params: toJsonColumn(params.params),
        },
        z.array(SkillOptimizationArmSchema),
      );
      created.push(rows[0]);
    }
 
    return created;
  },
 
  updateSkillOptimizationArm: async (
    c: AppContext,
    id: string,
    update: SkillOptimizationArmUpdateParams,
  ): Promise<SkillOptimizationArm> => {
    const { params, ...rest } = update as SkillOptimizationArmUpdateParams &
      Record<string, unknown>;
 
    const rows = await updateIn(
      getLibsqlClient(c),
      'skill_optimization_arms',
      { id },
      {
        ...asColumns(rest),
        params: params === undefined ? undefined : toJsonColumn(params),
      },
      z.array(SkillOptimizationArmSchema),
    );
    return rows[0];
  },
 
  /**
   * Replaces the `update_arm_and_increment_counters` RPC.
   *
   * This is the one operation that genuinely needs a transaction rather than a
   * batch: the arm stats, the cluster counters and the skill counter have to
   * move together, and the stat update is read-modify-write per evaluation.
   */
  updateArmAndIncrementCounters: async (
    c: AppContext,
    armId: string,
    evaluationResults: Array<{ evaluation_id: string; score: number }>,
  ): Promise<{
    arm: SkillOptimizationArm;
    cluster: SkillOptimizationCluster;
    skill: Skill;
  }> => {
    const client = getLibsqlClient(c);
    const tx = await client.transaction('write');
 
    try {
      const armRow = await tx.execute({
        sql: 'SELECT agent_id, skill_id, cluster_id FROM skill_optimization_arms WHERE id = ?',
        args: [armId],
      });
 
      if (armRow.rows.length === 0) {
        throw new Error(`Arm with id ${armId} not found`);
      }
 
      const agentId = String(armRow.rows[0].agent_id);
      const skillId = String(armRow.rows[0].skill_id);
      const clusterId = String(armRow.rows[0].cluster_id);
 
      for (const { evaluation_id, score } of evaluationResults) {
        const existing = await tx.execute({
          sql: 'SELECT n, total_reward, n2 FROM skill_optimization_arm_stats WHERE arm_id = ? AND evaluation_id = ?',
          args: [armId, evaluation_id],
        });
 
        const oldN = Number(existing.rows[0]?.n ?? 0);
        const oldTotal = Number(existing.rows[0]?.total_reward ?? 0);
        const oldN2 = Number(existing.rows[0]?.n2 ?? 0);
 
        // Incremental update formulas used by Thompson Sampling, matching the
        // plpgsql version exactly.
        const newN = oldN + 1;
        const newTotal = oldTotal + score;
        const newMean = newTotal / newN;
        const newN2 = oldN2 + score * score;
 
        await tx.execute({
          sql: `INSERT INTO skill_optimization_arm_stats
                  (arm_id, evaluation_id, agent_id, skill_id, cluster_id, n, mean, n2, total_reward)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON CONFLICT (arm_id, evaluation_id) DO UPDATE SET
                  n = excluded.n,
                  mean = excluded.mean,
                  n2 = excluded.n2,
                  total_reward = excluded.total_reward,
                  updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`,
          args: [
            armId,
            evaluation_id,
            agentId,
            skillId,
            clusterId,
            newN,
            newMean,
            newN2,
            newTotal,
          ],
        });
      }
 
      const clusterUpdate = await tx.execute({
        sql: `UPDATE skill_optimization_clusters
              SET total_steps = total_steps + 1,
                  observability_total_requests = observability_total_requests + 1
              WHERE id = ?`,
        args: [clusterId],
      });
      if (clusterUpdate.rowsAffected === 0) {
        throw new Error(`Cluster with id ${clusterId} not found`);
      }
 
      const skillUpdate = await tx.execute({
        sql: 'UPDATE skills SET total_requests = total_requests + 1 WHERE id = ?',
        args: [skillId],
      });
      if (skillUpdate.rowsAffected === 0) {
        throw new Error(`Skill with id ${skillId} not found`);
      }
 
      const [arm, cluster, skill] = await Promise.all([
        selectFrom(
          tx,
          'skill_optimization_arms',
          { id: armId },
          z.array(SkillOptimizationArmSchema),
        ),
        selectFrom(
          tx,
          'skill_optimization_clusters',
          { id: clusterId },
          z.array(SkillOptimizationClusterSchema),
        ),
        selectFrom(tx, 'skills', { id: skillId }, z.array(SkillSchema)),
      ]);
 
      await tx.commit();
 
      return { arm: arm[0], cluster: cluster[0], skill: skill[0] };
    } catch (e) {
      await tx.rollback();
      throw e;
    }
  },
 
  deleteSkillOptimizationArm: async (
    c: AppContext,
    id: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_arms', { id });
  },
 
  deleteSkillOptimizationArmsForSkill: async (
    c: AppContext,
    skillId: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_arms', {
      skill_id: skillId,
    });
  },
 
  deleteSkillOptimizationArmsForCluster: async (
    c: AppContext,
    clusterId: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_arms', {
      cluster_id: clusterId,
    });
  },
 
  // ----------------------------------------- Skill Optimization Arm Stats
  getSkillOptimizationArmStats: async (
    c: AppContext,
    queryParams: SkillOptimizationArmStatQueryParams,
  ): Promise<SkillOptimizationArmStat[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skill_optimization_arm_stats',
      {
        arm_id: queryParams.arm_id,
        evaluation_id: queryParams.evaluation_id,
        agent_id: queryParams.agent_id,
        skill_id: queryParams.skill_id,
        cluster_id: queryParams.cluster_id,
      },
      z.array(SkillOptimizationArmStatSchema),
      {
        orderBy: 'created_at desc',
        limit: queryParams.limit,
        offset: queryParams.offset,
      },
    ),
 
  deleteSkillOptimizationArmStats: async (
    c: AppContext,
    queryParams: SkillOptimizationArmStatQueryParams,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_arm_stats', {
      arm_id: queryParams.arm_id,
      evaluation_id: queryParams.evaluation_id,
      agent_id: queryParams.agent_id,
      skill_id: queryParams.skill_id,
      cluster_id: queryParams.cluster_id,
    });
  },
 
  // --------------------------------------- Skill Optimization Evaluations
  getSkillOptimizationEvaluations: async (
    c: AppContext,
    queryParams: SkillOptimizationEvaluationQueryParams,
  ): Promise<SkillOptimizationEvaluation[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skill_optimization_evaluations',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        skill_id: queryParams.skill_id,
        evaluation_method: queryParams.evaluation_method,
      },
      z.array(SkillOptimizationEvaluationSchema),
      {
        orderBy: 'created_at desc',
        limit: queryParams.limit,
        offset: queryParams.offset,
      },
    ),
 
  createSkillOptimizationEvaluations: async (
    c: AppContext,
    params_list: SkillOptimizationEvaluationCreateParams[],
  ): Promise<SkillOptimizationEvaluation[]> => {
    const client = getLibsqlClient(c);
    const created: SkillOptimizationEvaluation[] = [];
 
    for (const params of params_list) {
      const rows = await insertInto(
        client,
        'skill_optimization_evaluations',
        {
          ...withId(
            params as SkillOptimizationEvaluationCreateParams & {
              id?: string;
            },
          ),
          params: toJsonColumn(params.params ?? {}),
        },
        z.array(SkillOptimizationEvaluationSchema),
      );
      created.push(rows[0]);
    }
 
    return created;
  },
 
  updateSkillOptimizationEvaluation: async (
    c: AppContext,
    id: string,
    update: SkillOptimizationEvaluationUpdateParams,
  ): Promise<SkillOptimizationEvaluation> => {
    const { params, ...rest } =
      update as SkillOptimizationEvaluationUpdateParams &
        Record<string, unknown>;
 
    const rows = await updateIn(
      getLibsqlClient(c),
      'skill_optimization_evaluations',
      { id },
      {
        ...asColumns(rest),
        params: params === undefined ? undefined : toJsonColumn(params),
      },
      z.array(SkillOptimizationEvaluationSchema),
    );
 
    if (rows.length === 0) {
      throw new Error('Evaluation not found');
    }
 
    return rows[0];
  },
 
  deleteSkillOptimizationEvaluation: async (
    c: AppContext,
    id: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_evaluations', {
      id,
    });
  },
 
  deleteSkillOptimizationEvaluationsForSkill: async (
    c: AppContext,
    skillId: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_evaluations', {
      skill_id: skillId,
    });
  },
 
  // ----------------------------------- Skill Optimization Evaluation Runs
  getSkillOptimizationEvaluationRuns: async (
    c: AppContext,
    queryParams: SkillOptimizationEvaluationRunQueryParams,
  ): Promise<SkillOptimizationEvaluationRun[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skill_optimization_evaluation_runs',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        skill_id: queryParams.skill_id,
        log_id: queryParams.log_id,
      },
      z.array(SkillOptimizationEvaluationRunSchema),
      {
        orderBy: 'created_at desc',
        limit: queryParams.limit,
        offset: queryParams.offset,
      },
    ),
 
  createSkillOptimizationEvaluationRun: async (
    c: AppContext,
    params: SkillOptimizationEvaluationRunCreateParams,
  ): Promise<SkillOptimizationEvaluationRun> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'skill_optimization_evaluation_runs',
      {
        ...withId(
          params as SkillOptimizationEvaluationRunCreateParams & {
            id?: string;
          },
        ),
        results: toJsonColumn(params.results),
      },
      z.array(SkillOptimizationEvaluationRunSchema),
    );
    return rows[0];
  },
 
  deleteSkillOptimizationEvaluationRun: async (
    c: AppContext,
    id: string,
  ): Promise<void> => {
    await deleteFrom(getLibsqlClient(c), 'skill_optimization_evaluation_runs', {
      id,
    });
  },
 
  getEvaluationScoresByTimeBucket: async (
    c: AppContext,
    params: EvaluationScoresByTimeBucketParams,
  ) => aggregateScoresByTimeBucket(getLibsqlClient(c), params),
 
  // --------------------------------------------------------- Skill Events
  getSkillEvents: async (
    c: AppContext,
    queryParams: SkillEventQueryParams,
  ): Promise<SkillEvent[]> =>
    selectFrom(
      getLibsqlClient(c),
      'skill_events',
      {
        id: queryParams.id,
        agent_id: queryParams.agent_id,
        skill_id: queryParams.skill_id,
        cluster_id: queryParams.cluster_id,
        event_type: queryParams.event_type,
      },
      z.array(SkillEventSchema),
      {
        orderBy: 'created_at desc',
        limit: queryParams.limit,
        offset: queryParams.offset,
      },
    ),
 
  createSkillEvent: async (
    c: AppContext,
    params: SkillEventCreateParams,
  ): Promise<SkillEvent> => {
    const rows = await insertInto(
      getLibsqlClient(c),
      'skill_events',
      {
        ...withId(params as SkillEventCreateParams & { id?: string }),
        metadata: toJsonColumn(params.metadata ?? {}),
      },
      z.array(SkillEventSchema),
    );
 
    emitSSEEvent('skill-optimization:event-created', {
      eventId: rows[0].id,
      skillId: rows[0].skill_id,
      clusterId: rows[0].cluster_id,
      eventType: rows[0].event_type,
    });
 
    return rows[0];
  },
 
  // ------------------------------------------------------- System Settings
  getSystemSettings: async (c: AppContext): Promise<SystemSettings> => {
    const rows = await selectFrom(
      getLibsqlClient(c),
      'system_settings',
      {},
      z.array(SystemSettingsSchema),
      { limit: 1 },
    );
    // Seeded by migration 0003, so there is always exactly one row.
    return rows[0];
  },
 
  updateSystemSettings: async (
    c: AppContext,
    update: SystemSettingsUpdateParams,
  ): Promise<SystemSettings> => {
    const client = getLibsqlClient(c);
    const current = await selectFrom(
      client,
      'system_settings',
      {},
      z.array(SystemSettingsSchema),
      { limit: 1 },
    );
 
    const { developer_mode, ...rest } = update as SystemSettingsUpdateParams &
      Record<string, unknown>;
 
    const rows = await updateIn(
      client,
      'system_settings',
      { id: current[0].id },
      {
        ...asColumns(rest),
        developer_mode:
          developer_mode === undefined ? undefined : developer_mode ? 1 : 0,
      },
      z.array(SystemSettingsSchema),
    );
    return rows[0];
  },
};