Skip to content
pi-c Artifact [b9cdf6eefe]
Login

Artifact [b9cdf6eefe]

Artifact b9cdf6eefe32a2dda35e94415568ea92464063595d7aeb1cbd636c0474c5d481:


/* The codemode tool: Pi's codemode (packages/coding-agent/src/extensions/codemode) on Bellard's
 * QuickJS. A call's script runs in a worker, pic itself exec'd as `pic __codemode-worker` with no
 * environment, no database handle and nothing open but descriptor 3, a socket to the call. The
 * worker owns the VM: 256 MB of heap, a 1 MB stack, the script's deadline and Ctrl-C through
 * QuickJS's interrupt handler, no timers, network or files. Every tool call the script makes comes
 * back to the call over the socket, and the call runs each round of them through
 * pic_tool_hooks.call, so the loop journals, gates and runs them as calls nested in this one
 * (loop.c). Only the script's output is the call's result.
 *
 * Frames both ways are a type byte, a 64-bit length and that many bytes (toolpar.c's shape):
 *   to the worker:  I  the call's JSON input and the tool catalog (JSON), as two byte strings
 *                   R  a round's results: a count, then for each its id, ok and payload (the
 *                      value as JSON, or the error's text)
 *   from it:        T  the script's options, "TIMEOUT_MS MAX_OUTPUT_TOKENS" (-1: not given)
 *                   C  a tool call: its id, the tool's name and its arguments as JSON
 *                   W  the script waits on the calls sent since the last W
 *                   D  the end: {ok, body, images, calls}, or {invalid} for input it refused */
#include "codemode.h"

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include "image.h"
#include "platform.h"
#include "quickjs.h"
#include "rpc.h"
#include "sqlite3.h"
#include "userdb.h"

#include "codemode_js.inc"

#define CM_NONE UINT64_MAX
#define CM_FRAME_MAX ((uint64_t)256 << 20)
#define CM_HEAP ((size_t)256 << 20)
#define CM_STACK ((size_t)1 << 20)
#define CM_MAX_CALLS 256
#define CM_DEFAULT_TOKENS 10000
#define CM_CHARS_PER_TOKEN 4
#define CM_INLINE_BUDGET 3000 /* Pi's codemode.inlineBudget, in estimated tokens */

/* ---- frames ------------------------------------------------------------------------------------ */

typedef struct {
    char *p;
    size_t n, cap;
    int bad;
} cm_buf;

static void cm_put(cm_buf *b, const void *src, size_t n) {
    if (b->bad || n == 0) {
        return;
    }
    if (b->n + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 256;
        char *grown;
        while (cap < b->n + n + 1) {
            cap *= 2;
        }
        if (!(grown = realloc(b->p, cap))) {
            b->bad = 1;
            return;
        }
        b->p = grown;
        b->cap = cap;
    }
    memcpy(b->p + b->n, src, n);
    b->n += n;
    b->p[b->n] = '\0';
}

static void cm_puts(cm_buf *b, const char *s) { cm_put(b, s, strlen(s)); }

static void cm_put_u64(cm_buf *b, uint64_t v) { cm_put(b, &v, sizeof v); }

static void cm_put_bytes(cm_buf *b, const void *src, size_t n) {
    cm_put_u64(b, src ? (uint64_t)n : CM_NONE);
    cm_put(b, src, n);
}

static int cm_write_all(int fd, const void *p, size_t n) {
    const char *c = p;
    while (n > 0) {
        ssize_t w = write(fd, c, n);
        if (w < 0 && errno == EINTR) {
            continue;
        }
        if (w <= 0) {
            return -1;
        }
        c += w;
        n -= (size_t)w;
    }
    return 0;
}

static int cm_read_all(int fd, void *p, size_t n) {
    char *c = p;
    while (n > 0) {
        ssize_t r = read(fd, c, n);
        if (r < 0 && errno == EINTR) {
            continue;
        }
        if (r <= 0) {
            return -1;
        }
        c += r;
        n -= (size_t)r;
    }
    return 0;
}

static int cm_send(int fd, char type, const void *payload, size_t n) {
    uint64_t len = n;
    return cm_write_all(fd, &type, 1) || cm_write_all(fd, &len, sizeof len) || (n && cm_write_all(fd, payload, n)) ? -1 : 0;
}

/* The next frame: its type, and its payload (malloc'd, NUL after *len bytes). -1 at EOF. */
static int cm_recv(int fd, char *type, char **payload, size_t *len) {
    uint64_t n = 0;
    *payload = NULL;
    if (cm_read_all(fd, type, 1) != 0 || cm_read_all(fd, &n, sizeof n) != 0 || n > CM_FRAME_MAX ||
        !(*payload = malloc((size_t)n + 1))) {
        return -1;
    }
    if (cm_read_all(fd, *payload, (size_t)n) != 0) {
        free(*payload);
        *payload = NULL;
        return -1;
    }
    (*payload)[n] = '\0';
    *len = (size_t)n;
    return 0;
}

typedef struct {
    const char *p;
    size_t n, at;
    int bad;
} cm_rd;

static uint64_t cm_get_u64(cm_rd *r) {
    uint64_t v = 0;
    if (r->bad || r->n - r->at < sizeof v) {
        r->bad = 1;
        return 0;
    }
    memcpy(&v, r->p + r->at, sizeof v);
    r->at += sizeof v;
    return v;
}

static char *cm_get_bytes(cm_rd *r, size_t *len) {
    uint64_t n = cm_get_u64(r);
    char *out;
    if (r->bad || n == CM_NONE) {
        return NULL;
    }
    if (n > r->n - r->at || !(out = malloc((size_t)n + 1))) {
        r->bad = 1;
        return NULL;
    }
    memcpy(out, r->p + r->at, (size_t)n);
    out[n] = '\0';
    r->at += (size_t)n;
    if (len) {
        *len = (size_t)n;
    }
    return out;
}

static long long cm_now_ms(void) {
    struct timespec t;
    (void)clock_gettime(CLOCK_MONOTONIC, &t);
    return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}

/* ---- the description and the catalog ------------------------------------------------------------ */

