Skip to content
pi-c Documentation
Login

Documentation

/* Scripted provider. The reply for a turn depends only on the script, the turn
 * number and the attempt, so a restarted process asks for, and gets, the same
 * reply. It produces Messages API content blocks, so the journal and the
 * request builder see the same shapes as with the real provider.
 *
 * Script lines, one per turn:
 *   text ANSWER                    the final answer
 *   tool write PATH CONTENT        one tool call; several calls in one turn
 *   tool exec COMMAND              are separated by TABs (exec is bash);
 *   tool raw NAME JSON             any tool with a JSON input
 *   flaky K LINE                   attempts 1..K fail (retryable), then LINE
 *   reject MESSAGE                 a non-retryable provider failure
 *   refuse                         stop_reason refusal */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pic.h"

#define PIC_SCRIPT_LINE_CAP 8192

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;
}

/* SELECT returning one text value with up to four text arguments. */
static char *sql_text(pic_store *s, const char *sql, const char *a, const char *b, const char *c, const char *d) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    const char *args[4] = {a, b, c, d};
    if (sqlite3_prepare_v2(s->db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    for (int i = 0; i < 4 && i < sqlite3_bind_parameter_count(q); i++) {
        sqlite3_bind_text(q, i + 1, args[i], -1, SQLITE_STATIC);
    }
    if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
        out = dup_string((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    return out;
}

/* One call as a tool_use block: "write PATH CONTENT", "exec COMMAND" or
 * "bash COMMAND", or "raw NAME JSON" for any tool and input. */
static char *tool_block(pic_store *s, char *call, const char *id) {
    char *space = strchr(call, ' ');
    if (!space) {
        return NULL;
    }
    *space = '\0';
    if (strcmp(call, "write") == 0 || strcmp(call, "raw") == 0) {
        char *name = space + 1, *rest = strchr(name, ' ');
        if (!rest) {
            return NULL;
        }
        *rest++ = '\0';
        if (strcmp(call, "raw") == 0) {
            return sql_text(s,
                            "SELECT CASE WHEN json_valid(?3) THEN json_object('type','tool_use','id',?1,'name',?2,"
                            "'input',json(?3)) END",
                            id, name, rest, NULL);
        }
        return sql_text(s,
                        "SELECT json_object('type','tool_use','id',?1,'name','write','input',"
                        "json_object('path',?2,'content',?3))",
                        id, name, rest, NULL);
    }
    if (strcmp(call, "exec") != 0 && strcmp(call, "bash") != 0) {
        return NULL;
    }
    return sql_text(s, "SELECT json_object('type','tool_use','id',?1,'name','bash','input',json_object('command',?2))",
                    id, space + 1, NULL, NULL);
}

static int reply_line(pic_store *s, char *line, int64_t turn, int64_t attempt, pic_reply *out, int *retryable,
                      char *err, size_t errcap) {
    if (strncmp(line, "flaky ", 6) == 0) {
        char *end;
        long k = strtol(line + 6, &end, 10);
        if (end == line + 6 || *end != ' ') {
            (void)snprintf(err, errcap, "script flaky line needs a count");
            return -1;
        }
        if (attempt <= k) {
            *retryable = 1;
            (void)snprintf(err, errcap, "scripted transient failure on attempt %lld", (long long)attempt);
            return -1;
        }
        return reply_line(s, end + 1, turn, attempt, out, retryable, err, errcap);
    }
    if (strncmp(line, "reject ", 7) == 0) {
        (void)snprintf(err, errcap, "scripted rejection: %.200s", line + 7);
        return -1;
    }
    if (strcmp(line, "refuse") == 0) {
        out->native = dup_string("[]");
        out->stop_reason = dup_string("refusal");
        return out->native && out->stop_reason ? 0 : -1;
    }
    if (strncmp(line, "text ", 5) == 0) {
        out->native = sql_text(s, "SELECT json_array(json_object('type','text','text',?1))", line + 5, NULL, NULL, NULL);
        out->stop_reason = dup_string("stop");
        return out->native && out->stop_reason ? 0 : -1;
    }
    if (strncmp(line, "tool ", 5) == 0) {
        char *content = dup_string("[]"), *call = line + 5;
        for (int ordinal = 0; call && content; ordinal++) {
            char *next = strchr(call, '\t'), id[64], *block, *grown;
            if (next) {
                *next++ = '\0';
            }
            (void)snprintf(id, sizeof id, "toolu_fake_%lld_%d", (long long)turn, ordinal);
            block = tool_block(s, call, id);
            if (!block) {
                free(content);
                (void)snprintf(err, errcap, "malformed script tool call");
                return -1;
            }
            grown = sql_text(s, "SELECT json_insert(?1, '$[#]', json(?2))", content, block, NULL, NULL);
            free(block);
            free(content);
            content = grown;
            call = next;
        }
        out->native = content;
        out->stop_reason = dup_string("toolUse");
        return out->native && out->stop_reason ? 0 : -1;
    }
    (void)snprintf(err, errcap, "unrecognized script line: %.60s", line);
    return -1;
}

static int script_reply(pic_provider *p, pic_store *s, int64_t submission, int64_t turn, pic_reply *out, int *retryable,
                        char *err, size_t errcap) {
    char line[PIC_SCRIPT_LINE_CAP];
    FILE *f = fopen(p->state, "r");
    int64_t index = 0, attempt = 0;
    sqlite3_stmt *q = NULL;
    int rc = -1;
    *retryable = 0;
    if (!f) {
        (void)snprintf(err, errcap, "cannot open script %s", (const char *)p->state);
        return -1;
    }
    if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_generation WHERE submission_id=? AND turn=? AND purpose='reply'", -1, &q,
                           NULL) == SQLITE_OK) {
        sqlite3_bind_int64(q, 1, submission);
        sqlite3_bind_int64(q, 2, turn);
        if (sqlite3_step(q) == SQLITE_ROW) {
            attempt = sqlite3_column_int64(q, 0);
        }
        sqlite3_finalize(q);
    }
    while (fgets(line, sizeof line, f)) {
        if (index++ == turn) {
            line[strcspn(line, "\n")] = '\0';
            rc = reply_line(s, line, turn, attempt, out, retryable, err, errcap);
            /* Script replies are Anthropic-shaped; their origin is the script. */
            if (rc == 0) {
                out->neutral = pic_neutral_from_anthropic(s->db, out->native);
                out->provider = dup_string("script");
                out->api = dup_string("anthropic-messages");
                out->model = dup_string("script");
                rc = out->neutral && out->provider && out->api && out->model ? 0 : -1;
            }
            break;
        }
    }
    if (index <= turn) {
        (void)snprintf(err, errcap, "script has no reply for turn %lld", (long long)turn);
    }
    fclose(f);
    if (rc != 0) {
        pic_reply_free(out);
    }
    return rc;
}

/* A fixed summary, so scripted runs compact without a network. */
static int script_summarize(pic_provider *p, pic_store *s, const char *system, const char *user, char **text,
                            char **usage, int *retryable, char *err, size_t errcap) {
    (void)p;
    (void)s;
    (void)system;
    (void)err;
    (void)errcap;
    *retryable = 0;
    *usage = NULL;
    *text = dup_string(strstr(user, "<previous-summary>") ? "scripted summary, updated" : "scripted summary");
    return *text ? 0 : -1;
}

static void script_free(pic_provider *p) {
    free(p->state);
    p->state = NULL;
}

int pic_provider_script(pic_provider *p, const char *script) {
    p->reply = script_reply;
    p->summarize = script_summarize;
    p->count = NULL;
    (void)snprintf(p->model, sizeof p->model, "script");
    p->cache_seconds = pic_cache_seconds(NULL);
    p->free = script_free;
    p->state = dup_string(script);
    return p->state ? 0 : -1;
}