State
pic's state lives in SQLite: the journal per workspace (WORKSPACE/.pic/journal.sqlite, pic_*
tables) and ~/.pic/pic.sqlite (picu_* tables) for settings, the model catalog, credentials,
trust decisions, process records and the conversation lines that ctx archives. Several pic
processes share a journal, one conversation each; durability says what is committed
when and who may work a conversation. Remote control adds two picu_ tables for the
keys and paired phones of the relay.
The operating system seams
What touches the operating system sits behind two interfaces: pic_platform (clocks, entropy, the
locks, input files, the SQLite VFS, this program's path, a file's stamp and running a program) and pic_executor (file
operations and running commands).
Host-only code stays behind them, which is what makes the targets in where pic can
run reachable.
The terminal interface
The terminal interface is a module in the pic binary (src/tui/). It runs each request as a child
pic --json process and knows the run only through Pi's JSON events, so a fault in the interface
cannot touch a run.
Everything else it needs from a component or the user's state it asks as a command: the root hands
it ask (pic_tui_options), which answers Pi's RPC JSON in its process with the RPC command
registry (pic_rpc_answer), so whatever the interface asks, any RPC client can ask. Core's own
commands for a client (settings, trust, the model scope, bug reports, phones, hooks, process
records) are in src/rpc_core.c.
The model source
Core holds the model a request uses (pic_model, src/model.h) and Pi's thinking-level rules; a
registered source (pic_model_source_register; src/models.c by default) says what a name means
and what a reply costs. The wire API is a name, and an adapter registers under it.
The RPC command registry
pic --mode rpc (src/rpc.c, core) answers Pi's session commands itself and hands the rest to
components by name, without including their headers. A component declares a pic_rpc_command
(src/rpc.h): the command's name, a one-line help, flags, and an answer function over a
pic_rpc_call. PIC_RPC_JOURNAL_FREE answers with no journal open; PIC_RPC_IMMEDIATE answers
at once while a request runs instead of after it. The call carries the journal (or NULL), the
conversation id, the model, the workspace and the command line; answer returns 0 with data
(the response's JSON, or NULL), or -1 with err, and sets switched and next to move to
another conversation. The response, its id and the errors are core's, so a command keeps Pi's
shape whoever answers it.
To add one: declare the entry in the component (pic_rewind_rpc in src/rewind.c,
pic_models_rpc and pic_commands_rpc in src/listings.c), add it to rpc_commands in
src/main.c, and give the command its row in docs/reference/rpc-commands.md; make test-docs
finds the entry by its pic_rpc_command NAME = {"type" declaration. A name core answers itself
cannot be taken. Core asks the registry too: set_model, cycle_model and get_state read the
model list from whatever answers get_available_models, and with no component the list is empty.
Provider adapters
Each wire API is a bundled adapter that the composition root registers with core
(pic_provider_register, src/provider_http.h); core finds one by the model's API and speaks
only the neutral form. Provider adapters has the interface and how to add one.
The tool registry
Every tool a request can offer is a registration (pic_tool_def, src/toolreg.h): its name, the
definition providers are sent, whether a started call may run again after a crash, whether it runs
alone (Pi's sequential), its tier, whether it is one of pic's built-in tools and on by default,
and the function that runs it. Core registers read, bash, edit and write itself; the composition
root registers grep, find and ls (src/search.c) and send_message (src/peer.c) after them, which
is the order requests declare tools in. With nothing else registered, core offers its four.
The run function follows pic_tool_run's contract: hooks->started() exactly once before any
external effect, then the result. The call's JSON input is hooks->input; pic_tool_args holds
only the fields pic's own tools read. A call to a tool not in play answers "Tool X not found".
A tool may call tools: after it has started, hooks->call runs one round of inner calls
(pic_nested_call, a name and JSON input each) and returns when every one has its result. The loop
(nested_call in loop.c) refuses a tool not in play, codemode itself and the caller's own tool, and
input that is not an object; journals the round in pic_nested_effect (durability.md); gates each
call with PreToolUse, parent_tool_use_id in the hook's input; runs them on the normal path, at
once through pic_par_run when the reply's calls could be; and fires each one's ordinary
PostToolUse hooks. A required PostToolUse hook runs only on the calling call's own result. Inner
calls get Pi's tool_execution_* events with parentToolCallId and the id CALLER/N. A caller
running in a forked child asks pic for the round over toolpar's C frame. A call's deadline_ms
runs it in a child even alone, which pic_par_run tells to abort at the deadline (a tool that runs
alone gets the rest as its command timeout). An inner write or edit records its file history and an
inner bash its whole output, keyed by minus the row's id, so rewind and read reach them.
Codemode
Tier: bundled (src/codemode.c, vendor/quickjs), on the tool registry and the nested-call seam.
Clock: pi. Record: an effect per script and a nested effect per inner call. Default: off.
The root registers pic_codemode_tool last and calls pic_codemode_prepare once the tool flags are
applied: its description lists the tools then in play (Pi's declarations, rendered from each
schema, within Pi's 3000-token inline budget), and the same list is the script's ALL_TOOLS.
The engine is a seam, src/jsengine.h (make, evaluate, pump promise jobs, an interrupt, one
__host(KIND, ...) function of strings); jsengine_quickjs.c is its backend. The prelude,
src/codemode_js.inc, is ES5 and engine-neutral, and gives scripts calls that return values (the
host blocks while pic runs them) and parallel(). On a hosted build a call forks and execs pic __codemode-worker with
an empty environment and every descriptor closed but 3, a socket; the worker holds the engine (256
MB heap, 1 MB stack, the deadline and SIGINT through the interrupt) and sends each call or
parallel() round as a C frame, which the call hands to hooks->call with the script's deadline
and answers. A worker dies with its call (SIGIO on the socket's EOF). Codemode is sequential, so
a pic runs one worker at a time. The no-OS build (PIC_CODEMODE_INPROC, make pic-inproc builds
its shape on a host) runs the engine in pic itself, with the same limits, and calls hooks->call
from __host. The call truncates the output to max_output_tokens, the whole kept as
pic:output/N.
Replay safety is recorded with each call when the reply is (pic_effect.replay_safe, from the
registration), and recovery reads only that: a replay-safe call that started runs again, an unsafe
one becomes "outcome unknown" and never runs again (durability), even when the
recovering pic has no such tool registered.
The tool flags and the defaultTools setting are kept as given and applied, by Pi's rules, to
whatever is registered when asked, so a component may register a tool at startup or later
(pic_tool_register, pic_tool_unregister). A tool that is not built-in and is on by default
joins the defaults, --no-builtin-tools keeps it and --no-tools drops it; names, patterns,
+name, -name and --exclude-tools choose it like any tool. A session freezes the tools it
declares at its first request, so a tool registered later reaches only sessions that start after
it. The registry is plain C with no operating-system code. PIC_TEST_TOOL registers a tool in dev
builds for test/pic/registry.sh.
MCP servers
Tier: bundled (src/mcp.c, src/mcp_wire.c), on the tool registry and the credential store's
sealing (pic_cred_box). Clock: vendor. Record: an effect per call, as every tool's; each
server's last tool list in its row. Default: on, with no servers.
The composition root calls pic_mcp_register before the tool flags are applied: each enabled
server's saved tool list becomes registrations named mcp__SERVER__TOOL, replay-safe only when
the server marks the tool readOnlyHint, sequential for a stdio server. A call runs in the forked
child like any tool's: it opens the server's sealed values quietly (pic_cred_quiet, never asking
for a passphrase), checks they belong to the server's origin, connects and asks tools/call; the
text, cut at 20 KB with the whole kept as the call's pic:output/N, is the result. mcp_wire.c
speaks 2026-07-28 first (server/discover, _meta and MCP-Protocol-Version, Mcp-Method and
Mcp-Name on every request) and falls back to the 2025 handshake when a refusal is not one of that
revision's errors (-32020, -32021, -32022); a cached current revision that a server no longer
speaks is noticed on the refused request, which is then asked again. A 2025 session id is kept for
the connection only (pic_http_resp.want) and ended with DELETE.
A stdio server goes through the pipe seam in mcp_wire.h (pic_mcp_pipe_ops), which the
composition root fills with mcp_stdio.c on a host; without it a stdio server is refused.
pic_executor is not used: its run and spawn are one-shot, and a server needs a pipe held
across calls. Its tools are sequential, so a reply's calls to it run in pic itself, one by one,
on one process kept for the rest of the request and stopped at exit (stdin closed, then SIGTERM and
SIGKILL to its group); it is reported to pic ps as kind mcp.
A tool whose exposure (its toolExposure entry, else its server's) is deferred or codemode is
marked deferred in the registry (pic_tool_defer, with PIC_DEFER_SEARCH or PIC_DEFER_CODEMODE):
it runs and is chosen by the tool flags like any tool, but pic_toolset_schemas leaves it out of
the tools a session freezes, codemode's description does not list it (its catalog does), and a
deferred tool is in play whatever a plain --tools list names unless --exclude-tools or an
mcp__ entry removes it. PIC_DEFER_SEARCH tools are what pic_toolset_deferred gives
tool_search, and they switch it on; PIC_DEFER_CODEMODE tools switch codemode on (unless its
setting or PIC_CODEMODE says), are never searched or revealed, and pic_toolset_run answers "not
found" to a call of one that is not nested in a script. A hidden tool is not registered, nor is
one whose exposure is not an exposure. A project's override is a second layer kept beside the user's
(proj_exposure, proj_tool_exposure): mcp_exposure_of resolves the tool in each layer (a null
entry is no opinion, any other non-exposure is hidden) and takes the narrower (direct >
deferred > codemode > hidden), and the server is enabled only when both layers allow it.
Project entries find the user's server by its normalised name (- as _), as pic mcp add refuses
a second name that normalises the same. Whether a server has resources comes from the capabilities
server/discover or initialize gives, so listing a server asks again rather than using the cached
revision. pic_codemode_prepare runs after pic_mcp_register, so the catalog scripts get has the
MCP tools; --no-mcp skips pic_mcp_register.
The resource tools (list_mcp_resources, list_mcp_resource_templates, read_mcp_resource) are
registered when a reachable server's capabilities named resources at its last listing (resources
in its row), with the widest exposure among those servers; they are replay-safe, not read_only, and
sequential when one of them is a stdio server. Each stands for the servers a call reaches
(pic_tool_stand_for: mcp__SERVER__ per server), so perm.c counts it read-only only when
readOnlyTools names every one whole; the registry holds the function, so core never reads MCP. A
call asks the server in the child, as a tool call does (mcp_row_ask).
tool_search
Tier: bundled (src/toolsearch.c), on the tool registry. Clock: pi. Record: an effect per call, and
pic_tool_reveal(effect_id, ordinal, name) rows in the result's transaction. Default: on when some
registered tool is deferred.
tool_search is replay-safe and sequential, so it runs in pic itself, one call at a time. It
ranks the deferred tools in play with Pi's BM25 (names weigh three times a term's IDF; a query that
is a tool's name ranks it first), skipping those already declared on the branch
(pic_tool_hooks.declared, from the journal), and hands the names it found back in
pic_tool_hooks.reveal. run_effect writes them as pic_tool_reveal rows in the same transaction
as the result, so a crash leaves both or neither. pic_session_text(..., "tools"), which every
adapter's request reads, appends the schema of each tool revealed by an effect on the branch (the
chain of entries from the conversation's head, so a fork made after a search has it and one made
before does not) to the session's frozen tools, in the order they were revealed, and skips names
already there or no longer registered. The frozen pic_session.tools is never rewritten, and a
revealed tool's schema is read from the registry when the request is built.
/mcp (src/tui/app.c) is the settings panel's frame with rows from get_mcp_servers. It
reconnects through a pic mcp list child, so a slow server never holds the screen, and asks
set_mcp_server_enabled, set_mcp_tool_exposure, remove_mcp_server and add_mcp_server in
process; the interface never links mcp.c.
Where the manual's facts are kept
- Lapse compaction:
pic_generation.reason(lapse),idle_secondsandcontext_tokens. Every cold cache with lapse compaction on is the context policy's PreRequest answer, apic_hook_runrow (reasonlapse,refthe turn, always 0: a lapse is only answered before a submission's first request) whose context carries its arm (compact,holdoutorsmall, under the floor), mode (trimorsummary) and calibration. The first answer for a turn stands.pic usage --lapsesums each answer's window: the done requests from it to the next in the session, by mode. Journals from before the seam keep theirpic_lapserows, read as summary mode. - Imported usage (
pic import --claude): theusageof the reply'spic_generationrow, as a native reply's (input_tokens,cache_read_input_tokens,cache_creation_input_tokens,output_tokens) plusmodeland"imported":true, with nopic_tokensorpic_cost. Lapse calibration and the context estimate read it like any reply's;pic usage --by-trialskips rows withimported(its token sums fall back to the raw fields, so the marker is what keeps them out of spend), and cost sums read onlypic_cost. A message id Claude Code wrote several times gives one row, each field the largest seen; absent or non-integer fields are left out, and a reply with none has no usage. It is written after the import's own chars/4 estimate, so that figure stays a pure estimate. No schema change:importedis a key of the usage JSON. - Trial labels:
pic_submission.trial. - What started a conversation:
pic_session_origin(session_id, origin, parent), a table of its own (no schema version: durability).originis one ofperson,phone,agent,wakeandheadless;parent, an agent's, isJOURNAL/IDwith the journal's resolved path. A conversation with no row (made before the table, or by an older pic) reads asperson(PIC_STARTED_BY_SQL). A process takes its origin fromPIC_ORIGINandPIC_PARENTat start, elsepersonwith a terminal on stdin and stderr, elseheadless(pic_store_origin), and unsets both; new conversations record it (pic_session_stamp). A loop's own new conversation recordswakeunless a person or a phone made the loop. When a request starts, its process sets both toagentand the conversation (pic_session_env), so what its tool calls and hooks start records it as parent; the terminal hands its own to its request children, andpic remotesetsphone.pic remoteopens journals narrowly, which never creates the table: its queries fall back to reading every conversation as a person's. - The Pi lines hooks read:
picu_pi_session_linein~/.pic/pic.sqlite. - Process records (
pic ps):picu_procin~/.pic/pic.sqlite. - Saved model endpoints (endpoints.c):
picu_endpoint(name, url, models, added_ms, fetched_ms, error)in~/.pic/pic.sqlite;modelsis the JSON array[{id, owned_by}]of the last fetch that worked,errorthe last failure's reason. The key ispicu_credential's row named for the endpoint. models.c resolvesNAME/MODELto the URL (openai-completions) only when no built-in or models-file provider has the name. - MCP servers (mcp.c):
picu_mcp_server(name, transport, url, command, cwd, header_names, env_names, sealed, description, exposure, timeout, enabled, era, tools, added_ms, listed_ms, error, resources, tool_exposure)in~/.pic/pic.sqlite;tool_exposureis Pi'stoolExposure, a JSON object of tool names or patterns to exposures, andresourceswhether the last listing's capabilities named resources.commandis the stdio argv as a JSON array;header_namesandenv_namesare JSON arrays of names only.sealedis one JSON object,{"origin", "headers": [[name, value]], "env": [[name, value]]}, sealed under the AADmcp-server:NAME;pic auth rekeyreseals it andpic auth resetclears it.toolsis the lasttools/listas given,erathe revision spoken. A trusted project's servers are read from its files each time and their listings kept inpicu_mcp_project(workspace, name, entry, era, tools, listed_ms, error, resources), keyed by the workspace's real path; the cachedtoolscount only whileentry(the file's entry, asjson()normalises it) is unchanged. - Skill use, for ranking the skill list under its budget:
picu_skill_use(name, path, uses, last_ms)in~/.pic/pic.sqlite, keyed by the skill's name and the path it was discovered at. skills.c adds a row on/skill:NAMEand, through the tools' read observer (pic_tool_read_observer, wired in main.c), on a read of a skill's file. The write waits 250 ms at most and its failure is ignored. The score isuses x max(0.5^(days since last_ms / 7), 0.1). The listing is built by skills.c, which readsskillBudgetitself; core handspic_system_promptonly the model's context window.
The manual in the binary
src/manual.inc holds docs/manual and docs/reference as C strings, built by tools/manual-inc.sh;
src/help.c serves them to pic help and the terminal's /help TOPIC. They cost about 65 KB of
the binary. The text is a constant in the image, so it works with no filesystem.
The credential store
Each stored key is sealed with ChaCha20-Poly1305 (the provider's name bound as associated data), so
no plaintext key reaches the database, its WAL, a backup or a log. picu_credential_key records
where the 32-byte master key comes from (source) and a verifier (a known text sealed under it), so
a wrong key is refused cleanly. The sources (key sources):
source |
The key | kdf |
|---|---|---|
keychain |
random, a generic-password item (service pic credential store, account the store's path), as 64 hex digits |
none |
file |
random, ~/.pic/master.key beside the store: 64 hex digits, 0600, written to a temporary and renamed |
none |
passphrase |
stretched with PBKDF2-HMAC-SHA256 (600,000 iterations, the row's random salt) | pbkdf2-sha256 |
Core asks the platform for the key through secret_key (the recorded source, the store's path, and
for a passphrase --passphrase-fd or the command), keeps a new raw key with secret_keep (NULL: the
platform's choice for a new store) and clears an old one with secret_drop. On a host, only
platform.c runs /usr/bin/security, secret-tool and tmutil (as children, by posix_spawn)
and reads or writes the key file. A keychain is used only for the store under the account's own
home; PIC_TEST_KEYCHAIN names a stand-in. pic_cred_quiet opens or makes a store when no one has
to type anything; the terminal interface calls it before it shows a passphrase field.
pic_cred_rekey reseals every sealed row (picu_credential under key:NAME, picu_remote_key
under remote-key:NAME, picu_remote_device under remote-device: and the id in hex) in one
BEGIN IMMEDIATE transaction with the new record, then clears the old source. After a passphrase
typed at a prompt, core calls the interface's offer (pic_cred_offer_register); a no is the setting
cred.offer = declined. What the store protects against is in
credentials.
A subscription sign-in is a row of kind oauth: a JSON object (access, refresh, expires in
ms, and whatever else its flow keeps, such as OpenAI's issued clientId), sealed whole like a key.
Core (cred.c) knows only that shape; the flows are bundled files (oauth_*.c, over oauth.c)
that the composition root registers through pic_cred_oauth_register, so core names no provider and
links without them. A refresh, before expiry (within a minute) or after a 401 (once per request),
runs under an exclusive lock on ~/.pic/credential.lock, not a database transaction, so no writer
of pic.sqlite waits on the network. Inside the lock the row is read again: when another process
already replaced the refused token, its token is used and the refresh token, which may rotate, is
not spent twice. A picu_credential made before the oauth kind is rebuilt once with the wider
CHECK.
Named keys and their health
A provider's extra keys are rows named provider:label, sealed under key:provider:label; the row
named provider stays its default. Which one a request uses (cred.c, cred_choose): the label
pic_cred_override set for the process (--key), else the setting activeKey:PROVIDER, else the
provider's row, else its oldest named row, else the models file's literal, else the variable;
env and file name the last two. A chosen label the provider lacks is an error, never a fall back.
picu_credential_health(name, state, reason, status, until_ms, checked_ms, remaining, unit, probed_ms) keeps, per
credential name, the last thing a reply said: ok, invalid, credit or limited (transient
and other failures are not written). checked_ms of a failure seen again keeps its first time. A
variable's name is env:VAR: and twelve hex digits of HMAC-SHA256 over its value under a random
per-install salt (picu_meta.credential_salt); recording one value's state drops the others' of
the same variable. No key text is stored.
http.c keeps the anthropic-ratelimit-* and x-ratelimit-* header lines of a response;
provider_http.c hands a refusal's status, body, message and those lines to
pic_cred_classify, which asks the registered pic_cred_failure_ops (keyhealth.c: vendor wording
as data rows) or falls back on the status. A 200 records ok. Only a transient class is retried.
The store carries the credential and label each request used (s->credential), and the loop writes
it to pic_generation.credential with the attempt's outcome (schema 18).
The behavioural reference
reference/pi.lock.json pins the Pi revision used as the behavioural reference. Pi's source is not
part of this repository. The decisions in force are in the implementation
plan.