/* One text value of SQL over up to two text parameters (malloc'd), or NULL. */
static char *cm_sql_text(sqlite3 *db, const char *sql, const char *a, const char *b) {
    sqlite3_stmt *q = NULL;
    char *out = NULL;
    if (sqlite3_prepare_v2(db, sql, -1, &q, NULL) != SQLITE_OK) {
        return NULL;
    }
    if (sqlite3_bind_parameter_count(q) >= 1) {
        sqlite3_bind_text(q, 1, a, -1, SQLITE_STATIC);
    }
    if (sqlite3_bind_parameter_count(q) >= 2) {
        sqlite3_bind_text(q, 2, b, -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;
}

/* Pi's toCodemodeIdentifier: what is not valid in a JavaScript identifier becomes _. */
static void cm_identifier(const char *name, char *out, size_t cap) {
    size_t i = 0;
    for (; name[i] && i + 1 < cap; i++) {
        char c = name[i];
        int ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == '$' || (i > 0 && c >= '0' && c <= '9');
        out[i] = ok ? c : '_';
    }
    if (i == 0 && cap > 1) {
        out[i++] = '_';
    }
    out[i] = '\0';
}

/* A JSON schema as a TypeScript type, as Pi's schemaToType renders it in short: objects on one line
 * with their properties by name, or one per line with a // comment when a property has a
 * description; Array<T>; unions for enum, anyOf and oneOf; unknown past four levels. */
static void cm_type(sqlite3 *db, const char *js_schema, int depth, cm_buf *out) {
    sqlite3_stmt *q = NULL;
    char *type = NULL, *items = NULL;
    int n = 0;
    if (!js_schema || depth > 4) {
        cm_puts(out, "unknown");
        return;
    }
    if (sqlite3_prepare_v2(db, "SELECT value FROM json_each(?1, '$.enum')", -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, js_schema, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            sqlite3_stmt *v = NULL;
            cm_puts(out, n++ ? " | " : "");
            if (sqlite3_prepare_v2(db, "SELECT json_quote(?1)", -1, &v, NULL) == SQLITE_OK) {
                sqlite3_bind_value(v, 1, sqlite3_column_value(q, 0));
                if (sqlite3_step(v) == SQLITE_ROW && sqlite3_column_text(v, 0)) {
                    cm_puts(out, (const char *)sqlite3_column_text(v, 0));
                }
            }
            sqlite3_finalize(v);
        }
    }
    sqlite3_finalize(q);
    if (n) {
        return;
    }
    if (sqlite3_prepare_v2(db, "SELECT value FROM json_each(coalesce(json_extract(?1, '$.anyOf'), json_extract(?1, '$.oneOf')))",
                           -1, &q, NULL) == SQLITE_OK) {
        sqlite3_bind_text(q, 1, js_schema, -1, SQLITE_STATIC);
        while (sqlite3_step(q) == SQLITE_ROW) {
            cm_puts(out, n++ ? " | " : "");
            cm_type(db, (const char *)sqlite3_column_text(q, 0), depth + 1, out);
        }
    }
    sqlite3_finalize(q);
    if (n) {
        return;
    }
    type = cm_sql_text(db,
                       "SELECT CASE json_type(?1, '$.type') WHEN 'text' THEN json_extract(?1, '$.type')"
                       " WHEN 'array' THEN json_extract(?1, '$.type[0]')"
                       " ELSE CASE WHEN json_type(?1, '$.properties') = 'object' THEN 'object' END END",
                       js_schema, NULL);
    if (!type) {
        cm_puts(out, "unknown");
    } else if (strcmp(type, "string") == 0 || strcmp(type, "boolean") == 0 || strcmp(type, "null") == 0) {
        cm_puts(out, type);
    } else if (strcmp(type, "number") == 0 || strcmp(type, "integer") == 0) {
        cm_puts(out, "number");
    } else if (strcmp(type, "array") == 0) {
        items = cm_sql_text(db, "SELECT json_extract(?1, '$.items')", schema, NULL);
        cm_puts(out, "Array<");
        cm_type(db, items, depth + 1, out);
        cm_puts(out, ">");
    } else if (strcmp(type, "object") == 0) {
        int lines = 0, count = 0;
        char pad[16];
        (void)snprintf(pad, sizeof pad, "%*s", (depth + 1) * 2, "");
        if (sqlite3_prepare_v2(db,
                               "SELECT count(*), count(json_extract(value, '$.description')) FROM json_each(?1, '$.properties')",
                               -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, js_schema, -1, SQLITE_STATIC);
            if (sqlite3_step(q) == SQLITE_ROW) {
                count = sqlite3_column_int(q, 0);
                lines = sqlite3_column_int(q, 1) > 0;
            }
        }
        sqlite3_finalize(q);
        if (!count) {
            cm_puts(out, "Record<string, unknown>");
        } else if (sqlite3_prepare_v2(db,
                                      "SELECT key, value, key IN (SELECT value FROM json_each(?1, '$.required')),"
                                      " replace(replace(json_extract(value, '$.description'), char(10), ' '), char(13), ' ')"
                                      " FROM json_each(?1, '$.properties') ORDER BY key",
                                      -1, &q, NULL) == SQLITE_OK) {
            sqlite3_bind_text(q, 1, js_schema, -1, SQLITE_STATIC);
            cm_puts(out, lines ? "{\n" : "{ ");
            while (sqlite3_step(q) == SQLITE_ROW) {
                const char *key = (const char *)sqlite3_column_text(q, 0), *doc = (const char *)sqlite3_column_text(q, 3);
                char id[128];
                cm_identifier(key, id, sizeof id);
                if (lines) {
                    cm_puts(out, pad);
                }
                if (strcmp(id, key) == 0) {
                    cm_puts(out, key);
                } else {
                    char *quoted = cm_sql_text(db, "SELECT json_quote(?1)", key, NULL);
                    cm_puts(out, quoted ? quoted : key);
                    free(quoted);
                }
                cm_puts(out, sqlite3_column_int(q, 2) ? ": " : "?: ");
                cm_type(db, (const char *)sqlite3_column_text(q, 1), depth + 1, out);
                cm_puts(out, ";");
                if (lines && doc && *doc) {
                    cm_puts(out, " // ");
                    cm_puts(out, doc);
                }
                cm_puts(out, lines ? "\n" : " ");
            }
            sqlite3_finalize(q);
            if (lines) {
                (void)snprintf(pad, sizeof pad, "%*s", depth * 2, "");
                cm_puts(out, pad);
            }
            cm_puts(out, "}");
        }
    } else {
        cm_puts(out, "unknown");
    }
    free(type);
    free(items);
}

/* Pi's renderToolSample: the description, then the tool as a member of `tools`. */
static char *cm_sample(sqlite3 *db, const char *name, const char *js_schema) {
    cm_buf b = {NULL, 0, 0, 0};
    char id[128], *desc = cm_sql_text(db, "SELECT trim(json_extract(?1, '$.description'))", schema, NULL),
                  *input = cm_sql_text(db, "SELECT coalesce(json_extract(?1, '$.input_schema'), json_extract(?1, '$.parameters'))",
                                       js_schema, NULL);
    cm_identifier(name, id, sizeof id);
    cm_puts(&b, desc ? desc : "");
    cm_puts(&b, "\n\ncodemode tool declaration:\n```ts\ndeclare const tools: { ");
    cm_puts(&b, id);
    cm_puts(&b, "(args: ");
    cm_type(db, input, 0, &b);
    cm_puts(&b, "): Promise<string>; };\n```");
    free(desc);
    free(input);
    if (b.bad) {
        free(b.p);
        return NULL;
    }
    return b.p;
}

static const char cm_intro[] =
    "Run JavaScript that calls other tools. The input is {\"script\": SOURCE}: raw JavaScript as a JSON string (no code "
    "fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file "
    "system, network, or timers.\n"
    "- `await tools.<name>({ ...args })` resolves to the tool's text output (an image read resolves to an image block "
    "for `image()`), and rejects with an Error carrying the tool's error text on failure. Calls still running when the "
    "script ends are cancelled.\n"
    "- Optional first line of the script: `// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}`\n\n"
    "Globals:\n"
    "- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends "
    "the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the "
    "other output in one `<console_output>` block. The first image is attached to the result.\n"
    "- `store(key, value)` and `load(key)` keep JSON values for the rest of the script.\n"
    "- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await "
    "describeNamespace(name)`: find unlisted tools, such as MCP tools.";

/* The schema providers are sent (malloc'd once prepared), and the catalog scripts get. */
static char *cm_schema_built, *cm_catalog;
static const char cm_schema_bare[] =
    "{\"name\":\"codemode\",\"description\":\"Run JavaScript that calls other tools.\",\"input_schema\":{\"type\":\"object\","
    "\"properties\":{\"script\":{\"type\":\"string\",\"description\":\"Raw JavaScript source.\"}},\"required\":[\"script\"]}}";

/* An MCP tool's namespace is its server: mcp__SERVER__TOOL. */
static void cm_namespace(const char *name, char *out, size_t cap) {
    const char *end;
    out[0] = '\0';
    if (strncmp(name, "mcp__", 5) == 0 && (end = strstr(name + 5, "__")) && (size_t)(end - name - 5) < cap) {
        (void)snprintf(out, cap, "%.*s", (int)(end - name - 5), name + 5);
    }
}

typedef struct {
    const char *name;
    char ns[128];
    char *section;
    size_t cost;
    int shown;
} cm_entry;

static int cm_by_cost(const void *a, const void *b) {
    const cm_entry *x = a, *y = b;
    int ns = strcmp(x->ns, y->ns);
    return ns ? ns : x->cost < y->cost ? -1 : x->cost > y->cost;
}

void pic_codemode_prepare(void) {
    const char *names[256];
    size_t n = pic_toolset_names(names, sizeof names / sizeof names[0]), k = 0;
    sqlite3 *db = NULL;
    cm_entry *entries = calloc(n ? n : 1, sizeof *entries);
    cm_buf desc = {NULL, 0, 0, 0}, catalog = {NULL, 0, 0, 0};
    long budget = (long)CM_INLINE_BUDGET;
    if (!entries || sqlite3_open(":memory:", &db) != SQLITE_OK) {
        free(entries);
        sqlite3_close(db);
        return;
    }
    cm_puts(&catalog, "[");
    for (size_t i = 0; i < n; i++) {
        const pic_tool_def *d = pic_tool_named(names[i]);
        char id[128], heading[300], *sample;
        if (!d || strcmp(names[i], pic_codemode_tool.name) == 0 || !(sample = cm_sample(db, names[i], d->schema))) {
            continue;
        }
        cm_identifier(names[i], id, sizeof id);
        cm_namespace(names[i], entries[k].ns, sizeof entries[k].ns);
        {
            sqlite3_stmt *q = NULL;
            if (sqlite3_prepare_v2(db, "SELECT json_object('name', ?1, 'jsName', ?2, 'description', ?3, 'namespace', nullif(?4, ''))",
                                   -1, &q, NULL) == SQLITE_OK) {
                sqlite3_bind_text(q, 1, names[i], -1, SQLITE_STATIC);
                sqlite3_bind_text(q, 2, id, -1, SQLITE_STATIC);
                sqlite3_bind_text(q, 3, sample, -1, SQLITE_STATIC);
                sqlite3_bind_text(q, 4, entries[k].ns, -1, SQLITE_STATIC);
                if (sqlite3_step(q) == SQLITE_ROW) {
                    cm_puts(&catalog, k ? "," : "");
                    cm_puts(&catalog, (const char *)sqlite3_column_text(q, 0));
                }
            }
            sqlite3_finalize(q);
        }
        if (strcmp(id, names[i]) == 0) {
            (void)snprintf(heading, sizeof heading, "### `%s`\n", id);
        } else {
            (void)snprintf(heading, sizeof heading, "### `%s` (`%s`)\n", id, names[i]);
        }
        {
            size_t len = strlen(heading) + strlen(sample) + 1;
            if ((entries[k].section = malloc(len))) {
                (void)snprintf(entries[k].section, len, "%s%s", heading, sample);
                entries[k].name = names[i];
                entries[k].cost = (len + CM_CHARS_PER_TOKEN - 1) / CM_CHARS_PER_TOKEN;
                k++;
            }
        }
        free(sample);
    }
    cm_puts(&catalog, "]");
    /* Pi's selectCatalog: round by round, each group (tools of no namespace first, then each
     * namespace by name) places its cheapest remaining tool while it fits. */
    qsort(entries, k, sizeof *entries, cm_by_cost);
    for (int placed = 1; placed;) {
        placed = 0;
        for (size_t g = 0; g < k;) {
            size_t end = g;
            while (end < k && strcmp(entries[end].ns, entries[g].ns) == 0) {
                end++;
            }
            for (size_t i = g; i < end; i++) {
                if (!entries[i].shown) {
                    if ((long)entries[i].cost <= budget) {
                        budget -= (long)entries[i].cost;
                        entries[i].shown = 1;
                        placed = 1;
                    }
                    break;
                }
            }
            g = end;
        }
    }
    cm_puts(&desc, cm_intro);
    if (k) {
        const char *ns = NULL;
        cm_puts(&desc, "\n\nNested tools:");
        for (size_t i = 0; i < k; i++) {
            if (entries[i].ns[0] && (!ns || strcmp(ns, entries[i].ns) != 0)) {
                size_t shown = 0, all = 0;
                for (size_t j = i; j < k && strcmp(entries[j].ns, entries[i].ns) == 0; j++) {
                    shown += (size_t)entries[j].shown;
                    all++;
                }
                cm_puts(&desc, "\n\n## ");
                cm_puts(&desc, entries[i].ns);
                cm_puts(&desc, shown == all ? "" : shown ? " (some tools not listed)" : " (tools not listed)");
            }
            ns = entries[i].ns;
            if (entries[i].shown) {
                cm_puts(&desc, "\n\n");
                cm_puts(&desc, entries[i].section);
            }
        }
    }
    if (!desc.bad && !catalog.bad) {
        char *js_schema = cm_sql_text(db,
                                   "SELECT json_object('name', 'codemode', 'description', ?1, 'input_schema',"
                                   " json('{\"type\":\"object\",\"properties\":{\"script\":{\"type\":\"string\","
                                   "\"description\":\"Raw JavaScript source.\"}},\"required\":[\"script\"]}'))",
                                   desc.p, NULL);
        if (js_schema) {
            free(cm_schema_built);
            free(cm_catalog);
            cm_schema_built = js_schema;
            cm_catalog = catalog.p;
            catalog.p = NULL;
            pic_codemode_tool.schema = cm_schema_built;
        }
    }
    for (size_t i = 0; i < k; i++) {
        free(entries[i].section);
    }
    free(entries);
    free(desc.p);
    free(catalog.p);
    sqlite3_close(db);
}

/* ---- the call ------------------------------------------------------------------------------------ */

typedef struct {
    uint64_t id;
    char *name, *args;
} cm_pending;

/* The worker, started: its pid and pic's end of its socket. */
static int cm_spawn(int *fd, pid_t *pid) {
    const pic_platform *pl = pic_platform_get();
    char self[4096];
    int sv[2];
    if (!pl || !pl->self_path || pl->self_path(self, sizeof self) != 0 || socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) {
        return -1;
    }
    (void)fcntl(sv[0], F_SETFD, FD_CLOEXEC);
    *pid = fork();
    if (*pid == 0) {
        char *const argv[] = {self, (char *)(uintptr_t) "__codemode-worker", NULL};
        char *const envp[] = {NULL};
        long max = sysconf(_SC_OPEN_MAX);
        if (sv[1] != 3 && dup2(sv[1], 3) != 3) {
            _exit(127);
        }
        for (long f = 4; f < (max > 0 && max < 65536 ? max : 65536); f++) {
            (void)close((int)f);
        }
        (void)fcntl(3, F_SETFD, 0);
        (void)signal(SIGPIPE, SIG_DFL);
        execve(self, argv, envp);
        _exit(127);
    }
    close(sv[1]);
    if (*pid < 0) {
        close(sv[0]);
        return -1;
    }
    *fd = sv[0];
    return 0;
}

/* The value a script gets for a finished call, as JSON (malloc'd): the text, or for an image an
 * image block with the text as its note. */
static char *cm_value(sqlite3 *db, const pic_nested_call *c) {
    char *b64 = NULL, *out;
    sqlite3_stmt *q = NULL;
    if (c->image && c->mime) {
        if (!(b64 = malloc(4 * ((c->image_len + 2) / 3) + 1))) {
            return NULL;
        }
        (void)pic_base64_encode(c->image, c->image_len, b64);
    }
    if (sqlite3_prepare_v2(db,
                           b64 ? "SELECT json_object('type', 'image', 'data', ?2, 'mimeType', ?3, 'note', ?1)" : "SELECT json_quote(?1)",
                           -1, &q, NULL) != SQLITE_OK) {
        free(b64);
        return NULL;
    }
    sqlite3_bind_text(q, 1, c->result, -1, SQLITE_STATIC);
    if (b64) {
        sqlite3_bind_text(q, 2, b64, -1, SQLITE_STATIC);
        sqlite3_bind_text(q, 3, c->mime, -1, SQLITE_STATIC);
    }
    out = sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0) ? strdup((const char *)sqlite3_column_text(q, 0)) : NULL;
    sqlite3_finalize(q);
    free(b64);
    return out;
}

/* Runs a round of the script's calls and answers them: 0, or -1 when an outcome was lost. */
static int cm_round(int fd, sqlite3 *db, const pic_tool_hooks *h, cm_pending *round, size_t n, size_t *made) {
    pic_nested_call *calls = calloc(n ? n : 1, sizeof *calls);
    size_t *slot = calloc(n ? n : 1, sizeof *slot), m = 0;
    cm_buf b = {NULL, 0, 0, 0};
    int rc = 0;
    if (!calls || !slot) {
        free(calls);
        free(slot);
        return -1;
    }
    for (size_t i = 0; i < n; i++) {
        if (*made + m < CM_MAX_CALLS) {
            calls[m].tool = round[i].name;
            calls[m].input = round[i].args;
            slot[i] = ++m;
        }
    }
    if (m && h->call(h->call_ctx, calls, m) != 0) {
        rc = -1;
    }
    *made += m;
    cm_put_u64(&b, (uint64_t)n);
    for (size_t i = 0; rc == 0 && i < n; i++) {
        const pic_nested_call *c = slot[i] ? &calls[slot[i] - 1] : NULL;
        char *value = c && !c->is_error ? cm_value(db, c) : NULL;
        char ok = value != NULL;
        const char *text = value ? value
                           : c   ? (c->result && *c->result ? c->result : "the tool failed")
                                 : "a script may make at most 256 tool calls";
        cm_put_u64(&b, round[i].id);
        cm_put(&b, &ok, 1);
        cm_put_bytes(&b, text, strlen(text));
        free(value);
    }
    for (size_t i = 0; i < m; i++) {
        free(calls[i].result);
        free(calls[i].image);
    }
    free(calls);
    free(slot);
    if (rc == 0 && (b.bad || cm_send(fd, 'R', b.p, b.n) != 0)) {
        rc = 1; /* the worker is gone: the script ends as the worker's end says */
    }
    free(b.p);
    return rc < 0 ? -1 : 0;
}

/* Keeps the start and end of TEXT within MAX_TOKENS (Pi's truncateOutput); the whole goes to the
 * call's output, which the loop journals as h->output_name. A new string (malloc'd). */
static char *cm_truncate(const char *text, long long max_tokens, const pic_tool_hooks *h) {
    size_t len = strlen(text), budget = (size_t)max_tokens * CM_CHARS_PER_TOKEN, head, tail, lines = 1, n;
    char *out;
    if (len <= budget) {
        return strdup(text);
    }
    head = budget / 2;
    tail = budget - head;
    while (head > 0 && (text[head] & 0xC0) == 0x80) { /* never inside a UTF-8 sequence */
        head--;
    }
    while (tail > 0 && (text[len - tail] & 0xC0) == 0x80) {
        tail--;
    }
    for (const char *c = text; *c; c++) {
        lines += *c == '\n';
    }
    n = head + tail + 512 + (h->output_name ? strlen(h->output_name) : 0);
    if (!(out = malloc(n))) {
        return NULL;
    }
    (void)snprintf(out, n,
                   "Warning: truncated output (original token count: %zu)\nTotal output lines: %zu\n\n%.*s\xe2\x80\xa6%zu tokens "
                   "truncated\xe2\x80\xa6%s",
                   (len + CM_CHARS_PER_TOKEN - 1) / CM_CHARS_PER_TOKEN, lines, (int)head, text,
                   (len - head - tail + CM_CHARS_PER_TOKEN - 1) / CM_CHARS_PER_TOKEN, text + len - tail);
    if (h->output_name && h->output && (h->output->data = strdup(text))) {
        h->output->len = len;
        (void)snprintf(out + strlen(out), n - strlen(out), "\n\n[Full output: %s (read with offset/limit)]", h->output_name);
    } else {
        (void)snprintf(out + strlen(out), n - strlen(out), "\n\n[The full output was not kept]");
    }
    return out;
}

/* The result from the worker's D frame (malloc'd). */
static char *cm_finish(sqlite3 *db, const char *done, long long started_ms, long long max_tokens, const pic_tool_hooks *h,
                       int *is_error) {
    char *invalid = cm_sql_text(db, "SELECT json_extract(?1, '$.invalid')", done, NULL), *body, *kept, *out, *data, *mime;
    int ok;
    size_t n;
    if (invalid) {
        *is_error = 1;
        return invalid;
    }
    ok = (body = cm_sql_text(db, "SELECT CASE WHEN json_extract(?1, '$.ok') THEN 'ok' END", done, NULL)) != NULL;
    free(body);
    body = cm_sql_text(db, "SELECT coalesce(json_extract(?1, '$.body'), '')", done, NULL);
    data = cm_sql_text(db, "SELECT json_extract(?1, '$.images[0].data')", done, NULL);
    mime = cm_sql_text(db, "SELECT json_extract(?1, '$.images[0].mimeType')", done, NULL);
    if (data && mime && h->image) {
        size_t cap = strlen(data) / 4 * 3 + 3, got;
        pic_image img;
        unsigned char *bytes = malloc(cap);
        char why[128];
        memset(&img, 0, sizeof img);
        if (bytes && (got = pic_base64_decode(data, strlen(data), bytes)) != (size_t)-1) {
            img.data = bytes;
            img.len = got;
            if (pic_image_inspect(&img, NULL, why, sizeof why) == PIC_IMAGE_OK) {
                h->image->mime = img.mime;
                h->image->data = bytes;
                h->image->len = got;
                h->image->width = img.width;
                h->image->height = img.height;
                bytes = NULL;
            }
        }
        free(bytes);
    }
    free(data);
    free(mime);
    kept = cm_truncate(body ? body : "", max_tokens, h);
    free(body);
    if (!kept) {
        return NULL;
    }
    n = strlen(kept) + 96;
    if ((out = malloc(n))) {
        (void)snprintf(out, n, "%s\nWall time %.1f seconds\nOutput:\n%s", ok ? "Script completed" : "Script failed",
                       (double)(cm_now_ms() - started_ms) / 1000.0, kept);
    }
    free(kept);
    *is_error = !ok;
    return out;
}

/* A script that ended without its D frame: the worker died, or was stopped. */
static char *cm_ended(const char *why, long long started_ms, int *is_error) {
    size_t n = strlen(why) + 160;
    char *out = malloc(n);
    *is_error = 1;
    if (out) {
        (void)snprintf(out, n, "Script failed\nWall time %.1f seconds\nOutput:\nScript error:\n%s",
                       (double)(cm_now_ms() - started_ms) / 1000.0, why);
    }
    return out;
}

static int cm_on(void) {
    const char *env = getenv("PIC_CODEMODE");
    char *v;
    int on;
    if (env && *env) {
        return strcmp(env, "on") == 0 || strcmp(env, "true") == 0;
    }
    v = pic_setting("codemode");
    on = v && strcmp(v, "true") == 0;
    free(v);
    return on;
}

static char *cm_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args, const pic_tool_hooks *h,
                    int *is_error) {
    long long started_ms = cm_now_ms(), deadline = 0, max_tokens = CM_DEFAULT_TOKENS;
    cm_pending *round = NULL;
    size_t nround = 0, made = 0;
    cm_buf init = {NULL, 0, 0, 0};
    sqlite3 *db = NULL;
    char *result = NULL, *done = NULL, *why = NULL;
    int fd = -1, lost = 0, told = 0, status = 0;
    pid_t pid = -1;
    (void)state;
    (void)workspace;
    (void)tool;
    (void)args;
    *is_error = 0;
    if (h->started(h->ctx, NULL, 0) != 0) {
        return NULL;
    }
    if (!h->call) {
        *is_error = 1;
        return strdup("codemode cannot run here: its calls have nowhere to go");
    }
    if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
        sqlite3_close(db);
        return NULL;
    }
    cm_put_bytes(&init, h->input ? h->input : "{}", strlen(h->input ? h->input : "{}"));
    cm_put_bytes(&init, cm_catalog ? cm_catalog : "[]", strlen(cm_catalog ? cm_catalog : "[]"));
    if (init.bad || cm_spawn(&fd, &pid) != 0 || cm_send(fd, 'I', init.p, init.n) != 0) {
        why = strdup("Script sandbox failed: the worker could not be started");
    }
    free(init.p);
    while (!why && !done && !lost) {
        struct pollfd p = {fd, POLLIN, 0};
        long long now = cm_now_ms();
        char type = 0, *payload = NULL;
        size_t len = 0;
        if (pic_interrupted && !told) { /* Ctrl-C, or an abort the inbox delivered: the VM is interrupted */
            (void)kill(pid, SIGINT);
            told = 1;
        }
        /* The worker keeps the deadline itself; past it by five seconds, it is not listening. */
        if (deadline && now > deadline + 5000) {
            why = strdup("Script timed out: the worker did not stop at its deadline");
            break;
        }
        if (poll(&p, 1, 200) <= 0) {
            continue;
        }
        if (cm_recv(fd, &type, &payload, &len) != 0) {
            why = strdup("Script sandbox failed: the worker ended without a result");
            break;
        }
        if (type == 'T') {
            long long timeout = -1, tokens = -1;
            if (sscanf(payload, "%lld %lld", &timeout, &tokens) == 2) {
                deadline = timeout > 0 ? started_ms + timeout : 0;
                max_tokens = tokens >= 0 ? tokens : CM_DEFAULT_TOKENS;
            }
        } else if (type == 'C') {
            cm_rd r = {payload, len, 0, 0};
            cm_pending *grown = realloc(round, (nround + 1) * sizeof *grown);
            if (grown) {
                round = grown;
                round[nround].id = cm_get_u64(&r);
                round[nround].name = cm_get_bytes(&r, NULL);
                round[nround].args = cm_get_bytes(&r, NULL);
                if (!r.bad && round[nround].name && round[nround].args) {
                    nround++;
                } else {
                    free(round[nround].name);
                    free(round[nround].args);
                }
            }
        } else if (type == 'W') {
            lost = cm_round(fd, db, h, round, nround, &made) != 0;
            for (size_t i = 0; i < nround; i++) {
                free(round[i].name);
                free(round[i].args);
            }
            nround = 0;
        } else if (type == 'D') {
            done = payload;
            payload = NULL;
        }
        free(payload);
    }
    for (size_t i = 0; i < nround; i++) {
        free(round[i].name);
        free(round[i].args);
    }
    free(round);
    if (fd >= 0) {
        close(fd);
    }
    if (pid > 0) {
        if (!done) {
            (void)kill(pid, SIGKILL);
        }
        while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
        }
    }
    if (!lost) {
        result = done ? cm_finish(db, done, started_ms, max_tokens, h, is_error)
                      : cm_ended(why ? why : "Script sandbox failed", started_ms, is_error);
    }
    free(done);
    free(why);
    sqlite3_close(db);
    return result; /* NULL when an inner call's outcome was lost: the loop settles the script */
}

