print/JSON/RPC schemas, models.json, tool selection, and project trust and security boundaries.

Difficulty: ★★ | Prerequisites:01、02

1. Overview of four operating modes

Official CLI Integration documentation:The four modes share the same set of agents, sessions, resources and tools;Mode only determines how input enters, how output is exposed, and whether the process is resident.

  • Interactive

    interface
    Terminal UI
    life cycle
    until user exits
    Applicable scenarios
    People collaborate directly with Pi
  • Print

    interface
    stdout outputs the final text
    life cycle
    one call
    Applicable scenarios
    The script only requires the final reply
  • JSON

    interface
    stdout outputs JSONL events
    life cycle
    one call
    Applicable scenarios
    The process requires a structured progression
  • RPC

    interface
    JSONL commands/responses/events
    life cycle
    permanent
    Applicable scenarios
    Process requires two-way control
modeinterfacelife cycleApplicable scenarios
InteractiveTerminal UIuntil user exitsPeople collaborate directly with Pi
Printstdout outputs the final textone callThe script only requires the final reply
JSONstdout outputs JSONL eventsone callThe process requires a structured progression
RPCJSONL commands/responses/eventspermanentProcess requires two-way control

SDK No CLI mode, which embeds the agent directly into the Node.js/Bun process (see 06 SDK and RPC)。

1.1 Automatic selection rules of modes

  • stdin and stdout are both terminals: TUI is opened by default (unless specified --print、--mode json、--mode rpc);
  • Any redirected and no JSON/RPC selected: automatically used print mode;
  • --mode text Under terminal TUI will still be open, if you want to execute it all at once, please use --print。
pi [options] [--] [@files...] [messages...]
  • message

    behavior
    initial prompt
  • @path

    behavior
    Add a text file or image to the first tip
  • pipe stdin

    behavior
    Content is forwarded to the first prompt
  • --

    behavior
    Stop parsing option (prompt with - used at the beginning)
inputbehavior
messageinitial prompt
@pathAdd a text file or image to the first tip
pipe stdinContent is forwarded to the first prompt
--Stop parsing option (prompt with - used at the beginning)

2. Print mode

pi --print "Summarize the changes in this repository"
git diff | pi --print "Review this change"
pi -p @README.md "Summarize the project in three sentences"

Exit code rules:

  • final reply stopReason for error / aborted → non-zero exit;
  • Because the upper limit of the output token is truncated (length)→ still prints part of the text to stdout, stderr warning,Non-zero exit;
  • Error writes to stderr.

Suitable for: command substitution, pipelines, one-time jobs, git hooks, CI.

3. JSON event stream pattern

pi --mode json "Inspect this repository" > events.jsonl
pi --mode json "List files" 2>/dev/null | jq -c 'select(.type == "message_end")'

Key points:

  • The first record is session header({"type":"session",...}), followed by session events, and exit after running;
  • it is Structured event output, not "let the model output JSON";
  • message_update Contains only delta, use contentIndex splicing, and finally with message_end.message shall prevail;
  • The failed or aborted reply appears in the event stream, but does not by itself result in a non-zero exit code, you need to check the event yourself;
  • Strict JSONL framing: Press only LF (\n) split. Official special reminder:Node.js readline Not applicable, because it will also be split according to the Unicode line delimiter U+2028/U+2029, and these two characters are legal in the JSON string;
  • Stdout must be read continuously, otherwise Pi will be stuck if the pipe buffer is full; the log is on stderr.

message_update Nested event types in:text_start/delta/end、thinking_start/delta/end、toolcall_start/delta/end、done、error. Tool execution events:tool_execution_start/update/end. Others:queue_update、compaction_start/end、auto_retry_start/end Wait.

4. RPC mode (for introduction, see 06 SDK and RPC)

pi --mode rpc --no-session

stdin writes JSONL commands, and stdout reads responses and events:

{"id":"req-1","type":"get_state"}
{"id":"req-1","type":"response","command":"get_state","success":true,"data":{"...":"..."}}
RPC mode rejection `@file` Parameters, please use `prompt` The command is sent.

5. Model and Provider

5.1 Select the connection method (official decision table)

  • Supported subscriptions

    Recommended method
    /login Login
  • Provider API Key

    Recommended method
    /login Save, or set environment variables
  • Native GGUF model

    Recommended method
    Connect llama.cpp router(/llama management)
  • OpenAI / Anthropic / Google compatible endpoints

    Recommended method
    write models.json
  • Custom protocol or authentication process

    Recommended method
    Write or install a Provider extension (see 07 Advanced: MCP, Codemode and package distribution)
