Skip to content
pi-c Artifact [5d6029ba8d]
Login

Artifact [5d6029ba8d]

Artifact 5d6029ba8dfeeb17b2e3d97feae65f07c5288a25c111151d3b097423f0dec953:


/* pic attach: see attach.h. Every pass reads the journal in one read
 * transaction (one snapshot), so a request's end is never seen before its
 * last entries. Events carry "seq" where they come from an entry, so a
 * client that restarts with --from its last seq sees no gap and no
 * duplicate. */
#include <errno.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "attach.h"
#include "inbox.h"
#include "pic.h"

#define ATT_KEYS 64

typedef struct {
    pic_store s;
    const pic_attach_options *o;
    char sid[64];
    long long from, last;
    long long open;   /* the request whose events are open (0: none) */
    int open_live;    /* something of it was shown, or it was running at attach */
    int open_ended;   /* its agent_end went out */
    long long *started; /* effects of the open request whose start went out */
    size_t nstarted, capstarted;
    char keys[ATT_KEYS][40]; /* -i: messages sent and not yet settled */
    char kinds[ATT_KEYS][16];
    int nkeys;
    char *in; /* -i: stdin read so far */
    size_t inlen, incap;
    int in_eof;
} att_state;

static int att_out(att_state *a, const char *line) {
    (void)a;
    if (fputs(line, stdout) == EOF || fputc('\n', stdout) == EOF || fflush(stdout) == EOF) {
        return -1;
    }
    return 0;
}

static int att_note(att_state *a, const char *fmt, const char *x, const char *y) {
    char line[1024];
    (void)snprintf(line, sizeof line, fmt, x ? x : "", y ? y : "");
    return att_out(a, line);
}

static int att_sql_fail(att_state *a) {
    fprintf(stderr, "pic: attach: %s\n", sqlite3_errmsg(a->s.db));
    return -1;
}

static int att_was_started(const att_state *a, long long effect) {
    for (size_t i = 0; i < a->nstarted; i++) {
        if (a->started[i] == effect) {
            return 1;
        }
    }
    return 0;
}

static int att_mark_started(att_state *a, long long effect) {
    if (a->nstarted == a->capstarted) {
        size_t cap = a->capstarted ? a->capstarted * 2 : 16;
        long long *grown = realloc(a->started, cap * sizeof *grown);
        if (!grown) {
            return -1;
        }
        a->started = grown;
        a->capstarted = cap;
    }
    a->started[a->nstarted++] = effect;
    return 0;
}

/* tool_execution_start for the open request's calls that have left intent:
 * those of entry ENTRY (0: of every entry shown so far), or call EFFECT
 * alone. A call whose turn came before --from is not repeated. */