static int cm_by_default(void) { return cm_on(); }

/* set_codemode {enabled}: on or off for this process and what it starts (PIC_CODEMODE), and for the
 * open conversation, whose tools were fixed at its first request: codemode joins them or leaves. */
static int cm_rpc_set(pic_rpc_call *c) {
    char *v = pic_rpc_text(c, "$.enabled");
    int on = v && (strcmp(v, "1") == 0 || strcmp(v, "true") == 0), rc = 0;
    free(v);
    if (setenv("PIC_CODEMODE", on ? "on" : "off", 1) != 0) {
        (void)snprintf(c->err, sizeof c->err, "cannot set PIC_CODEMODE");
        return -1;
    }
    if (c->s && c->session && c->session[0]) {
        sqlite3_stmt *q = NULL;
        if (pic_begin(c->s) != 0) {
            (void)snprintf(c->err, sizeof c->err, "%s", c->s->err);
            return -1;
        }
        rc = sqlite3_prepare_v2(c->s->db,
                                on ? "UPDATE pic_session SET tools = json_insert(tools, '$[#]', json(?2)) WHERE id = ?1"
                                     " AND tools IS NOT NULL AND NOT EXISTS (SELECT 1 FROM json_each(tools)"
                                     " WHERE json_extract(value, '$.name') = 'codemode')"
                                   : "UPDATE pic_session SET tools = (SELECT json_group_array(json(value)) FROM json_each(tools)"
                                     " WHERE json_extract(value, '$.name') IS NOT 'codemode') WHERE id = ?1 AND tools IS NOT NULL",
                                -1, &q, NULL) == SQLITE_OK
                 ? 0
                 : -1;
        if (rc == 0) {
            sqlite3_bind_text(q, 1, c->session, -1, SQLITE_STATIC);
            if (on) {
                sqlite3_bind_text(q, 2, pic_codemode_tool.schema, -1, SQLITE_STATIC);
            }
            rc = sqlite3_step(q) == SQLITE_DONE ? 0 : -1;
        }
        if (rc != 0) {
            (void)snprintf(c->err, sizeof c->err, "sql: %s", sqlite3_errmsg(c->s->db));
        }
        sqlite3_finalize(q);
        if (rc != 0 || pic_commit(c->s) != 0) {
            pic_rollback(c->s);
            return -1;
        }
    }
    c->data = strdup(on ? "{\"enabled\":true}" : "{\"enabled\":false}");
    return c->data ? 0 : -1;
}