you haveRecommended method
Supported subscriptions/login Login
Provider API Key/login Save, or set environment variables
Native GGUF modelConnect llama.cpp router(/llama management)
OpenAI / Anthropic / Google compatible endpointswrite models.json
Custom protocol or authentication processWrite or install a Provider extension (see 07 Advanced: MCP, Codemode and package distribution)

Model directory:https://pi.dev/models . Pi has a built-in directory and can overlay and update data from pi.dev;pi update --models Force refresh;--offline or PI_OFFLINE=1 Disable automatic network activity.

5.2 Credential priority

--api-key(runtime)> auth.json Credentials saved in > models.json of apiKey > Provider environment variables/cloud environment credentials.

Use the key manager without writing the key to disk: in auth.json In the key, write it as ! The command at the beginning:

{
  "anthropic": {
    "type": "api_key",
    "key": "!security find-generic-password -ws 'anthropic'"
  }
}

Check credentials (can be used in scripts):

pi auth check --provider openai --json   # output ready / not_ready / invalid,exit code 0/1/2

5.3 Selecting models and thinking levels

Interacting:/model(Ctrl+S Save as default),/thinking、Ctrl+P Looping through scope models,/scoped-models Configure a circular list.

Command line:

pi --model sonnet:high                     # fuzzy matching + :thinking suffix
pi --provider anthropic --model claude-sonnet-4-5
pi --models "claude-*,gpt-5*"              # Startup and loop scoping support glob
pi --thinking low                          # off/minimal/low/medium/high/xhigh/max
pi --list-models qwen                      # List available models

Sessions record model and thought level changes; reverting to a session restores them, but Do not change defaults for new sessions. 1.0 fixes:--provider Without --model Errors are now reported instead of ignored.

5.4 Access compatible endpoints:models.json

File location:~/.pi/agent/models.json. Ollama example (official):

{
  "$schema": "https://pi.dev/schemas/models.schema.json",
  "providers": {
    "ollama": {
      "baseUrl": "http://localhost:11434/v1",
      "api": "openai-completions",
      "apiKey": "ollama",
      "models": [
        { "id": "qwen2.5-coder:7b" }
      ]
    }
  }
}

Key points:

  • The fake key is just to make the model "usable", Ollama will ignore it;
  • apiKey with header value support $NAME / ${NAME} environment variable interpolation, literal value, or !command(Executed on each request, not cached);
  • open /model The file will be reloaded;
  • If you want to add a proxy to the built-in Provider, just set baseUrl That’s it:
{
  "providers": {
    "anthropic": { "baseUrl": "https://proxy.example.com/v1" }
  }
}
  • modelOverrides Metadata of existing built-in models can be modified without replacing the entire list;
  • Also supports inputLimits.images.resize(Image encoding restrictions),promptCache(cache life),samplingParams / samplingParamsByThinkingLevel(OpenAI compatible API only) and other advanced fields, see the Models Configuration document for complete fields.

Applicable to Ollama, LM Studio, vLLM, SGLang and various agents.

5.5 Local model: llama.cpp

Pi directly integrates llama.cpp router: router discovers GGUF files and loads them on demand,/llama manage router,/model Select the loaded model. See details https://pi.dev/docs/latest/llama-cpp 。

6. Tool selection

pi --tools read,grep,find,ls --print "Review this project"   # read-only review
pi --tools +codemode,-write                                  # Increase or decrease based on the default (1.1+)
pi --no-builtin-tools                                        # Close built-in tools and keep extended tools
pi --no-tools                                                # Close all
pi --exclude-tools 'mcp__*'                                  # Exclude by pattern

Rules:

  • --tools When using a common name, it is whitelist, will replace the entire selection;
  • Contains only +name / -name is added or subtracted from the default collection (cannot be mixed with ordinary names, not supported) *);
  • --tools Default Do not remove MCP tool, unless an item starts with mcp__ Beginning;
  • Persistence: Settings defaultTools, for example {"defaultTools": ["+codemode"]}。

7. Session related command line options

  • -c, --continue

    function
    Continue current project recent session
  • -r, --resume

    function
    Open session selector
  • `--session <path

    function
    id>`
  • --session-id <id>

    function
    Open or create a session with the specified ID
  • `--fork <path

    function
    id>`
  • --no-session

    function
    Not persistent
  • -n, --name <name>

    function
    Set session display name
  • --export <input> [output]

    function
    Export the session file to HTML and exit
Optionsfunction
-c, --continueContinue current project recent session
-r, --resumeOpen session selector
`--session <pathid>`
--session-id <id>Open or create a session with the specified ID
`--fork <pathid>`
--no-sessionNot persistent
-n, --name <name>Set session display name
--export <input> [output]Export the session file to HTML and exit

