/* The codemode tool: Pi's codemode (packages/coding-agent/src/extensions/codemode), with one
* synchronous script API: a tool call returns its value, and parallel([...]) runs calls at once.
* The script runs on the build's JavaScript engine (jsengine.h). Hosted builds run Bellard's
* QuickJS 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 no-OS build
* (PIC_CODEMODE_INPROC) runs it in pic's own process. Either way: 256 MB of heap, a 1 MB
* stack, the script's deadline and Ctrl-C through the engine's interrupt, no timers, network or
* files. Every call the script makes goes to the call's pic_tool_hooks.call, so the loop
* journals, gates and runs it as a call nested in this one (loop.c), in program order. Only the
* script's output is the call's result.
*
* Frames between the call and its worker 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 the answers to a C frame, a JSON array of {ok, value} or {ok: false, error}
* from it: T the script's options, "TIMEOUT_MS MAX_OUTPUT_TOKENS" (-1: not given)
* C calls to run, at once: one "NAME\tARGS_JSON" line each; the worker waits for R
* D the end: {ok, body, images}, or {invalid} for input it refused */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#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 "jsengine.h"
#include "net.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)); }
#ifndef PIC_CODEMODE_INPROC /* the worker's frames */
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;
}
#endif
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')", js_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'))", js_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"
"- Calls return values: `tools.<name>({ ...args })` returns the tool's text output (an image read returns an image "
"block for `image()`) and throws an Error carrying the tool's error text on failure. Use `parallel([() => tools.a({...}), "
"() => tools.b({...})])` for concurrency: the calls run at once and their results come back in order (`{ settled: true }` "
"gives `{ status, value | reason }` each instead of throwing). `await` and `Promise.all` work but run calls one by one.\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 *ents = calloc(n ? n : 1, sizeof *ents);
cm_buf desc = {NULL, 0, 0, 0}, catalog = {NULL, 0, 0, 0};
long budget = (long)CM_INLINE_BUDGET;
if (!ents || sqlite3_open(":memory:", &db) != SQLITE_OK) {
free(ents);
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], ents[k].ns, sizeof ents[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, ents[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 ((ents[k].section = malloc(len))) {
(void)snprintf(ents[k].section, len, "%s%s", heading, sample);
ents[k].name = names[i];
ents[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. */
if (k > 1) { /* glibc: qsort's array may not be NULL, even empty */
qsort(ents, k, sizeof *ents, 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(ents[end].ns, ents[g].ns) == 0) {
end++;
}
for (size_t i = g; i < end; i++) {
if (!ents[i].shown) {
if ((long)ents[i].cost <= budget) {
budget -= (long)ents[i].cost;
ents[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 (ents[i].ns[0] && (!ns || strcmp(ns, ents[i].ns) != 0)) {
size_t shown = 0, all = 0;
for (size_t j = i; j < k && strcmp(ents[j].ns, ents[i].ns) == 0; j++) {
shown += (size_t)ents[j].shown;
all++;
}
cm_puts(&desc, "\n\n## ");
cm_puts(&desc, ents[i].ns);
cm_puts(&desc, shown == all ? "" : shown ? " (some tools not listed)" : " (tools not listed)");
}
ns = ents[i].ns;
if (ents[i].shown) {
cm_puts(&desc, "\n\n");
cm_puts(&desc, ents[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(ents[i].section);
}
free(ents);
free(desc.p);
free(catalog.p);
sqlite3_close(db);
}
/* ---- the script, on either engine ---------------------------------------------------------------- */
/* One script's run on the engine (jsengine.h): the prelude, the script, and its __host. How its
* calls reach pic, its options and its end are the caller's: a socket to the call in the worker,
* the call's own hooks in process. */
typedef struct {
const char *input, *catalog;
/* A round of calls, "NAME\tARGS" lines: their answers as a JSON array of {ok, value} or
* {ok: false, error} (malloc'd); NULL when an outcome was lost (the script ends, unanswered). */
char *(*call)(void *ctx, const char *lines);
void (*options)(void *ctx, long long timeout_ms, long long max_tokens);
void (*finish)(void *ctx, const char *result_json);
void *ctx;
volatile sig_atomic_t *stop; /* Ctrl-C */
long long deadline, timeout;
int quiet, done, lost;
} cm_script;
/* Past the deadline, after Ctrl-C or a lost call, the script gets an error it cannot catch; while
* the failure is written, JavaScript may run. */
static int cm_interrupt(void *ctx) {
cm_script *sc = ctx;
return !sc->quiet && ((sc->stop && *sc->stop) || sc->lost || (sc->deadline && cm_now_ms() > sc->deadline));
}
/* Why the script was cut off, as its error {kind, message} (JSON, malloc'd), or NULL. */
static char *cm_why(cm_script *sc) {
char out[160];
if (sc->stop && *sc->stop) {
(void)snprintf(out, sizeof out, "{\"kind\":\"aborted\",\"message\":\"Execution aborted\"}");
} else if (sc->deadline && cm_now_ms() > sc->deadline) {
(void)snprintf(out, sizeof out, "{\"kind\":\"timeout\",\"message\":\"Execution timed out after %lld ms\"}", sc->timeout);
} else {
return NULL;
}
sc->quiet = 1;
return strdup(out);
}
static char *cm_host(void *ctx, int argc, const char *const *argv, int *thrown) {
cm_script *sc = ctx;
const char *kind = argc > 0 && argv[0] ? argv[0] : "", *a = argc > 1 ? argv[1] : NULL, *b = argc > 2 ? argv[2] : NULL;
char *out = NULL;
*thrown = 0;
if (strcmp(kind, "input") == 0) {
out = strdup(sc->input);
} else if (strcmp(kind, "catalog") == 0) {
out = strdup(sc->catalog);
} else if (strcmp(kind, "options") == 0) {
long long timeout = a ? atoll(a) : -1, tokens = b ? atoll(b) : -1;
if (timeout > 0) {
sc->timeout = timeout;
sc->deadline = cm_now_ms() + timeout;
}
sc->options(sc->ctx, timeout, tokens);
} else if (strcmp(kind, "call") == 0 && a && !sc->lost) {
if (!(out = sc->call(sc->ctx, a))) {
sc->lost = 1; /* the interrupt ends the script; nothing it says now counts */
*thrown = 1;
out = strdup("interrupted");
} else if ((sc->stop && *sc->stop) || (sc->deadline && cm_now_ms() > sc->deadline)) {
free(out); /* the calls ended at the deadline or Ctrl-C: so does the script */
*thrown = 1;
out = strdup("interrupted");
}
} else if (strcmp(kind, "done") == 0 && a) {
sc->done = 1;
if (!sc->lost) {
sc->finish(sc->ctx, a);
}
} else if (strcmp(kind, "why") == 0) {
out = cm_why(sc);
}
return out;
}
/* A chunked script from codemode_js.inc, appended. */
static void cm_put_chunks(cm_buf *b, const char *const *chunks) {
for (; *chunks; chunks++) {
cm_puts(b, *chunks);
}
}
/* The script cut off (the interrupt, an engine failure): it fails with what it had made. */
static void cm_cut(pic_js *js, cm_script *sc) {
const char *kind = sc->stop && *sc->stop ? "aborted" : sc->deadline && cm_now_ms() > sc->deadline ? "timeout" : "sandbox";
char src[200], *err = NULL;
sc->quiet = 1;
if (strcmp(kind, "timeout") == 0) {
(void)snprintf(src, sizeof src, "__pic.cut(\"timeout\", \"Execution timed out after %lld ms\")", sc->timeout);
} else {
(void)snprintf(src, sizeof src, "__pic.cut(\"%s\", \"%s\")", kind,
strcmp(kind, "aborted") == 0 ? "Execution aborted" : "the engine failed");
}
(void)pic_js_eval(js, src, "codemode-run.js", &err);
free(err);
}
/* Runs the script to its end: 0 when it reported one (sc->finish), -1 when it could not run or a
* call was lost. */
static int cm_script_run(cm_script *sc) {
pic_js *js = pic_js_new(CM_HEAP, CM_STACK, cm_interrupt, cm_host, sc);
cm_buf prelude = {NULL, 0, 0, 0};
char *err = NULL;
if (!js) {
return -1;
}
cm_put_chunks(&prelude, cm_source_js);
cm_puts(&prelude, "\nvar __pic = ");
cm_put_chunks(&prelude, cm_prelude_js);
cm_puts(&prelude, pic_js_async() ? "(__host, true);\n" : "(__host, false);\n");
if (prelude.bad || pic_js_eval(js, prelude.p, "codemode-prelude.js", &err) != 0) {
free(prelude.p);
free(err);
pic_js_free(js);
return -1;
}
free(prelude.p);
if (pic_js_eval(js, "var __fn = __pic.start(); if (__fn) __pic.run(__fn);", "codemode-run.js", &err) != 0) {
cm_cut(js, sc);
}
free(err);
err = NULL;
while (!sc->done && !sc->lost) {
if (pic_js_pump(js) != 0) {
cm_cut(js, sc);
continue;
}
if (!sc->done && pic_js_eval(js, "__pic.stalled()", "codemode-run.js", &err) != 0) {
cm_cut(js, sc);
}
free(err);
err = NULL;
if (!sc->done && !sc->lost) { /* nothing left to run and no result: the engine failed */
static const char lost[] = "{\"ok\":false,\"body\":\"Script error:\\nScript sandbox failed: the script ended "
"without a result\",\"images\":[]}";
sc->done = 1;
sc->finish(sc->ctx, lost);
}
}
pic_js_free(js);
return sc->lost ? -1 : 0;
}
/* ---- the calls -------------------------------------------------------------------------------- */
/* 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 ("NAME\tARGS" lines) through H->call, at most CM_MAX_CALLS a
* script, each cut at DEADLINE (0: none). The answers as a JSON array (malloc'd), or NULL when
* an outcome was lost. */
static char *cm_answers(sqlite3 *db, const pic_tool_hooks *h, const char *lines, size_t *made, long long deadline) {
size_t n = 1, m = 0;
pic_nested_call *calls;
char **names, **args, *copy = strdup(lines), *line, *save = NULL;
cm_buf b = {NULL, 0, 0, 0};
int lost = 0;
for (const char *c = lines; *c; c++) {
n += *c == '\n';
}
calls = calloc(n, sizeof *calls);
names = calloc(n, sizeof *names);
args = calloc(n, sizeof *args);
if (!copy || !calls || !names || !args) {
free(copy);
free(calls);
free(names);
free(args);
return NULL;
}
n = 0;
for (line = strtok_r(copy, "\n", &save); line; line = strtok_r(NULL, "\n", &save)) {
char *tab = strchr(line, '\t');
if (tab) {
*tab = '\0';
}
names[n] = line;
args[n++] = tab ? tab + 1 : "{}";
}
for (size_t i = 0; i < n && *made + m < CM_MAX_CALLS; i++, m++) {
calls[m].tool = names[i];
calls[m].input = args[i];
calls[m].deadline_ms = deadline;
}
if (m && h->call(h->call_ctx, calls, m) != 0) {
lost = 1;
}
*made += m;
cm_puts(&b, "[");
for (size_t i = 0; !lost && i < n; i++) {
const pic_nested_call *c = i < m ? &calls[i] : NULL;
char *value = c && !c->is_error ? cm_value(db, c) : NULL, *item;
const char *error = c ? (c->result && *c->result ? c->result : "the tool failed") : "a script may make at most 256 tool calls";
item = value ? cm_sql_text(db, "SELECT json_object('ok', json('true'), 'value', json(?1))", value, NULL)
: cm_sql_text(db, "SELECT json_object('ok', json('false'), 'error', ?1)", error, NULL);
cm_puts(&b, i ? "," : "");
cm_puts(&b, item ? item : "{\"ok\":false,\"error\":\"out of memory\"}");
free(item);
free(value);
}
cm_puts(&b, "]");
for (size_t i = 0; i < m; i++) {
free(calls[i].result);
free(calls[i].image);
}
free(calls);
free(names);
free(args);
free(copy);
if (lost || b.bad) {
free(b.p);
return NULL;
}
return b.p;
}
/* 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 int cm_by_default(void) { return cm_on(); }
#ifndef PIC_CODEMODE_INPROC
/* ---- hosted: the script in a worker process ------------------------------------------------------- */
/* 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;
}
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;
size_t 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};
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 && cm_now_ms() > 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) {
/* From now: never before the worker's own, so a call cut here finds the script past it. */
deadline = timeout > 0 ? cm_now_ms() + timeout : 0;
max_tokens = tokens >= 0 ? tokens : CM_DEFAULT_TOKENS;
}
} else if (type == 'C') {
/* The script waits while pic runs its calls; each is cut at the script's deadline. */
char *answers = cm_answers(db, h, payload, &made, deadline);
if (!answers) {
lost = 1;
} else {
(void)cm_send(fd, 'R', answers, strlen(answers)); /* a worker gone ends as its EOF says */
free(answers);
}
} else if (type == 'D') {
done = payload;
payload = NULL;
}
free(payload);
}
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 */
}
/* The worker's side of a script: its calls, options and end go to the call over descriptor 3. */
static volatile sig_atomic_t cm_stop;
static const int cm_fd = 3;
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;
}
static char *cm_worker_call(void *ctx, const char *lines) {
char type = 0, *payload = NULL;
size_t len = 0;
(void)ctx;
if (cm_send(cm_fd, 'C', lines, strlen(lines)) != 0 || cm_recv(cm_fd, &type, &payload, &len) != 0 || type != 'R') {
free(payload);
_exit(1); /* the call is gone, or lost an outcome: it settles the script */
}
return payload;
}
static void cm_worker_options(void *ctx, long long timeout_ms, long long max_tokens) {
char opts[64];
(void)ctx;
(void)snprintf(opts, sizeof opts, "%lld %lld", timeout_ms > 0 ? timeout_ms : -1, max_tokens);
if (cm_send(cm_fd, 'T', opts, strlen(opts)) != 0) {
_exit(1);
}
}
static void cm_worker_finish(void *ctx, const char *json) {
(void)ctx;
if (cm_send(cm_fd, 'D', json, strlen(json)) != 0) {
_exit(1);
}
}
int pic_codemode_worker(void) {
struct sigaction sa;
cm_script sc;
char type = 0, *payload = NULL, *input, *catalog;
size_t len = 0;
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);
cm_on_io(0);
if (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;
}
}
memset(&sc, 0, sizeof sc);
sc.input = input;
sc.catalog = catalog;
sc.call = cm_worker_call;
sc.options = cm_worker_options;
sc.finish = cm_worker_finish;
sc.stop = &cm_stop;
return cm_script_run(&sc) == 0 ? 0 : 1;
}
#else
/* ---- no-OS: the script in pic's own process --------------------------------------------------- */
typedef struct {
sqlite3 *db;
const pic_tool_hooks *h;
size_t made;
long long max_tokens;
cm_script *sc;
char *done;
} cm_inproc;
static char *cm_inproc_call(void *ctx, const char *lines) {
cm_inproc *ip = ctx;
return cm_answers(ip->db, ip->h, lines, &ip->made, ip->sc->deadline);
}
static void cm_inproc_options(void *ctx, long long timeout_ms, long long max_tokens) {
cm_inproc *ip = ctx;
(void)timeout_ms;
ip->max_tokens = max_tokens >= 0 ? max_tokens : CM_DEFAULT_TOKENS;
}
static void cm_inproc_finish(void *ctx, const char *json) {
cm_inproc *ip = ctx;
free(ip->done);
ip->done = strdup(json);
}
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();
cm_script sc;
cm_inproc ip;
char *result = NULL;
int rc;
(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");
}
memset(&ip, 0, sizeof ip);
memset(&sc, 0, sizeof sc);
if (sqlite3_open(":memory:", &ip.db) != SQLITE_OK) {
sqlite3_close(ip.db);
return NULL;
}
ip.h = h;
ip.max_tokens = CM_DEFAULT_TOKENS;
ip.sc = ≻
sc.input = h->input ? h->input : "{}";
sc.catalog = cm_catalog ? cm_catalog : "[]";
sc.call = cm_inproc_call;
sc.options = cm_inproc_options;
sc.finish = cm_inproc_finish;
sc.ctx = &ip;
sc.stop = &pic_interrupted;
rc = cm_script_run(&sc);
if (rc == 0 || !sc.lost) {
result = ip.done ? cm_finish(ip.db, ip.done, started_ms, ip.max_tokens, h, is_error)
: cm_ended("Script sandbox failed: the engine could not start", started_ms, is_error);
}
free(ip.done);
sqlite3_close(ip.db);
return result;
}
int pic_codemode_worker(void) { return 1; } /* nothing to exec on a platform with no processes */
#endif
/* 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};
/* Sequential: one script at a time in a pic process, so one worker; a script's own calls run at
* once through parallel(). */
pic_tool_def pic_codemode_tool = {"codemode", cm_schema_bare, 0, 1, PIC_TIER_BUNDLED, 0, cm_by_default, cm_run, NULL};