Skip to content
pi-c Documentation
Login

Documentation

/* 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 {
    char *url, *model, *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. */
static char *build_messages(pic_store *s, 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',f.call_id,'content',e.body,"
            "   'is_error',json(iif(f.is_error,'true','false')))"
            " ELSE json_object('role','assistant','content',json(e.body)) END"
            " FROM pic_entry e LEFT JOIN pic_effect f ON f.id=e.effect_id WHERE e.submission_id=? 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_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);
        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, -1, SQLITE_STATIC);
    sqlite3_bind_int(q, 2, 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;
}

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;
    const char *headers[3];
    int rc = -1;
    (void)turn;
    *retryable = 0;
    memset(out, 0, sizeof *out);
    messages = build_messages(s, 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;
    }
    if (pic_cred_get("anthropic", key, sizeof key, err, errcap) != 0) {
        free(body);
        return -1;
    }
    (void)snprintf(auth, sizeof auth, "x-api-key: %s", key);
    pic_cred_wipe(key, sizeof key);
    headers[0] = auth;
    headers[1] = "anthropic-version: " API_VERSION;
    headers[2] = "Accept: text/event-stream";
    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, 3, 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->content = dec.msg.content;
                dec.msg.content = NULL;
                out->stop_reason = dec.msg.stop_reason ? dup_string(dec.msg.stop_reason) : NULL;
                out->usage = dec.msg.usage ? dup_string(dec.msg.usage) : NULL;
                out->request_id = resp.request_id[0] ? dup_string(resp.request_id) : NULL;
                rc = out->content ? 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->model);
        free(st->workspace);
        free(st);
    }
    p->state = NULL;
}

int pic_provider_anthropic(pic_provider *p, const char *url, const char *model, const char *workspace, char *err,
                           size_t errcap) {
    state *st = calloc(1, sizeof *st);
    p->reply = anthropic_reply;
    p->free = anthropic_free;
    p->state = st;
    if (!st || !(st->url = dup_string(url)) || !(st->model = dup_string(model)) ||
        !(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;
}