const pic_rpc_command pic_set_codemode_rpc = {"set_codemode", "codemode on or off for this session, the open conversation included",
                                              0, cm_rpc_set};

pic_tool_def pic_codemode_tool = {"codemode", cm_schema_bare, 0, 0, PIC_TIER_BUNDLED, 0, cm_by_default, cm_run, NULL};

/* ---- the worker ---------------------------------------------------------------------------------- */

static volatile sig_atomic_t cm_stop;
static long long cm_deadline, cm_timeout;
static int cm_quiet, cm_fd = 3, cm_done;

static void cm_on_signal(int sig) {
    (void)sig;
    cm_stop = 1;
}

/* The call gone (its end of the socket closed, pic killed): the worker goes too, whatever the
 * script is doing. SIGIO comes on every arrival; only EOF ends it. */
static void cm_on_io(int sig) {
    char c;
    int saved = errno;
    (void)sig;
    if (recv(cm_fd, &c, 1, MSG_PEEK | MSG_DONTWAIT) == 0) {
        _exit(0);
    }
    errno = saved;
}

/* QuickJS polls this while the script runs: past the deadline or after Ctrl-C the script gets an
 * uncatchable error. While the worker writes the failure, it lets JavaScript run. */
static int cm_interrupt(JSRuntime *rt, void *opaque) {
    (void)rt;
    (void)opaque;
    return !cm_quiet && (cm_stop || (cm_deadline && cm_now_ms() > cm_deadline));
}

