Skip to content
pi-c Artifact [a6a15479a0]
Login

Artifact [a6a15479a0]

Artifact a6a15479a0870d485a12a792592f3686df472cdee16ed214c85abc5151dcf63e:


/* Goals: see goal.h. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "goal.h"
#include "userdb.h"
#include "wake.h"

/* SQL's first text column over FACTS (?1), malloc'd; NULL when none. */
static char *goal_text(sqlite3 *db, const char *sql, const char *facts) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, facts, -1, SQLITE_STATIC);
        if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
            out = strdup((const char *)sqlite3_column_text(q, 0));
        }
    }
    sqlite3_finalize(q);
    return out;
}

/* A check that exits 0 meets the goal; without one, the model's word does. A round that changed no
 * file and ran no command, or whose check said what it said last time (or was cut off), made no
 * progress: a stall. Blocked needs the person. */
static int goal_answer(sqlite3 *db, int64_t submission, int64_t ref, const char *facts, pic_hook_answer *a) {
    (void)submission;
    (void)ref;
    a->context = goal_text(
        db,
        "SELECT json_object('goal', CASE WHEN json_type(?1, '$.check') = 'object' AND json_extract(?1, '$.check.exitCode') = 0"
        " THEN 'done' WHEN json_type(?1, '$.check') IS NOT 'object' AND json_extract(?1, '$.declared.state') = 'done' THEN 'done'"
        " WHEN json_extract(?1, '$.declared.state') = 'blocked' THEN 'needs' ELSE 'continue' END, 'stall', json(iif("
        " NOT json_extract(?1, '$.worked') OR (json_type(?1, '$.check') = 'object' AND (json_extract(?1, '$.check.same')"
        " OR json_type(?1, '$.check.exitCode') IS NULL)), 'true', 'false')))",
        facts);
    a->reason = goal_text(db,
                          "SELECT CASE WHEN json_type(?1, '$.check') = 'object' AND json_extract(?1, '$.check.exitCode') = 0 THEN"
                          " 'met: `' || json_extract(?1, '$.check.command') || '` passed'"
                          " WHEN json_type(?1, '$.check') IS NOT 'object' AND json_extract(?1, '$.declared.state') = 'done' THEN"
                          " 'declared done, not checked: ' || coalesce(json_extract(?1, '$.declared.reason'), '')"
                          " WHEN json_extract(?1, '$.declared.state') = 'blocked' THEN 'blocked: ' ||"
                          " coalesce(json_extract(?1, '$.declared.reason'), '') ELSE 'not met yet' END",
                          facts);
    return a->context ? 0 : -1;
}

const pic_stop_policy pic_goal_policy = {"goal", goal_answer};

/* ---- the wake tool ------------------------------------------------------------------------------ */

static const char goal_schema[] =
    "{\"name\":\"wake\",\"description\":\"Work that runs on its own in this conversation. action monitor: run command in the "
    "background; each new line it prints wakes you with that line (done: true wakes you once, when it exits, with its status: "
    "'tell me when the build finishes'). action loop: send prompt to this conversation every interval (every: '5m', 1m to 7d; "
    "none: you pace it with loop_next). action goal: keep working in rounds until condition is true; check is a shell command "
    "that exits 0 once it is (without one, you end it with goal_done). A loop or a goal waits for the user's OK, which pic "
    "asks for itself: it starts only if they approve, and a message tells you their answer. action loop_next: the loop that sent this request runs next "
    "in seconds (60 to 3600). action goal_done or goal_blocked: this conversation's goal is met, or cannot be met, with "
    "reason.\",\"input_schema\":{\"type\":\"object\",\"properties\":{"
    "\"action\":{\"type\":\"string\",\"enum\":[\"monitor\",\"loop\",\"goal\",\"loop_next\",\"goal_done\",\"goal_blocked\"]},"
    "\"command\":{\"type\":\"string\",\"description\":\"monitor: the shell command\"},"
    "\"done\":{\"type\":\"boolean\",\"description\":\"monitor: wake once, when the command exits\"},"
    "\"prompt\":{\"type\":\"string\",\"description\":\"loop: what each run sends\"},"
    "\"every\":{\"type\":\"string\",\"description\":\"loop: the interval, as 5m, 90s, 2h\"},"
    "\"condition\":{\"type\":\"string\",\"description\":\"goal: what is true when it is met\"},"
    "\"check\":{\"type\":\"string\",\"description\":\"goal: a command that exits 0 when it is met\"},"
    "\"seconds\":{\"type\":\"integer\",\"description\":\"loop_next: when the loop runs next\"},"
    "\"reason\":{\"type\":\"string\",\"description\":\"goal_done, goal_blocked: why\"}},"
    "\"required\":[\"action\"]}}";

static int goal_default(void) {
    char *v = pic_setting("loops.tool");
    int off = v && (strcmp(v, "false") == 0 || strcmp(v, "off") == 0 || strcmp(v, "0") == 0);
    free(v);
    return !off;
}

static char *goal_say(int *is_error, int error, const char *text) {
    *is_error = error;
    return strdup(text);
}

