Artifact f4b31582a04eef9bbc95dc3681ccd38c59e6d0caca27d94ceb4edbadf375d280:
- File
src/provider_anthropic.c
— part of check-in
[ffaf5a4afb]
at
2026-11-19 02:04:10
on branch stage-5
— Add follow-up conversations, forks and in-place instruction updates
Entries form a tree: a trigger links each new entry to its conversation head and moves the head, inside the inserting transaction. Requests are built from the path, so pic ask -c and an explicit id continue a conversation and pic fork branches one from a point that ends a turn. Each conversation freezes its opening prompt and tools; edited project instructions are appended once as an update at that point. New commands list, name and print conversations. Schema 5, with journals of earlier versions stepped up in place. (user: dmestas, size: 10170) [annotate] [blame] [check-ins using] [more...]
/* Messages API adapter: the request built from the journal, streamed through * the shared POST (provider_http.c) and the event decoder (anthropic.c). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "anthropic.h" #include "provider_http.h" #define API_VERSION "2026-10-21" #define MAX_TOKENS 64000 typedef struct { pic_model model; /* provider, id, key and headers from the registry */ char *url, *workspace; pic_net *net; } state; /* 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, PIC_PATH_CTE "SELECT e.kind, CASE e.kind" " WHEN 'user' THEN json_object('role','user','content',e.body)" " WHEN 'instructions' THEN json_object('type','text','text'," " '<project_instructions_update>' || char(10) || e.body || char(10) || '</project_instructions_update>')" " 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 JOIN p ON p.seq = e.seq LEFT JOIN pic_effect f ON f.id=e.effect_id" " LEFT JOIN pic_entry a ON a.seq=f.entry_seq 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) { /* Tool results and instruction updates are blocks of one user message. */ const char *kind = (const char *)sqlite3_column_text(q, 0); int result = strcmp(kind, "tool_result") == 0 || strcmp(kind, "instructions") == 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, int64_t submission, const char *messages) { sqlite3_stmt *q = NULL; char *body = NULL, *system_prompt = pic_session_text(s, submission, "system_prompt"), *tools = pic_session_text(s, submission, "tools"); if (!system_prompt || !tools) { free(system_prompt); free(tools); 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); free(tools); 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, tools, -1, SQLITE_STATIC); sqlite3_bind_text(q, 5, messages, -1, SQLITE_STATIC); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { body = pic_strdup((const char *)sqlite3_column_text(q, 0)); } sqlite3_finalize(q); free(system_prompt); free(tools); return body; } /* Pi's stop reasons from the Messages API's. */ static char *stop_reason(const char *s) { if (!s) { return NULL; } return pic_strdup(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); } /* The event decoder, wrapped for pic_stream_post. */ typedef struct { sqlite3 *db; pic_anthropic dec; } decoding; static int dec_begin(void *ctx) { decoding *d = ctx; return pic_anthropic_init(&d->dec, d->db); } static int dec_finish(void *ctx, char *why, size_t cap) { decoding *d = ctx; if (pic_anthropic_finish(&d->dec) == 0 && !d->dec.msg.error) { return 0; } (void)snprintf(why, cap, "%s", d->dec.msg.error ? d->dec.msg.error : d->dec.err); return -1; } static int dec_event(void *ctx, const char *event, const char *data, size_t len) { return pic_anthropic_event(&((decoding *)ctx)->dec, event, data, len); } static void dec_end(void *ctx) { pic_anthropic_free(&((decoding *)ctx)->dec); } 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; static const char *const extra[] = {"anthropic-version: " API_VERSION, "Accept: text/event-stream"}; decoding d; pic_stream_decoder dec = {dec_begin, dec_event, dec_finish, dec_end, &d}; char *messages, *body, request_id[128]; int rc; (void)turn; *retryable = 0; memset(out, 0, sizeof *out); memset(&d, 0, sizeof d); d.db = s->db; messages = build_messages(s, st, submission, err, errcap); body = messages ? build_body(s, st, submission, messages) : NULL; sqlite3_free(messages); if (!body) { if (!err[0]) { (void)snprintf(err, errcap, "could not build the request body"); } return -1; } rc = pic_stream_post(st->net, s, &st->model, st->url, PIC_AUTH_X_API_KEY, extra, 2, body, &dec, request_id, sizeof request_id, retryable, err, errcap); free(body); if (rc != 0) { return -1; } out->native = d.dec.msg.content; d.dec.msg.content = NULL; out->neutral = out->native ? pic_neutral_from_anthropic(s->db, out->native) : NULL; out->stop_reason = stop_reason(d.dec.msg.stop_reason); out->usage = d.dec.msg.usage ? pic_strdup(d.dec.msg.usage) : NULL; out->request_id = request_id[0] ? pic_strdup(request_id) : NULL; out->provider = pic_strdup(st->model.provider); out->api = pic_strdup(pic_api_name(st->model.api)); out->model = pic_strdup(st->model.id); dec_end(&d); if (!out->native || !out->neutral || !out->provider || !out->api || !out->model) { pic_reply_free(out); (void)snprintf(err, errcap, "out of memory"); return -1; } return 0; } 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_anthropic_new(pic_provider *p, const pic_model *m, const char *url, const char *workspace, char *err, size_t errcap) { char endpoint[512]; state *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 = *m; pic_model_url(m, endpoint, sizeof endpoint); if (!(st->url = pic_strdup(url ? url : endpoint)) || !(st->workspace = pic_strdup(workspace))) { (void)snprintf(err, errcap, "out of memory"); return -1; } st->net = pic_net_new(err, errcap); return st->net ? 0 : -1; }