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

Artifact [5efdf4866d]

Artifact 5efdf4866d69519f6117ce3ade8835016377285c24c344a69909d61611e05c61:


/* The system prompt, in Pi's section order: preamble, tools, rules, project
 * context, skills, working directory. Project instructions are found as Pi finds
 * them: in each directory the first of AGENTS.override.md, AGENTS.md,
 * AGENTS.MD, CLAUDE.md, CLAUDE.MD, from the filesystem root down to the
 * workspace, after an optional global file ~/.pic/AGENTS.md. */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "input.h"
#include "pic.h"
#include "skills.h"
#include "userdb.h"

#define INSTRUCTIONS_CAP (256u * 1024u) /* bytes kept from one instructions file */

static const char preamble[] =
    "You are a coding assistant running inside pic, a durable coding agent harness. Help users inspect files, run "
    "commands, and modify code.";

static const char *const ctx_names[] = {"AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"};

typedef struct {
    char *buf;
    size_t len, cap;
    int failed;
} ctx_text;

static void ctx_add(ctx_text *t, const char *s, size_t n) {
    if (t->failed) {
        return;
    }
    if (t->len + n + 1 > t->cap) {
        size_t cap = t->cap ? t->cap : 4096;
        char *p;
        while (cap < t->len + n + 1) {
            cap *= 2;
        }
        if (!(p = realloc(t->buf, cap))) {
            t->failed = 1;
            return;
        }
        t->buf = p;
        t->cap = cap;
    }
    memcpy(t->buf + t->len, s, n);
    t->len += n;
    t->buf[t->len] = '\0';
}

static void adds(ctx_text *t, const char *s) { ctx_add(t, s, strlen(s)); }

/* Pi's per-tool prompt snippet and guideline rules, for the tools in play. */
static const struct {
    const char *name, *snippet, *guidelines[3];
} tool_prompts[] = {
    {"read", "Read file contents", {"Use read to examine files instead of cat or sed."}},
    {"bash", "Execute bash commands (ls, grep, find, etc.)", {NULL}},
    {"edit",
     "Make precise file edits with exact text replacement, including multiple disjoint edits in one call",
     {"Use edit for targeted changes. Batch changes to one file in a single call.",
      "Each edits[].oldText must exactly and uniquely match the original file. Keep matches short and "
      "non-overlapping; merge nearby changes without including large unchanged regions."}},
    {"write", "Create or overwrite files", {"Use write only for new files or complete rewrites."}},
    {"grep", "Search file contents for patterns (respects .gitignore)", {NULL}},
    {"find", "Find files by glob pattern (respects .gitignore)", {NULL}},
    {"ls", "List directory contents", {NULL}},
};

static void add_tools_and_rules(ctx_text *t) {
    const char *on[8];
    size_t n = pic_toolset_names(on, 8);
    adds(t, "<tools>\n");
    if (n == 0) {
        adds(t, "(none)\n");
    }
    for (size_t i = 0; i < n; i++) {
        for (size_t k = 0; k < sizeof tool_prompts / sizeof tool_prompts[0]; k++) {
            if (strcmp(on[i], tool_prompts[k].name) == 0) {
                adds(t, "- ");
                adds(t, on[i]);
                adds(t, ": ");
                adds(t, tool_prompts[k].snippet);
                adds(t, "\n");
            }
        }
    }
    adds(t, "</tools>\n\n<rules>\n");
    if (pic_toolset_on("bash") && !pic_toolset_on("grep") && !pic_toolset_on("find") && !pic_toolset_on("ls")) {
        adds(t, "- Use bash for file operations like ls, rg, find\n");
    }
    for (size_t i = 0; i < n; i++) {
        for (size_t k = 0; k < sizeof tool_prompts / sizeof tool_prompts[0]; k++) {
            if (strcmp(on[i], tool_prompts[k].name) == 0) {
                for (size_t g = 0; g < 3 && tool_prompts[k].guidelines[g]; g++) {
                    adds(t, "- ");
                    adds(t, tool_prompts[k].guidelines[g]);
                    adds(t, "\n");
                }
            }
        }
    }
    adds(t, "- Be concise in your responses\n"
            "- Show file paths clearly when working with files\n"
            "</rules>");
}

/* Appends one instructions block if path is a readable regular file. */
static int add_file(ctx_text *t, const char *path, int *any) {
    size_t len = 0;
    int cut = 0;
    char *buf = pic_input_read(path, INSTRUCTIONS_CAP + 3, PIC_INPUT_TRUNCATE, &len, &cut), *body;
    if (!buf) {
        return 0;
    }
    body = len >= 3 && memcmp(buf, "\xEF\xBB\xBF", 3) == 0 ? buf + 3 : buf; /* drop a byte-order mark */
    len -= (size_t)(body - buf);
    if (len > INSTRUCTIONS_CAP) {
        len = INSTRUCTIONS_CAP;
        cut = 1;
    }
    if (!*any) {
        adds(t, "<project_context>\nProject-specific instructions and guidelines:\n");
        *any = 1;
    }
    adds(t, "\n<project_instructions path=\"");
    adds(t, path);
    adds(t, "\">\n");
    ctx_add(t, body, len);
    if (cut) {
        adds(t, "\n[pic: instructions truncated at 256KB]");
    }
    free(buf);
    adds(t, "\n</project_instructions>\n");
    return 1;
}

/* The first instructions file in dir, if any. */
static void add_dir(ctx_text *t, const char *dir, int *any) {
    for (size_t i = 0; i < sizeof ctx_names / sizeof ctx_names[0]; i++) {
        char path[PATH_MAX];
        if (snprintf(path, sizeof path, "%s/%s", strcmp(dir, "/") == 0 ? "" : dir, ctx_names[i]) >= (int)sizeof path) {
            return;
        }
        if (add_file(t, path, any)) {
            return;
        }
    }
}