static char *goal_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
                      const pic_tool_hooks *hooks, int *is_error) {
    pic_store s;
    char *action = NULL, *res = NULL;
    long long submission = 0;
    (void)state;
    (void)tool;
    *is_error = 0;
    if (hooks->started == NULL || hooks->started(hooks->ctx, NULL, 0) != 0) {
        return NULL;
    }
    if (args->bad_input) {
        return goal_say(is_error, 1, args->bad_input);
    }
    if (!hooks->journal || !hooks->input) {
        return goal_say(is_error, 1, "wake runs only inside a pic request");
    }
    if (pic_open_narrow(&s, hooks->journal) != 0) {
        char err[PIC_ERR_CAP + 40];
        (void)snprintf(err, sizeof err, "cannot read this conversation's journal: %s", s.err);
        pic_close(&s);
        return goal_say(is_error, 1, err);
    }
    {
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s.db,
                               "SELECT e.submission_id FROM pic_effect f JOIN pic_entry e ON e.seq = f.entry_seq WHERE f.id = ?1", -1,
                               &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, hooks->effect);
            if (sqlite3_step(q) == SQLITE_ROW) {
                submission = sqlite3_column_int64(q, 0);
            }
        }
        sqlite3_finalize(q);
    }
    action = goal_text(s.db, "SELECT CASE json_type(?1, '$.action') WHEN 'text' THEN json_extract(?1, '$.action') END", hooks->input);
    if (!submission) {
        res = goal_say(is_error, 1, "cannot read this call in the journal");
    } else if (!action) {
        res = goal_say(is_error, 1, "wake needs an action: monitor, loop, goal, loop_next, goal_done or goal_blocked");
    } else if (strcmp(action, "goal_done") == 0 || strcmp(action, "goal_blocked") == 0) {
        char *reason = goal_text(s.db, "SELECT json_extract(?1, '$.reason')", hooks->input);
        int rc = pic_wake_goal_declare(&s, submission, action[5] == 'd' ? "done" : "blocked", reason);
        res = rc == 0 ? goal_say(is_error, 0, action[5] == 'd' ? "Recorded: when this request ends, the goal ends as done."
                                                              : "Recorded: when this request ends, the goal waits for the user.")
                      : goal_say(is_error, 1, s.err);
        free(reason);
    } else if (strcmp(action, "loop_next") == 0) {
        char *sec = goal_text(s.db, "SELECT CASE json_type(?1, '$.seconds') WHEN 'integer' THEN json_extract(?1, '$.seconds') END",
                              hooks->input);
        int rc = sec ? pic_wake_loop_next(&s, submission, strtoll(sec, NULL, 10) * 1000) : 1;
        if (!sec) {
            (void)snprintf(s.err, sizeof s.err, "loop_next needs seconds (60 to 3600)");
        }
        res = rc == 0 ? goal_say(is_error, 0, "The loop runs next then.") : goal_say(is_error, 1, s.err);
        free(sec);
    } else if (strcmp(action, "monitor") == 0 || strcmp(action, "loop") == 0 || strcmp(action, "goal") == 0) {
        char *session = NULL;
        char *every = goal_text(s.db, "SELECT json_extract(?1, '$.every')", hooks->input);
        char *text = goal_text(s.db, strcmp(action, "goal") == 0 ? "SELECT json_extract(?1, '$.condition')" : "SELECT json_extract(?1, '$.prompt')",
                               hooks->input);
        char *command = goal_text(s.db, strcmp(action, "goal") == 0 ? "SELECT json_extract(?1, '$.check')" : "SELECT json_extract(?1, '$.command')",
                                  hooks->input);
        char *done = goal_text(s.db, "SELECT json_extract(?1, '$.done')", hooks->input);
        sqlite3_stmt *q = NULL;
        if (sqlite3_prepare_v2(s.db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_int64(q, 1, submission);
            if (sqlite3_step(q) == SQLITE_ROW) {
                session = strdup((const char *)sqlite3_column_text(q, 0));
            }
        }
        sqlite3_finalize(q);
        {
            pic_wake_new w;
            long long id = 0, ms = 0;
            char sid[64], msg[400];
            memset(&w, 0, sizeof w);
            w.session = session;
            w.kind = action;
            w.creator = "model";
            w.workspace = workspace;
            w.ask = strcmp(action, "monitor") != 0; /* a loop or a goal waits for the person's OK */
            if (strcmp(action, "monitor") == 0) {
                w.command = command;
                w.done = done && strcmp(done, "1") == 0;
            } else if (strcmp(action, "loop") == 0) {
                w.prompt = text;
                if (every && pic_wake_parse_every(every, &ms) != 0) {
                    ms = -1;
                }
                w.every_ms = ms;
            } else {
                w.prompt = text;
                w.check = command;
            }
            if (ms < 0) {
                res = goal_say(is_error, 1, "every is an interval: 5m, 90s, 2h, 1d");
            } else if (pic_wake_create(&s, &w, &id, sid, sizeof sid) != 0) {
                res = goal_say(is_error, 1, s.err);
            } else if (w.ask) {
                (void)snprintf(msg, sizeof msg,
                               "%s %c%lld is waiting for the user's OK: pic asks them, and it starts only if they approve. A message"
                               " tells you their answer; do not ask again or start it another way.",
                               action[0] == 'l' ? "Loop" : "Goal", action[0] == 'l' ? 'L' : 'G', id);
                res = goal_say(is_error, 0, msg);
            } else {
                (void)snprintf(msg, sizeof msg, "Monitor M%lld started. The user sees it in the footer and stops it with /loop stop M%lld.",
                               id, id);
                res = goal_say(is_error, 0, msg);
            }
        }
        free(session);
        free(every);
        free(text);
        free(command);
        free(done);
    } else {
        res = goal_say(is_error, 1, "wake's actions are monitor, loop, goal, loop_next, goal_done and goal_blocked");
    }
    pic_close(&s);
    free(action);
    return res ? res : goal_say(is_error, 1, "out of memory");
}

/* Not replay-safe: a call cut off by a crash may have started its monitor, so it is never run again. */
const pic_tool_def pic_wake_tool = {"wake", goal_schema, 0, 0, PIC_TIER_BUNDLED, 1, goal_default, goal_run, NULL};