Skip to content
pi-c Artifact [99f511b945]
Login

Artifact [99f511b945]

Artifact 99f511b945ead55af0dd02adeeb3cd3f3eb51767c75cb3b9318f1ee4df88dd55:


/* Messages API provider: request built from the journal, sent over pic's own
 * HTTPS stack, streamed through the SSE framer and the event decoder.
 *
 * Retries inside one generation happen only before any byte of a successful
 * stream: connection failures, 429, 5xx and 529, honouring Retry-After. A
 * stream that breaks after it started fails this generation (retryable); the
 * loop journals that attempt and asks again. Other statuses fail for good. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "anthropic.h"
#include "cred.h"
#include "http.h"
#include "net.h"
#include "pic.h"
#include "sse.h"

#define API_VERSION "2026-10-21"
#define MAX_TOKENS 64000
#define HTTP_TRIES 4
#define IDLE_SECONDS 120     /* a stream may pause while the model thinks */
#define DEADLINE_SECONDS 900 /* one whole request */
#define ERROR_BODY_CAP 8192
#define KEY_CAP 512

typedef struct {
    pic_model model; /* provider, id, key and headers from the registry */
    char *url, *workspace;
    pic_net *net;
} state;

typedef struct {
    pic_http_resp *resp;
    pic_sse *sse;
    char error_body[ERROR_BODY_CAP];
    size_t error_len;
    int stream_failed;
} sink;

static char *dup_string(const char *s) {
    size_t n = strlen(s) + 1;
    char *p = malloc(n);
    if (p) {
        memcpy(p, s, n);
    }
    return p;
}

static int on_body(void *ctx, const char *bytes, size_t n) {
    sink *k = ctx;
    if (k->resp->status == 200) {
        int rc = pic_sse_feed(k->sse, bytes, n);
        if (rc != 0) {
            k->stream_failed = 1;
        }
        return rc;
    }
    if (n > sizeof k->error_body - 1 - k->error_len) {
        n = sizeof k->error_body - 1 - k->error_len;
    }
    memcpy(k->error_body + k->error_len, bytes, n);
    k->error_len += n;
    k->error_body[k->error_len] = '\0';
    return 0;
}

/* The messages array: the user's text, each assistant content array as it was
 * received, and each run of tool results as one user message. */
/* The messages array: the user's text; each assistant turn verbatim if this
 * provider, API and model produced it, else rebuilt from its neutral form
 * (thinking dropped, tool-call ids normalised); each run of tool results as
 * one user message, with ids normalised exactly as their calls were. */