/* The project instructions block for a workspace (resolved path in real),
 * appended to t; nothing when there are no instruction files. */
static void project_context(ctx_text *t, char *real) {
    char *home = getenv("HOME");
    int any = 0;
    if (home && *home) {
        char global[PATH_MAX];
        if (snprintf(global, sizeof global, "%s/.pic/AGENTS.md", home) < (int)sizeof global) {
            (void)add_file(t, global, &any);
        }
    }
    /* Outermost directory first, the workspace last. */
    add_dir(t, "/", &any);
    for (size_t i = 1; real[0] == '/' && real[i]; i++) {
        if (real[i] == '/') {
            real[i] = '\0';
            add_dir(t, real, &any);
            real[i] = '/';
        }
    }
    if (strcmp(real, "/") != 0) {
        add_dir(t, real, &any);
    }
    if (any) {
        adds(t, "</project_context>");
    }
}

static const char *replace_arg;
static const char *append_arg[PIC_SYSTEM_APPEND_MAX];
static size_t append_n;

void pic_system_prompt_args(const char *replace, const char *const *append, size_t n) {
    replace_arg = replace;
    append_n = n < PIC_SYSTEM_APPEND_MAX ? n : PIC_SYSTEM_APPEND_MAX;
    for (size_t i = 0; i < append_n; i++) {
        append_arg[i] = append[i];
    }
}

/* The contents of the regular file at path (a byte-order mark dropped), or NULL. */
static char *read_text(const char *path) {
    size_t len = 0;
    int cut = 0;
    char *buf = pic_input_read(path, INSTRUCTIONS_CAP, PIC_INPUT_TRUNCATE, &len, &cut);
    if (buf && len >= 3 && memcmp(buf, "\xEF\xBB\xBF", 3) == 0) {
        memmove(buf, buf + 3, len - 2);
    }
    return buf;
}

/* Pi's resolvePromptInput: the file's contents when input names a readable
 * file, else input itself. NULL for an empty input. */
static char *prompt_input(const char *input) {
    char *ctx_text;
    if (!*input) {
        return NULL;
    }
    ctx_text = read_text(input);
    return ctx_text ? ctx_text : strdup(input);
}

/* Pi's discoverSystemPromptFile: WORKSPACE/.pic/NAME when the workspace is
 * trusted, else ~/.pic/NAME. */
static char *discovered(const char *real, const char *name) {
    char path[PATH_MAX], *home = getenv("HOME"), *ctx_text = NULL;
    if (pic_trust_get(real) == 1 && snprintf(path, sizeof path, "%s/.pic/%s", real, name) < (int)sizeof path) {
        ctx_text = read_text(path);
    }
    if (!ctx_text && home && *home && snprintf(path, sizeof path, "%s/.pic/%s", home, name) < (int)sizeof path) {
        ctx_text = read_text(path);
    }
    return ctx_text;
}

char *pic_project_instructions(const char *workspace) {
    ctx_text t = {NULL, 0, 0, 0};
    char real[PATH_MAX];
    if (!realpath(workspace, real)) {
        (void)snprintf(real, sizeof real, "%s", workspace);
    }
    adds(&t, "");
    project_context(&t, real);
    if (t.failed) {
        free(t.buf);
        return NULL;
    }
    return t.buf;
}

char *pic_system_prompt(const char *workspace) {
    ctx_text t = {NULL, 0, 0, 0};
    char real[PATH_MAX], *instructions = pic_project_instructions(workspace);
    if (!instructions) {
        return NULL;
    }
    if (!realpath(workspace, real)) {
        (void)snprintf(real, sizeof real, "%s", workspace);
    }
    {
        char *custom = replace_arg ? prompt_input(replace_arg) : discovered(real, "SYSTEM.md");
        if (custom) { /* Pi's custom prompt replaces the preamble, the tools and the rules */
            adds(&t, custom);
            free(custom);
        } else {
            adds(&t, preamble);
            adds(&t, "\n\n");
            add_tools_and_rules(&t);
        }
    }
    {
        ctx_text extra = {NULL, 0, 0, 0};
        if (append_n == 0) {
            char *found = discovered(real, "APPEND_SYSTEM.md");
            if (found) {
                adds(&extra, found);
                free(found);
            }
        }
        for (size_t i = 0; i < append_n; i++) {
            char *one = prompt_input(append_arg[i]);
            if (one) {
                adds(&extra, extra.len ? "\n\n" : "");
                adds(&extra, one);
                free(one);
            }
        }
        if (extra.len) {
            adds(&t, "\n\n<addendum>\n");
            adds(&t, extra.buf);
            adds(&t, "\n</addendum>");
        }
        t.failed |= extra.failed;
        free(extra.buf);
    }
    if (*instructions) {
        adds(&t, "\n\n");
        adds(&t, instructions);
    }
    free(instructions);
    {
        pic_skills skills;
        char *listing;
        if (pic_skills_load(&skills, real, pic_trust_get(real) == 1, NULL) == 0) {
            listing = pic_skills_prompt(&skills);
            if (listing && *listing) {
                adds(&t, "\n\n");
                adds(&t, listing);
            }
            free(listing);
            pic_skills_free(&skills);
        }
    }
    adds(&t, "\n\n<cwd>\n");
    adds(&t, real);
    adds(&t, "\n</cwd>");
    if (t.failed) {
        free(t.buf);
        return NULL;
    }
    return t.buf;
}