/* Why the VM was cut off, as the script's error {kind, message} (JSON, into OUT); "" when it was
 * not. From here on the worker lets JavaScript run, to write the failure. */
static void cm_why(char *out, size_t cap) {
    out[0] = '\0';
    if (cm_stop) {
        (void)snprintf(out, cap, "{\"kind\":\"aborted\",\"message\":\"Execution aborted\"}");
    } else if (cm_deadline && cm_now_ms() > cm_deadline) {
        (void)snprintf(out, cap, "{\"kind\":\"timeout\",\"message\":\"Execution timed out after %lld ms\"}", cm_timeout);
    } else {
        return;
    }
    cm_quiet = 1;
}

static JSValue cm_bridge(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) {
    const char *kind = argc > 0 ? JS_ToCString(ctx, argv[0]) : NULL;
    (void)this_val;
    if (kind && strcmp(kind, "why") == 0) {
        char why[128];
        cm_why(why, sizeof why);
        JS_FreeCString(ctx, kind);
        return JS_NewString(ctx, why);
    }
    if (kind && strcmp(kind, "call") == 0 && argc >= 4) {
        cm_buf b = {NULL, 0, 0, 0};
        int64_t id = 0;
        const char *name = JS_ToCString(ctx, argv[2]), *json = JS_ToCString(ctx, argv[3]);
        (void)JS_ToInt64(ctx, &id, argv[1]);
        cm_put_u64(&b, (uint64_t)id);
        cm_put_bytes(&b, name ? name : "", name ? strlen(name) : 0);
        cm_put_bytes(&b, json ? json : "{}", json ? strlen(json) : 2);
        if (b.bad || cm_send(cm_fd, 'C', b.p, b.n) != 0) {
            _exit(1); /* the call is gone */
        }
        free(b.p);
        JS_FreeCString(ctx, name);
        JS_FreeCString(ctx, json);
    } else if (kind && strcmp(kind, "done") == 0 && argc >= 2) {
        size_t len = 0;
        const char *json = JS_ToCStringLen(ctx, &len, argv[1]);
        if (!json || cm_send(cm_fd, 'D', json, len) != 0) {
            _exit(1);
        }
        JS_FreeCString(ctx, json);
        cm_done = 1;
    }
    JS_FreeCString(ctx, kind);
    return JS_UNDEFINED;
}