static char *build_messages(pic_store *s, const state *st, int64_t submission, char *err, size_t errcap) {
    sqlite3_stmt *q = NULL;
    sqlite3_str *out = sqlite3_str_new(s->db);
    int in_results = 0, first = 1, step;
    if (sqlite3_prepare_v2(
            s->db,
            "SELECT e.kind, CASE e.kind"
            " WHEN 'user' THEN json_object('role','user','content',e.body)"
            " WHEN 'tool_result' THEN json_object('type','tool_result','tool_use_id',"
            "   CASE WHEN a.provider IS ?2 AND a.api IS ?3 AND a.model IS ?4 THEN f.call_id"
            "   ELSE pic_norm_id(f.call_id,'anthropic-messages',?2) END,"
            "   'content',e.body,'is_error',json(iif(f.is_error,'true','false')))"
            " ELSE CASE WHEN e.provider IS ?2 AND e.api IS ?3 AND e.model IS ?4"
            "   THEN json_object('role','assistant','content',json(e.native))"
            "   ELSE json_object('role','assistant','content',json((SELECT coalesce(json_group_array(json(y)),'[]') FROM"
            "     (SELECT CASE json_extract(value,'$.type')"
            "       WHEN 'text' THEN json_object('type','text','text',json_extract(value,'$.text'))"
            "       WHEN 'toolCall' THEN json_object('type','tool_use','id',"
            "         pic_norm_id(json_extract(value,'$.id'),'anthropic-messages',?2),"
            "         'name',json_extract(value,'$.name'),'input',json(json_extract(value,'$.arguments')))"
            "       END AS y FROM json_each(e.body) ORDER BY key) WHERE y IS NOT NULL))) END END"
            " FROM pic_entry e LEFT JOIN pic_effect f ON f.id=e.effect_id LEFT JOIN pic_entry a ON a.seq=f.entry_seq"
            " WHERE e.submission_id=?1 ORDER BY e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        (void)snprintf(err, errcap, "sql: %s", sqlite3_errmsg(s->db));
        sqlite3_free(sqlite3_str_finish(out));
        return NULL;
    }
    sqlite3_bind_int64(q, 1, submission);
    sqlite3_bind_text(q, 2, st->model.provider, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 3, pic_api_name(st->model.api), -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, st->model.id, -1, SQLITE_STATIC);
    sqlite3_str_appendall(out, "[");
    while ((step = sqlite3_step(q)) == SQLITE_ROW) {
        int result = strcmp((const char *)sqlite3_column_text(q, 0), "tool_result") == 0;
        const char *item = (const char *)sqlite3_column_text(q, 1);
        /* A foreign turn with nothing this API can take (only thinking) is
         * left out; the API refuses an empty assistant message. */
        if (item && strcmp(item, "{\"role\":\"assistant\",\"content\":[]}") == 0) {
            continue;
        }
        if (in_results && !result) {
            sqlite3_str_appendall(out, "]}");
            in_results = 0;
        }
        if (result && in_results) {
            sqlite3_str_appendall(out, ",");
        } else {
            sqlite3_str_appendall(out, first ? "" : ",");
            if (result) {
                sqlite3_str_appendall(out, "{\"role\":\"user\",\"content\":[");
                in_results = 1;
            }
        }
        sqlite3_str_appendall(out, item ? item : "null");
        first = 0;
    }
    sqlite3_finalize(q);
    if (in_results) {
        sqlite3_str_appendall(out, "]}");
    }
    sqlite3_str_appendall(out, "]");
    if (step != SQLITE_DONE || sqlite3_str_errcode(out) != SQLITE_OK) {
        (void)snprintf(err, errcap, "could not build the request");
        sqlite3_free(sqlite3_str_finish(out));
        return NULL;
    }
    return sqlite3_str_finish(out);
}

static char *build_body(pic_store *s, const state *st, const char *messages) {
    sqlite3_stmt *q = NULL;
    char *body = NULL, *system_prompt = pic_system_prompt(st->workspace);
    if (!system_prompt) {
        return NULL;
    }
    if (sqlite3_prepare_v2(s->db,
                           "SELECT json_object('model',?1,'max_tokens',?2,'stream',json('true'),'system',?3,"
                           "'tools',json(?4),'messages',json(?5))",
                           -1, &q, NULL) != SQLITE_OK) {
        free(system_prompt);
        return NULL;
    }
    sqlite3_bind_text(q, 1, st->model.id, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, st->model.max_tokens < MAX_TOKENS ? st->model.max_tokens : MAX_TOKENS);
    sqlite3_bind_text(q, 3, system_prompt, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 4, pic_tool_schemas, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 5, messages, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        body = dup_string((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    free(system_prompt);
    return body;
}

/* error.message from an error response body, or the status alone. */
static void error_text(pic_store *s, int status, const char *body, char *err, size_t errcap) {
    sqlite3_stmt *q = NULL;
    const char *msg = NULL;
    if (sqlite3_prepare_v2(s->db, "SELECT CASE WHEN json_valid(?1) THEN json_extract(?1,'$.error.message') END", -1, &q,
                           NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, body, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            msg = (const char *)sqlite3_column_text(q, 0);
        }
    }
    (void)snprintf(err, errcap, "HTTP %d%s%.300s", status, msg ? ": " : "", msg ? msg : "");
    sqlite3_finalize(q);
}

static void pause_ms(long ms) {
    struct timespec ts;
    ts.tv_sec = ms / 1000;
    ts.tv_nsec = (ms % 1000) * 1000000L;
    while (nanosleep(&ts, &ts) != 0) {
    }
}

/* Milliseconds to wait before try number `tryno` (1-based) after a failure. */
static long backoff_ms(const pic_http_resp *r, int tryno) {
    long ms = 500L << (tryno - 1);
    if (r && r->retry_after[0]) {
        char *end;
        long secs = strtol(r->retry_after, &end, 10);
        if (*end == '\0' && secs >= 0) {
            ms = secs * 1000;
        }
    }
    return ms > 30000 ? 30000 : ms;
}

/* Pi's stop reasons from the Messages API's. */
static char *stop_reason(const char *s) {
    if (!s) {
        return NULL;
    }
    return dup_string(strcmp(s, "end_turn") == 0 || strcmp(s, "stop_sequence") == 0 ? "stop"
                      : strcmp(s, "max_tokens") == 0                                  ? "length"
                      : strcmp(s, "tool_use") == 0                                    ? "toolUse"
                      : strcmp(s, "pause_turn") == 0                                  ? "pause"
                                                                                      : s);
}

#define EXTRA_HEADERS 16

static int anthropic_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out,
                           int *retryable, char *err, size_t errcap) {
    state *st = p->state;
    char key[KEY_CAP], auth[KEY_CAP + 16], *messages, *body, extra[sizeof st->model.headers];
    const char *headers[3 + EXTRA_HEADERS];
    size_t nheaders = 0;
    int rc = -1, keyed;
    (void)turn;
    *retryable = 0;
    memset(out, 0, sizeof *out);
    messages = build_messages(s, st, submission, err, errcap);
    body = messages ? build_body(s, st, messages) : NULL;
    sqlite3_free(messages);
    if (!body) {
        if (!err[0]) {
            (void)snprintf(err, errcap, "could not build the request body");
        }
        return -1;
    }
    keyed = pic_cred_get(st->model.key_env, st->model.key_literal, key, sizeof key, err, errcap);
    if (keyed < 0) {
        free(body);
        return -1;
    }
    auth[0] = '\0';
    if (keyed == 0) {
        (void)snprintf(auth, sizeof auth, "x-api-key: %s", key);
        headers[nheaders++] = auth;
    }
    pic_cred_wipe(key, sizeof key);
    headers[nheaders++] = "anthropic-version: " API_VERSION;
    headers[nheaders++] = "Accept: text/event-stream";
    /* Headers from the models file, one per line. */
    (void)snprintf(extra, sizeof extra, "%s", st->model.headers);
    for (char *line = extra; *line && nheaders < sizeof headers / sizeof headers[0];) {
        char *nl = strchr(line, '\n');
        if (nl) {
            *nl = '\0';
        }
        headers[nheaders++] = line;
        if (!nl) {
            break;
        }
        line = nl + 1;
    }
    for (int tryno = 1; tryno <= HTTP_TRIES; tryno++) {
        pic_http_resp resp;
        pic_anthropic dec;
        pic_sse sse;
        sink k;
        int post, transient;
        memset(&k, 0, sizeof k);
        if (pic_anthropic_init(&dec, s->db) != 0 ||
            pic_sse_init(&sse, 1u << 20, PIC_MESSAGE_CAP, pic_anthropic_event, &dec) != 0) {
            pic_anthropic_free(&dec);
            (void)snprintf(err, errcap, "out of memory");
            break;
        }
        k.resp = &resp;
        k.sse = &sse;
        pic_http_resp_init(&resp, on_body, &k);
        post = pic_http_post(st->net, st->url, headers, nheaders, body, strlen(body), &resp, IDLE_SECONDS,
                             DEADLINE_SECONDS, err, errcap);
        pic_fault("after-response");
        if (resp.status == 200) {
            if (post == 0 && !k.stream_failed && pic_sse_pending(&sse) == 0 && pic_anthropic_finish(&dec) == 0 &&
                !dec.msg.error) {
                out->native = dec.msg.content;
                dec.msg.content = NULL;
                out->neutral = out->native ? pic_neutral_from_anthropic(s->db, out->native) : NULL;
                out->stop_reason = stop_reason(dec.msg.stop_reason);
                out->usage = dec.msg.usage ? dup_string(dec.msg.usage) : NULL;
                out->request_id = resp.request_id[0] ? dup_string(resp.request_id) : NULL;
                out->provider = dup_string(st->model.provider);
                out->api = dup_string(pic_api_name(st->model.api));
                out->model = dup_string(st->model.id);
                rc = out->native && out->neutral && out->provider && out->api && out->model ? 0 : -1;
            } else {
                /* The stream broke after it began: no retry here. */
                char why[320];
                (void)snprintf(why, sizeof why, "%s",
                               dec.msg.error ? dec.msg.error
                               : dec.err[0] ? dec.err
                               : post != 0  ? err
                                            : "incomplete stream");
                *retryable = 1;
                (void)snprintf(err, errcap, "stream failed: %.300s", why);
            }
            pic_sse_free(&sse);
            pic_anthropic_free(&dec);
            break;
        }
        pic_sse_free(&sse);
        pic_anthropic_free(&dec);
        transient = post != 0 ? !pic_net_tls_failed(st->net)
                              : resp.status == 429 || resp.status == 529 || resp.status >= 500;
        if (post == 0) {
            error_text(s, resp.status, k.error_body, err, errcap);
        }
        if (!transient) {
            break;
        }
        *retryable = 1;
        if (tryno < HTTP_TRIES) {
            pause_ms(backoff_ms(post == 0 ? &resp : NULL, tryno));
        }
    }
    pic_cred_wipe(auth, sizeof auth);
    free(body);
    if (rc != 0) {
        pic_reply_free(out);
    } else {
        *retryable = 0;
    }
    return rc;
}

static void anthropic_free(pic_provider *p) {
    state *st = p->state;
    if (st) {
        pic_net_free(st->net);
        free(st->url);
        free(st->workspace);
        free(st);
    }
    p->state = NULL;
}

int pic_provider_for_model(pic_provider *p, const pic_model *model, const char *url, const char *workspace,
                           char *err, size_t errcap) {
    char endpoint[512];
    state *st;
    if (model->api != PIC_API_ANTHROPIC) {
        (void)snprintf(err, errcap, "%s models are not supported yet (provider %s)", pic_api_name(model->api),
                       model->provider);
        return -1;
    }
    st = calloc(1, sizeof *st);
    p->reply = anthropic_reply;
    p->free = anthropic_free;
    p->state = st;
    if (!st) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    st->model = *model;
    pic_model_url(model, endpoint, sizeof endpoint);
    if (!(st->url = dup_string(url ? url : endpoint)) || !(st->workspace = dup_string(workspace))) {
        (void)snprintf(err, errcap, "out of memory");
        return -1;
    }
    st->net = pic_net_new(err, errcap);
    return st->net ? 0 : -1;
}