/* Messages API stream decoder: SSE events in, one assistant message out.
* A strict state machine; any event out of order fails the stream. JSON is
* parsed with SQLite's JSON functions on a caller-supplied connection. */
#ifndef PIC_ANTHROPIC_H
#define PIC_ANTHROPIC_H
#include <stddef.h>
#include "sqlite3.h"
#define PIC_MESSAGE_CAP (16u << 20) /* bound on one assistant message */
typedef struct {
char *buf;
size_t len, cap;
} pic_buf;
typedef struct {
char *id; /* provider message id */
char *model; /* model that served it */
char *stop_reason; /* end_turn, tool_use, max_tokens, refusal, ... */
char *usage; /* JSON object: message_start usage patched by message_delta */
char *content; /* JSON array of content blocks, verbatim for replay */
char *error; /* stream error event, "type: message" */
} pic_message;
typedef struct {
sqlite3 *db;
sqlite3_stmt *get; /* SELECT json_extract(?1, ?2) on valid JSON */
int state; /* 0 before message_start, 1 open, 2 stopped, -1 failed */
int open; /* index of the open block, -1 if none */
int blocks; /* blocks completed so far */
char *block; /* content_block from content_block_start */
char *block_type;
pic_buf text; /* text or thinking accumulated from deltas */
pic_buf extra; /* signature, or partial tool input JSON */
int extra_is_input; /* the open block received input_json_delta */
pic_buf content; /* "[" block "," block ... */
size_t total; /* bytes buffered for this message */
pic_message msg;
char err[256];
} pic_anthropic;
int pic_anthropic_init(pic_anthropic *d, sqlite3 *db);
void pic_anthropic_free(pic_anthropic *d);
/* Fits pic_sse_event_fn with ctx = the decoder. 0, or -1 with d->err set. */
int pic_anthropic_event(void *ctx, const char *event, const char *data, size_t len);
/* End of stream: 0 when a complete message was decoded (d->msg filled; a
* stream error event also counts as complete, with msg.error set), -1 when the
* stream was truncated or failed. */
int pic_anthropic_finish(pic_anthropic *d);
#endif