static int att_tool_starts(att_state *a, long long entry, long long effect) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (sqlite3_prepare_v2(a->s.db,
                           "SELECT f.id, json_object('type', 'tool_execution_start', 'toolCallId', f.call_id, 'toolName', f.tool,"
                           " 'args', json(CASE WHEN json_valid(f.input) THEN f.input ELSE '{}' END)), f.tool,"
                           " substr(replace(coalesce(json_extract(CASE WHEN json_valid(f.input) THEN f.input END, '$.command'),"
                           " json_extract(CASE WHEN json_valid(f.input) THEN f.input END, '$.path'), ''), char(10), ' '), 1, 100)"
                           " FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq"
                           " WHERE e.submission_id = ?1 AND e.seq > ?2 AND e.seq <= ?3 AND f.state != 'intent'"
                           " AND (?4 = 0 OR e.seq = ?4) AND (?5 = 0 OR f.id = ?5) ORDER BY f.entry_seq, f.ordinal",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, a->open);
    sqlite3_bind_int64(q, 2, a->from);
    sqlite3_bind_int64(q, 3, a->last);
    sqlite3_bind_int64(q, 4, entry);
    sqlite3_bind_int64(q, 5, effect);
    while (rc == 0 && sqlite3_step(q) == SQLITE_ROW) {
        long long id = sqlite3_column_int64(q, 0);
        if (att_was_started(a, id)) {
            continue;
        }
        rc = att_mark_started(a, id);
        if (rc == 0) {
            rc = a->o->text ? att_note(a, "       -> %s %s", (const char *)sqlite3_column_text(q, 2),
                                       (const char *)sqlite3_column_text(q, 3))
                            : att_out(a, (const char *)sqlite3_column_text(q, 1));
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* agent_end for the open request once it has ended. */
static int att_maybe_end(att_state *a) {
    sqlite3_stmt *q = NULL;
    int rc = 0;
    if (!a->open || !a->open_live || a->open_ended) {
        return 0;
    }
    if (sqlite3_prepare_v2(a->s.db,
                           "SELECT status, json_patch('{}', json_object('type', 'agent_end', 'messages', json('[]'), 'request',"
                           " request_key, 'status', status, 'errorMessage', error, 'stopReason', stop_reason)),"
                           " coalesce(error, stop_reason, '') FROM pic_submission WHERE id = ?",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_int64(q, 1, a->open);
    if (sqlite3_step(q) == SQLITE_ROW && strcmp((const char *)sqlite3_column_text(q, 0), "admitted") != 0) {
        const char *status = (const char *)sqlite3_column_text(q, 0), *why = (const char *)sqlite3_column_text(q, 2);
        a->open_ended = 1;
        if (!a->o->text) {
            rc = att_out(a, (const char *)sqlite3_column_text(q, 1));
        } else if (strcmp(status, "answered") == 0) {
            rc = att_out(a, "       (done)");
        } else if (strcmp(status, "failed") == 0) {
            rc = strcmp(why, "cancelled") == 0 ? att_out(a, "       (request cancelled)")
                                               : att_note(a, "       (request failed: %s)%s", why, NULL);
        } else {
            rc = att_note(a, "       (request stopped: %s)%s", why, NULL);
        }
    }
    sqlite3_finalize(q);
    return rc;
}

/* Every entry of the conversation after the last one shown, in seq order,
 * with the events around them. */
static int att_entries(att_state *a) {
    sqlite3_stmt *q = NULL;
    int rc = 0, step;
    if (sqlite3_prepare_v2(
            a->s.db,
            "SELECT e.seq, e.kind, e.submission_id, coalesce(e.effect_id, 0),"
            " (SELECT min(x.seq) FROM pic_entry x WHERE x.submission_id = e.submission_id),"
            " json_patch('{}', json_object('type', 'agent_start', 'request', u.request_key, 'conversation', u.session_id, 'model', u.model)),"
            " CASE e.kind"
            "  WHEN 'user' THEN json_object('type', 'message_end', 'seq', e.seq, 'message', json_object('role', 'user',"
            "   'content', json_array(json_object('type', 'text', 'text', e.body))))"
            "  WHEN 'tool_result' THEN json_object('type', 'tool_execution_end', 'seq', e.seq, 'toolCallId', f.call_id,"
            "   'toolName', f.tool, 'result', json_object('content', json_array(json_object('type', 'text', 'text', e.body))),"
            "   'isError', json(iif(f.is_error, 'true', 'false')))"
            "  WHEN 'assistant' THEN NULL WHEN 'answer' THEN NULL ELSE NULL END,"
            " CASE WHEN e.kind IN ('assistant', 'answer') THEN json_object('type', 'message_end', 'seq', e.seq, 'message',"
            "   json_object('role', 'assistant', 'content', json(CASE WHEN json_valid(e.body) THEN e.body ELSE '[]' END),"
            "   'stopReason', (SELECT g.stop_reason FROM pic_generation g WHERE g.entry_seq = e.seq AND g.state = 'done' LIMIT 1),"
            "   'provider', e.provider, 'api', e.api, 'model', e.model)) END,"
            " CASE e.kind WHEN 'user' THEN e.body"
            "  WHEN 'tool_result' THEN substr(replace(e.body, char(10), ' '), 1, 100)"
            "  ELSE coalesce((SELECT group_concat(json_extract(value, '$.text'), char(10)) FROM json_each(CASE WHEN"
            "   json_valid(e.body) THEN e.body ELSE '[]' END) WHERE json_extract(value, '$.type') = 'text'), '') END,"
            " coalesce(f.is_error, 0), coalesce((SELECT a.seq FROM pic_entry a WHERE a.seq = f.entry_seq), 0),"
            " CASE WHEN e.kind = 'user' THEN json_object('type', 'message_start', 'message', json_object('role', 'user',"
            "   'content', json_array(json_object('type', 'text', 'text', e.body)))) END"
            " FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id LEFT JOIN pic_effect f ON f.id = e.effect_id"
            " AND e.kind = 'tool_result'"
            " WHERE u.session_id = ?1 AND e.seq > ?2 ORDER BY e.seq",
            -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
    sqlite3_bind_int64(q, 2, a->last);
    while (rc == 0 && (step = sqlite3_step(q)) == SQLITE_ROW) {
        long long seq = sqlite3_column_int64(q, 0), sub = sqlite3_column_int64(q, 2), effect = sqlite3_column_int64(q, 3);
        long long first = sqlite3_column_int64(q, 4), call_seq = sqlite3_column_int64(q, 10);
        const char *kind = (const char *)sqlite3_column_text(q, 1), *text = (const char *)sqlite3_column_text(q, 8);
        char tag[32];
        if (sub != a->open) {
            /* A new request: the one before it has ended. */
            if ((rc = att_maybe_end(a)) != 0) {
                break;
            }
            a->open = sub;
            a->open_live = a->open_ended = 0;
            a->nstarted = 0;
            if (first == seq && !a->o->text) {
                rc = att_out(a, (const char *)sqlite3_column_text(q, 5));
            }
        }
        a->open_live = 1;
        a->last = seq;
        (void)snprintf(tag, sizeof tag, "[%lld]", seq);
        if (rc != 0) {
            break;
        }
        if (strcmp(kind, "user") == 0) {
            if (a->o->text) {
                rc = att_note(a, "\n%s you: %s", tag, text);
            } else { /* message_start, then message_end, as the owner sends them */
                rc = att_out(a, (const char *)sqlite3_column_text(q, 11));
                if (rc == 0) {
                    rc = att_out(a, (const char *)sqlite3_column_text(q, 6));
                }
            }
        } else if (strcmp(kind, "assistant") == 0 || strcmp(kind, "answer") == 0) {
            rc = a->o->text ? (*text ? att_note(a, "%s pic: %s", tag, text) : 0) : att_out(a, (const char *)sqlite3_column_text(q, 7));
            if (rc == 0) {
                rc = att_tool_starts(a, seq, 0);
            }
        } else if (strcmp(kind, "tool_result") == 0) {
            if (call_seq > a->from && !att_was_started(a, effect)) {
                rc = att_tool_starts(a, 0, effect);
            }
            if (rc == 0) {
                rc = a->o->text ? att_note(a, sqlite3_column_int(q, 9) ? "%s    = error: %s" : "%s    = %s", tag, text)
                                : att_out(a, (const char *)sqlite3_column_text(q, 6));
            }
        }
    }
    sqlite3_finalize(q);
    if (rc == 0 && step != SQLITE_DONE && step != SQLITE_ROW) {
        return att_sql_fail(a);
    }
    return rc;
}

/* One pass over what was committed since the last. */
static int att_sync(att_state *a) {
    int rc;
    if (sqlite3_exec(a->s.db, "BEGIN", NULL, NULL, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    rc = att_entries(a);
    if (rc == 0 && a->open) {
        rc = att_tool_starts(a, 0, 0);
    }
    if (rc == 0) {
        rc = att_maybe_end(a);
    }
    (void)sqlite3_exec(a->s.db, "COMMIT", NULL, NULL, NULL);
    return rc;
}

/* -i: the messages sent that have settled since the last look. */
static int att_settled(att_state *a) {
    for (int i = 0; i < a->nkeys; i++) {
        char state[16];
        char *response = NULL;
        int rc = pic_inbox_status(&a->s, a->keys[i], state, sizeof state, &response);
        if (rc < 0) {
            return att_sql_fail(a);
        }
        if (rc == 0 && strcmp(state, "pending") == 0) {
            free(response);
            continue;
        }
        if (!a->o->text) {
            rc = response ? att_out(a, response) : 0;
        } else if (strcmp(state, "delivered") == 0) {
            rc = att_note(a, "       (%s delivered)%s", a->kinds[i], NULL);
        } else {
            char why[300] = "";
            sqlite3_stmt *q = NULL;
            if (response && sqlite3_prepare_v2(a->s.db, "SELECT coalesce(json_extract(?, '$.error'), '')", -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, response, -1, SQLITE_STATIC);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    (void)snprintf(why, sizeof why, "%s", (const char *)sqlite3_column_text(q, 0));
                }
            }
            sqlite3_finalize(q);
            rc = att_note(a, "       (%s not delivered: %s)", a->kinds[i], why[0] ? why : state);
        }
        free(response);
        if (rc != 0) {
            return -1;
        }
        memmove(a->keys[i], a->keys[i + 1], (size_t)(a->nkeys - i - 1) * sizeof a->keys[0]);
        memmove(a->kinds[i], a->kinds[i + 1], (size_t)(a->nkeys - i - 1) * sizeof a->kinds[0]);
        a->nkeys--;
        i--;
    }
    return 0;
}

/* -i: one line of stdin to the inbox. "/abort" aborts; a JSON object is
 * sent as the RPC command it is; other text is a steer while a request
 * runs, a follow-up otherwise. */
static int att_send(att_state *a, const char *text) {
    sqlite3_stmt *q = NULL;
    pic_inbox_msg m;
    char key[64], state[16], kind[16] = "";
    char *line = NULL;
    int rc;
    if (!*text) {
        return 0;
    }
    if (sqlite3_prepare_v2(a->s.db,
                           "SELECT CASE WHEN ?2 = '/abort' THEN json_object('type', 'abort')"
                           " WHEN substr(?2, 1, 1) = '{' THEN ?2"
                           " ELSE json_object('type', iif(EXISTS (SELECT 1 FROM pic_submission WHERE session_id = ?1"
                           " AND status = 'admitted'), 'steer', 'follow_up'), 'message', ?2) END",
                           -1, &q, NULL) != SQLITE_OK) {
        return att_sql_fail(a);
    }
    sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
    sqlite3_bind_text(q, 2, text, -1, SQLITE_STATIC);
    if (sqlite3_step(q) == SQLITE_ROW) {
        line = strdup((const char *)sqlite3_column_text(q, 0));
    }
    sqlite3_finalize(q);
    if (!line) {
        return att_sql_fail(a);
    }
    if (sqlite3_prepare_v2(a->s.db, "SELECT coalesce(CASE WHEN json_valid(?1) THEN json_extract(?1, '$.type') END, '')", -1, &q,
                           NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, line, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW) {
            (void)snprintf(kind, sizeof kind, "%s", (const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    memset(&m, 0, sizeof m);
    m.session = a->sid;
    m.line = line;
    m.sender = "attach";
    rc = pic_inbox_accept(&a->s, &m, key, sizeof key, state, sizeof state);
    free(line);
    if (rc != 0) {
        if (rc < 0) {
            fprintf(stderr, "pic: attach: %s\n", a->s.err);
            return -1;
        }
        return a->o->text ? att_note(a, "       (not sent: %s)%s", a->s.err, NULL)
                          : (fprintf(stderr, "pic: attach: %s\n", a->s.err), 0);
    }
    if (a->o->text && strcmp(kind, "follow_up") == 0) {
        rc = att_out(a, "       (follow-up sent: it runs when a request next runs here)");
    } else if (a->o->text) {
        rc = att_note(a, "       (%s sent)%s", kind, NULL);
    }
    if (a->nkeys < ATT_KEYS) {
        (void)snprintf(a->keys[a->nkeys], sizeof a->keys[0], "%s", key);
        (void)snprintf(a->kinds[a->nkeys], sizeof a->kinds[0], "%s", kind[0] ? kind : "message");
        a->nkeys++;
    }
    return rc;
}

/* -i: what stdin has, each complete line sent. */
static int att_read(att_state *a) {
    ssize_t n;
    if (a->incap - a->inlen < 4097) {
        size_t cap = a->incap ? a->incap * 2 : 8192;
        char *grown = cap > PIC_INBOX_LINE_CAP + 8192 ? NULL : realloc(a->in, cap);
        if (!grown) {
            fprintf(stderr, "pic: attach: a line longer than 16 MB\n");
            return -1;
        }
        a->in = grown;
        a->incap = cap;
    }
    n = read(STDIN_FILENO, a->in + a->inlen, a->incap - a->inlen - 1);
    if (n < 0) {
        return errno == EINTR || errno == EAGAIN ? 0 : -1;
    }
    if (n == 0) {
        a->in_eof = 1;
        if (a->inlen) { /* the last line, without its newline */
            a->in[a->inlen++] = '\n';
        }
    }
    a->inlen += (size_t)n;
    for (;;) {
        char *nl = memchr(a->in, '\n', a->inlen);
        size_t len;
        int rc;
        if (!nl) {
            break;
        }
        len = (size_t)(nl - a->in);
        *nl = '\0';
        if (len && a->in[len - 1] == '\r') {
            a->in[len - 1] = '\0';
        }
        rc = att_send(a, a->in);
        memmove(a->in, nl + 1, a->inlen - len - 1);
        a->inlen -= len + 1;
        if (rc != 0) {
            return -1;
        }
    }
    return 0;
}

/* -i at the end of input: messages still to settle. A follow-up sent while
 * nothing ran waits for a request that may be a day away; it is left. */
static int att_waiting(const att_state *a) {
    int n = 0;
    for (int i = 0; i < a->nkeys; i++) {
        n += strcmp(a->kinds[i], "follow_up") != 0;
    }
    return n;
}

static long long att_data_version(att_state *a) {
    sqlite3_stmt *q = NULL;
    long long v = -1;
    if (sqlite3_prepare_v2(a->s.db, "PRAGMA data_version", -1, &q, NULL) == SQLITE_OK && sqlite3_step(q) == SQLITE_ROW) {
        v = sqlite3_column_int64(q, 0);
    }
    sqlite3_finalize(q);
    return v;
}

/* Where to start: the latest request's first entry, unless --from says. A
 * request running at the start counts as shown, so its end is shown. */
static int att_start(att_state *a) {
    sqlite3_stmt *q = NULL;
    if (a->o->from < 0) {
        if (sqlite3_prepare_v2(a->s.db,
                               "SELECT coalesce((SELECT min(e.seq) - 1 FROM pic_entry e WHERE e.submission_id ="
                               " (SELECT max(id) FROM pic_submission WHERE session_id = ?1)), 0)",
                               -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
        a->from = sqlite3_step(q) == SQLITE_ROW ? sqlite3_column_int64(q, 0) : 0;
        sqlite3_finalize(q);
    } else {
        a->from = a->o->from;
    }
    a->last = a->from;
    if (a->from > 0) {
        if (sqlite3_prepare_v2(a->s.db,
                               "SELECT u.id, u.status = 'admitted' FROM pic_entry e JOIN pic_submission u ON u.id = e.submission_id"
                               " WHERE u.session_id = ?1 AND e.seq <= ?2 ORDER BY e.seq DESC LIMIT 1",
                               -1, &q, NULL) != SQLITE_OK) {
            return att_sql_fail(a);
        }
        sqlite3_bind_text(q, 1, a->sid, -1, SQLITE_STATIC);
        sqlite3_bind_int64(q, 2, a->from);
        if (sqlite3_step(q) == SQLITE_ROW) {
            a->open = sqlite3_column_int64(q, 0);
            a->open_live = sqlite3_column_int(q, 1);
        }
        sqlite3_finalize(q);
    }
    return 0;
}

int pic_attach_main(const pic_attach_options *o) {
    att_state a;
    long long seen = -2;
    int rc = 0;
    memset(&a, 0, sizeof a);
    a.o = o;
    if (pic_open_narrow(&a.s, o->db) != 0 || pic_session_resolve(&a.s, o->session, a.sid, sizeof a.sid) != 0 ||
        att_start(&a) != 0) {
        fprintf(stderr, "pic: attach: %s\n", a.s.err[0] ? a.s.err : "cannot read the journal");
        pic_close(&a.s);
        return 1;
    }
    if (o->text) {
        rc = att_note(&a, "pic: attached to %s (read-only%s)", a.sid, o->interactive ? "; lines you type are sent to it" : "");
    }
    while (rc == 0) {
        long long v = att_data_version(&a);
        struct pollfd p = {o->interactive && !a.in_eof ? STDIN_FILENO : -1, POLLIN, 0};
        if (v != seen) {
            seen = v;
            rc = att_sync(&a);
            if (rc == 0 && a.nkeys) {
                rc = att_settled(&a);
            }
        }
        if (rc != 0) {
            break;
        }
        /* Done: --no-follow once caught up; -i once stdin has ended and
         * every message it sent has settled. */
        if (o->interactive ? a.in_eof && !att_waiting(&a) : !o->follow) {
            break;
        }
        if (poll(&p, 1, 100) > 0 && p.revents) {
            rc = att_read(&a);
            seen = -2; /* look at once: a sent message may settle quickly */
        }
    }
    free(a.started);
    free(a.in);
    pic_close(&a.s);
    return rc == 0 ? 0 : 1;
}