/* A chunked script from codemode_js.inc as one string (malloc'd). */
static char *cm_joined(const char *const *chunks) {
    cm_buf b = {NULL, 0, 0, 0};
    for (; *chunks; chunks++) {
        cm_puts(&b, *chunks);
    }
    return b.bad ? (free(b.p), NULL) : b.p;
}

static JSValue cm_eval(JSContext *ctx, const char *const *chunks, const char *file) {
    char *src = cm_joined(chunks);
    JSValue v = src ? JS_Eval(ctx, src, strlen(src), file, JS_EVAL_TYPE_GLOBAL) : JS_EXCEPTION;
    free(src);
    return v;
}

static JSValue cm_method(JSContext *ctx, JSValueConst api, const char *name, int argc, JSValueConst *argv) {
    JSValue fn = JS_GetPropertyStr(ctx, api, name), out = JS_Call(ctx, fn, api, argc, argv);
    JS_FreeValue(ctx, fn);
    return out;
}

/* The VM was cut off (its interrupt, or an error no script can catch): the script fails with
 * what it had made so far. */
static void cm_cut(JSContext *ctx, JSValueConst api) {
    const char *kind = cm_stop ? "aborted" : cm_deadline && cm_now_ms() > cm_deadline ? "timeout" : "sandbox";
    char message[96];
    JSValue argv[2], r;
    JS_FreeValue(ctx, JS_GetException(ctx));
    if (strcmp(kind, "timeout") == 0) {
        (void)snprintf(message, sizeof message, "Execution timed out after %lld ms", cm_timeout);
    } else {
        (void)snprintf(message, sizeof message, "%s", strcmp(kind, "aborted") == 0 ? "Execution aborted" : "the VM failed");
    }
    cm_quiet = 1;
    argv[0] = JS_NewString(ctx, kind);
    argv[1] = JS_NewString(ctx, message);
    r = cm_method(ctx, api, "fail", 2, argv);
    JS_FreeValue(ctx, r);
    JS_FreeValue(ctx, argv[0]);
    JS_FreeValue(ctx, argv[1]);
}

