Skip to content
pi-c Artifact [201809eff5]
Login

Artifact [201809eff5]

Artifact 201809eff5a5db99b2bb2eee0f07190025bf5d1a1a467e1e7d77b4e3604fd76c:


/* The model catalog: the built-in snapshot of Pi's catalog, with fresher
 * per-provider lists from pi.dev laid over it as Pi does
 * (reference/pi/packages/coding-agent/src/core/remote-catalog-provider.ts):
 * a stored list counts when its Last-Modified is newer than the snapshot,
 * and its models replace the snapshot's of the same id. */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include "catalog.h"
#include "sqlite3.h"

#include "model_catalog.inc"

#define BODY_CAP (8u << 20) /* the largest store read */

const char *const pic_catalog_providers[PIC_CATALOG_NPROVIDERS] = {"anthropic", "openai",    "openrouter",  "xai",    "groq",       "cerebras", "deepseek",
                                        "together",  "fireworks", "huggingface", "nvidia", "moonshotai", "zai"};

int pic_catalog_store_path(char *out, size_t cap, int make_dir) {
    const char *home = getenv("HOME");
    char dir[PATH_MAX];
    if (!home || !*home || snprintf(dir, sizeof dir, "%s/.pic", home) >= (int)sizeof dir ||
        snprintf(out, cap, "%s/models-store.json", dir) >= (int)cap) {
        return -1;
    }
    if (make_dir && mkdir(dir, 0700) != 0 && errno != EEXIST) {
        return -1;
    }
    return 0;
}

/* The store's text, or "{}" when there is none or it is unreadable. */
char *pic_catalog_read_store(void) {
    char path[PATH_MAX];
    FILE *f;
    char *buf = NULL;
    long n;
    if (pic_catalog_store_path(path, sizeof path, 0) == 0 && (f = fopen(path, "rb"))) {
        if (fseek(f, 0, SEEK_END) == 0 && (n = ftell(f)) > 0 && n < (long)BODY_CAP * 16 && fseek(f, 0, SEEK_SET) == 0 &&
            (buf = malloc((size_t)n + 1))) {
            if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
                free(buf);
                buf = NULL;
            } else {
                buf[n] = '\0';
            }
        }
        fclose(f);
    }
    return buf ? buf : strdup("{}");
}

/* The stored models of PROVIDER when newer than the snapshot (malloc'd JSON
 * array), else NULL. */
static char *overlay(sqlite3 *db, const char *store, const char *provider) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db,
                           "SELECT (SELECT json_group_array(json(m.value)) FROM json_each(json_extract(?1, '$.\"' || ?2 || '\".models')) m"
                           "   WHERE json_extract(m.value, '$.api') IN ('anthropic-messages','openai-completions','openai-responses')"
                           "   AND coalesce(json_extract(m.value, '$.type'), 'chat') = 'chat') WHERE json_valid(?1)"
                           " AND coalesce(json_extract(?1, '$.\"' || ?2 || '\".lastModified'), 0) > ?3"
                           " AND json_type(?1, '$.\"' || ?2 || '\".models') = 'array'",
                           -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, store, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, provider, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 3, PIC_CATALOG_GENERATED_MS);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

/* The model with ID in a JSON array of models (malloc'd), or NULL. */
static char *in_array(sqlite3 *db, const char *array, const char *id) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (!array || sqlite3_prepare_v2(db, "SELECT value FROM json_each(?1) WHERE json_extract(value, '$.id') = ?2 LIMIT 1",
                                     -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    sqlite3_bind_text(q, 1, array, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, id, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        out = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

char *pic_catalog_find(const char *provider, const char *id) {
    sqlite3 *db = NULL;
    char *store = pic_catalog_read_store(), *list, *out = NULL;
    if (sqlite3_open(":memory:", &db) == SQLITE_OK) {
        list = overlay(db, store, provider);
        out = in_array(db, list, id);
        free(list);
    }
    sqlite3_close(db);
    free(store);
    for (size_t i = 0; !out && i < sizeof catalog_snapshot / sizeof catalog_snapshot[0]; i++) {
        if (strcmp(catalog_snapshot[i].provider, provider) == 0 && strcmp(catalog_snapshot[i].id, id) == 0) {
            out = strdup(catalog_snapshot[i].json);
        }
    }
    return out;
}

int pic_catalog_each(int (*fn)(void *ctx, const char *provider, const char *json), void *ctx) {
    sqlite3 *db = NULL;
    char *store = pic_catalog_read_store();
    int stop = 0;
    if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
        free(store);
        return -1;
    }
    for (size_t p = 0; !stop && p < PIC_CATALOG_NPROVIDERS; p++) {
        char *list = overlay(db, store, pic_catalog_providers[p]);
        sqlite3_stmt *q = NULL;
        /* The stored models first; the snapshot's for ids they lack. */
        if (list && sqlite3_prepare_v2(db, "SELECT value FROM json_each(?1)", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, list, -1, SQLITE_STATIC);
            while (!stop && sqlite3_step(q) == SQLITE_ROW) {
                stop = fn(ctx, pic_catalog_providers[p], (const char *)sqlite3_column_text(q, 0));
            }
            sqlite3_finalize(q);
        }
        for (size_t i = 0; !stop && i < sizeof catalog_snapshot / sizeof catalog_snapshot[0]; i++) {
            char *dup;
            if (strcmp(catalog_snapshot[i].provider, pic_catalog_providers[p]) != 0) {
                continue;
            }
            dup = in_array(db, list, catalog_snapshot[i].id);
            if (!dup) {
                stop = fn(ctx, pic_catalog_providers[p], catalog_snapshot[i].json);
            }
            free(dup);
        }
        free(list);
    }
    sqlite3_close(db);
    free(store);
    return 0;
}