8. Options related to resources and prompts

  • -e, --extension <path>

    function
    Load extension (repeatable; also possible builtin:mcp or npm:@x/y)
  • -ne, --no-extensions

    function
    Disable discovered, configured and built-in extensions
  • --skill / -ns

    function
    Load skills/disable skill discovery
  • --prompt-template / -np

    function
    Load templates/disable template discovery
  • --theme / --use-theme / --no-themes

    function
    Topic
  • -nc, --no-context-files

    function
    Disable AGENTS.md/CLAUDE.md discover
  • `--system-prompt <text

    function
    path>`
  • `--append-system-prompt <text

    function
    path>`
  • -a, --approve / -na, --no-approve

    function
    This process trusts/ignores project local configuration
  • --no-mcp

    function
    Disable built-in MCP for this run
Optionsfunction
-e, --extension <path>Load extension (repeatable; also possible builtin:mcp or npm:@x/y)
-ne, --no-extensionsDisable discovered, configured and built-in extensions
--skill / -nsLoad skills/disable skill discovery
--prompt-template / -npLoad templates/disable template discovery
--theme / --use-theme / --no-themesTopic
-nc, --no-context-filesDisable AGENTS.md/CLAUDE.md discover
`--system-prompt <textpath>`
`--append-system-prompt <textpath>`
-a, --approve / -na, --no-approveThis process trusts/ignores project local configuration
--no-mcpDisable built-in MCP for this run

9. Security: What you need to know

The core points of the official Security documentation:

  • Treat model-generated commands and code as untrustworthy. Pi reads, changes, and executes files with the permissions of the account that started it,Approval will not be requested before each tool call;
  • Files, comments, command output, and model replies may all pass prompt injection manipulating models;
  • Observe dialogue, project trust, review and modification Neither constitutes a safe boundary. Security comes from limiting the files, credentials, processes, and networks that Pi can access.

9.1 Comparison of operating modes

  • Run directly as current OS user

    protected content
    Things that this user cannot access
  • The entire Pi runs in a container/VM/sandbox

    protected content
    Host files and processes not exposed to the environment (usually the strongest practical option)
  • Pi outside, only built-in tools in an isolated environment (such as Gondolin)

    protected content
    Actions performed through these tools are isolated
Operation modeprotected content
Run directly as current OS userThings that this user cannot access
The entire Pi runs in a container/VM/sandboxHost files and processes not exposed to the environment (usually the strongest practical option)
Pi outside, only built-in tools in an isolated environment (such as Gondolin)Actions performed through these tools are isolated

9.2 Project trust

Pi requires a trust decision when the following resources exist:.pi/settings.json、.pi/mcp.json、.pi/extensions|skills|prompts|themes、.pi/SYSTEM.md|APPEND_SYSTEM.md, project .agents/skills。

Decision Sequence: Command Line --approve/--no-approve → User-level extended project_trust Event → ~/.pi/agent/trust.json Decisions saved in (/trust save) → global defaultProjectTrust(Default "ask")。

The trust prompt cannot pop up in non-interactive mode (print/JSON/RPC):"always" loading,"ask"/"never" Skip.

Note:AGENTS.md/CLAUDE.md context file Will be loaded whether trusted or not。

9.3 Isolation with Docker (official example)

FROM node:24-bookworm-slim

RUN apt-get update \\

&& apt-get install -y --no-install-recommends bash ca-certificates git ripgrep \\

&& rm -rf /var/lib/apt/lists/*

RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent

WORKDIR /workspace

ENTRYPOINT ["pi"]
docker build -t pi-sandbox -f Dockerfile.pi .

docker run --rm -it \\

-e ANTHROPIC_API_KEY \\

-v "$PWD:/workspace" \\

-v pi-agent-home:/root/.pi/agent \\

  pi-sandbox

Do not mount the host ~/.pi/agent, unless you want the container to have access to the host's configuration and credentials.

10. Small exercises

  1. Print + Pipe: Run in a git repository git diff HEAD~1 | pi -p "用中文列出这次提交的风险点", check the exit code echo $?。
  2. JSON Statistics:Run pi --mode json "列出当前目录的文件并统计行数" 2>/dev/null > ev.jsonl, use jq Statistics type the number of occurrences and find all tool_execution_start of toolName。
  3. read-only mode: use pi --tools read,grep,find,ls Start it, ask it to "modify the README", and see how it responds without the writing tools.
  4. Access local model: If you have Ollama installed, write according to Section 5.4 models.json, use pi --list-models qwen Confirm that it is visible before using --model Run a print.
  5. Credential checking:Write a shell script, first pi auth check --provider <你的provider>, executed only once when ready pi -p。
  6. Docker sandbox: Build the image according to 9.3 and run it in a temporary directory, confirm that Pi can only see the mounting directory.

11. Official sources