/* Runs promise jobs until none is left: 0, or -1 when the VM was cut off. */
static int cm_drain(JSRuntime *rt) {
    JSContext *job;
    int r, jobs = 0;
    while ((r = JS_ExecutePendingJob(rt, &job)) != 0) {
        if (r < 0 || (++jobs % 50 == 0 && cm_interrupt(rt, NULL))) {
            return -1;
        }
    }
    return 0;
}

int pic_codemode_worker(void) {
    struct sigaction sa;
    JSRuntime *rt;
    JSContext *ctx;
    JSValue parse, parsed, prelude, api, script = JS_UNDEFINED, argv[3];
    char type = 0, *payload = NULL, *input = NULL, *catalog = NULL, *code = NULL, opts[64];
    size_t len = 0;
    long long tokens = -1;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = cm_on_signal;
    sigemptyset(&sa.sa_mask);
    (void)sigaction(SIGINT, &sa, NULL);
    (void)sigaction(SIGTERM, &sa, NULL);
    (void)signal(SIGPIPE, SIG_IGN);
    sa.sa_handler = cm_on_io;
    sa.sa_flags = SA_RESTART;
    (void)sigaction(SIGIO, &sa, NULL);
    (void)fcntl(cm_fd, F_SETOWN, getpid());
    (void)fcntl(cm_fd, F_SETFL, fcntl(cm_fd, F_GETFL) | O_ASYNC);
    if (cm_on_io(0), cm_recv(cm_fd, &type, &payload, &len) != 0 || type != 'I') {
        return 1;
    }
    {
        cm_rd r = {payload, len, 0, 0};
        input = cm_get_bytes(&r, NULL);
        catalog = cm_get_bytes(&r, NULL);
        free(payload);
        if (r.bad || !input || !catalog) {
            return 1;
        }
    }
    if (!(rt = JS_NewRuntime())) {
        return 1;
    }
    JS_SetMemoryLimit(rt, CM_HEAP);
    JS_SetMaxStackSize(rt, CM_STACK);
    JS_SetInterruptHandler(rt, cm_interrupt, NULL);
    if (!(ctx = JS_NewContext(rt))) {
        return 1;
    }
    /* The input and its options line, before anything runs. */
    parse = cm_eval(ctx, cm_source_js, "codemode-source.js");
    argv[0] = JS_NewString(ctx, input);
    parsed = JS_Call(ctx, parse, JS_UNDEFINED, 1, argv);
    JS_FreeValue(ctx, argv[0]);
    JS_FreeValue(ctx, parse);
    {
        JSValue error = JS_GetPropertyStr(ctx, parsed, "error"), c = JS_GetPropertyStr(ctx, parsed, "code"),
                t = JS_GetPropertyStr(ctx, parsed, "timeoutMs"), m = JS_GetPropertyStr(ctx, parsed, "maxOutputTokens");
        int64_t v = 0;
        if (JS_IsString(error)) {
            JSValue wrap = JS_NewObject(ctx), json;
            const char *s;
            size_t n = 0;
            JS_SetPropertyStr(ctx, wrap, "invalid", JS_DupValue(ctx, error));
            json = JS_JSONStringify(ctx, wrap, JS_UNDEFINED, JS_UNDEFINED);
            s = JS_ToCStringLen(ctx, &n, json);
            (void)(s && cm_send(cm_fd, 'D', s, n));
            JS_FreeCString(ctx, s);
            JS_FreeValue(ctx, json);
            JS_FreeValue(ctx, wrap);
            return 0;
        }
        if (JS_IsString(c)) {
            const char *s = JS_ToCString(ctx, c);
            code = s ? strdup(s) : NULL;
            JS_FreeCString(ctx, s);
        }
        if (JS_IsNumber(t) && JS_ToInt64(ctx, &v, t) == 0 && v > 0) {
            cm_timeout = v;
            cm_deadline = cm_now_ms() + v;
        }
        if (JS_IsNumber(m) && JS_ToInt64(ctx, &v, m) == 0) {
            tokens = v;
        }
        JS_FreeValue(ctx, error);
        JS_FreeValue(ctx, c);
        JS_FreeValue(ctx, t);
        JS_FreeValue(ctx, m);
        JS_FreeValue(ctx, parsed);
    }
    (void)snprintf(opts, sizeof opts, "%lld %lld", cm_timeout > 0 ? cm_timeout : -1, tokens);
    if (!code || cm_send(cm_fd, 'T', opts, strlen(opts)) != 0) {
        return 1;
    }
    prelude = cm_eval(ctx, cm_prelude_js, "codemode-prelude.js");
    argv[0] = JS_NewCFunction(ctx, cm_bridge, "bridge", 2);
    argv[1] = JS_NewString(ctx, catalog);
    argv[2] = JS_NewString(ctx, "{}");
    api = JS_Call(ctx, prelude, JS_UNDEFINED, 3, argv);
    for (int i = 0; i < 3; i++) {
        JS_FreeValue(ctx, argv[i]);
    }
    JS_FreeValue(ctx, prelude);
    if (JS_IsException(api)) {
        return 1;
    }
    /* The prefix shares the first line with the script, so its line numbers are the script's. */
    {
        size_t n = strlen(code) + 64;
        char *wrapped = malloc(n);
        if (!wrapped) {
            return 1;
        }
        (void)snprintf(wrapped, n, "(async (tools, console) => {%s\n})", code);
        script = JS_Eval(ctx, wrapped, strlen(wrapped), "codemode.js", JS_EVAL_TYPE_GLOBAL);
        free(wrapped);
    }
    if (JS_IsException(script)) {
        JSValue e = JS_GetException(ctx), a[2];
        a[0] = JS_NewString(ctx, "script");
        a[1] = e;
        JS_FreeValue(ctx, cm_method(ctx, api, "fail", 2, a));
        JS_FreeValue(ctx, a[0]);
        JS_FreeValue(ctx, e);
    } else {
        JSValue r = cm_method(ctx, api, "run", 1, &script);
        if (JS_IsException(r)) {
            cm_cut(ctx, api);
        }
        JS_FreeValue(ctx, r);
    }
    JS_FreeValue(ctx, script);
    while (!cm_done) {
        JSValue r;
        if (cm_drain(rt) != 0) {
            cm_cut(ctx, api);
            continue;
        }
        r = cm_method(ctx, api, "stalled", 0, NULL);
        JS_FreeValue(ctx, r);
        if (cm_done) {
            break;
        }
        /* Waiting on the calls it made: pic runs them as a round and answers each. */
        if (cm_send(cm_fd, 'W', NULL, 0) != 0 || cm_recv(cm_fd, &type, &payload, &len) != 0 || type != 'R') {
            return 1;
        }
        {
            cm_rd rd = {payload, len, 0, 0};
            uint64_t n = cm_get_u64(&rd);
            for (uint64_t i = 0; i < n && !rd.bad; i++) {
                uint64_t id = cm_get_u64(&rd);
                char ok = rd.at < rd.n ? rd.p[rd.at] : 0;
                char *text;
                JSValue a[3];
                rd.at++;
                if (!(text = cm_get_bytes(&rd, NULL))) {
                    break;
                }
                a[0] = JS_NewInt64(ctx, (int64_t)id);
                a[1] = JS_NewBool(ctx, ok != 0);
                a[2] = JS_NewString(ctx, text);
                r = cm_method(ctx, api, "settle", 3, a);
                if (JS_IsException(r)) {
                    cm_cut(ctx, api);
                }
                JS_FreeValue(ctx, r);
                for (int k = 0; k < 3; k++) {
                    JS_FreeValue(ctx, a[k]);
                }
                free(text);
            }
            free(payload);
            payload = NULL;
        }
        if (cm_stop || (cm_deadline && cm_now_ms() > cm_deadline)) {
            cm_cut(ctx, api); /* calls answered after the deadline or a Ctrl-C end the script */
        }
    }
    /* The VM goes with the process: freeing a heap a cut-off script left half built proves nothing. */
    free(input);
    free(catalog);
    free(code);
    return 0;
}