Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Update pi-agent skill to latest Pi docs
Timothy Kassisef1b2d8026bd
diff --git a/skills/pi-agent/SKILL.md b/skills/pi-agent/SKILL.mdindex 7ef8b114..c40f9f37 100644--- a/skills/pi-agent/SKILL.md+++ b/skills/pi-agent/SKILL.md@@ -1,10 +1,10 @@---name: pi-agent-description: Build with and use Pi, the minimal terminal coding harness. Use for installing Pi, configuring providers/models/settings, creating Pi skills/extensions/packages/themes/prompt templates, embedding Pi through the SDK, integrating over RPC or JSON event streams, parsing sessions, developing custom Pi providers and TUI components, or using ecosystem packages such as pi-subagents (delegation/orchestration), pi-mcp-adapter (MCP servers), pi-interview (interactive forms), and pi-web-access (web search, fetching, video understanding).+description: Build with and use Pi, the minimal terminal coding harness. Use for installing Pi, configuring providers/models/settings/environment variables, creating Pi skills/extensions/packages/themes/prompt templates, embedding Pi through the SDK, integrating over RPC or JSON event streams, parsing sessions, running local models through the llama.cpp router, developing custom Pi providers and TUI components, or using ecosystem packages such as pi-subagents (delegation/orchestration), pi-mcp-adapter (MCP servers), pi-interview (interactive forms), and pi-web-access (web search, fetching, video understanding).license: MITcompatibility: Requires Node.js/npm for Pi CLI and SDK usage. Pi package name is @earendil-works/pi-coding-agent.metadata:- version: "1.1"+ version: "1.2"skill-author: K-Dense Inc.---@@ -18,10 +18,14 @@ Pick the reference before answering or coding:| User intent | Read ||---|---|+| What Pi is, docs map, install methods | `references/overview.md` || Install, authenticate, first run | `references/quickstart.md` |-| Day-to-day CLI usage, commands, modes, flags | `references/usage.md` |+| Day-to-day CLI usage, commands, modes, flags, project trust | `references/usage.md` || Provider auth, API keys, cloud provider setup | `references/providers.md` |-| Custom model entries, local models, proxies | `references/models.md` |+| Custom model entries, local models, proxies, compat flags | `references/models.md` |+| Local llama.cpp router, `/llama`, model download/load | `references/llama-cpp.md` |+| Settings keys and defaults | `references/settings.md` |+| `PI_*` and other environment variables | `references/environment-variables.md` || Extension development, custom tools, events, commands | `references/extensions.md` || Custom provider implementation, OAuth, custom streaming | `references/custom-provider.md` || Embed Pi in Node/TypeScript | `references/sdk.md` |@@ -42,9 +46,9 @@ Pick the reference before answering or coding:## Build-On-Pi Defaults-Prefer the SDK for Node/TypeScript apps that need type safety, direct state access, in-process custom tools/extensions, or custom resource loading. Use `createAgentSession()` for a single stable session; use `createAgentSessionRuntime()` when the app must replace sessions through new/resume/fork/clone/import flows.+Prefer the SDK for Node/TypeScript apps that need type safety, direct state access, in-process custom tools/extensions, or custom resource loading. Use `createAgentSession()` for a single stable session; use `createAgentSessionRuntime()` when the app must replace sessions through new/resume/fork/clone/import flows. Auth and model lookup go through `ModelRuntime.create()`.-Prefer RPC mode when the client is not Node.js, needs process isolation, or wants a language-agnostic JSONL protocol. Start with `pi --mode rpc --no-session` for stateless subprocess integration, then add session flags when persistence matters.+Prefer RPC mode when the client is not Node.js, needs process isolation, or wants a language-agnostic JSONL protocol. Start with `pi --mode rpc --no-session` for stateless subprocess integration, then add session flags when persistence matters. Split records on `\n` only — Node `readline` is not protocol-compliant.Prefer JSON mode for one-shot command-line pipelines that only need streamed events, not bidirectional control: `pi --mode json "prompt"`.@@ -54,7 +58,7 @@ Use packages when sharing or installing reusable extensions, skills, prompt temp## Safety Defaults-Pi is local and not sandboxed by default. Treat extensions, packages, skills, shell commands, and project-local `.pi` resources as code with the permissions of the Pi process. For untrusted repos or unattended automation, isolate with Docker, OpenShell, Gondolin, a VM, or a remote sandbox.+Pi is local and not sandboxed by default. Treat extensions, packages, skills, shell commands, and project-local `.pi` resources as code with the permissions of the Pi process. Project trust only guards which project inputs load — it is not a sandbox. For untrusted repos or unattended automation, isolate with Docker, OpenShell, Gondolin, a VM, or a remote sandbox.Do not store secrets in project files. Prefer env vars, `~/.pi/agent/auth.json`, OAuth via `/login`, or command-backed secret lookups in `models.json`/provider config.@@ -67,9 +71,12 @@ pi -p "Summarize this codebase"pi --mode json "List files"pi --mode rpc --no-sessionpi --provider anthropic --model claude-sonnet-4-5+pi --model sonnet:high "Solve this complex problem"pi --tools read,grep,find,ls -p "Review this repository"+pi install npm:pi-subagents+pi update --all```## Source Coverage-These references summarize the Pi documentation at `https://pi.dev/docs/latest` and each docs page found under it as of this skill version, plus the package pages for `pi-subagents`, `pi-mcp-adapter`, `pi-interview`, and `pi-web-access` at `https://pi.dev/packages/`. When exact API behavior matters, prefer the cited reference page and inspect installed TypeScript definitions under `node_modules/@earendil-works/pi-coding-agent/dist/` and `node_modules/@earendil-works/pi-ai/dist/`.+These references summarize the Pi documentation at `https://pi.dev/docs/latest` and every docs page found under it as of this skill version, plus the package pages for `pi-subagents`, `pi-mcp-adapter`, `pi-interview`, and `pi-web-access` at `https://pi.dev/packages/`. Package details were cross-checked against the published npm READMEs (`pi-web-access` 0.14.0, `pi-mcp-adapter` 2.15.0, `pi-subagents` 0.37.0, `pi-interview` 0.9.0). When exact API behavior matters, prefer the cited reference page and inspect installed TypeScript definitions under `node_modules/@earendil-works/pi-coding-agent/dist/` and `node_modules/@earendil-works/pi-ai/dist/`.diff --git a/skills/pi-agent/references/compaction.md b/skills/pi-agent/references/compaction.mdindex 2271623b..e5b09749 100644--- a/skills/pi-agent/references/compaction.md+++ b/skills/pi-agent/references/compaction.md@@ -2,46 +2,66 @@Source: https://pi.dev/docs/latest/compaction-Pi uses compaction to summarize older content when context grows too long, and branch summarization to preserve context when changing branches.--## Mechanisms+Pi has two summarization mechanisms that share the same structured summary format and track file operations cumulatively.| Mechanism | Trigger | Purpose ||---|---|---|-| Compaction | context exceeds threshold or `/compact` | Summarize old messages to free context |+| Compaction | context exceeds threshold, or `/compact` | Summarize old messages to free context || Branch summarization | `/tree` navigation | Preserve context when switching branches |-## Auto-Compaction+Both use fresh routing session IDs and, where the provider supports it, disable prompt-cache writes because these one-off prompts are unlikely to be reused.-Triggers when:+## Auto-Compaction-```text-contextTokens > contextWindow - reserveTokens-```+Triggers when `contextTokens > contextWindow - reserveTokens`. Defaults: `reserveTokens` 16384, `keepRecentTokens` 20000, configured under `compaction` in global or project settings. `/compact [instructions]` works even with auto-compaction disabled.-Defaults: `reserveTokens` 16384, `keepRecentTokens` 20000. Configure under `compaction` in settings.+Steps: walk backwards from the newest message accumulating token estimates until `keepRecentTokens` is reached (the cut point) → collect messages from the previous kept boundary (or session start) to the cut point → summarize with the structured format, passing any previous summary as iterative context → append a `CompactionEntry` → reload context as summary plus messages from `firstKeptEntryId`.-Compaction finds a cut point, summarizes old messages, appends a `CompactionEntry`, then reloads session context as summary plus kept messages.+On repeated compactions the summarized span starts at the previous compaction's kept boundary (`firstKeptEntryId`), not at the compaction entry, falling back to the entry after the previous compaction when that kept entry is not on the path. This re-includes messages that survived the earlier pass. `tokensBefore` is recalculated from the rebuilt context before writing the new entry.-Valid cut points: user messages, assistant messages, bash execution messages, and custom messages. Pi never cuts at tool results.+Valid cut points: user messages, assistant messages, bash execution messages, and custom messages (`custom_message`, `branch_summary`). Pi never cuts at tool results.## Split Turns-If one turn exceeds `keepRecentTokens`, Pi may cut mid-turn at an assistant message, generate a history summary plus turn-prefix summary, and merge them.+A turn starts with a user message and includes all assistant responses and tool calls until the next user message. When a single turn exceeds `keepRecentTokens`, the cut lands mid-turn at an assistant message (`isSplitTurn`). Pi then generates two summaries — a history summary for previous context and a turn-prefix summary for the early part of the split turn — and merges them.++## Branch Summarization++On `/tree` navigation to a different branch: find the deepest common ancestor, walk from the old leaf back to it, include messages up to the token budget newest-first, summarize, and append a `BranchSummaryEntry` at the navigation point.++Both mechanisms extract file operations from the tool calls being summarized **and** from previous compaction/branch-summary `details`, so read/modified file tracking accumulates across passes.## Entry Shapes-`CompactionEntry` contains `type`, `id`, `parentId`, `timestamp`, `summary`, `firstKeptEntryId`, `tokensBefore`, optional `fromHook`, and optional `details`.+`CompactionEntry`: `type`, `id`, `parentId`, `timestamp`, `summary`, `firstKeptEntryId`, `tokensBefore`, optional `usage` (LLM usage that generated the summary; counted in session totals), optional `fromHook` (legacy name for "provided by extension"), optional `details`.++`BranchSummaryEntry`: same plus `fromId` instead of `firstKeptEntryId`.-`BranchSummaryEntry` contains `type`, `id`, `parentId`, `timestamp`, `summary`, `fromId`, optional `fromHook`, and optional `details`.+Default `details` is `{ readFiles: string[], modifiedFiles: string[] }`; extensions may store any JSON-serializable structure. Newer harness-generated compactions also embed `retainedTail` — see `references/session-format.md`.-Default details track `readFiles` and `modifiedFiles`; extensions may store JSON-serializable custom details.+## Summary Format++Sections: `## Goal`, `## Constraints & Preferences`, `## Progress` (Done / In Progress / Blocked), `## Key Decisions`, `## Next Steps`, `## Critical Context`, then `<read-files>` and `<modified-files>` blocks.++## Message Serialization++`serializeConversation()` renders messages as `[User]:`, `[Assistant thinking]:`, `[Assistant]:`, `[Assistant tool calls]:`, `[Tool result]:` lines so the model does not treat the input as a conversation to continue. Tool results are truncated to 2000 characters during serialization, with a marker showing how many characters were dropped — `read` and `bash` results are usually the largest contributors to context.## Extension Hooks-`session_before_compact` can cancel or provide custom compaction. Convert messages with `convertToLlm()` and `serializeConversation()` when using a custom summarizer.+`session_before_compact` receives `{ preparation, branchEntries, customInstructions, reason, willRetry, signal }`. `preparation` exposes `messagesToSummarize`, `turnPrefixMessages`, `previousSummary`, `fileOps`, `tokensBefore`, `firstKeptEntryId`, and `settings`; `reason` is `"manual"`, `"threshold"`, or `"overflow"`; `willRetry` indicates overflow recovery. Return `{ cancel: true }` or `{ compaction: { summary, firstKeptEntryId, tokensBefore, usage?, details? } }`.++To summarize with your own model, convert messages first:++```ts+import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";++const text = serializeConversation(convertToLlm(preparation.messagesToSummarize));+```++`session_before_tree` receives `{ preparation, signal }` with `targetId`, `oldLeafId`, `commonAncestorId`, `entriesToSummarize`, and `userWantsSummary`. It always fires, whether or not the user chose to summarize. Return `{ cancel: true }` to cancel navigation, or `{ summary: { summary, usage?, details? } }` (used only when `userWantsSummary`).-`session_before_tree` can cancel navigation or provide a custom branch summary when the user chose to summarize.+For direct programmatic summarization, `generateSummary()` returns the text and `generateSummaryWithUsage()` returns `{ text, usage }`.## Settingsdiff --git a/skills/pi-agent/references/containerization.md b/skills/pi-agent/references/containerization.mdindex 6a941a02..4a8db2ab 100644--- a/skills/pi-agent/references/containerization.md+++ b/skills/pi-agent/references/containerization.md@@ -2,51 +2,79 @@Source: https://pi.dev/docs/latest/containerization-Pi runs with all permissions by default. Isolation patterns either run the whole Pi process inside a boundary or run Pi on the host while routing tools into a boundary.+Pi runs with all permissions by default. Two general approaches: run the whole `pi` process inside an isolated environment, or run `pi` on the host and route tool execution into an isolated environment.-## Patterns+| Pattern | What is isolated | Best for | Notes |+|---|---|---|---|+| Gondolin extension | Built-in tools and `!` commands | Local micro-VM isolation while keeping auth on host | `examples/extensions/gondolin/` |+| Plain Docker | Whole `pi` process | Simplest local container boundary | Provider API keys enter the container |+| OpenShell | Whole `pi` process | Local or remote policy-controlled sandbox | Requires an OpenShell gateway |-- OpenShell: whole Pi process inside policy-controlled sandbox; best for local or remote managed sandboxing.-- Gondolin extension: host Pi with built-in tools and `!` commands routed into a local Linux micro-VM.-- Plain Docker: whole Pi process in a local container.--Extensions run wherever the Pi process runs. If host Pi routes built-ins into a VM, other extension tools still run on host unless they delegate too.--## OpenShell--```bash-openshell gateway add <gateway-url> --name <name>-openshell gateway select <name>-openshell sandbox create --name pi-sandbox --from pi -- pi-```--Remote gateways do not bind-mount local project files automatically. Upload/download project files explicitly. OpenShell can also route inference so raw provider keys stay outside the sandbox.+Extensions run wherever the `pi` process runs. If host Pi routes built-ins into a VM, other custom extension tools still run on the host unless they delegate too.## Gondolin+[Gondolin](https://github.com/earendil-works/gondolin) is a local Linux micro-VM.+```bashcp -R packages/coding-agent/examples/extensions/gondolin ~/.pi/agent/extensions/gondolincd ~/.pi/agent/extensions/gondolinnpm install --ignore-scripts+cd /path/to/projectpi -e ~/.pi/agent/extensions/gondolin```-The extension mounts host cwd at `/workspace` in the VM and overrides `read`, `write`, `edit`, `bash`, `grep`, `find`, and `ls`. Writes under `/workspace` write through to the host. Requires Node.js >= 23.6.0 and QEMU.+The extension mounts the host cwd at `/workspace` in the VM and overrides `read`, `write`, `edit`, `bash`, `grep`, `find`, and `ls`. User `!` commands are routed into the VM as well, and file changes under `/workspace` write through to the host.++Requirements: Node.js >= 23.6.0 for `@earendil-works/gondolin`, plus QEMU installed through your package manager.-## Docker+## Plain Docker++`Dockerfile.pi`:```dockerfileFROM 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 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 /workspaceENTRYPOINT ["pi"]``````bashdocker 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++docker run --rm -it \+ -e ANTHROPIC_API_KEY \+ -v "$PWD:/workspace" \+ -v pi-agent-home:/root/.pi/agent \+ pi-sandbox+```++`-v "$PWD:/workspace"` means reads and writes inside `/workspace` affect host files directly. Use a named volume for `/root/.pi/agent` if you want container-local settings and sessions — mounting host `~/.pi/agent` exposes host auth and session files to the container.++## OpenShell++[NVIDIA OpenShell](https://docs.nvidia.com/openshell/about/overview) provides a policy-controlled sandbox with filesystem, process, network, credential, and inference controls. It runs sandboxes through a local gateway backed by Docker, Podman, or a VM runtime, or through a remote Kubernetes gateway. Every sandbox requires an active gateway:++```bash+openshell gateway add <gateway-url> --name <name>+openshell gateway select <name>++openshell sandbox create --name pi-sandbox --from pi -- pi+```++The whole `pi` process runs inside the sandbox, so built-in tools, `!` commands, and extension tools all execute inside the boundary.++Remote gateways do not bind-mount host project files, so sandbox writes are not reflected on your machine. Clone the repository inside the sandbox or transfer files explicitly:++```bash+openshell sandbox upload pi-sandbox ./repo /workspace+openshell sandbox download pi-sandbox /workspace/repo ./repo-out```-Mounting host `~/.pi/agent` exposes host auth and session files. Use a named volume for container-local settings and sessions.+OpenShell providers can keep raw model API keys outside the sandbox: with inference routing configured, code inside the sandbox calls `https://inference.local` and the gateway injects provider credentials upstream. Point Pi at the corresponding OpenAI-compatible or Anthropic-compatible endpoint to use that route.diff --git a/skills/pi-agent/references/custom-provider.md b/skills/pi-agent/references/custom-provider.mdindex b5424aa0..d2b47952 100644--- a/skills/pi-agent/references/custom-provider.md+++ b/skills/pi-agent/references/custom-provider.md@@ -2,66 +2,130 @@Source: https://pi.dev/docs/latest/custom-provider-Extensions can register providers with `pi.registerProvider()` for proxies, private deployments, OAuth/SSO, and non-standard streaming APIs.+Extensions register providers with `pi.registerProvider()` for proxies, private deployments, OAuth/SSO, and non-standard streaming APIs. Two forms exist: a complete pi-ai `Provider` (preferred when you need custom authentication, filtering, refresh, or streaming) and the legacy provider-config object. `models.json` overrides compose **above** registered native providers.-## Quick Reference+## Complete Provider Form```ts+import { createProvider, openAICompletionsApi } from "@earendil-works/pi-ai";import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";export default function (pi: ExtensionAPI) {- pi.registerProvider("anthropic", { baseUrl: "https://proxy.example.com" });-- pi.registerProvider("my-provider", {- name: "My Provider",- baseUrl: "https://api.example.com",- apiKey: "$MY_API_KEY",- api: "openai-completions",- models: [{- id: "my-model",- name: "My Model",- reasoning: false,- input: ["text", "image"],- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },- contextWindow: 128000,- maxTokens: 4096- }]- });+ pi.registerProvider(createProvider({+ id: "native-local",+ name: "Native Local",+ baseUrl: "http://localhost:8080/v1",+ auth: {+ apiKey: {+ name: "Local server API key",+ async login(interaction) {+ return { type: "api_key", key: await interaction.prompt({ type: "secret", message: "API key" }) };+ },+ async resolve({ credential }) {+ return credential?.key ? { auth: { apiKey: credential.key }, source: "stored API key" } : undefined;+ },+ },+ },+ models: [],+ api: openAICompletionsApi(),+ }));}```-Use an async extension factory for dynamic model discovery so models are available during startup and `pi --list-models`.+The object form accepts a complete `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple`.-## Overrides and New Providers+## Legacy Config Form-When only `baseUrl` and/or `headers` are provided, existing models for a built-in provider are preserved. When `models` is provided, it replaces dynamic models for that provider.+```ts+// Override baseUrl and/or headers only — existing models are preserved+pi.registerProvider("anthropic", { baseUrl: "https://proxy.example.com" });+pi.registerProvider("openai", { headers: { "X-Custom-Header": "value" } });++// New provider with models — replaces all existing models for that provider+pi.registerProvider("my-provider", {+ name: "My Provider",+ baseUrl: "https://api.example.com",+ apiKey: "$MY_API_KEY",+ api: "openai-completions",+ models: [{+ id: "my-model",+ name: "My Model",+ reasoning: false,+ input: ["text", "image"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 128000,+ maxTokens: 4096,+ }],+});+```++Use an **async extension factory** for dynamic model discovery so models are registered before startup finishes and are visible to `pi --list-models`. Dynamic providers can also implement `refreshModels({ signal, store, ... })`; Pi calls it during model refresh and publishes the result synchronously. Persist through `context.store` only when the catalog should survive — live servers such as llama.cpp can ignore it.-`pi.unregisterProvider(name)` removes dynamic models, API key fallback, OAuth registration, and custom stream handlers, restoring built-in behavior where relevant.+`pi.unregisterProvider(name)` removes that provider's dynamic models, API key fallback, OAuth registration, and custom stream handlers, restoring overridden built-in behavior. Calls made after the initial load phase take effect immediately — no `/reload`.## API Types-Common values: `anthropic-messages`, `openai-completions`, `openai-responses`, `azure-openai-responses`, `openai-codex-responses`, `mistral-conversations`, `google-generative-ai`, `google-vertex`, `bedrock-converse-stream`.+`anthropic-messages`, `openai-completions`, `openai-responses`, `azure-openai-responses`, `openai-codex-responses`, `mistral-conversations`, `google-generative-ai`, `google-vertex`, `bedrock-converse-stream`.-Most OpenAI-compatible providers work with `openai-completions`; use `compat` for quirks and `thinkingLevelMap` for model-specific thinking levels.+Most OpenAI-compatible providers work with `openai-completions`; use model-level `thinkingLevelMap` for thinking levels and `compat` for quirks (full flag list in `references/models.md`). `xhigh` and `max` are opt-in and require non-null map entries. Mistral moved from `openai-completions` to `mistral-conversations` — use the latter for native Mistral models.## Auth Header and Secrets-Set `authHeader: true` to add `Authorization: Bearer <apiKey>`. `apiKey` and custom header values use `!command`, `$ENV`, `${ENV}`, `$$`, and `$!` resolution like `models.json`.+`authHeader: true` adds `Authorization: Bearer <apiKey>`; the key is resolved per request and an explicit request `Authorization` header wins. `apiKey` and custom header values use the same syntax as `models.json`: leading `!command` executes for the whole value, `$ENV`/`${ENV}` interpolate, `$$` and `$!` escape literals.## OAuth-Register `oauth` with `login(callbacks)`, `refreshToken(credentials)`, `getApiKey(credentials)`, and optional `modifyModels(models, credentials)`. Credentials persist in `~/.pi/agent/auth.json` with `refresh`, `access`, and `expires` fields. Users authenticate with `/login provider-name`.+```ts+oauth: {+ name: "Corporate AI (SSO)",+ async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials>,+ async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials>,+ getApiKey(credentials: OAuthCredentials): string,+}+```++`OAuthLoginCallbacks`: `onAuth({ url })` (open in browser), `onDeviceCode({ userCode, verificationUri, intervalSeconds?, expiresInSeconds? })`, `onProgress?(message)`, `onPrompt({ message }): Promise<string>`, `onSelect({ message, options: { id, label }[] }): Promise<string | undefined>`.-Callbacks include `onAuth`, `onDeviceCode`, `onPrompt`, and `onSelect`.+`OAuthCredentials` is `{ refresh, access, expires }` (expiry in ms), persisted in `~/.pi/agent/auth.json`. Users authenticate with `/login <provider-name>`.## Custom Streaming-For non-standard APIs, implement `streamSimple(model, context, options)`. Create an `AssistantMessage`, push `{ type: "start", partial }`, push content events as data arrives, then push `{ type: "done", reason, message }` or `{ type: "error", reason, error }`, and end the stream.+Implement `streamSimple(model, context, options?)` returning an `AssistantMessageEventStream` from `createAssistantMessageEventStream()`. Initialize an `AssistantMessage` (`role`, `content: []`, `api`, `provider`, `model`, zeroed `usage`, `stopReason: "stop"`, `timestamp`), then:++1. `stream.push({ type: "start", partial: output })`+2. Content events, tracking `contentIndex` per block: `text_start`, `text_delta`, `text_end`, `thinking_start`, `thinking_delta`, `thinking_end`, `toolcall_start`, `toolcall_delta`, `toolcall_end`+3. `stream.push({ type: "done", reason, message })` or `{ type: "error", reason, error }`, then `stream.end()`++Every event carries `partial` with the current `AssistantMessage` state — mutate `output.content` as data arrives and pass `output`. Tool calls accumulate JSON deltas, parse into `{ id, name, arguments }`, and finish with `toolcall_end` carrying the full `toolCall`. Update usage from the API response and call `calculateCost(model, output.usage)`. Register with `streamSimple` on the provider config.-Content events include `text_start`, `text_delta`, `text_end`, `thinking_start`, `thinking_delta`, `thinking_end`, `toolcall_start`, `toolcall_delta`, and `toolcall_end`. Keep `partial` updated with the current assistant message state.+Reference implementations in `packages/ai/src/providers/`: `anthropic.ts`, `mistral.ts`, `openai-completions.ts`, `openai-responses.ts`, `google.ts`, `amazon-bedrock.ts`.-For tool calls, accumulate JSON deltas, parse into `{ id, name, arguments }`, and end with `toolcall_end`.+## Context Overflow Errors++Pi auto-recovers from context overflow by compacting and retrying once, but only when it recognizes the failure: `stopReason === "error"` and `errorMessage` matching a known pattern (see `packages/ai/src/utils/overflow.ts`). If your provider's message is unrecognized, normalize it from the same extension with a `message_end` handler so `errorMessage` starts with a recognized phrase — `context_length_exceeded` is the safest:++```ts+pi.on("message_end", (event, ctx) => {+ const message = event.message;+ if (message.role !== "assistant" || message.stopReason !== "error") return;+ if (message.provider !== "my-provider" && ctx.model?.provider !== "my-provider") return;+ const errorMessage = message.errorMessage ?? "";+ if (errorMessage.includes("context_length_exceeded")) return;+ if (!MY_PROVIDER_OVERFLOW_PATTERN.test(errorMessage)) return;+ return { message: { ...message, errorMessage: `context_length_exceeded: ${errorMessage}` } };+});+```++`message_end` runs before Pi tracks the message for auto-compaction, so the rewrite is what Pi checks. Scope it to your provider, match a provider-specific pattern (never Pi's generic ones — rewriting rate-limit errors would trigger compaction instead of retry-with-backoff), and skip when the phrase is already present so the handler is idempotent.## Testing-Test provider registration with `pi --list-models`, authenticate through `/login` or env vars, run a simple prompt, then exercise tools, thinking levels, image input, cache behavior, retry behavior, and context overflow errors.+Adapt the suites in `packages/ai/test/` for your provider/model pairs: `stream.test.ts`, `tokens.test.ts`, `abort.test.ts`, `empty.test.ts`, `context-overflow.test.ts`, `image-limits.test.ts`, `unicode-surrogate.test.ts`, `tool-call-without-result.test.ts`, `image-tool-result.test.ts`, `total-tokens.test.ts`, `cross-provider-handoff.test.ts`. Verify registration with `pi --list-models`, then exercise auth, tools, thinking levels, image input, cache behavior, retries, and context overflow.++## Config Reference++`ProviderConfig`: `name?`, `baseUrl?`, `apiKey?`, `api?`, `streamSimple?`, `headers?`, `authHeader?`, `models?`, `refreshModels?`, `oauth?`.++`ProviderModelConfig`: `id`, `name`, `api?`, `baseUrl?` (per-model endpoint override), `reasoning`, `thinkingLevelMap?`, `input`, `cost` (`input`, `output`, `cacheRead`, `cacheWrite` per million tokens), `contextWindow`, `maxTokens`, `headers?`, `compat?`.++Example extensions: `examples/extensions/custom-provider-anthropic/` and `examples/extensions/custom-provider-gitlab-duo/`.diff --git a/skills/pi-agent/references/environment-variables.md b/skills/pi-agent/references/environment-variables.mdnew file mode 100644index 00000000..723091f1--- /dev/null+++ b/skills/pi-agent/references/environment-variables.md@@ -0,0 +1,51 @@+# Environment Variables++Source: https://pi.dev/docs/latest/environment-variables++Pi uses environment variables three ways: variables that configure the Pi process, a marker Pi sets so child processes know they run inside Pi, and session metadata injected into commands run by the LLM-callable bash tool. Provider API-key variables live in `references/providers.md`.++## Process Marker++The CLI and RPC entry points set `PI_CODING_AGENT=true`. Child processes inherit it. It is not session-specific and is **not** set automatically when Pi is embedded through the SDK.++## Bash Tool Session Environment++Commands run by the LLM-callable bash tool receive:++| Variable | Description |+|---|---|+| `PI_SESSION_ID` | Current session ID |+| `PI_SESSION_FILE` | Absolute path to the session JSONL file; unset for ephemeral sessions |+| `PI_PROVIDER` | Currently selected model provider |+| `PI_MODEL` | Currently selected model ID |+| `PI_REASONING_LEVEL` | Effective reasoning level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |++Values resolve when each command starts, so switching models affects the next bash command without restarting. `PI_PROVIDER`/`PI_MODEL` identify the selected Pi model, not an upstream model a router picks internally. When asked which model is running, inspect these variables instead of inferring from the system prompt:++```bash+printf '%s/%s\n' "$PI_PROVIDER" "$PI_MODEL"+```++These are injected into the LLM-callable bash tool only — not into user-entered `!` or `!!` commands.++Custom bash tools built with `createBashTool()` expose the same variables by default, injected **before** `spawnHook` so hooks see them in `ctx.env`. Disable with `exposeSessionEnvironment: false`; Pi then also clears inherited values so nested Pi processes do not leak stale parent-session metadata.++## Pi Process Configuration++| Variable | Description |+|---|---|+| `PI_CODING_AGENT_DIR` | Override the config directory; default `~/.pi/agent` |+| `PI_CODING_AGENT_SESSION_DIR` | Override session storage; overridden by `--session-dir` |+| `PI_PACKAGE_DIR` | Override the package directory (useful for Nix/Guix store paths) |+| `PI_OFFLINE` | Disable startup network operations: update checks, package updates, install/update telemetry |+| `PI_SKIP_VERSION_CHECK` | Disable the `pi.dev` latest-version request |+| `PI_TELEMETRY` | Override install/update telemetry and provider attribution headers: `1`/`true`/`yes` or `0`/`false`/`no` |+| `PI_CACHE_RETENTION` | Set to `long` for extended provider prompt caching where supported |+| `PI_SHARE_VIEWER_URL` | Override the base URL used by `/share` |+| `PI_HARDWARE_CURSOR` | Set to `1` to show the hardware cursor (IME positioning) |+| `VISUAL`, `EDITOR` | External editor fallback when the `externalEditor` setting is unset |+| `HTTP_PROXY`, `HTTPS_PROXY` | Proxy outbound HTTP requests |++Names are derived from the rebrandable app name (`package.json` `piConfig.name`), so a fork uses a different prefix — see `references/development.md`.++Other variables documented elsewhere: `PI_EXPERIMENTAL` (experimental first-time setup, `references/settings.md`), `PI_TUI_WRITE_LOG` (raw ANSI capture, `references/tui.md`), `AWS_BEDROCK_FORCE_CACHE` and other cloud variables (`references/providers.md`), `LLAMA_BASE_URL`/`LLAMA_API_KEY` (`references/llama-cpp.md`).diff --git a/skills/pi-agent/references/extensions.md b/skills/pi-agent/references/extensions.mdindex c7252ec7..f2d27c47 100644--- a/skills/pi-agent/references/extensions.md+++ b/skills/pi-agent/references/extensions.md@@ -2,17 +2,15 @@Source: https://pi.dev/docs/latest/extensions-Extensions are TypeScript modules that extend Pi. They can register tools, commands, shortcuts, flags, custom providers, UI, event handlers, and persistent session entries.+Extensions are TypeScript modules that extend Pi. They register tools, commands, shortcuts, CLI flags, providers, renderers, UI, event handlers, and persistent session entries. They run with the full permissions of the Pi process — only install extensions you trust.## Locations-- `~/.pi/agent/extensions/*.ts`-- `~/.pi/agent/extensions/*/index.ts`-- `.pi/extensions/*.ts`-- `.pi/extensions/*/index.ts`-- Paths from settings or packages+- `~/.pi/agent/extensions/*.ts` and `~/.pi/agent/extensions/*/index.ts` (global)+- `.pi/extensions/*.ts` and `.pi/extensions/*/index.ts` (project-local, loaded only after project trust)+- Paths from `settings.json` `extensions` / `packages`-Project-local extensions load only after project trust. Use `pi -e ./my-extension.ts` for quick tests. Auto-discovered extensions can be hot-reloaded with `/reload`.+Use `pi -e ./my-extension.ts` for quick tests only; auto-discovered extensions can be hot-reloaded with `/reload`. Extensions load via [jiti](https://github.com/unjs/jiti), so TypeScript needs no compilation.## Quick Extension@@ -51,39 +49,122 @@ export default function (pi: ExtensionAPI) {## Imports-- `@earendil-works/pi-coding-agent`: extension types and APIs.-- `typebox`: schemas for tool parameters.-- `@earendil-works/pi-ai`: AI utilities.-- `@earendil-works/pi-tui`: TUI components.+`@earendil-works/pi-coding-agent` (extension types and APIs), `typebox` (tool parameter schemas), `@earendil-works/pi-ai` (`StringEnum` for Google-compatible enums), `@earendil-works/pi-tui` (TUI components), plus Node built-ins. Add a `package.json` next to the extension and run `npm install` for npm dependencies. Distributed packages must put runtime deps in `dependencies` — package installs use `npm install --omit=dev`.-Runtime dependencies for distributed packages belong in `dependencies`; package installs use production installs by default.+## Factory Semantics-## Event Flow+The default export receives `ExtensionAPI` and may be async; Pi awaits it before `session_start`, `resources_discover`, and flushing queued `pi.registerProvider()` calls. Use async factories for one-time startup work such as dynamic model discovery. Do **not** start background resources (processes, sockets, watchers, timers) in the factory — factories can run in invocations that never start a session. Start them in `session_start` or on demand, and close them in an idempotent `session_shutdown` handler.-Startup: `project_trust`, `session_start`, `resources_discover`.+## Event Lifecycle-Prompt: extension commands, `input`, skill/template expansion, `before_agent_start`, `agent_start`, message events, turn events, provider request/response hooks, tool events, `agent_end`.+Startup: `project_trust` (user/global and CLI `-e` extensions only) → `session_start { reason: "startup" }` → `resources_discover { reason: "startup" }`.-Session changes: `session_before_switch`, `session_shutdown`, `session_start`, `resources_discover`. Fork/clone use `session_before_fork`.+Prompt: extension commands checked first (they bypass `input`) → `input` → skill/template expansion → `before_agent_start` → `agent_start` → message events → per turn: `turn_start`, `context`, `before_provider_headers`, `before_provider_request`, `after_provider_response`, then `tool_execution_start`, `tool_call`, `tool_execution_update`, `tool_result`, `tool_execution_end` → `turn_end` → `agent_end` → `agent_settled`.-Compaction/tree: `session_before_compact`, `session_compact`, `session_before_tree`, `session_tree`.+Session replacement (`/new`, `/resume`): `session_before_switch` (cancellable) → `session_shutdown` → `session_start { reason: "new" | "resume", previousSessionFile }` → `resources_discover`. `/fork` and `/clone` use `session_before_fork` (with `position: "before" | "at"`) then `reason: "fork"`. `/name` emits `session_info_changed`. Compaction: `session_before_compact` → `session_compact`. `/tree`: `session_before_tree` → `session_tree`. Model changes: `thinking_level_select` then `model_select`. Exit: `session_shutdown`.-Model changes: `model_select`, `thinking_level_select`.+## High-Value Hooks-Shutdown: `session_shutdown`.+- `project_trust` — must return `{ trusted: "yes" | "no" | "undecided", remember?: boolean }`. First yes/no decision wins and suppresses the built-in prompt. `ctx` is a limited trust context (cwd, mode, hasUI, select/confirm/input/notify).+- `resources_discover` — return `{ skillPaths, promptPaths, themePaths }`.+- `before_agent_start` — return `{ message }` to inject a persistent custom message and/or `{ systemPrompt }` to replace it for this turn (chained across handlers). `event.systemPromptOptions` exposes the structured inputs Pi used: `customPrompt`, `selectedTools`, `toolSnippets`, `promptGuidelines`, `appendSystemPrompt`, `cwd`, `contextFiles`, `skills`.+- `context` — `event.messages` is a deep copy; return `{ messages }` to modify what the LLM sees.+- `before_provider_headers` — mutate `event.headers` in place; a string adds/overrides, `null` deletes. Fires once per request; retries reuse the headers.+- `before_provider_request` — inspect or replace `event.payload`; handlers run in load order and `undefined` keeps it unchanged. Payload-level system-instruction rewrites are not reflected by `ctx.getSystemPrompt()`.+- `after_provider_response` — `event.status` and normalized `event.headers` before the stream body is consumed.+- `tool_call` — `event.input` is mutable and mutations affect execution (no re-validation); return `{ block: true, reason? }` to block. Narrow with `isToolCallEventType("bash", event)`, or `isToolCallEventType<"my_tool", MyToolInput>(...)` for custom tools.+- `tool_result` — middleware-style chain; return partial patches (`content`, `details`, `isError`, `usage`). Use `isBashToolResult(event)` for typed bash details and `ctx.signal` for nested async work.+- `message_end` — return `{ message }` to replace the finalized message; the replacement must keep the same `role`.+- `user_bash` — intercept `!`/`!!`: return `{ operations }` (optionally wrapping `createLocalBashOperations()`) or `{ result }`.+- `input` — sees raw text before skill/template expansion. Return `{ action: "continue" | "transform" | "handled" }`; `event.source` is `"interactive" | "rpc" | "extension"` and `event.streamingBehavior` is `"steer" | "followUp" | undefined`.-## High-Value Hooks+In parallel tool mode, sibling tool calls are preflighted sequentially then executed concurrently, so `tool_call` is not guaranteed to see sibling tool results; `tool_result`/`tool_execution_end` may interleave in completion order while final `toolResult` message events stay in assistant source order.++## ExtensionContext++`ctx.ui` (see Custom UI), `ctx.mode` (`"tui" | "rpc" | "json" | "print"`), `ctx.hasUI` (true in TUI and RPC), `ctx.cwd`, `ctx.signal` (agent abort signal; usually `undefined` outside active turns), `ctx.isProjectTrusted()`, `ctx.sessionManager` (read-only: `getEntries`, `getBranch`, `buildContextEntries`, `getLeafId`, …), `ctx.modelRegistry` (`getProvider(id)`, `getProviderAuth(id)`, `find(...)`), `ctx.model`, `ctx.thinkingLevel`, `ctx.isIdle()`, `ctx.abort()`, `ctx.hasPendingMessages()`, `ctx.shutdown()`, `ctx.getContextUsage()`, `ctx.compact({ customInstructions, onComplete, onError })`, `ctx.getSystemPrompt()`.++Use the exported `CONFIG_DIR_NAME` instead of hardcoding `.pi` — rebranded distributions use a different name.++## ExtensionCommandContext++Command handlers additionally get session-control methods that would deadlock from event handlers: `getSystemPromptOptions()`, `waitForIdle()`, `newSession({ parentSession, setup, withSession })`, `fork(entryId, { position: "before" | "at", withSession })`, `navigateTree(targetId, { summarize, customInstructions, replaceInstructions, label })`, `switchSession(path, { withSession })`, `reload()`.++`withSession` receives a fresh `ReplacedSessionContext` with async `sendMessage()`/`sendUserMessage()`. It runs only after the old session emitted `session_shutdown` and the new instance already received `session_start`, but still executes in the original closure — so captured old `pi`/`ctx`/`sessionManager` objects are stale and throw. Capture only plain data (strings, ids) across the boundary. Treat `await ctx.reload()` as terminal for that handler (`await ctx.reload(); return;`); tools cannot call it, so expose a command and have the tool queue it with `pi.sendUserMessage("/my-reload", { deliverAs: "followUp" })`.++## ExtensionAPI++Tools: `registerTool(definition)` (works during load and at runtime — new tools are callable without `/reload`), `getActiveTools()`, `getAllTools()` (returns `name`, `description`, `parameters`, `promptGuidelines`, `sourceInfo`), `setActiveTools(names)`.++Messages and session: `sendMessage(message, { deliverAs: "steer" | "followUp" | "nextTurn", triggerTurn })`, `sendUserMessage(content, { deliverAs })` (required while streaming), `appendEntry(customType, data)`, `setSessionName`, `getSessionName`, `setLabel(entryId, label)`.++Commands and input: `registerCommand(name, { description, handler, getArgumentCompletions })` (duplicate names get `:1`/`:2` suffixes in load order), `getCommands()` (extension → prompt → skill order, each with `sourceInfo.scope`/`origin`), `registerShortcut(key, options)`, `registerFlag(name, options)` + `getFlag(name)`.++Rendering: `registerMessageRenderer(customType, renderer)` (custom messages, in LLM context), `registerEntryRenderer(customType, renderer)` (custom entries, TUI only).++Model and provider: `setModel(model)` (returns `false` without an API key), `getThinkingLevel()`, `setThinkingLevel(level)`, `registerProvider(nameOrProvider, config?)`, `unregisterProvider(name)`. Calls after the load phase take effect immediately. Dynamic providers can implement `refreshModels`, and a complete pi-ai `Provider` from `createProvider(...)` can be registered as the composition base with `models.json` overrides layered above.++Other: `exec(command, args, { signal, timeout })` → `{ stdout, stderr, code, killed }`, `on(event, handler)`, `events` (inter-extension bus).++## Custom Tools++```ts+pi.registerTool({+ name: "my_tool",+ label: "My Tool",+ description: "What this tool does (shown to the LLM)",+ promptSnippet: "One-line entry in the system prompt's Available tools section",+ promptGuidelines: ["Use my_tool when the user asks to summarize generated text."],+ parameters: Type.Object({ action: StringEnum(["list", "add"] as const), text: Type.Optional(Type.String()) }),+ prepareArguments(args) { return args; },+ async execute(toolCallId, params, signal, onUpdate, ctx) {+ onUpdate?.({ content: [{ type: "text", text: "Working..." }], details: { progress: 50 } });+ return { content: [{ type: "text", text: "Done" }], details: {}, terminate: true };+ },+ renderShell: "self",+ renderCall(args, theme, context) { /* Component */ },+ renderResult(result, options, theme, context) { /* Component */ },+});+```++- Use `StringEnum` from `@earendil-works/pi-ai` for string enums; `Type.Union`/`Type.Literal` breaks Google's API.+- `promptGuidelines` bullets are appended flat with no tool-name prefix — always name the tool ("Use my_tool when…"), never "this tool".+- `prepareArguments` runs before schema validation; use it to fold legacy argument shapes from resumed sessions instead of loosening `parameters`.+- Signal errors by **throwing** — returning a value never sets `isError`.+- `terminate: true` hints that the follow-up LLM call should be skipped, and only applies when every finalized result in the batch terminates.+- Return `usage` for nested LLM calls; Pi persists it and includes it in footer, `/session`, and RPC totals.+- Strip a leading `@` from path arguments (some models add it), and wrap read-modify-write windows in `withFileMutationQueue(absolutePath, fn)` so the tool shares the per-file queue with built-in `edit`/`write` — tools run in parallel by default. Resolve to an absolute path first; the helper canonicalizes existing files through `realpath()`.+- Truncate output. The built-in limit is 50 KB / 2000 lines, whichever hits first. Use `truncateHead` (beginning matters), `truncateTail` (end matters), `truncateLine`, `formatSize`, `DEFAULT_MAX_BYTES`, `DEFAULT_MAX_LINES`, and tell the LLM where the full output was saved.++Overriding built-ins (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`) works by registering the same name; interactive mode warns. Renderer inheritance is per slot, so omitting `renderCall`/`renderResult` keeps the built-in UI. `promptSnippet`/`promptGuidelines` are **not** inherited. The result shape, including `details`, must match exactly.++Remote execution: built-in tool factories accept pluggable `operations` (`ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`). `createBashTool(cwd, { spawnHook, exposeSessionEnvironment })` can rewrite command/cwd/env; session variables are injected before `spawnHook` (`references/environment-variables.md`).++### Dynamic Tool Loading++Register every tool, keep only loader tools active, then call `pi.setActiveTools([...current, ...matched])` during loader execution. The change must be purely additive. Pi records the added names on the loader's tool result and exposes the definitions before the next model request — natively via `defer_loading`/`tool_reference` on Anthropic Sonnet/Opus/Fable 4.5+ and via `tool_search_call`/`tool_search_output` on OpenAI `gpt-5.4`+, otherwise by sending the normal active tool list. Verified custom endpoints can opt in with `compat.supportsToolReferences` (anthropic-messages) or `compat.supportsToolSearch` (openai-responses / openai-codex-responses). Non-additive changes fall back to the full list. Lazily loaded tools should rely on `description` and omit `promptSnippet`/`promptGuidelines`, which rebuild the system prompt and can invalidate the cached prefix.++## State Management++Store state in tool result `details` so branching works, and rebuild it in `session_start` by walking `ctx.sessionManager.getBranch()`. `pi.appendEntry(customType, data)` persists extension state that does not enter LLM context.++## Custom UI++Dialogs: `ctx.ui.select(title, options)`, `confirm(title, message)`, `input(prompt, placeholder)`, `editor(title, prefill)`, `notify(message, "info" | "warning" | "error")`. Dialogs accept `{ timeout }` (live countdown; `select`/`input` return `undefined`, `confirm` returns `false`) or `{ signal }` when you need to distinguish timeout from user cancel.++Chrome: `setStatus(key, text)`, `setWidget(key, lines | factory, { placement: "aboveEditor" | "belowEditor" })`, `setFooter(factory)`, `setHeader(...)`, `setTitle(text)`, `setEditorText` / `getEditorText` / `pasteToEditor`, `setWorkingMessage`, `setWorkingVisible`, `setWorkingIndicator({ frames, intervalMs })`, `setToolsExpanded` / `getToolsExpanded`, `setEditorComponent(factory)` / `getEditorComponent()`, `addAutocompleteProvider(current => provider)`, `getAllThemes` / `getTheme` / `setTheme` / `theme`, and `custom(factory, { overlay, overlayOptions, onHandle })`.++Custom-component details, overlays, built-in components, and copy-paste patterns are in `references/tui.md`. Syntax highlighting helpers: `highlightCode(code, lang, theme)`, `getLanguageFromPath(path)`. Keybinding hints: `keyHint(id, description)`, `keyText(id)`, `rawKeyHint(key, description)` with namespaced ids (`app.*` for the coding agent, `tui.*` for shared TUI).++## Error Handling and Mode Behavior-- `project_trust`: user/global or CLI extensions can decide project trust.-- `resources_discover`: contribute skill, prompt, and theme paths.-- `before_agent_start`: inject custom messages or modify the system prompt.-- `context`: non-destructively modify messages before each LLM call.-- `before_provider_request`: inspect/replace provider payload for debugging or compatibility.-- `after_provider_response`: inspect status/headers before streaming body is consumed.-- `tool_call`: block or mutate tool inputs before execution.-- `tool_result`: modify tool results.-- `message_end`: replace finalized message while preserving role.+Extension errors are logged and the agent continues; `tool_call` errors block the tool (fail-safe); tool `execute` errors must be thrown and are reported to the LLM with `isError: true`.-## Runtime Notes+| Mode | `ctx.mode` | `ctx.hasUI` | Notes |+|---|---|---|---|+| Interactive | `"tui"` | `true` | Full TUI |+| RPC | `"rpc"` | `true` | Dialogs/notifications over the JSON protocol; `custom()` returns `undefined` |+| JSON | `"json"` | `false` | UI methods are no-ops |+| Print (`-p`) | `"print"` | `false` | Extensions run but cannot prompt |-Extension factories may be async; Pi awaits them before startup continues. Use async factories for startup-only work such as dynamic model discovery. In RPC or JSON/print mode, guard TUI-specific UI with `ctx.mode === "tui"` and check `ctx.hasUI` before prompting.+Guard TUI-only features with `ctx.mode === "tui"`; guard dialogs and notifications with `ctx.hasUI`.diff --git a/skills/pi-agent/references/json.md b/skills/pi-agent/references/json.mdindex da2866b3..3271708d 100644--- a/skills/pi-agent/references/json.md+++ b/skills/pi-agent/references/json.md@@ -10,17 +10,23 @@ pi --mode json "Your prompt"## Event Types-`AgentSessionEvent` includes base agent events plus queue, compaction, and retry events:+`AgentSessionEvent` is `AgentEvent` plus session-level events:-- `agent_start`, `agent_end`-- `turn_start`, `turn_end`-- `message_start`, `message_update`, `message_end`-- `tool_execution_start`, `tool_execution_update`, `tool_execution_end`-- `queue_update`-- `compaction_start`, `compaction_end`-- `auto_retry_start`, `auto_retry_end`+- `queue_update` — `{ steering: readonly string[], followUp: readonly string[] }`, emitted whenever either queue changes+- `compaction_start` — `{ reason: "manual" | "threshold" | "overflow" }`+- `compaction_end` — `{ reason, result: CompactionResult | undefined, aborted, willRetry, errorMessage? }`+- `auto_retry_start` — `{ attempt, maxAttempts, delayMs, errorMessage }`+- `auto_retry_end` — `{ success, attempt, finalError? }`+- `summarization_retry_scheduled` — `{ attempt, maxAttempts, delayMs, errorMessage }`+- `summarization_retry_attempt_start` — `{ source: "branchSummary" }` or `{ source: "compaction", reason }`+- `summarization_retry_finished`-`queue_update` emits full pending steering and follow-up queues. Compaction events cover manual and automatic compaction.+Base `AgentEvent` types:++- `agent_start`, `agent_end` (`messages`)+- `turn_start`, `turn_end` (`message`, `toolResults`)+- `message_start` (`message`), `message_update` (`message`, `assistantMessageEvent`), `message_end` (`message`)+- `tool_execution_start` (`toolCallId`, `toolName`, `args`), `tool_execution_update` (+ `partialResult`), `tool_execution_end` (`result`, `isError`)## Output Format@@ -30,12 +36,15 @@ First line is the session header:{"type":"session","version":3,"id":"uuid","timestamp":"...","cwd":"/path"}```-Subsequent lines are events:+Then events as they occur:```json{"type":"agent_start"}{"type":"turn_start"}+{"type":"message_start","message":{"role":"assistant","content":[]}}{"type":"message_update","message":{},"assistantMessageEvent":{"type":"text_delta","delta":"Hello"}}+{"type":"message_end","message":{}}+{"type":"turn_end","message":{},"toolResults":[]}{"type":"agent_end","messages":[]}```diff --git a/skills/pi-agent/references/keybindings.md b/skills/pi-agent/references/keybindings.mdindex 24f41d06..ab56d1aa 100644--- a/skills/pi-agent/references/keybindings.md+++ b/skills/pi-agent/references/keybindings.md@@ -2,25 +2,40 @@Source: https://pi.dev/docs/latest/keybindings-All shortcuts can be customized in `~/.pi/agent/keybindings.json`. Run `/reload` after editing.+All shortcuts are customizable in `~/.pi/agent/keybindings.json`, which uses the same namespaced ids Pi uses internally and that extension authors pass to `keyHint()` and the injected `keybindings` manager. Pre-namespaced ids from older configs (`cursorUp`, `expandTools`, …) migrate automatically on startup. Run `/reload` after editing.## Key Format-Use `modifier+key`; modifiers are `ctrl`, `shift`, and `alt`. Keys include letters, digits, special keys, function keys, and symbols.+`modifier+key` where modifiers are `ctrl`, `shift`, `alt` (combinable, e.g. `ctrl+shift+x`, `alt+ctrl+1`). Keys:-## Common Defaults+- Letters `a-z`, digits `0-9`+- Special: `escape`/`esc`, `enter`/`return`, `tab`, `space`, `backspace`, `delete`, `insert`, `clear`, `home`, `end`, `pageUp`, `pageDown`, `up`, `down`, `left`, `right`+- Function: `f1`–`f12`+- Symbols: `` ` ``, `-`, `=`, `[`, `]`, `\`, `;`, `'`, `,`, `.`, `/`, `!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `(`, `)`, `_`, `+`, `|`, `~`, `{`, `}`, `:`, `<`, `>`, `?`-Editor movement: arrows, Ctrl+B/F, Alt+Left/Right, Ctrl+A/E, PageUp/PageDown.+## Actions-Deletion: Backspace, Delete/Ctrl+D, Ctrl+W, Alt+Backspace, Alt+D, Ctrl+U, Ctrl+K.+**`tui.editor.*` cursor** — `cursorUp` (up), `cursorDown` (down), `cursorLeft` (left, ctrl+b), `cursorRight` (right, ctrl+f), `cursorWordLeft` (alt+left, ctrl+left, alt+b), `cursorWordRight` (alt+right, ctrl+right, alt+f), `cursorLineStart` (home, ctrl+a), `cursorLineEnd` (end, ctrl+e), `jumpForward` (ctrl+]), `jumpBackward` (ctrl+alt+]), `pageUp`, `pageDown`.-Input: `tui.input.submit` is Enter, `tui.input.newLine` is Shift+Enter, `tui.input.tab` is Tab.+**`tui.editor.*` deletion** — `deleteCharBackward` (backspace), `deleteCharForward` (delete, ctrl+d), `deleteWordBackward` (ctrl+w, alt+backspace), `deleteWordForward` (alt+d, alt+delete), `deleteToLineStart` (ctrl+u), `deleteToLineEnd` (ctrl+k).-Application: Escape interrupts, Ctrl+C clears editor/copies selection depending context, Ctrl+D exits when editor empty, Ctrl+G opens external editor, Ctrl+V/Alt+V pastes image.+**`tui.editor.*` kill ring** — `yank` (ctrl+y), `yankPop` (alt+y), `undo` (ctrl+-).-Models: Ctrl+L opens model selector, Ctrl+P cycles forward, Shift+Ctrl+P cycles backward, Shift+Tab cycles thinking level, Ctrl+T toggles thinking block display.+**`tui.input.*`** — `newLine` (shift+enter, ctrl+j), `submit` (enter), `tab` (tab), `copy` (ctrl+c).-Messages: Ctrl+O expands tools, Alt+Enter queues follow-up, Alt+Up retrieves queued messages.+**`tui.select.*`** — `up`, `down`, `pageUp`, `pageDown`, `confirm` (enter), `cancel` (escape, ctrl+c).++**`app.*` application** — `interrupt` (escape), `clear` (ctrl+c), `exit` (ctrl+d when editor empty), `suspend` (ctrl+z; none on Windows), `editor.external` (ctrl+g), `clipboard.pasteImage` (ctrl+v; alt+v on Windows).++**`app.session.*`** — `new`, `tree`, `fork`, `resume` (no defaults), `togglePath` (ctrl+p), `toggleSort` (ctrl+s), `toggleNamedFilter` (ctrl+n), `rename` (ctrl+r), `delete` (ctrl+d), `deleteNoninvasive` (ctrl+backspace).++**`app.model.*` / `app.thinking.*`** — `model.select` (ctrl+l), `model.cycleForward` (ctrl+p), `model.cycleBackward` (shift+ctrl+p), `thinking.cycle` (shift+tab), `thinking.toggle` (ctrl+t).++**`app.tools.*` / `app.message.*`** — `tools.expand` (ctrl+o), `message.copy` (ctrl+x), `message.followUp` (alt+enter), `message.dequeue` (alt+up).++**`app.tree.*`** — `foldOrUp` (ctrl+left, alt+left), `unfoldOrDown` (ctrl+right, alt+right), `editLabel` (shift+l), `toggleLabelTimestamp` (shift+t), `filter.default` (ctrl+d), `filter.noTools` (ctrl+t), `filter.userOnly` (ctrl+u), `filter.labeledOnly` (ctrl+l), `filter.all` (ctrl+a), `filter.cycleForward` (ctrl+o), `filter.cycleBackward` (shift+ctrl+o).++**`app.models.*`** (inside the `/scoped-models` selector) — `save` (ctrl+s), `enableAll` (ctrl+a), `clearAll` (ctrl+x), `toggleProvider` (ctrl+p), `reorderUp` (alt+up), `reorderDown` (alt+down).## Custom Config@@ -32,4 +47,6 @@ Messages: Ctrl+O expands tools, Alt+Enter queues follow-up, Alt+Up retrieves que}```-User config overrides defaults. Native Windows has no default `app.suspend` binding; WSL uses normal Unix Ctrl+Z/fg behavior.+Each action takes a single key or an array; user config overrides defaults. The docs include full Emacs and Vim example configs.++On native Windows, `app.suspend` has no default because Windows terminals lack Unix job control — bound manually, Pi shows a status message instead of suspending. WSL keeps normal `ctrl+z`/`fg` behavior.diff --git a/skills/pi-agent/references/llama-cpp.md b/skills/pi-agent/references/llama-cpp.mdnew file mode 100644index 00000000..d72f7607--- /dev/null+++ b/skills/pi-agent/references/llama-cpp.md@@ -0,0 +1,69 @@+# llama.cpp++Source: https://pi.dev/docs/latest/llama-cpp++Pi supports the llama.cpp **router** server, which discovers multiple GGUF models and loads or unloads them on demand. Use a current llama.cpp build with router support.++## Start the Router++Start `llama-server` **without** `--model`, `-m`, or `-hf`. Passing a model starts single-model mode instead of router mode.++```bash+llama-server \+ --models-dir ~/models \+ --no-models-autoload \+ --jinja \+ --host 127.0.0.1 \+ --port 8080 \+ -ngl 999 \+ -c 32768+```++- `--models-dir` discovers local GGUF files.+- `--no-models-autoload` keeps loading explicit through `/llama`.+- `--jinja` enables compatible chat templates and tool calling.+- `-ngl 999` offloads as many layers as possible to the GPU.+- `-c 32768` sets the context window per loaded model; omit to use the model's native context (may need much more memory).++Single-file models sit directly in the models directory. Multimodal and multi-shard models go in their own subdirectories with all components included. Restart the router after manually adding files; use llama.cpp model presets for per-model context sizes.++## Configure Pi++```text+/login llama.cpp+```++Enter the router URL (default `http://127.0.0.1:8080`) and optional API key. Environment variables configure the same values without `/login`:++```bash+export LLAMA_BASE_URL=http://127.0.0.1:8080+export LLAMA_API_KEY=optional-secret+pi+```++If the server uses an API key, start `llama-server` with the matching `--api-key`. Keep `--host 127.0.0.1` for local-only access.++## Manage Models with `/llama`++- Select an unloaded model to load it; select a loaded model to unload it.+- Select **Download model…** to search Hugging Face, then choose a repository and quantization. Exact `owner/repository[:quant]` values also work.+- Escape during a load or download prompts to confirm cancellation.+- If the router disconnects, `/llama` offers **Retry** and **Close**; Retry reconnects and refreshes state without replaying the interrupted operation.++Hugging Face search uses `HF_TOKEN` when set, then `$HF_TOKEN_PATH`, `$HF_HOME/token`, `$XDG_CACHE_HOME/huggingface/token`, and `~/.cache/huggingface/token`. Search works unauthenticated with lower rate limits. Pi warns before downloading gated repositories. The llama.cpp server performs the download, so its process also needs `HF_TOKEN` for gated repositories.++Pi never silently unloads models and never deletes model files; it asks whether to unload others first. The router may be shared with other clients, so `/llama` always displays the router's current state.++Only loaded models appear in `/model`. Load with `/llama`, then select the model with `/model`.++## Troubleshooting++```bash+curl http://127.0.0.1:8080/health+curl http://127.0.0.1:8080/models+```++- No models in `/llama`: check `--models-dir`, the directory layout, and restart the router.+- Model missing from `/model`: load it with `/llama` first.+- Load fails or uses too much memory: lower `-c` or unload another model.+- Server not in router mode: start it without `--model`, `-m`, or `-hf`.diff --git a/skills/pi-agent/references/models.md b/skills/pi-agent/references/models.mdindex 80ce6caa..8672f7a5 100644--- a/skills/pi-agent/references/models.md+++ b/skills/pi-agent/references/models.md@@ -26,41 +26,78 @@ Add custom providers and models through `~/.pi/agent/models.json` for Ollama, LM}```-The `apiKey` is required even when the server ignores it. Edit during a session; `/model` reloads the file.+Only `id` is required per model. The `apiKey` placeholder matters because Pi treats models as requiring auth before they appear in `/model`; keyless local servers should keep a dummy value, store a key via `/login`, or pass `--api-key`. Set `compat.supportsDeveloperRole: false` for OpenAI-compatible servers that reject the `developer` role, and `compat.supportsReasoningEffort: false` when `reasoning_effort` is unsupported. `compat` can be set at provider level (all models) or model level (override). The file reloads each time `/model` opens — no restart needed.++For `google-generative-ai` custom models, `baseUrl` is required (for example `https://generativelanguage.googleapis.com/v1beta`).## Supported APIs-- `openai-completions`: OpenAI Chat Completions and compatibles.-- `openai-responses`: OpenAI Responses API.-- `anthropic-messages`: Anthropic Messages API.-- `google-generative-ai`: Google Generative AI.+`openai-completions` (most compatible), `openai-responses`, `anthropic-messages`, `google-generative-ai`. Set `api` at provider level as the default, or per model to override.## Provider Fields-`baseUrl`, `api`, `apiKey`, `headers`, `authHeader`, `models`, `modelOverrides`.+`baseUrl`, `api`, `apiKey`, `oauth`, `headers`, `authHeader`, `models`, `modelOverrides`.++- `oauth`: dynamic OAuth provider type; currently `"radius"`, which requires the gateway `baseUrl`.+- `authHeader: true` adds `Authorization: Bearer <apiKey>`.+- `apiKey` is optional — omit it when auth comes from `/login`/`auth.json`/`--api-key`. Non-built-in providers with `models` need `baseUrl` and an `api` value at provider or model level. Without any auth, models load but stay unavailable in `/model` and `--list-models`.-`apiKey` and `headers` support command execution (`!command`), env interpolation (`$ENV`/`${ENV}`), escapes (`$$`, `$!`), and literals. Shell commands in `models.json` resolve at request time and do not get built-in TTL/recovery; wrap slow or flaky secret commands yourself.+`apiKey` and `headers` support command execution (`!command`, whole value), env interpolation (`$ENV` / `${ENV}`, works inside larger literals), escapes (`$$`, `$!`), and literals (plain uppercase strings are literals). Shell commands in `models.json` resolve at request time with no built-in TTL, stale reuse, or recovery — wrap slow or flaky secret commands yourself. `/model` availability checks use configured auth presence and do not execute shell commands.## Model Fields-Required: `id`.+Required: `id`. Optional: `name` (defaults to `id`), `api`, `reasoning` (`false`), `thinkingLevelMap`, `input` (`["text"]` or `["text","image"]`), `contextWindow` (`128000`), `maxTokens` (`16384`), `cost` (zeros), `compat` (merged with provider `compat`).++`/model`, `--list-models`, and the footer display entries by model `id`; `name` is used for `--model` pattern matching and secondary detail text.++`cost` is per million tokens and supports request-wide input pricing tiers. A tier supplies a complete alternate rate set and applies to the whole request when `input + cacheRead + cacheWrite` exceeds `inputTokensAbove`; the highest matching threshold wins.++```json+{+ "cost": {+ "input": 5, "output": 30, "cacheRead": 0.5, "cacheWrite": 6.25,+ "tiers": [{ "inputTokensAbove": 272000, "input": 10, "output": 45, "cacheRead": 1, "cacheWrite": 12.5 }]+ }+}+```++## Thinking Level Map-Optional: `name`, `api`, `reasoning`, `thinkingLevelMap`, `input`, `contextWindow`, `maxTokens`, `cost`, `compat`.+Keys are Pi levels: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Maps may have holes. Values are tristate: omitted means standard levels through `high` use the provider default mapping while `xhigh`/`max` are unsupported; a string is sent to the provider; `null` marks the level unsupported so it is hidden/skipped/clamped away.-`thinkingLevelMap` maps Pi levels (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`) to provider values; `null` hides unsupported levels.+```json+{ "id": "deepseek-v4-pro", "reasoning": true,+ "thinkingLevelMap": { "minimal": null, "low": null, "medium": null, "high": "high", "xhigh": null, "max": "max" } }+```++Use `{ "off": null }` for models where thinking cannot be disabled. Older `compat.reasoningEffortMap` configs should move to model-level `thinkingLevelMap`.-## Built-in Overrides+## Overriding Built-in Providers-Override a provider base URL without redefining models:+Base-URL-only overrides keep all built-in models and existing auth:```json{ "providers": { "anthropic": { "baseUrl": "https://my-proxy.example.com/v1" } } }```-If `models` is included, custom models merge into built-ins by `id`; matching IDs replace built-ins. Use `modelOverrides` to modify specific built-in models without replacing the provider list.+If `models` is included, built-in models are kept and custom models are upserted by `id` — a matching `id` replaces the built-in, a new `id` is added.++`modelOverrides` customizes built-in and matching extension-registered models without replacing the provider list. Supported per-model fields: `name`, `reasoning`, `thinkingLevelMap`, `input`, `cost` (partial), `contextWindow`, `maxTokens`, `headers`, `compat`. Unknown model IDs are ignored; provider-level `baseUrl`/`headers` can be combined with it. If `models` is also defined, custom models merge after built-in overrides.++Example — opt a direct OpenAI GPT-5.6 model into the 1.05M context window (they default to `272000` to stay in the short-context pricing tier):++```json+{ "providers": { "openai": { "modelOverrides": { "gpt-5.6-sol": { "contextWindow": 1050000 } } } } }+```++## Anthropic Messages Compatibility Flags++`supportsEagerToolInputStreaming` (default `true`; `false` omits `tools[].eager_input_streaming` and sends the legacy fine-grained-tool-streaming beta header), `supportsLongCacheRetention` (default `true`, `cache_control.ttl: "1h"`), `sendSessionAffinityHeaders` (auto-detected), `supportsCacheControlOnTools` (default `true`), `forceAdaptiveThinking` (`thinking.type: "adaptive"` plus `output_config.effort`; built-in adaptive models set it automatically), `allowEmptySignature` (replay empty thinking signatures as `signature: ""`), `supportsStrictTools` (default `false`; built-in Anthropic models enable it).++## OpenAI Compatibility Flags-## Compatibility Flags+`supportsStore`, `supportsDeveloperRole`, `supportsReasoningEffort`, `supportsUsageInStreaming` (default `true`), `maxTokensField` (`max_completion_tokens` | `max_tokens`), `requiresToolResultName`, `requiresAssistantAfterToolResult`, `requiresThinkingAsText`, `requiresReasoningContentOnAssistantMessages`, `thinkingFormat` (`reasoning_effort`, `openrouter`, `deepseek`, `together`, `zai`, `qwen`, `chat-template`, `qwen-chat-template`), `chatTemplateKwargs`, `cacheControlFormat` (`anthropic`), `sendSessionAffinityHeaders` (default `false`), `sessionAffinityFormat` (`openai`, `openai-nosession`, `openrouter`), `supportsStrictMode`, `supportsOpenAIGrammarTools` (default `false`; the built-in catalog enables it for GPT-5+ on OpenAI, OpenAI Codex, Azure OpenAI, GitHub Copilot, opencode, Cloudflare AI Gateway), `deferredToolsMode` (`"kimi"`), `supportsLongCacheRetention` (default `true`; `prompt_cache_retention: "24h"`), `openRouterRouting`, `vercelGatewayRouting`.-Anthropic flags include `supportsEagerToolInputStreaming`, `supportsLongCacheRetention`, `sendSessionAffinityHeaders`, `supportsCacheControlOnTools`, `forceAdaptiveThinking`, and `allowEmptySignature`.+Thinking-format notes: `openrouter` uses `reasoning: { effort }`; `together` uses `reasoning: { enabled }` plus `reasoning_effort` when `supportsReasoningEffort`; `qwen` uses top-level `enable_thinking`; `qwen-chat-template` targets local Qwen servers needing `chat_template_kwargs.enable_thinking` and `preserve_thinking`; `chat-template` plus `chatTemplateKwargs` targets vLLM/Hugging Face templates, e.g. `chatTemplateKwargs: { "thinking": { "$var": "thinking.enabled" } }` for DeepSeek V3.x. `$var` accepts `thinking.enabled` or `thinking.effort`.-OpenAI compatibility flags include `supportsStore`, `supportsDeveloperRole`, `supportsReasoningEffort`, `supportsUsageInStreaming`, `maxTokensField`, `requiresToolResultName`, `requiresAssistantAfterToolResult`, `requiresThinkingAsText`, `requiresReasoningContentOnAssistantMessages`, `thinkingFormat`, `cacheControlFormat`, `supportsStrictMode`, `supportsLongCacheRetention`, `openRouterRouting`, and `vercelGatewayRouting`.+`openRouterRouting` is sent as-is in the OpenRouter `provider` field (`only`, `order`, `ignore`, `sort`, `max_price`, `quantizations`, `zdr`, …). `vercelGatewayRouting` takes `only`/`order`.diff --git a/skills/pi-agent/references/overview.md b/skills/pi-agent/references/overview.mdindex c897f5e5..d4c82797 100644--- a/skills/pi-agent/references/overview.md+++ b/skills/pi-agent/references/overview.md@@ -2,14 +2,14 @@Source: https://pi.dev/docs/latest-Pi is a minimal terminal coding harness. The core stays small and most workflow-specific behavior lives in TypeScript extensions, skills, prompt templates, themes, and Pi packages.+Pi is a minimal terminal coding harness. The core stays small and most workflow-specific behavior lives in TypeScript extensions, skills, prompt templates, themes, and Pi packages. Positioning on `https://pi.dev/`: "There are many agent harnesses but this one is yours" — four run modes (interactive, print/JSON, RPC, SDK), 15+ providers with mid-session model switching, tree-structured shareable sessions, steering and follow-up during a run, and extensible primitives instead of baked-in features.## Top-Level Areas-- Start here: quickstart, usage, providers, security, containerization, settings, keybindings, sessions, compaction.+- Start here: quickstart, usage, providers, llama.cpp, security, containerization, settings, keybindings, sessions, compaction.- Customization: extensions, skills, prompt templates, themes, Pi packages, custom models, custom providers.- Programmatic usage: SDK, RPC mode, JSON event stream mode, TUI components.-- Reference: session file format and SessionManager API.+- Reference: environment variables, session file format and SessionManager API.- Platform setup: Windows, Termux, tmux, terminal setup, shell aliases.- Development: local source setup, rebranding, debug logs, tests, package structure.@@ -20,10 +20,16 @@ npm install -g --ignore-scripts @earendil-works/pi-coding-agentpi```-On Linux/macOS, the installer is also available:+On Linux/macOS the installer is also available:```bashcurl -fsSL https://pi.dev/install.sh | sh```+pnpm and bun global installs work too (`pnpm add -g --ignore-scripts ...`, `bun add -g --ignore-scripts ...`).+Authenticate with `/login` for subscription providers or set API keys such as `ANTHROPIC_API_KEY` before startup.++## Ecosystem++Package gallery at `https://pi.dev/packages` lists community extensions tagged `pi-package`. Source: `https://github.com/earendil-works/pi-mono` (docs live under `packages/coding-agent/docs/`).diff --git a/skills/pi-agent/references/packages.md b/skills/pi-agent/references/packages.mdindex a05c9628..7fe58cfc 100644--- a/skills/pi-agent/references/packages.md+++ b/skills/pi-agent/references/packages.md@@ -2,7 +2,7 @@Source: https://pi.dev/docs/latest/packages-Pi packages bundle extensions, skills, prompt templates, and themes for sharing through npm, git, URL, or local paths.+Pi packages bundle extensions, skills, prompt templates, and themes for sharing through npm, git, URL, or local paths. Packages run with full system access — extensions execute arbitrary code and skills can instruct the model to run executables. Review third-party source before installing.## Install and Manage@@ -12,24 +12,34 @@ pi install git:github.com/user/repo@v1pi install https://github.com/user/repopi install /absolute/path/to/packagepi install ./relative/path/to/package+pi remove npm:@foo/bar-pi list-pi update-pi update --extensions-pi update --self-pi update npm:@foo/bar+pi list # installed packages from settings+pi update # update pi only+pi update --all # pi + packages; reconcile pinned git refs+pi update --extensions # packages only; reconcile pinned git refs+pi update --models # refresh model catalogs only+pi update --self # update pi only+pi update --self --force # reinstall pi even if current+pi update npm:@foo/bar # update one packagepi update --extension npm:@foo/bar+pi config # enable/disable package resources```-Use `-l` to write install/remove to project settings `.pi/settings.json`; otherwise user settings are updated. Project packages install automatically after trust. Use `-e/--extension` to try a package for one run without installing.+`install`/`remove` write to user settings by default; `-l` writes to project settings (`.pi/settings.json`), which can be shared with a team — Pi installs missing project packages automatically on startup after the project is trusted. To try a package for one run without installing, use `-e`/`--extension` (installs to a temporary directory):++```bash+pi -e npm:@foo/bar+pi -e git:github.com/user/repo+```## Sources-npm specs support pins. User installs go under `~/.pi/agent/npm/`; project installs under `.pi/npm/`. `npmCommand` can pin npm operations to a wrapper such as `mise`.+**npm** — `npm:@scope/[email protected]` or `npm:pkg`. Versioned specs are pinned and skipped by package updates. User installs go under `~/.pi/agent/npm/`, project installs under `.pi/npm/`. `npmCommand` in settings pins npm operations to a wrapper such as `mise`.-Git specs support HTTPS, SSH, and shorthand with `git:`. Refs are pinned tags or commits. Reconciliation may reset/clean clones and run `npm install` when `package.json` exists.+**git** — `git:github.com/user/repo@v1`, `git:[email protected]:user/repo@v1`, `https://github.com/user/repo@v1`, `ssh://[email protected]/user/repo@v1`. Without the `git:` prefix only protocol URLs are accepted (`https://`, `http://`, `ssh://`, `git://`); with it, shorthand forms work. SSH URLs use your configured keys and respect `~/.ssh/config`. For CI, set `GIT_TERMINAL_PROMPT=0` and `GIT_SSH_COMMAND` (e.g. `ssh -o BatchMode=yes -o ConnectTimeout=5`) to fail fast. Refs are pinned tags or commits — updates reconcile an existing clone to the configured ref but never move it to a newer ref; use `pi install git:host/user/repo@new-ref` to move it. Clones live in `~/.pi/agent/git/<host>/<path>` or `.pi/git/<host>/<path>`. Reconciliation resets and cleans the clone, then runs `npm install` when `package.json` exists.-Local paths are referenced in settings without copying. Relative paths resolve against the settings file.+**Local paths** — absolute or relative, added to settings without copying. Relative paths resolve against the settings file. A file loads as a single extension; a directory loads using package rules.## Package Manifest@@ -46,24 +56,48 @@ Local paths are referenced in settings without copying. Relative paths resolve a}```-If no manifest exists, Pi auto-discovers conventional directories: `extensions/`, `skills/`, `prompts/`, `themes/`.+Paths are relative to the package root and support glob patterns and `!exclusions`. The `pi-package` keyword makes the package visible in the [gallery](https://pi.dev/packages); add `pi.video` (MP4 only, autoplays on hover) or `pi.image` (PNG/JPEG/GIF/WebP) for a preview — video wins if both are set.++Without a manifest, Pi auto-discovers convention directories: `extensions/` (`.ts` and `.js`), `skills/` (recursive `SKILL.md` folders plus top-level `.md` files), `prompts/` (`.md`), `themes/` (`.json`).## Dependencies-Runtime deps belong in `dependencies`. Pi bundles core packages for extensions/skills; imports of `@earendil-works/pi-ai`, `@earendil-works/pi-agent-core`, `@earendil-works/pi-coding-agent`, `@earendil-works/pi-tui`, and `typebox` should be peer dependencies with `"*"` and not bundled.+Third-party runtime dependencies belong in `dependencies`; Pi runs `npm install` when installing from npm or git.++Pi bundles core packages for extensions and skills. If you import `@earendil-works/pi-ai`, `@earendil-works/pi-agent-core`, `@earendil-works/pi-coding-agent`, `@earendil-works/pi-tui`, or `typebox`, list them in `peerDependencies` with `"*"` and do not bundle them.++Other Pi packages must be bundled: add them to `dependencies` **and** `bundledDependencies`, then reference their resources through `node_modules/` paths. Pi loads packages with separate module roots, so separate installs neither collide nor share modules.## Filtering-Object settings can include/exclude resources with globs, `!pattern`, exact `+path`, exact `-path`, or `[]` to load none for a resource type.+```json+{+ "packages": [+ "npm:simple-pkg",+ {+ "source": "npm:my-package",+ "extensions": ["extensions/*.ts", "!extensions/legacy.ts"],+ "skills": [],+ "prompts": ["prompts/review.md"],+ "themes": ["+themes/legacy.json"]+ }+ ]+}+```++Omit a key to load all of that type, `[]` to load none, `!pattern` to exclude matches, `+path` to force-include an exact path, `-path` to force-exclude. `+`/`-` paths are exact and relative to the package root. Filters narrow what the manifest already allows.++## Enable/Disable and Scope++`pi config` toggles extensions, skills, prompt templates, and themes from installed packages and local directories. It starts in global settings; Tab switches between global and project-local, and `pi config -l` starts in project overrides with inherited global resources dimmed.++A package can appear in both global and project settings. The project entry wins unless it sets `autoload: false`, in which case it applies as a delta over the global entry. Identity: npm package name, git repository URL without ref, or resolved absolute path for local packages.## Notable Ecosystem Packages-- `pi install npm:pi-subagents` — delegate to child agents, chains, parallel runs: `references/pi-subagents.md`+- `pi install npm:pi-subagents` — delegation, chains, parallel runs: `references/pi-subagents.md`- `pi install npm:pi-mcp-adapter` — token-efficient MCP server access: `references/pi-mcp-adapter.md`-- `pi install npm:pi-interview` — interactive interview forms for structured user input: `references/pi-interview.md`- `pi install npm:pi-web-access` — web search, URL/PDF/repo fetching, video understanding: `references/pi-web-access.md`-- `pi install npm:pi-intercom` — child-to-parent coordination companion for pi-subagents--## Security--Packages run with full system access. Review third-party package code before installing.+- `pi install npm:pi-interview` — interactive interview forms: `references/pi-interview.md`+- `pi install npm:glimpseui` — native macOS WebView windows used by several packages+- `pi install npm:@gotgenes/pi-permission-system` — runtime allow/ask/deny policy, composes with pi-subagentsdiff --git a/skills/pi-agent/references/pi-interview.md b/skills/pi-agent/references/pi-interview.mdindex c0b4341f..918bea3d 100644--- a/skills/pi-agent/references/pi-interview.md+++ b/skills/pi-agent/references/pi-interview.md@@ -2,25 +2,29 @@Source: https://pi.dev/packages/pi-interview-Interactive interview form extension: the agent collects structured user responses through forms with single/multi-select, text input, image upload, and info panels, plus rich media (code, diffs, Markdown, images, Chart.js charts, Mermaid diagrams, tables, HTML). Requires pi-agent v0.35.0+.+Interactive interview forms: the agent collects structured user responses through a form with single/multi-select, text input, image upload, and info panels, plus rich media (code, diffs, Markdown, images, Chart.js charts, Mermaid diagrams, tables, HTML).```bashpi install npm:pi-interview-pi install npm:glimpseui # optional: native macOS windows (browser fallback otherwise)+pi install npm:glimpseui # optional: native macOS window; browser fallback otherwise```-## Invocation+Requires Pi v0.82.1 or later. Restart Pi after installing.-Agents call the tool directly:+## Invocation```javascriptawait interview({questions: '/path/to/questions.json',- timeout: 600, // optional, seconds+ timeout: 600, // optional, seconds (default 600)verbose: false // optional, debug logging});```+Lifecycle: the tool starts a local server and opens a Glimpse window (macOS) or browser tab → the user answers at their own pace with auto-save and timeout reset on any activity → the session ends by Submit (`⌘+Enter`), timeout (warning overlay with an option to stay), or Escape twice → the window closes and the agent receives responses, or `null` if cancelled.++With multiple concurrent interviews, only the first auto-opens; the rest are queued and surfaced as URLs in tool output, plus a top-right toast with a dropdown to open queued sessions. Submitting the active interview redirects the window to the next queued one. A status bar shows project path, git branch, and session ID.+## Question Schema```json@@ -28,10 +32,15 @@ await interview({"title": "Project Setup","description": "Review my suggestions and adjust as needed.","questions": [- { "id": "context", "type": "info", "question": "Architecture context", "context": "This project needs SSR and edge deployment support." },+ { "id": "context", "type": "info", "question": "Architecture context",+ "context": "This project needs SSR and edge deployment support." },{ "id": "framework", "type": "single", "question": "Which framework?","options": ["React", "Vue", "Svelte"],- "recommended": "React", "conviction": "strong", "weight": "critical" }+ "recommended": "React", "conviction": "strong", "weight": "critical" },+ { "id": "features", "type": "multi", "question": "Which features?",+ "options": ["Auth", "Database", "API"], "recommended": ["Auth", "Database"] },+ { "id": "notes", "type": "text", "question": "Additional requirements?" },+ { "id": "mockup", "type": "image", "question": "Upload a design mockup" }]}```@@ -41,18 +50,24 @@ Question types: `single` (radio), `multi` (checkbox), `text`, `image` (upload),| Field | Purpose ||---|---|| `id`, `type`, `question` | Identifier, type, question text |-| `options` | Choices for single/multi; strings or `{ label, content }` objects |-| `recommended` | Pre-selected option(s) with badge |-| `conviction` | `"strong"` or `"slight"` — controls pre-selection |-| `weight` | `"critical"` or `"minor"` — visual prominence |-| `context` | Help text |-| `content` | Code/diff/Markdown block: `{ source, lang, file, lines, highlights, showSource }`; `lang: "diff"` renders diffs, `lang: "md"` renders Markdown preview |-| `media` | Object or array: types `image`, `table`, `chart`, `mermaid`, `html`; each supports `position`: `"above"`/`"below"`/`"side"` and `caption`; tables take `{ headers, rows, highlights }` |+| `options` | Choices for single/multi; strings or `{ label, content? }` objects |+| `recommended` | Pre-selected option(s) with a "Recommended" badge |+| `conviction` | `"strong"` or `"slight"` (slight opts out of pre-selection); requires `recommended` |+| `weight` | `"critical"` (prominent card) or `"minor"` (compact card) |+| `context` | Help text below the question |+| `content` | Code/diff/Markdown block: `{ source, lang, file, lines, highlights, showSource }`; `lang: "diff"` renders a diff, `lang: "md"`/`"markdown"` previews Markdown |+| `media` | Object or array of `image`, `table`, `chart`, `mermaid`, `html`; each supports `position` (`"above"`/`"below"`/`"side"`) and `caption`; tables take `{ headers, rows, highlights }` |++Single/multi questions also support an "Other" custom-text option, per-question image attachments (button or drag & drop), "✦ Generate more" and "↻ Review options" LLM actions, an "Ask about an option" inline assistant panel with prompt chips and provider/model overrides, and an optional per-option clarification field.## Response Format```typescript-interface Response { id: string; value: string | string[]; attachments?: string[]; }+interface Response {+ id: string;+ value: string | string[];+ attachments?: string[]; // image paths attached to non-image questions+}```## Settings@@ -67,19 +82,30 @@ interface Response { id: string; value: string | string[]; attachments?: string["snapshotDir": "~/.pi/interview-snapshots/","autoSaveOnSubmit": true,"generateModel": "anthropic/claude-haiku-4-5",- "theme": { "mode": "auto", "name": "default", "lightPath": "/path/to/light.css", "darkPath": "/path/to/dark.css", "toggleHotkey": "mod+shift+l" }+ "glimpseFloating": false,+ "theme": {+ "mode": "auto",+ "name": "default",+ "lightPath": "/path/to/light.css",+ "darkPath": "/path/to/dark.css",+ "toggleHotkey": "mod+shift+l"+ }}}```-Timeout precedence: function parameter > settings > default 600s. Built-in themes: `default` (monospace) and `tufte` (serif); modes `dark` (default), `light`, `auto`. Custom themes are CSS files overriding variables like `--bg-body`, `--bg-card`, `--accent`, `--error`.+Timeout precedence: function parameter > settings > default 600s. A fixed `port` keeps the URL stable across sessions. `generateModel` drives the generate/review option actions, defaulting to the agent's current model then a cheap available model; if an explicitly configured model fails and the session uses a different one, it retries once with the session model. `glimpseFloating` keeps the native macOS window above others (browser fallback unaffected).-## Recovery and Snapshots+Themes: built-ins are `default` (monospace) and `tufte` (serif); modes are `dark` (default), `light`, and `auto` (follows the OS, user override persists in localStorage). Custom themes are CSS files overriding variables such as `--bg-body`, `--bg-card`, `--bg-elevated`, `--bg-selected`, `--fg`, `--fg-muted`, `--accent`, `--border`, `--success`, `--warning`, `--error`, `--focus-ring`.++## Keyboard-Abandoned/timed-out interviews save to `~/.pi/interview-recovery/{date}_{time}_{project}_{branch}_{sessionId}.json` (auto-deleted after 7 days). Submissions can auto-save snapshots (`index.html` + `images/`) to `~/.pi/interview-snapshots/`. Resume either by passing the recovery JSON or snapshot `index.html` path as `questions`.+`↑`/`↓` navigate options, `⌘+←`/`⌘+→` navigate questions (Ctrl off macOS), `Tab` cycles, `Enter`/`Space` selects, `⌘+V` pastes into the focused input, `⌘+Enter` submits, `Esc` shows the exit overlay (twice to quit), `⌘+Shift+L` toggles the theme when enabled.++## Recovery and Snapshots-## Keyboard and Limits+Abandoned or timed-out interviews save their questions to `~/.pi/interview-recovery/{date}_{time}_{project}_{branch}_{sessionId}.json`, auto-deleted after 7 days. Snapshots (manual Save button, or automatic on submit with `autoSaveOnSubmit`) land in `~/.pi/interview-snapshots/{title}-{project}-{branch}-{timestamp}[-submitted]/` as `index.html` plus an `images/` subfolder. Resume either by passing the recovery JSON or the snapshot `index.html` path as `questions` — the form reopens with answers pre-populated.-`↑`/`↓` navigate options, `⌘+←`/`⌘+→` navigate questions (Ctrl on non-macOS), `Tab` cycles, `Enter`/`Space` selects, `⌘+Enter` submits, `Esc` twice quits, `⌘+Shift+L` toggles theme. Auto-saves via localStorage; detects multi-agent queues.+## Limits-Image limits: max 12 per submission, 5MB each, 4096×4096 px, PNG/JPG/GIF/WebP.+Max 12 images per submission, 5 MB per image, 4096×4096 pixels, types PNG/JPG/GIF/WebP.diff --git a/skills/pi-agent/references/pi-mcp-adapter.md b/skills/pi-agent/references/pi-mcp-adapter.mdindex 07b97d82..acddcf9d 100644--- a/skills/pi-agent/references/pi-mcp-adapter.md+++ b/skills/pi-agent/references/pi-mcp-adapter.md@@ -2,22 +2,24 @@Source: https://pi.dev/packages/pi-mcp-adapter-MCP adapter extension for Pi. Instead of loading hundreds of MCP tool definitions upfront (10,000+ tokens per server), it exposes one `mcp` proxy tool (~200 tokens) that discovers and calls tools on demand. Servers connect lazily and disconnect when idle.+MCP adapter extension for Pi. Instead of loading hundreds of tool definitions upfront, it exposes one `mcp` proxy tool (~200 tokens) that discovers and calls tools on demand. Servers connect lazily and disconnect when idle; tool metadata is cached to disk so search/describe work offline.```bashpi install npm:pi-mcp-adapter```-Restart Pi after installation.+Restart Pi after installation. On first run the adapter reads standard MCP files automatically. If you only have host-specific configs (Cursor, Claude Code, Codex, …), run `/mcp setup` to adopt them, or `pi-mcp-adapter init` to scan and add compatibility imports to the Pi agent dir config.## Configuration Files-Precedence (highest to lowest):+Precedence, lowest to highest:-1. `~/.config/mcp/mcp.json` — user-global shared config-2. `<Pi agent dir>/mcp.json` — Pi global override-3. `.mcp.json` — project-local shared config-4. `.pi/mcp.json` — Pi project override+1. `~/.config/mcp/mcp.json` — user-global shared+2. `~/.agents/mcp.json` — user-global tool-agnostic+3. `~/.agents/mcp/mcp.json` — user-global tool-agnostic+4. `<Pi agent dir>/mcp.json` — Pi global override (`~/.pi/agent/mcp.json`, or `$PI_CODING_AGENT_DIR/mcp.json`)+5. `.mcp.json` — project-local shared (preferred for projects)+6. `.pi/mcp.json` — Pi project override```json{@@ -27,58 +29,116 @@ Precedence (highest to lowest):}```-Import existing configs with `"imports": ["cursor", "claude-code", "claude-desktop"]` (also `vscode`, `windsurf`, `codex`).+Host-specific configs are detected but **not** loaded automatically. Opt in with `settings.hostConfigDiscovery: "on"` (or `pi-mcp-adapter init --discover-host-configs`); `"off"` is the default and `"prompt"` detects without activating. Host configs sit below every shared and Pi-owned source.++Import specific host formats explicitly with `"imports": ["cursor", "claude-code", "claude-desktop", "opencode", "vscode", "windsurf", "codex"]`.++`/mcp disable <server>` / `/mcp enable <server>` persist only the `disabled` field into `.pi/mcp.json` (never rewriting the source file or copying credentials); run `/reload` to apply. The manual equivalent is `{ "disabled": true }` in any MCP config.++### SDK Configuration++```ts+import { createMcpAdapter } from "pi-mcp-adapter";+const extension = createMcpAdapter({ config: { mcpServers: { docs: { url: "https://mcp.example.com/mcp", lifecycle: "eager" } } } });+```++A supplied `config` is a complete isolated snapshot — never merged with files, imports, or `--mcp-config`, and cloned per adapter/session. Status, reconnect, explicit `/mcp-auth <server>`, proxy calls, and direct tools still work; setup and no-argument auth/status panels report the limitation. With `configPath` and no `config`, normal file merging applies and that path outranks argv and `--mcp-config`. The package ships TypeScript source, so standalone Node processes need a TS-capable loader (e.g. `node --import tsx`).++OAuth credentials are stored in the OS credential store keyed by configured server name, with URL binding so credentials cannot be reused for a different server URL. `settings.oauthDir` / `MCP_OAUTH_DIR` are legacy plaintext `tokens.json` import locations only.## Server Options| Field | Description ||---|---|-| `command`, `args`, `env`, `cwd` | stdio transport; `env`/`cwd` support `${VAR}`, `$env:VAR`, `~` |-| `url`, `headers` | HTTP endpoint (StreamableHTTP with SSE fallback); headers support interpolation |+| `command`, `args` | stdio transport; mutually exclusive with `url` and `socket` |+| `socket` | `rmcp-mux` Unix socket path; supports `${VAR}`, `$env:VAR`, `~` |+| `env`, `cwd` | Interpolation supported; an `env` value starting with `!` runs a command at connect (`!!` escapes) |+| `url`, `headers` | StreamableHTTP with SSE fallback; interpolation supported, missing URL vars fail before any request || `auth` | `"bearer"` or `"oauth"` |-| `oauth` | `{ grantType, clientId, clientSecret, scope, redirectUri }` |-| `lifecycle` | `"lazy"` (default: connect on first call, idle disconnect), `"eager"` (connect at startup), `"keep-alive"` (startup + health checks + auto-reconnect) |-| `idleTimeout` | Minutes before idle disconnect (default 10) |-| `exposeResources` | Expose MCP resources as tools (default true) |-| `directTools` | `true`, `string[]`, or `false` — register tools directly instead of via proxy |-| `excludeTools` | Tool names to hide |-| `debug` | Show server stderr (default false) |+| `oauth.*` | `grantType` (`authorization_code` default, or `client_credentials`), `clientId`, `clientSecret`, `scope`, `redirectUri` (exact localhost callback for pre-registered clients), `clientName`, `clientUri` |+| `bearerToken` / `bearerTokenEnv` | Token or env var name; interpolation and `!command` supported |+| `lifecycle` | `"lazy"` (default), `"eager"`, `"keep-alive"`, `"lazy-keep-alive"` |+| `idleTimeout` | Minutes before idle disconnect (overrides global) |+| `requestTimeoutMs` | Per-server request timeout; omitted or `<= 0` uses the MCP SDK default |+| `exposeResources` | Expose MCP resources as tools (default `true`) |+| `directTools` | `true`, `string[]`, or `false` |+| `includeTools` / `excludeTools` | Names or glob patterns; `excludeTools` applies after `includeTools` |+| `debug` | Show server stderr (default `false`) |+| `trace` | Metadata-only JSONL protocol tracing for this server |+| `disabled` | Keep visible in config/status but block connections, auth, tools, resources (only literal `true`) |++Secret values in `headers`, `bearerToken`, `oauth.clientSecret`, and stdio `env` may use a leading `!command` resolved at connect/auth time: stdin and stderr suppressed, stdout capped at 1 MiB and trimmed, 10-second limit, non-empty output required. Commands never run during discovery, merging, previewing, hashing, or rendering config.++**Lifecycle modes** — `lazy`: connect on first tool call, disconnect after idle, cached metadata keeps search working. `eager`: connect at startup, no auto-reconnect, no idle timeout unless set. `keep-alive`: connect at startup with health checks and auto-reconnect. `lazy-keep-alive`: connect on first use, then stay resident with auto-reconnect. Any enabled `eager`/`keep-alive` server also triggers initialization at extension load, supporting hosts that never emit `session_start`.++**rmcp-mux** — point `socket` at an [`rmcp-mux`](https://github.com/VetCoders/rmcp-mux) service socket to share one stdio server across Pi sessions. The adapter owns only its client socket; the mux owns the upstream process, routing, restart policy, and socket permissions. A socket is an explicit trusted local endpoint.++## Global Settings++```json+{ "settings": { "toolPrefix": "server", "idleTimeout": 10, "requestTimeoutMs": 30000, "trace": { "enabled": true } } }+```-Global `settings` block: `toolPrefix`, `idleTimeout`, `directTools`, `disableProxyTool`, `autoAuth`, `sampling`, `samplingAutoApprove`, `elicitation`, `elicitationAutoOpenUrls`.+`toolPrefix` (`"server"` default, `"short"` strips a `-mcp` suffix, `"none"`, `"mcp"` prefixes `mcp__`), `idleTimeout` (minutes, default 10, `0` disables), `requestTimeoutMs`, `showStatusIcon` (default `true`), `hostConfigDiscovery`, `oauthDir`, `directTools` (global default, default `false`), `disableProxyTool`, `autoAuth` (default `false`), `sampling` (default `true` when UI approval is available; honors `modelPreferences.hints`), `samplingAutoApprove` (required for sampling in non-UI sessions), `elicitation` (default `true` with UI), `outputGuard`, `trace` (`{ enabled, file, maxBytes: 262144, maxEvents: 10000 }`; the per-session JSONL defaults to `.pi/mcp-traces/` and never records payloads, prompts, arguments/results, auth data, or URLs).-Direct tools cost 150–300 tokens each; use for 5–20 targeted tools, the proxy for everything else:+## Output Guard++On by default: inline text is capped at **50 KiB / 2000 lines** (matching Pi's `bash` guard), with the full text spilled to a temp file whose path is included so the agent can `read`/`grep` it. Image blocks pass through unchanged. In proxy mode `details.mcpResult` stays raw when its JSON is ≤ 16 KiB; larger results become a compact summary with the raw JSON spilled to a temp file (direct tools never carry `mcpResult`). Tune with `{ maxBytes, maxLines, detailsMaxBytes }`; disable with `"outputGuard": false` or `MCP_OUTPUT_GUARD=0`. Temp files are mode `0600` under the system temp dir and are not cleaned up automatically.++## Direct Tools```json{ "mcpServers": { "github": { "directTools": ["search_repositories", "get_file_contents"] } } }```+`true` registers all of a server's tools individually, an array registers only those (original MCP names), omitted/`false` is proxy-only. Per-server overrides the global default. `includeTools`/`excludeTools` filter direct tools, proxy search/list/describe, and the `/mcp` panel. Each direct tool costs ~150–300 tokens, so use targeted sets of 5–20; for 75+ tool servers stay on the proxy.++Direct tools register from the metadata cache (`~/.pi/agent/mcp-cache.json`, or `$PI_CODING_AGENT_DIR/mcp-cache.json`), so no startup connections are needed. The first session after adding `directTools` falls back to proxy-only while the cache populates, then hot-loads. Servers advertising list-change notifications refresh the current session. Force a refresh with `/mcp reconnect <server>`.+## Proxy Tool API```javascript-mcp({ }) // list servers-mcp({ server: "name" }) // server details-mcp({ search: "screenshot navigate" }) // search tools-mcp({ describe: "tool_name" }) // tool description-mcp({ tool: "chrome_devtools_take_screenshot", args: '{"format": "png"}' }) // call; args is a JSON string-mcp({ connect: "server-name" })-mcp({ action: "ui-messages" }) // retrieve MCP UI messages+mcp({ }) // status / list servers+mcp({ server: "name" }) // server details (+ instructions preview)+mcp({ search: "screenshot navigate" }) // search tools (OR'd words)+mcp({ describe: "tool_name" })+mcp({ instructions: "name" }) // full server instructions+mcp({ tool: "chrome_devtools_take_screenshot", args: { format: "png" } })+mcp({ connect: "server-name" }) // connect or refresh+mcp({ action: "ui-messages" })+mcp({ action: "auth-start", server: "name" })+mcp({ action: "auth-complete", server: "name", args: { redirectUrl: "http://localhost:19876/callback?code=...&state=..." } })```-## CLI Commands+`args` accepts a JSON object or a JSON string. Search covers MCP tools **and** Pi extension tools (prefixed `[pi tool]`, listed first). Names fuzzy-match on hyphens and underscores. Server `instructions` surface at three levels: a truncated head in the proxy tool description, a longer preview in `mcp({ server })`, and the full text via `mcp({ instructions })` — captured at connect time and cached.+Remote/headless OAuth uses `auth-start` then `auth-complete` (pass `redirectUrl`, or just `args: { code }`). Persistent OAuth requires an available OS credential store — on headless Linux, an unlocked Secret Service/libsecret keyring; the adapter fails closed rather than storing plaintext.++## Commands++`/mcp` (interactive panel: status, tools, direct/proxy toggles, reconnect, `ctrl+a` or Enter for OAuth), `/mcp setup`, `/mcp tools`, `/mcp prompts`, `/mcp reconnect [server]`, `/mcp disable <server>`, `/mcp enable <server>`, `/mcp logout <server>`, `/mcp-auth [server]`.++## Prompts, Elicitation, UI++MCP prompt templates register as slash commands `/mcp__<server>__<prompt>`, refreshed on connect. Arguments support positional and `key=value` forms with quoting; required arguments are validated before `prompts/get`. Results flatten into one user message preserving `[user]`/`[assistant]` markers.++Elicitation forms use Pi's `select()`/`input()` dialogs with validation and a review step; explicit refusal maps to MCP `decline`, dismissal to `cancel`. URL mode is TUI-only, always shows requesting server/host/URL, and requires consent; `-32042` URL-required tool errors are handled — retry the original call after completing the browser step.++MCP UI resources open in a native macOS window via Glimpse (`pi install npm:glimpseui`) or fall back to the browser. `MCP_UI_VIEWER=browser|glimpse|none` forces or suppresses the viewer (`none` still runs the tool and returns inline results). UIs talk back — message types `prompt`, `intent`, `notify`, `message`, plus custom types forwarded as intents — retrieved with `mcp({ action: "ui-messages" })` (each with `type`, `sessionId`, `serverName`, `toolName`, `timestamp`). Calling the same tool again pushes a new result into the open window instead of replacing it. Tool consent gates whether UIs may call MCP tools (never / once-per-server / always). Browser controls: Cmd/Ctrl+Enter completes, Escape cancels.++## Status Snapshots++```ts+import { MCP_STATUS_EVENT, type McpStatusSnapshot } from "pi-mcp-adapter";+pi.events.on(MCP_STATUS_EVENT, (snapshot) => { /* read-only */ });```-/mcp # interactive panel and first-run setup-/mcp setup # guided imports and config-/mcp tools # list all available tools-/mcp reconnect [server]-/mcp logout <server> # clear OAuth credentials-/mcp-auth [server] # OAuth setup picker-```-## Behavior Notes+Includes `totalTools`, `totalResources`, `connectedCount`, `disabledCount`, and per-server `name`, `status` (connected, cached, failed, needs-auth, not-connected, disabled), `toolCount`, `disabled`, plus `resourceCount` when known and `failedAgoSeconds` on active failure. Reading status never connects a lazy server, starts auth, or exposes clients, transports, credentials, or server definitions. An initial snapshot follows initialization; an empty snapshot is emitted on shutdown.++## Behavior Notes and Limitations-Tool metadata is cached to disk so search/describe work offline. npx-based servers resolve to direct binaries to skip npm overhead. MCP UI–capable tools open in a native macOS window via Glimpse (if installed) or a browser fallback; UI message types `prompt`, `intent`, `notify`, `message` are retrievable via `mcp({ action: "ui-messages" })`.+npx-based servers resolve to direct binaries, skipping the ~143 MB npm parent process. Advertised `outputSchema` supports JSON Schema draft-07 and 2020-12 (unstamped schemas use the SDK's 2020-12 default), and returned `structuredContent` is validated for both proxy and direct calls. Results render compactly (first three wrapped lines plus a Ctrl+O expand hint) while the model still receives the full result.-Limitations: no cross-session server sharing; MCP sampling is text-only (context, tools, audio, images rejected).+Limitations: no cross-session server sharing (each Pi session runs its own server processes, unless using rmcp-mux); MCP sampling is text-only (context inclusion, tools, stop sequences, audio, and images are rejected); inline images follow Pi's image display settings.-Subagents (`pi-subagents`) only receive direct MCP tools when listed in their `tools:` frontmatter with an `mcp:` prefix — see `references/pi-subagents.md`.+Subagents (`pi-subagents`) receive direct MCP tools only when listed with an `mcp:` prefix in their `tools:` frontmatter — a global `directTools: true` is not enough. See `references/pi-subagents.md`.diff --git a/skills/pi-agent/references/pi-subagents.md b/skills/pi-agent/references/pi-subagents.mdindex 20265425..74484c00 100644--- a/skills/pi-agent/references/pi-subagents.md+++ b/skills/pi-agent/references/pi-subagents.md@@ -2,7 +2,7 @@Source: https://pi.dev/packages/pi-subagents-Extension for delegating tasks to focused child agents with sequential chains, parallel execution, dynamic fanout, worktree isolation, and acceptance gates.+Delegate tasks to focused child agents with sequential chains, parallel groups, dynamic fanout, worktree isolation, acceptance gates, and background runs.```bashpi install npm:pi-subagents@@ -12,107 +12,174 @@ pi install npm:pi-subagents| Agent | Purpose ||---|---|-| `scout` | Fast local codebase recon: files, entry points, data flow, risks |-| `researcher` | Web/docs research with sources and a concise brief |-| `planner` | Concrete implementation plan from existing context |-| `worker` | Implementation: file editing and validation |-| `reviewer` | Code review and small fixes against task/plan |-| `context-builder` | Setup pass gathering code context and handoff material |-| `oracle` | Second opinion challenging assumptions; no edits |-| `delegate` | Lightweight general delegate close to parent behavior |+| `scout` | Fast local codebase recon: relevant files, entry points, data flow, risks, where to start |+| `researcher` | Web/docs research with sources; needs `pi-web-access` for `web_search`/`fetch_content`/`get_search_content` |+| `planner` | Concrete implementation plan from existing context; reads and plans, does not edit |+| `worker` | Implementation, including approved oracle handoffs; escalates unapproved decisions |+| `reviewer` | Code review and small fixes against task/plan, tests, edge cases, simplicity |+| `context-builder` | Stronger setup pass: gathers code context and writes handoff material (`context.md`, `meta-prompt.md`) |+| `oracle` (alias `advisor`) | Second opinion before acting; challenges assumptions, no edits |+| `delegate` | Lightweight general delegate close to parent behavior (uses append prompt mode) |-Packaged `planner`, `worker`, `oracle` default to `context: "fork"` (branch from parent session state); others default to `fresh`.+Builtins inherit the current Pi default model unless `subagents.defaultModel` or an override says otherwise. Packaged `planner`, `worker`, `oracle`, and `advisor` default to `context: "fork"`; others default to `fresh`. Builtins opt into project-instruction inheritance so they follow repo rules.## Commands```bash-/run <agent> [task] # single agent; --bg detached, --fork branch session-/run reviewer[model=anthropic/claude-sonnet-4] summarize this code-/chain scout "scan the codebase" -> planner "create an implementation plan"-/parallel scanner "find security issues" -> reviewer "check code style"-/run-chain <chainName> -- <task> # saved workflow-/subagents-doctor # setup diagnostics+/run <agent> [task] # single agent; --bg detached, --fork branched child session+/chain scout "scan" -> planner "plan" # sequential+/chain scout "scan" -> (reviewer "A" | reviewer "B")[concurrency=2,failFast,worktree] -> writer "fix"+/parallel scanner "security" -> reviewer "style"+/run-chain <chainName> -- <task> # saved .chain.md / .chain.json+/subagent-cost # parent + child token usage and cost+/subagents [agent] [model|thinking|prompt|details]+/subagents-doctor # read-only setup diagnostics+/subagents-models [agent] # runtime-loaded model mapping+/subagents-watchdog [status|on|off|recommend-model|model ...|session model ...|check]+/subagents-fleet # live fleet inspector (inspection only)+/subagents-stop [run-id]+/subagents-profiles | /subagents-load-profile <name> | /subagents-check-profile <name>+/subagents-refresh-provider-models <provider> [--force] | /subagents-generate-profiles <provider>```-Per-step config uses `[key=value,...]` on the agent name: `output=file.md`, `outputMode=file-only|inline`, `reads=a.md+b.md`, `model=...`, `skills=a+b`, `thinking=high`, `progress`.+Steps use `->`; a shared task uses one `--` before the task (`/chain scout planner -- analyze auth`). Inline parallel groups wrap two or more agents in `( ... )` separated by ` | `, only as a complete step, and only when the step opens with `(`. Dynamic fanout is not available inline — use the tool API or a `.chain.json`.-Natural language also works: "Use reviewer to review this diff", "Run parallel reviewers: one for correctness, one for tests".+Per-step config appends `[key=value,...]` to the agent name: `output`, `outputMode` (`inline`/`file-only`), `reads` (`a.md+b.md`), `model`, `skills` (`a+b`), `progress`, plus chain-only `as`, `label`, `phase`, `cwd`, `count`, `outputSchema`, `acceptance`. Values must not contain spaces or commas. `output=false`, `reads=false`, `skills=false` disable explicitly. `/run` and `/parallel` ignore chain-only keys.-Packaged prompt shortcuts: `/parallel-review`, `/review-loop`, `/parallel-research`, `/parallel-context-build`, `/parallel-handoff-plan`, `/gather-context-and-clarify`, `/parallel-cleanup` (add `autofix` to apply synthesized fixes).+Add `--bg` for background and `--fork` to branch each child from the parent's current leaf (combinable in either order).-## Programmatic API (subagent tool)+Packaged prompt shortcuts: `/parallel-review`, `/review-loop`, `/parallel-research`, `/parallel-context-build`, `/parallel-handoff-plan`, `/gather-context-and-clarify`, `/parallel-cleanup` (add `autofix` to `/parallel-review` or `/parallel-cleanup` to apply the synthesized fixes).++## Programmatic API (`subagent` tool)```javascript{ agent: "worker", task: "refactor auth" }-{ tasks: [{ agent: "scout", task: "audit frontend" }, { agent: "reviewer", task: "audit backend" }] } // parallel; count: N duplicates a task-{ chain: [{ agent: "scout", task: "Gather context" }, { agent: "planner" }, { agent: "worker" }, { agent: "reviewer" }] }-{ chain: [...], timeoutMs: 30000 }-{ agent: "worker", task: "...", maxRuntimeMs: 600000 }-{ action: "list" | "get" | "create" | "update" | "delete" | "status" | "interrupt" | "resume" | "doctor" }+{ tasks: [{ agent: "scout", task: "audit frontend" }, { agent: "reviewer", task: "audit backend" }], count: 3 }+{ chain: [{ agent: "scout", task: "Gather context" }, { agent: "planner" }, { agent: "worker" }] }+{ chain: [...], async: true, clarify: true }+{ action: "list" | "get" | "create" | "update" | "delete" | "enable" | "disable" | "status" | "interrupt" | "resume" | "stop" | "doctor" }+{ action: "status", id: "<run-id>", view: "fleet" | "transcript", index: 0 }{ action: "resume", id: "<run-id>", message: "follow-up" }+{ action: "watchdog.recommend-model" }+{ action: "watchdog.configure", model: "recommended", scope: "session" | "user" | "project" }```-Key parameters: `output` (file or `false`), `outputMode` (`inline`/`file-only`), `skill` (string/array/`false`), `model`, `concurrency` (default 4), `worktree`, `context` (`fresh`/`fork`), `chainDir`, `clarify` (default true for chains), `async`, `cwd`, `maxOutput` (default 200KB/5000 lines), `share` (Gist upload, off by default), `acceptance`.+Key parameters: `output` (file or `false`), `outputMode`, `skill` (string/array/`false`), `model`, `concurrency`, `worktree`, `context` (`fresh`/`fork`), `chainDir`, `clarify` (tool calls launch directly unless set), `async`, `cwd`, `timeoutMs`/`maxRuntimeMs`, `turnBudget`, `maxOutput`, `acceptance`.++`subagent_wait` blocks on background work: `{ all: true }`, `{ id }`, `{ timeoutMs }`. Background runs are detached — prefer returning control and letting Pi deliver the completion notification, and use `subagent_wait` only when the current turn must have results before it ends. Headless sessions auto-drain current-session work at `agent_end` as a safeguard.-Dynamic fanout: a chain step with `expand: { from: { output: "name", path: "/items" }, item: "target", maxItems: N }` plus `parallel: { agent, task: "Review {target.path}" }` and `collect: { as: "reviews" }` fans out over a prior step's structured output (`as` + `outputSchema`).+Dynamic fanout (`.chain.json` or tool API only): a step with `expand: { from: { output: "name", path: "/items" }, item: "target", key: "/path", maxItems: N }` plus `parallel: { agent, label, task: "Review {target.path}", outputSchema }` and `collect: { as: "reviews" }`. The source must be structured output (`as` + `outputSchema`); prose is never parsed, `maxItems` is required, and nested fanout is unsupported.## Agent Definition Files-Markdown with YAML frontmatter. Precedence: project `.pi/agents/**/*.md` > user `~/.pi/agent/agents/**/*.md` > builtin.+Markdown with YAML frontmatter. Precedence low → high: builtin (`~/.pi/agent/extensions/subagent/agents/`), installed package (`pi-subagents.agents` or `pi.subagents.agents` in `package.json`), user (`~/.pi/agent/agents/**/*.md`), project (`.pi/agents/**/*.md`; legacy `.agents/**/*.md` is also read, project config wins collisions). `agentScope: "user" | "project" | "both"` controls discovery.```yaml---name: scout+package: code-analysis # registers as code-analysis.scoutdescription: Fast codebase recon+tools: read, grep, find, ls, bash, mcp:chrome-devtools+extensions: # omitted = all; empty = none; list = allowlist+subagentOnlyExtensions: ./tools/child-only-search.tsmodel: claude-haiku-4-5fallbackModels: openai/gpt-5-mini, anthropic/claude-sonnet-4thinking: high-tools: read, grep, find, ls, bash # allowlist; mcp: prefix for direct MCP tools-extensions: mcp:chrome-devtools # omitted = all; empty = none-skills: safe-bash-systemPromptMode: replace # or append+systemPromptMode: replace # or append (keeps Pi's base prompt)inheritProjectContext: falseinheritSkills: false-defaultContext: fork # or fresh+skills: safe-bash, review-checklist+skillPath: ./skills, ../shared-skills+defaultContext: forkoutput: context.mddefaultReads: context.mddefaultProgress: true-completionGuard: false # false for non-implementation validators-interactive: true+async: true+timeoutMs: 900000+turnBudget: {"maxTurns":20,"graceTurns":2}+acceptance: {"level":"none","reason":"lightweight lookup"}+acceptanceRole: read-only # or writer+completionGuard: false # false for non-implementation validators+interactive: true # parsed, not enforced in v1maxSubagentDepth: 1-maxExecutionTimeMs: 600000-maxTokens: 50000+memory: { scope: project, path: security-reviewer }---Your system prompt goes here.```-Subagents only receive direct MCP tools when listed in `tools:` frontmatter (requires `pi-mcp-adapter`); a global `directTools: true` is insufficient.+Scalar list fields (`tools`, `defaultReads`, `skills`, `skillPath`, `fallbackModels`, `extensions`, `subagentOnlyExtensions`) accept comma-separated or YAML block-list form. Model ids match fuzzily (provider separator, id separator, case, trailing date stamps); a qualified provider query never switches providers.++Custom agents start with a clean prompt: they do not inherit Pi's base prompt, project instruction files, or the skills catalog unless `systemPromptMode: append`, `inheritProjectContext: true`, or `inheritSkills: true`.++Tool selection: omitting `tools` gives Pi's normal builtins; an explicit list is a strict allowlist; an empty field emits `--no-tools`. Allowlisting a name does not load the extension that registers it — load it through normal discovery, `extensions`, `subagentOnlyExtensions`, or a path-like `tools` entry. `mcp:` entries select direct MCP tools (requires `pi-mcp-adapter`; a global `directTools: true` is not sufficient). Children never get the `subagent` tool unless their resolved builtin `tools` explicitly includes it. Missing providers now fail the run before the first model turn instead of continuing silently.++Per-agent memory (`memory: { scope: "project" | "user", path }`) injects the first 200 lines of `MEMORY.md` from `<project>/.pi/agent-memory/<path>` or `~/.pi/agent/agent-memory/<path>` into the child prompt. Agents with write tools are told they may append dated entries; read-only agents get a read-only block. Paths are validated against traversal and symlink escape, and the directory is created lazily by the agent's own `write`.## Chain Files-Reusable workflows: project `.pi/chains/**/*.chain.md|.chain.json` > user `~/.pi/agent/chains/`. Markdown chains use `## agent` headings with per-step keys (`phase`, `label`, `as`, `output`, `outputMode`, `reads`, `model`, `skills`, `progress`, `outputSchema`) and a task body. Template variables: `{task}`, `{previous}`, `{chain_dir}`, `{outputs.name}`.+`.chain.md` for sequential chains, `.chain.json` when dynamic fanout is needed. Scopes: installed package (`pi-subagents.chains` / `pi.subagents.chains`), user `~/.pi/agent/chains/**`, project `.pi/chains/**`. Project beats user; `.chain.json` beats `.chain.md` within a scope.++```md+---+name: scout-planner+description: Gather context then plan implementation+---++## scout+phase: Context+label: Map auth flow+as: context+output: context.md++Analyze the codebase for {task}++## planner+reads: context.md+model: anthropic/claude-sonnet-4-5:high++Create an implementation plan based on {outputs.context}+```++Config lines (`phase`, `label`, `as`, `outputSchema`, `output`, `outputMode`, `reads`, `model`, `skills`, `progress`) go immediately after the `## agent` header, then a blank line, then the task text. For `output`/`reads`/`skills`/`progress`, behavior is three-state: omitted inherits from the agent, a value overrides, `false` disables. Template variables: `{task}`, `{previous}`, `{chain_dir}`, `{outputs.name}`. Duplicate `as` names, invalid identifiers, and unknown output references fail before child execution.## Configuration-Builtin agent overrides in `~/.pi/agent/settings.json` or `.pi/settings.json`:+`~/.pi/agent/settings.json` or `.pi/settings.json` (project wins):```json-{ "subagents": { "agentOverrides": { "reviewer": { "model": "anthropic/claude-sonnet-4", "thinking": "high" } }, "disableBuiltins": false } }+{+ "subagents": {+ "defaultModel": "deepseek-v4-flash",+ "defaultThinking": "medium",+ "defaultExtensions": [],+ "disableThinking": false,+ "disableBuiltins": false,+ "agentOverrides": {+ "reviewer": { "model": "anthropic/claude-sonnet-4", "thinking": "high", "fallbackModels": ["openai/gpt-5-mini"] }+ },+ "watchdog": { "enabled": true, "main": { "model": "anthropic/claude-opus-4-8", "thinking": "high" } },+ "modelScope": { "enforce": true, "allow": ["anthropic/*", "openai/gpt-5-*"] }+ }+}```-Override fields: `model`, `fallbackModels`, `thinking`, `systemPromptMode`, `inheritProjectContext`, `inheritSkills`, `defaultContext`, `disabled`, `skills`, `tools`, `systemPrompt`.+Override fields: `model`, `fallbackModels`, `thinking`, `systemPromptMode`, `inheritProjectContext`, `inheritSkills`, `defaultContext`, `acceptanceRole`, `disabled`, `skills`, `tools`, `systemPrompt`, `extensions`. Use `false` to clear an inherited `defaultContext`/`acceptanceRole`. `defaultModel`/`defaultThinking`/`defaultExtensions` apply to builtin, package, user, and project agents that omit the field; explicit frontmatter and per-run overrides still win. `disableThinking: true` clears bundled builtin thinking defaults for providers that reject `:level` suffixes.++`modelScope.allow` is glob-matched (only `*` is special, case-insensitive) against the resolved `provider/id`. Explicitly passed models that match nothing error and abort; models from frontmatter, `defaultModel`, or the inherited session model only warn. `enforce: true` requires a non-empty `allow`.-Extension config at `~/.pi/agent/extensions/subagent/config.json`: `asyncByDefault`, `forceTopLevelAsync`, `parallel: { maxTasks, concurrency }`, `defaultSessionDir`, `maxSubagentDepth`, `intercomBridge: { mode: "always"|"fork-only"|"off", instructionFile }`, `worktreeSetupHook` (+ `worktreeSetupHookTimeoutMs`; hook gets stdin JSON with repo/worktree paths and must print `{ "syntheticPaths": [...] }`).+Extension config at `~/.pi/agent/extensions/subagent/config.json`: `asyncByDefault`, `forceTopLevelAsync`, `parallel: { maxTasks, concurrency }`, `defaultSessionDir`, `singleRunOutputBaseDir`, `maxSubagentDepth`, `turnBudget`, `intercomBridge: { mode: "always" | "fork-only" | "off", instructionFile }`, `worktreeSetupHook` (+ `worktreeSetupHookTimeoutMs`; receives repo/worktree paths on stdin and must print `{ "syntheticPaths": [...] }`). Nesting depth defaults to 2; tighten or relax with `PI_SUBAGENT_MAX_DEPTH`, config `maxSubagentDepth`, or per-agent frontmatter (per-agent can only tighten).-Nesting depth defaults to 2 levels; tighten/relax via `PI_SUBAGENT_MAX_DEPTH` env var, config `maxSubagentDepth`, or per-agent frontmatter (per-agent can only tighten). Children never get the `subagent` tool unless their resolved tools explicitly include it.+Profiles live in `~/.pi/agent/profiles/pi-subagents/` and cached provider catalogs in `.../providers/`. Workflow: `/subagents-refresh-provider-models <provider>` → `/subagents-generate-profiles <provider>` → `/subagents-load-profile <provider>.quota`.-## Worktree Isolation+## Watchdog-`worktree: true` on parallel tasks or chain steps runs each agent in an isolated git worktree. Requires a git repo with a clean working tree; `node_modules/` is symlinked in; task-level `cwd` overrides must match the shared cwd.+Opt-in adversarial change reviewer — **not** the `reviewer` agent, and not configured by `defaultModel`/`agentOverrides.reviewer`. It runs at the `agent_end` boundary only when the repo's final state changed during the turn; multiple edits coalesce into one review, unchanged/reverted diffs are skipped, and `.pi-subagents/`/`tmp/` artifacts do not trigger it. When enabled it also checks changed TypeScript/JavaScript files for fresh language-server diagnostics (auto-detected `typescript-language-server` from `node_modules/.bin` or PATH; errors become blockers, warnings concerns) bounded by `watchdog.lsp.enabled`, `timeoutMs`, `maxFiles`, `maxDiagnostics`.-## Acceptance Gates+Use a strong complementary model: `/subagents-watchdog recommend-model` (current policy is Opus 4.8 high or GPT 5.5 high — use whichever your main session is not). `session model recommended` changes only this session; `model recommended` saves to settings without enabling. Settings keys: `watchdog.main.model`/`.thinking` (omitting `main.model` uses the session model; setting it without a thinking suffix runs with thinking off), `watchdog.children.model`, `watchdog.children.overrides.<agent>.model`.-Attach explicit contracts to any run/step:+## Worktrees and Acceptance Gates++`worktree: true` on parallel tasks, chain steps, or group options runs each agent in an isolated git worktree. Requires a git repo with a clean tree; `node_modules/` is symlinked in; task-level `cwd` overrides must match the shared cwd.```javascript{ agent: "worker", task: "Implement the fix", acceptance: {@@ -123,12 +190,32 @@ Attach explicit contracts to any run/step:} }```-Provenance levels reported: `attested`, `checked`, `verified`, `reviewed`, `rejected`.+Provenance levels reported: `attested`, `checked`, `verified`, `reviewed`, `rejected`. Inline `acceptance=` accepts scalar levels `auto`, `attested`, `checked`; object contracts need the tool API or `.chain.json`.++## Supervisor Coordination++Native, no `pi-intercom` required: children call `contact_supervisor({ reason, message })` with `reason` ∈ `need_decision`, `interview_request`, `progress_update`; the parent replies with `subagent_supervisor({ action: "reply", replyTo, message })` or checks `{ action: "pending" }`. Requests are scoped to the exact Pi session id that spawned the child. If no external `pi-intercom` owns the name, the native channel also exposes `intercom` as a compatibility fallback. `pi install npm:pi-intercom` remains available as a companion.++A foreground child may detach while awaiting a reply: reply first, then `subagent_wait({ id: runId })`.++## Observability++FleetView below the editor shows `main` plus active children with task, elapsed time, and token totals (↑/↓ or j/k to select, Enter to inspect, only when the editor is empty). `/subagents-fleet` opens the inspection-only fleet inspector (Shift+K/J scroll a line, PgUp/PgDn a page, `x`/Ctrl+O toggle tool details, `r` refresh, Esc close; Ctrl+Alt+F opens it mid-turn). Mutations stay explicit via `/subagents-stop`.++Async runs write lifecycle artifacts: `details.asyncDir` holds `status.json`, `events.jsonl`, `output-<index>.log`, `subagent-log-<runId>.md`, with the final summary as `<runId>.json` in Pi's results directory. Stable v1 status fields include `lifecycleArtifactVersion`, `runId`/`id`, `sessionId`, `mode`, `state`, timestamps, `cwd`, `asyncDir`, `sessionFile`, `outputFile`, `workflowGraph`, `steps`, `results`, `totalTokens`, `totalCost`, `model`/`attemptedModels`/`modelAttempts`, `toolCount`, `turnCount`, and nested `children`. Read these files rather than scraping terminal output, and ignore unknown fields for forward compatibility. Lifecycle artifact v3 adds `process-terminal-candidate.json` and `process-terminal.json`; a proof is `observed` only when the live parent saw the runner's `close` event, otherwise `unknown` — never infer exit from `endedAt`, result-file existence, PID disappearance, or lease absence.++## Extension Integration++Versioned in-process event-bus RPC: listen for `subagents:rpc:v1:ready`, emit on `subagents:rpc:v1:request` (`{ version: 1, requestId, method, params }`), read `subagents:rpc:v1:reply:<requestId>`. Methods: `ping`, `status`, `spawn` (async-only), `steer`, `interrupt`, `stop`. `ping.capabilities` advertises `processTerminalProof`, `nonRecoveringSteer`, and `events.asyncComplete`. `pi.events` is in-process only — use file artifacts or `pi-intercom` across processes.++Also exported: `pi-subagents/preflight` (`resolveSubagentLaunchContract`), `pi-subagents/delegation` (`SUBAGENT_DELEGATION_REQUEST_EVENT`, `SUBAGENT_DELEGATION_RESPONSE_EVENT`), and `pi-subagents/background-work` (`registerBackgroundWorkProvider`). Events on the bus: `subagent:async-started`, `subagent:async-complete`, `subagent:control-intercom`, `subagent:result-intercom`, `subagent:process-terminal`.++Optional `@gotgenes/pi-permission-system` adds a runtime `allow`/`ask`/`deny` policy layer via a `permission:` frontmatter block, composing independently with the visibility-based `tools:` allowlist. pi-subagents passes `PI_SUBAGENT_PARENT_SESSION` so headless children can forward `ask` prompts to the parent UI — place `ask` policies on direct children of the interactive session.-## Async, Clarify, Observability+## Skills and Bundled Skill-`--bg` / `async: true` detaches runs; status files under `<tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>/` (`status.json`, `events.jsonl`, logs). Chains open a clarify TUI by default to preview/edit steps (`e` edit, `m` model, `t` thinking, `s` skills, `b` background, `Enter` run, `Esc` cancel). Debug artifacts land in `{sessionDir}/subagent-artifacts/` with input/output/jsonl/meta per run; chain artifacts in `<tmpdir>/pi-subagents-<scope>/chain-runs/{runId}/`. Directories older than 24h are cleaned on startup. Events: `subagent:async-started`, `subagent:async-complete`, `subagent:control-intercom`, `subagent:result-intercom`.+Skills are `SKILL.md` files selected per agent; discovery is project-first (project config `skills/`, project/task packages, project settings, `~/.pi/agent/skills/`, user packages, user settings). Set them via agent defaults, per-run `skill: "tmux, safe-bash"`, or `skill: false`. For chains, top-level `skill` is additive and a step-level value overrides. Missing skills warn instead of failing. When an agent has an explicit `tools` allowlist plus resolved skills, `read` is added so skill files can be loaded.-Optional companion `pi install npm:pi-intercom` lets children call `contact_supervisor` (reasons: `need_decision`, `progress_update`) and groups completion delivery back to the parent.+The package bundles a `pi-subagents` skill for the **orchestrating parent only** — children never receive it, and forked child context is filtered to strip parent-only orchestration instructions, slash/status/control messages, and prior parent `subagent` tool history.Recommended implementation pattern: clarify → planner → worker → fresh reviewers → worker.diff --git a/skills/pi-agent/references/pi-web-access.md b/skills/pi-agent/references/pi-web-access.mdindex 28059042..5132cf96 100644--- a/skills/pi-agent/references/pi-web-access.md+++ b/skills/pi-agent/references/pi-web-access.md@@ -2,102 +2,140 @@Source: https://pi.dev/packages/pi-web-access-Extension adding web search, URL fetching, GitHub repo cloning, PDF extraction, YouTube video understanding, and local video analysis to Pi.+Web search, content extraction, GitHub repo cloning, PDF extraction, YouTube and local-video understanding for Pi.```bashpi install npm:pi-web-access```-Works immediately without API keys via Exa MCP. Optional: `brew install ffmpeg yt-dlp` for video frame extraction.+Requires Pi v0.37.3+. Works with no API keys — Exa MCP provides zero-config search, and OpenAI search can reuse Codex auth from `/login`. Optional binaries for frame extraction: `brew install ffmpeg` (frames, thumbnails, local video duration) and `brew install yt-dlp` (YouTube stream URLs). Without them, transcripts and Gemini-based analysis still work.## Tools### web_search-Searches via Exa, Perplexity, or Gemini with synthesized answers and citations.+Searches via OpenAI, Brave, Parallel, Tavily, SERPdive, AnySearch, self-hosted SearXNG, Exa, Perplexity, or Gemini and returns a synthesized answer with citations.```javascriptweb_search({ query: "TypeScript best practices 2025" })-web_search({ queries: ["query 1", "query 2"] })+web_search({ queries: ["query 1", "query 2"], workflow: "auto-summary" })web_search({ query: "latest news", numResults: 10, recencyFilter: "week" })-web_search({ query: "...", domainFilter: ["github.com"], provider: "exa" })+web_search({ query: "...", domainFilter: ["github.com", "-old.example.com"], provider: "openai" })```-Parameters: `query`/`queries`, `numResults`, `recencyFilter` (day/week/month/year), `domainFilter`, `provider` (auto/exa/perplexity/gemini), `includeContent`, `workflow`.+Parameters: `query`/`queries`, `numResults` (default 5, max 20), `recencyFilter` (`day`/`week`/`month`/`year`), `domainFilter` (prefix `-` to exclude), `provider` (`auto` or an explicit provider), `includeContent`, `workflow` (`none`, `summary-review` default, `auto-summary`).-### code_search--Code examples and API references; no API key required.--```javascript-code_search({ query: "React useEffect cleanup pattern" })-code_search({ query: "Express middleware error handling", maxTokens: 10000 })-```+In `auto` mode the fallback order is configured SearXNG → OpenAI (when suitable and available) → Exa (direct API if keyed, MCP if not) → Brave → Parallel → Tavily → SERPdive → Perplexity → Gemini API → Gemini Web (only with browser cookies enabled). AnySearch is explicit-only and never auto-selected.### fetch_content-Readable content from URLs, GitHub repos, YouTube videos, PDFs, and local video files.+Extracts readable markdown from URLs or local files, auto-detecting GitHub repos, YouTube videos, PDFs, local video files, and regular pages.```javascriptfetch_content({ url: "https://example.com/article" })-fetch_content({ urls: ["url1", "url2", "url3"] })+fetch_content({ urls: ["url1", "url2"] })fetch_content({ url: "https://github.com/owner/repo" })fetch_content({ url: "https://youtube.com/watch?v=abc", prompt: "What libraries are shown?" })fetch_content({ url: "/path/to/recording.mp4", prompt: "What error appears on screen?" })-fetch_content({ url: "https://youtube.com/watch?v=abc", timestamp: "23:41-25:00", frames: 4 })+fetch_content({ url: "...", timestamp: "23:41-25:00", frames: 4 })```-Parameters: `url`/`urls`, `prompt`, `timestamp`, `frames` (max 12), `forceClone`.+Parameters: `url`/`urls`, `prompt` (question about a video), `timestamp` (single `"23:41"`, range `"23:41-25:00"`, or bare seconds; accepts `H:MM:SS`, `MM:SS`, seconds), `frames` (max 12), `forceClone` (clone GitHub repos over the 350 MB threshold).### get_search_content-Stored content from previous searches (for content beyond the 30,000-character inline limit): `get_search_content({ responseId: "abc123", urlIndex: 0 })` or `{ responseId, url }`.+Retrieves stored content from previous searches or fetches. Content is stored in full but returned in bounded slices by default; page through with `offset`/`limit` (30,000-character bounds).-## Capabilities+```javascript+get_search_content({ responseId: "abc123", urlIndex: 0 })+get_search_content({ responseId: "abc123", url: "https://...", offset: 30000 })+```-- **GitHub repos**: cloned locally for real file contents — root URLs return tree + README, `/tree/` paths list directories, `/blob/` paths show files; repos over 350MB get lightweight API-based views.-- **YouTube**: visual descriptions, timestamped transcripts, chapter markers via Gemini.-- **Local video**: MP4/MOV/WebM/AVI up to 50MB via Gemini; frame extraction at timestamps with ffmpeg.-- **PDFs**: text extraction saved to `~/Downloads/` as markdown (no OCR).-- **Blocked pages**: automatic retry via Jina Reader, then Gemini URL Context API, for JS-heavy and anti-bot sites.+### source_check-## CLI Commands+Checks a claim and returns a machine-readable artifact with exact passage citations.+```javascript+source_check({ claim: "The API supports streaming responses",+ queries: ["API streaming documentation"], fetchContent: true, domainFilter: ["docs.example.com"] })```-/websearch [queries] # open curator; pre-fill comma-separated queries-/curator # toggle curator workflow-/curator on|off|summary-review # configure curator mode-/search # browse stored results interactively-/google-account # display active Google account++Results are deduplicated and capped at 20 sources; `fetchContent` fetches at most 5 pages. The artifact carries claim status (`supported`, `contradicted`, `unclear`, `missing-evidence`), source-quality hints, SHA-256 content hashes, and passage IDs with exact source offsets. Search and fetch errors stay in the artifact instead of being discarded. Artifacts are stored with the session and retrieved through `get_search_content` by `responseId`.++## Capabilities++- **GitHub repos** are cloned locally instead of scraped: root URLs return the tree plus README, `/tree/` paths return directory listings, `/blob/` paths return file contents, and the agent gets a local path to explore with `read`/`bash`. Repos over 350 MB use a lightweight API view (override with `forceClone`). Commit-SHA URLs go through the API. Clones are cached per session and wiped on session change; private repos need the `gh` CLI. Setting `githubClone.enabled: false` only skips the clone/API specialization — `fetch_content` still handles the URL through normal extraction.+- **YouTube** via Gemini: visual descriptions, timestamped transcripts, chapter markers, and the thumbnail. Fallback: Gemini Web (cookies enabled) → Gemini API → Perplexity (text only). Handles `/watch?v=`, `youtu.be/`, `/shorts/`, `/live/`, `/embed/`, `/v/`.+- **Local video** (`/`, `./`, `../`, or `file://`): MP4, MOV, WebM, AVI and other common formats up to 50 MB for Gemini analysis; a thumbnail frame is included when ffmpeg is present. Timestamp/frame extraction uses ffmpeg directly and works on larger files.+- **PDFs** are text-extracted and saved to `~/Downloads/` as markdown so the agent can `read` sections. No OCR.+- **Blocked pages**: Readability → Next.js RSC flight-data parser → configured Firecrawl (cache-only by default) → Jina Reader → Parallel → Gemini URL Context → Gemini Web extraction when cookies are enabled.++## Commands++```text+/websearch [queries] # open the curator; comma-separated pre-fill+/curator [on|off|summary-review]+/search # browse stored session results+/google-account # active Google account for Gemini Web```-`Ctrl+Shift+W` toggles an activity monitor with live request/response data.+`Ctrl+Shift+W` toggles a live activity monitor of request/response data. Results are injected when you approve the curator summary or send selected results without one; on timeout the curator auto-submits with a deterministic fallback summary. If a browser cannot be opened (Docker, WSL, SSH, headless), the curator URL appears in the tool output.## Configuration-All settings in `~/.pi/web-search.json` are optional. Env vars `EXA_API_KEY`, `GEMINI_API_KEY`, `PERPLEXITY_API_KEY` take precedence over the file.+Config defaults to `~/.pi/web-search.json`, or `web-search.json` under `PI_CODING_AGENT_DIR` / `XDG_CONFIG_HOME/pi`. Every field is optional. Config changes require a Pi restart.```json{+ "openaiApiKey": "sk-...",+ "braveApiKey": "BSA_...","exaApiKey": "exa-...",+ "parallelApiKey": "...",+ "tavilyApiKey": "tvly-...",+ "serpdiveApiKey": "sd_live_...",+ "serpdiveModel": "krill","perplexityApiKey": "pplx-...","geminiApiKey": "AIza...",- "provider": "exa",- "chromeProfile": "Profile 2",- "allowBrowserCookies": false,+ "geminiBaseUrl": "https://my-gateway.example.com/gemini",+ "cloudflareApiKey": "...",+ "searxngBaseUrl": "https://search.example.com",+ "firecrawlBaseUrl": "https://crawl.example.com",+ "firecrawlApiKey": "fc-...",+ "firecrawlApiVersion": "v2",+ "firecrawlFreshScrape": false,+ "provider": "openai",+ "searchRouting": { "providers": ["openai", "brave", "exa"], "fallbackOn": ["transient", "quota", "network"] },+ "webSearch": { "enabled": true },+ "toolNames": { "webSearch": "web_search", "sourceCheck": "source_check", "fetchContent": "fetch_content", "getSearchContent": "get_search_content" },"searchModel": "gemini-2.5-flash","summaryModel": "anthropic/claude-haiku-4-5","workflow": "summary-review","curatorTimeoutSeconds": 20,+ "chromeProfile": "Profile 2",+ "allowBrowserCookies": false,"githubClone": { "enabled": true, "maxRepoSizeMB": 350, "cloneTimeoutSeconds": 30, "clonePath": "/tmp/pi-github-repos" },"youtube": { "enabled": true, "preferredModel": "gemini-3-flash-preview" },"video": { "enabled": true, "preferredModel": "gemini-3-flash-preview", "maxSizeMB": 50 },- "shortcuts": { "curate": "ctrl+shift+s", "activity": "ctrl+shift+w" }+ "fetchContent": { "domainPolicy": { "allow": ["example.com"], "deny": ["blocked.example.com"] } },+ "shortcuts": { "curate": "ctrl+shift+s", "activity": "ctrl+shift+w" },+ "ssrf": { "allowRanges": ["198.18.0.0/15"], "trustEnvProxy": false }}```-Bundled skill `librarian` combines GitHub cloning, web search, and git operations for evidence-backed library investigation with permalink citations.+**Credential sources** (provider API-key fields only): `$NAME` / `${NAME}` reads one env var; a leading `!` runs a trusted local command at provider request time; `$$` and `$!` escape literal prefixes. Commands never run at load or tool registration — each selected provider request re-runs them with a 5-second timeout, 16 KiB output limit, minimized environment, and one-line non-empty stdout requirement (`OP_SESSION_*` is forwarded for 1Password). An explicit source overrides legacy env vars and fails that provider locally rather than falling back on a stale credential.++**Legacy env vars** (lower precedence than an explicit source, higher than literal config values): `OPENAI_API_KEY`, `BRAVE_API_KEY`, `PARALLEL_API_KEY`, `TAVILY_API_KEY`, `SERPDIVE_API_KEY`, `ANYSEARCH_API_KEY`, `FIRECRAWL_API_KEY`, `EXA_API_KEY`, `GEMINI_API_KEY`, `PERPLEXITY_API_KEY`, `GOOGLE_GEMINI_BASE_URL`, `CLOUDFLARE_API_KEY`. Also `SEARXNG_BASE_URL`, `FIRECRAWL_BASE_URL`, `FIRECRAWL_API_VERSION`, `FIRECRAWL_FRESH_SCRAPE`, `SERPDIVE_MODEL`, `PI_ALLOW_BROWSER_COOKIES`.++**Routing**: `provider` (or `searchProvider`) sets the default and takes precedence over `searchRouting`. `searchRouting` opts into an ordered `providers` list plus `fallbackOn` (`transient`, `quota`, `network`) — only those typed failures continue to the next candidate. Named providers stay strict and exhausted routes return per-provider diagnostics. `webSearch.enabled: false` unregisters the search and source-check tools while leaving fetch/content tools. `toolNames` renames the public tools for environments where the defaults collide.++**Models**: `searchModel` overrides only the Gemini API model used for search (default `gemini-2.5-flash`). `summaryModel` sets the curator/`auto-summary` draft model; when Pi's `enabledModels` is configured, summaries are limited to that allowlist and fall back to a deterministic summary rather than calling an unrelated model.++**Security**: `fetchContent.domainPolicy` is an optional hostname allow/deny policy checked before HTTP(S) handling and each redirect this extension follows — bare hostnames match subdomains, `deny` wins, and local/non-HTTP sources are exempt. It adds to, not replaces, the SSRF guard. `ssrf.allowRanges` exempts specific CIDRs (for TUN + fake-IP proxies such as Surge/Clash/Mihomo/Stash); it is off by default and all-address CIDRs are rejected. `ssrf.trustEnvProxy` skips local DNS preflight for proxied hostnames only, still blocking localhost, literal private IPs, and `NO_PROXY` matches. Firecrawl requests are cache-only (`lockdown: true`) unless `firecrawlFreshScrape` is set — only enable that for an isolated Firecrawl deployment, since this extension cannot control the Firecrawl server's own egress.++**SERPdive** `serpdiveModel` picks retrieval depth: `krill` (free default, extracted page content, answer assembled from sources), `mako` (1 credit, fact-carrying sentences plus synthesized answer), `moby` (1.5 credits, full readable content plus cited answer). Unrecognized values fall back to `krill` so a typo cannot cost money. SERPdive has no time-range or domain parameter, so `recencyFilter` is a ranking hint appended to the question and `domainFilter` is applied locally; `numResults` maps to `max_results`, a cap between 1 and 10.++**Gemini gateway**: `geminiBaseUrl` / `GOOGLE_GEMINI_BASE_URL` overrides the Gemini API host (bare host, no trailing slash or version segment). When the host contains `gateway.ai.cloudflare.com`, auth uses `cf-aig-authorization: Bearer <token>` from `cloudflareApiKey`/`CLOUDFLARE_API_KEY` and `GEMINI_API_KEY` is not required for generate-content calls — but local video upload still uses Google's Files API directly.-## Limitations+## Limits and Limitations-Chromium cookie extraction requires opt-in (`allowBrowserCookies: true`); age-restricted/private YouTube videos may fail; Gemini handles videos up to ~1 hour; non-code GitHub URLs fall through to standard web extraction.+Perplexity is capped at 10 requests/minute client-side; content fetches run 3 concurrent with a 30s timeout per URL; Gemini handles videos up to ~1 hour; local video upload is 50 MB max. Chromium cookie extraction for Gemini Web is opt-in (`allowBrowserCookies: true` or `PI_ALLOW_BROWSER_COOKIES=1`) and may trigger a macOS Keychain dialog; cookie DBs are copied to a temporary read-only working copy. Private/age-restricted YouTube videos may fail on all paths, PDFs are text-only, GitHub branch names with slashes may misresolve file paths, and non-code GitHub URLs (issues, PRs, wiki) fall through to normal web extraction.diff --git a/skills/pi-agent/references/prompt-templates.md b/skills/pi-agent/references/prompt-templates.mdindex 4e075a7b..30990ac0 100644--- a/skills/pi-agent/references/prompt-templates.md+++ b/skills/pi-agent/references/prompt-templates.md@@ -2,15 +2,15 @@Source: https://pi.dev/docs/latest/prompt-templates-Prompt templates are Markdown snippets that expand into full prompts. Invoke them by typing `/name` where `name` is the filename without `.md`.+Prompt templates are Markdown snippets that expand into full prompts. Type `/name` in the editor, where `name` is the filename without `.md` (`review.md` → `/review`).## Locations- Global: `~/.pi/agent/prompts/*.md`-- Project: `.pi/prompts/*.md` after project trust-- Packages: `prompts/` directories or `pi.prompts` manifest entries-- Settings: `prompts` array with files/directories-- CLI: `--prompt-template`, repeatable+- Project: `.pi/prompts/*.md` (only after project trust)+- Packages: `prompts/` directories or `pi.prompts` entries in `package.json`+- Settings: `prompts` array with files or directories+- CLI: `--prompt-template <path>` (repeatable)Disable discovery with `--no-prompt-templates`.@@ -19,19 +19,30 @@ Disable discovery with `--no-prompt-templates`.```md---description: Review staged git changes-argument-hint: "[focus]"+argument-hint: "<PR-URL>"---Review the staged changes (`git diff --cached`). Focus on: $ARGUMENTS```-The description is optional; if missing, Pi uses the first non-empty line. `argument-hint` appears in autocomplete.+`description` is optional — without it Pi uses the first non-empty line. `argument-hint` is optional and shown **before** the description in the autocomplete dropdown; use `<angle brackets>` for required arguments and `[square brackets]` for optional ones.++## Usage++```text+/review # expands review.md+/component Button # one argument+/component Button "click handler" # multiple arguments+```## Arguments-- `$1`, `$2`: positional args.-- `$@` or `$ARGUMENTS`: all args joined.-- `${1:-default}`: default value.-- `${@:N}`: args from N.-- `${@:N:L}`: L args starting at N.+- `$1`, `$2`, … positional+- `$@` or `$ARGUMENTS` all arguments joined+- `${1:-default}` argument 1 when present and non-empty, otherwise the default+- `${@:-default}` or `${ARGUMENTS:-default}` all arguments when present, otherwise the default+- `${@:N}` arguments from the Nth position (1-indexed)+- `${@:N:L}` `L` arguments starting at N++## Loading Rules-Discovery in `prompts/` is non-recursive unless subdirectories are explicitly configured in settings or package manifest.+Discovery in `prompts/` is non-recursive. Templates in subdirectories must be added explicitly through the `prompts` setting or a package manifest.diff --git a/skills/pi-agent/references/providers.md b/skills/pi-agent/references/providers.mdindex 09890b1e..e5ae6590 100644--- a/skills/pi-agent/references/providers.md+++ b/skills/pi-agent/references/providers.md@@ -2,31 +2,85 @@Source: https://pi.dev/docs/latest/providers-Pi supports subscription providers via OAuth and API-key providers via env vars or `~/.pi/agent/auth.json`. Built-in model lists are updated with each Pi release.+Pi supports subscription providers via OAuth and API-key providers via environment variables or `~/.pi/agent/auth.json`. Built-in catalogs ship with Pi; configured providers may refresh newer catalogs and cache them in `~/.pi/agent/models-store.json` for offline use.## Subscription Providers-Use `/login` and choose Claude Pro/Max, ChatGPT Plus/Pro (Codex), or GitHub Copilot. Use `/logout` to clear credentials. Tokens live in `~/.pi/agent/auth.json` and refresh automatically.+Run `/login` and select: ChatGPT Plus/Pro (Codex), Claude Pro/Max, GitHub Copilot, xAI (Grok/X subscription), OpenRouter, or Radius. `/logout` clears credentials. Tokens live in `auth.json` and auto-refresh.++- **OpenAI Codex** requires ChatGPT Plus or Pro.+- **Claude Pro/Max**: third-party harness usage draws from Anthropic "extra usage" and is billed per token, not against plan limits.+- **GitHub Copilot**: Enter for github.com, or enter a GitHub Enterprise Server domain. "Model not supported" is fixed by enabling the model in VS Code Copilot Chat.+- **xAI**: `/login xai` → **Use a subscription**; `XAI_API_KEY` remains available under **Use an API key**.+- **OpenRouter**: `/login openrouter` → **Sign in with OpenRouter** runs a PKCE flow that mints a user-controlled API key billed from OpenRouter credits (it does not expire automatically).+- **Radius**: a dynamic `pi-messages` gateway. `/login radius` stores OAuth tokens; the catalog refreshes independently into `models-store.json`. Custom Radius gateways can be declared in `models.json` with `"oauth": "radius"` plus a gateway `baseUrl`.## API Key Providers-Set env vars before startup or use `/login` to store keys. Common mappings:+Set an environment variable before startup, or store a key with `/login`.++| Provider | Environment Variable | `auth.json` key |+|---|---|---|+| Anthropic | `ANTHROPIC_API_KEY` | `anthropic` |+| Ant Ling | `ANT_LING_API_KEY` | `ant-ling` |+| Azure OpenAI Responses | `AZURE_OPENAI_API_KEY` | `azure-openai-responses` |+| OpenAI | `OPENAI_API_KEY` | `openai` |+| DeepSeek | `DEEPSEEK_API_KEY` | `deepseek` |+| NVIDIA NIM | `NVIDIA_API_KEY` | `nvidia` |+| Google Gemini | `GEMINI_API_KEY` | `google` |+| Amazon Bedrock | `AWS_BEARER_TOKEN_BEDROCK` | `amazon-bedrock` |+| Mistral | `MISTRAL_API_KEY` | `mistral` |+| Groq | `GROQ_API_KEY` | `groq` |+| Cerebras | `CEREBRAS_API_KEY` | `cerebras` |+| Cloudflare AI Gateway | `CLOUDFLARE_API_KEY` (+ `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_GATEWAY_ID`) | `cloudflare-ai-gateway` |+| Cloudflare Workers AI | `CLOUDFLARE_API_KEY` (+ `CLOUDFLARE_ACCOUNT_ID`) | `cloudflare-workers-ai` |+| xAI | `XAI_API_KEY` | `xai` |+| OpenRouter | `OPENROUTER_API_KEY` | `openrouter` |+| Vercel AI Gateway | `AI_GATEWAY_API_KEY` | `vercel-ai-gateway` |+| ZAI Coding Plan (Global / China) | `ZAI_API_KEY` / `ZAI_CODING_CN_API_KEY` | `zai` / `zai-coding-cn` |+| OpenCode Zen / Go | `OPENCODE_API_KEY` | `opencode` / `opencode-go` |+| Radius | `RADIUS_API_KEY` | `radius` |+| Hugging Face | `HF_TOKEN` | `huggingface` |+| Fireworks | `FIREWORKS_API_KEY` | `fireworks` |+| Together AI | `TOGETHER_API_KEY` | `together` |+| Kimi For Coding | `KIMI_API_KEY` | `kimi-coding` |+| MiniMax (Global / China) | `MINIMAX_API_KEY` / `MINIMAX_CN_API_KEY` | `minimax` / `minimax-cn` |+| Qwen Token Plan (Global / China) | `QWEN_TOKEN_PLAN_API_KEY` / `QWEN_TOKEN_PLAN_CN_API_KEY` | `qwen-token-plan` / `qwen-token-plan-cn` |+| Xiaomi MiMo | `XIAOMI_API_KEY` | `xiaomi` |+| Xiaomi MiMo Token Plan (CN / AMS / SGP) | `XIAOMI_TOKEN_PLAN_CN_API_KEY`, `XIAOMI_TOKEN_PLAN_AMS_API_KEY`, `XIAOMI_TOKEN_PLAN_SGP_API_KEY` | `xiaomi-token-plan-cn`, `-ams`, `-sgp` |++Authoritative source: `packages/ai/src/env-api-keys.ts` in `earendil-works/pi-mono`.++## Auth File++`~/.pi/agent/auth.json` is created with `0600` permissions and takes priority over environment variables.-- `ANTHROPIC_API_KEY` -> `anthropic`-- `OPENAI_API_KEY` -> `openai`-- `GEMINI_API_KEY` -> `google`-- `MISTRAL_API_KEY` -> `mistral`-- `GROQ_API_KEY` -> `groq`-- `OPENROUTER_API_KEY` -> `openrouter`-- `AI_GATEWAY_API_KEY` -> `vercel-ai-gateway`-- `CLOUDFLARE_API_KEY` plus account/gateway vars -> Cloudflare providers-- `AWS_*` credentials -> Amazon Bedrock+```json+{+ "anthropic": { "type": "api_key", "key": "sk-ant-..." },+ "openai": { "type": "api_key", "key": "sk-..." }+}+```-`auth.json` entries use `{ "type": "api_key", "key": "..." }` and are created with `0600` permissions.+An API-key credential can carry provider-scoped environment values in an `env` object. These are used before process environment variables when resolving the credential key, provider/model headers, and provider configuration such as Cloudflare account IDs, Azure settings, Vertex project/location, Bedrock settings, `PI_CACHE_RETENTION`, and `HTTP_PROXY`/`HTTPS_PROXY`:-## Key Resolution Syntax+```json+{+ "cloudflare-ai-gateway": {+ "type": "api_key",+ "key": "$CLOUDFLARE_API_KEY",+ "env": {+ "CLOUDFLARE_API_KEY": "...",+ "CLOUDFLARE_ACCOUNT_ID": "account-id",+ "CLOUDFLARE_GATEWAY_ID": "gateway-id"+ }+ }+}+```-The `key` field supports:+OAuth credentials are also stored here after `/login` and managed automatically.++## Key Resolution Syntax```json{ "type": "api_key", "key": "!op read 'op://vault/item/credential'" }@@ -36,21 +90,29 @@ The `key` field supports:{ "type": "api_key", "key": "$!literal-bang" }```-Auth file credentials take priority over environment variables.+A leading `!` executes the whole value as a command and uses stdout (cached for the process lifetime). `$VAR`/`${VAR}` interpolate, including inside larger literals; `$FOO_BAR` is the variable `FOO_BAR`, so use `${FOO}_BAR` when `BAR` is literal. Missing variables leave the value unresolved. Plain uppercase strings such as `MY_API_KEY` are literals.## Cloud Providers-Azure OpenAI needs `AZURE_OPENAI_API_KEY` plus `AZURE_OPENAI_BASE_URL` or `AZURE_OPENAI_RESOURCE_NAME`; optional `AZURE_OPENAI_API_VERSION` and deployment mapping.+**Azure OpenAI**: `AZURE_OPENAI_API_KEY` plus `AZURE_OPENAI_BASE_URL` (`*.ai.azure.com`, `*.cognitiveservices.azure.com`, or `*.openai.azure.com`; root endpoints auto-normalize to `/openai/v1`) or `AZURE_OPENAI_RESOURCE_NAME`. Optional `AZURE_OPENAI_API_VERSION` and `AZURE_OPENAI_DEPLOYMENT_NAME_MAP=gpt-4=my-gpt4,...`.++**Amazon Bedrock**: `/login amazon-bedrock` for an API key, or ambient AWS credentials — `AWS_PROFILE`, IAM keys (`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`), or `AWS_BEARER_TOKEN_BEDROCK`. `AWS_REGION` defaults to `us-east-1`. ECS task roles (`AWS_CONTAINER_CREDENTIALS_*`) and IRSA (`AWS_WEB_IDENTITY_TOKEN_FILE`) are supported. Prompt caching is automatic for Claude models whose ID contains a recognizable model name; for application inference profiles set `AWS_BEDROCK_FORCE_CACHE=1`. Proxy support: `AWS_ENDPOINT_URL_BEDROCK_RUNTIME`, `AWS_BEDROCK_SKIP_AUTH=1`, `AWS_BEDROCK_FORCE_HTTP1=1`.++**Cloudflare AI Gateway**: `CLOUDFLARE_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_GATEWAY_ID`. Routes to OpenAI (`/openai`, native IDs), Anthropic (`/anthropic`, native IDs), and Workers AI (Unified API `/compat`, `workers-ai/@cf/...` IDs). The Cloudflare token is sent as `cf-aig-authorization`. Upstream auth modes: Workers AI, unified billing, stored BYOK, or inline BYOK (needs an extra upstream `Authorization` header). Prefer unified billing or stored BYOK.++**Cloudflare Workers AI**: `CLOUDFLARE_API_KEY` + `CLOUDFLARE_ACCOUNT_ID`. Pi sets `x-session-affinity` for prefix-caching discounts.++**Google Vertex AI**: Application Default Credentials (`gcloud auth application-default login`) plus `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, or `GOOGLE_APPLICATION_CREDENTIALS` pointing at a service-account key.-Amazon Bedrock uses AWS profile, IAM keys, bearer token, ECS task roles, or IRSA. Set region through `AWS_REGION`. For application inference profiles that do not include recognizable model names, set `AWS_BEDROCK_FORCE_CACHE=1` to force cache points.+**llama.cpp**: `/login llama.cpp`, manage models with `/llama`, select with `/model` — see `references/llama-cpp.md`.-Cloudflare AI Gateway requires `CLOUDFLARE_API_KEY`, `CLOUDFLARE_ACCOUNT_ID`, and `CLOUDFLARE_GATEWAY_ID`. Prefer unified billing or stored BYOK.+## Custom Providers-Google Vertex AI uses Application Default Credentials plus `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`.+Via `models.json` for anything speaking a supported API (`references/models.md`); via extensions for custom APIs or OAuth flows (`references/custom-provider.md`).## Resolution Order1. CLI `--api-key`-2. `auth.json` entry+2. `auth.json` entry (API key or OAuth token)3. Environment variable4. Custom provider keys from `models.json`diff --git a/skills/pi-agent/references/quickstart.md b/skills/pi-agent/references/quickstart.mdindex e65c4a2b..22bee6d1 100644--- a/skills/pi-agent/references/quickstart.md+++ b/skills/pi-agent/references/quickstart.md@@ -10,40 +10,43 @@ npm install -g --ignore-scripts @earendil-works/pi-coding-agent`--ignore-scripts` disables dependency lifecycle scripts. Pi does not need install scripts for normal npm installs.-Uninstall with the matching package manager. Curl and npm installs are removed with:+Uninstall with the package manager that installed Pi. The curl installer uses global npm, so curl and npm installs both remove with npm:```bashnpm uninstall -g @earendil-works/pi-coding-agent+pnpm remove -g @earendil-works/pi-coding-agent+yarn global remove @earendil-works/pi-coding-agent+bun uninstall -g @earendil-works/pi-coding-agent```Uninstalling Pi leaves settings, credentials, sessions, and installed packages in `~/.pi/agent/`.## Authenticate-Use `/login` in interactive mode for subscription providers: Claude Pro/Max, ChatGPT Plus/Pro (Codex), and GitHub Copilot. API-key providers can be configured by environment variable or stored through `/login` in `~/.pi/agent/auth.json`.+Use `/login` in interactive mode for subscription providers; built-in subscription logins include Claude Pro/Max, ChatGPT Plus/Pro (Codex), and GitHub Copilot. API-key providers can be configured by environment variable or stored through `/login` in `~/.pi/agent/auth.json`.```bashexport ANTHROPIC_API_KEY=sk-ant-...pi```-## First Session+See `references/providers.md` for the full provider list.-Run Pi in the project directory:+## First Session```bashcd /path/to/projectpi```-By default, the model gets `read`, `write`, `edit`, and `bash`. Additional read-only built-ins `grep`, `find`, and `ls` are available through tool options.+By default the model gets four tools: `read`, `write` (create/overwrite), `edit` (patch), and `bash`. Read-only built-ins `grep`, `find`, and `ls` are available through tool options. Pi works in the current directory and can modify files there — use git or another checkpointing workflow for rollback.## Project InstructionsPi loads context files at startup:- `~/.pi/agent/AGENTS.md`-- `AGENTS.md` or `CLAUDE.md` from parent directories and current directory+- `AGENTS.md` or `CLAUDE.md` from parent directories and the current directoryRun `/reload` or restart after changing context files.@@ -60,8 +63,11 @@ pi --name "my task"pi --session <path|id>pi -p "Summarize this codebase"cat README.md | pi -p "Summarize this text"+pi -p @screenshot.png "What's in this image?"pi --mode json "List files"pi --mode rpc --no-session```-Use `!command` to run shell and send output to the model. Use `!!command` to run without adding output to model context.+Use `!command` to run shell and send output to the model; `!!command` runs without adding output to model context. Paste text or images with Ctrl+V (Alt+V on Windows), or drag images into supported terminals.++Switch models with `/model` or Ctrl+L, cycle thinking level with Shift+Tab, and cycle scoped models with Ctrl+P / Shift+Ctrl+P.diff --git a/skills/pi-agent/references/rpc.md b/skills/pi-agent/references/rpc.mdindex 958aa4cd..4761ebcb 100644--- a/skills/pi-agent/references/rpc.md+++ b/skills/pi-agent/references/rpc.md@@ -2,83 +2,85 @@Source: https://pi.dev/docs/latest/rpc-RPC mode runs Pi headlessly over stdin/stdout JSONL. Use it for language-agnostic clients, IDE integrations, custom UIs, or subprocess isolation.+RPC mode runs Pi headlessly over stdin/stdout JSONL. Use it for language-agnostic clients, IDE integrations, custom UIs, or subprocess isolation. For Node/TypeScript in-process apps prefer the SDK unless you want subprocess isolation.```bashpi --mode rpc [options]```-Common options: `--provider`, `--model`, `--name/-n`, `--no-session`, `--session-dir`.--For Node/TypeScript in-process apps, prefer the SDK unless subprocess isolation is desired.+Common options: `--provider`, `--model` (supports `provider/id` and `:<thinking>`), `--name`/`-n`, `--no-session`, `--session-dir`.## Framing-Commands are JSON objects sent to stdin, one per line. Responses and events are JSON objects streamed to stdout, one per line. Use LF (`-`) as the only record delimiter; strip trailing ` ` for CRLF input. Do not use generic line readers that split on Unicode separators. Node `readline` is not protocol-compliant because it also splits on U+2028/U+2029.--Commands can include optional `id`; corresponding responses echo it. Events do not include `id`.--## Prompting Commands--`prompt`: send a user prompt. Response means accepted, queued, or handled; later failures come through events.+Commands are JSON objects on stdin, one per line; responses (`type: "response"`) and events stream to stdout as JSON lines. Use LF (`\n`) as the only record delimiter, strip an optional trailing `\r`, and never use readers that split on Unicode separators — Node `readline` is not protocol-compliant because it also splits on U+2028/U+2029, which are valid inside JSON strings.-```json-{"id":"req-1","type":"prompt","message":"Hello"}-```+Commands accept an optional `id`; the response echoes it. Events generally omit `id`; `bash_execution_update` carries the `id` of its originating `bash` command.-Add images with `images: [{"type":"image","data":"base64...","mimeType":"image/png"}]`.+Responses have the shape `{"type":"response","command":"...","success":true|false,"data":{...},"error":"..."}`. Parse failures return `command: "parse"`.-If streaming, include `streamingBehavior: "steer"` or `"followUp"`. Extension commands execute immediately; skills and prompt templates expand before sending/queueing.+## Prompting Commands-`steer`: queue a steering message delivered after current assistant turn tool calls.+`prompt` — `{"id":"req-1","type":"prompt","message":"Hello"}`. Optional `images: [{"type":"image","data":"base64...","mimeType":"image/png"}]`. While streaming, `streamingBehavior` is required (`"steer"` or `"followUp"`) or the command errors. Extension commands execute immediately even during streaming; skill commands and prompt templates expand before sending or queueing. `success: true` means accepted, queued, or handled — later failures arrive as events, not a second response.-`follow_up`: queue a message delivered after the agent is fully done.+`steer` — queue a steering message delivered after the current assistant turn's tool calls. `follow_up` — queue a message delivered when the agent is fully done. Both accept `images` and expand skills/templates but reject extension commands.-`abort`: abort current agent operation.+`abort` — abort the current agent operation.-`new_session`: start fresh, optionally with `parentSession`; can be cancelled by extension.+`new_session` — optional `parentSession`; response `data: { cancelled }` (an extension may cancel via `session_before_switch`).-## State and Model Commands+## State, Model, Thinking-- `get_state`: returns model, thinkingLevel, streaming/compacting state, queue modes, session info, message counts, auto-compaction.-- `get_messages`: returns all `AgentMessage` objects.-- `set_model`: switch model.-- `cycle_model`: cycle next available/scoped model.-- `get_available_models`: list configured models.-- `set_thinking_level`: set `off`, `minimal`, `low`, `medium`, `high`, or `xhigh`.-- `cycle_thinking_level`: cycle supported levels.+- `get_state` → `model` (full Model object or `null`), `thinkingLevel`, `isStreaming`, `isCompacting`, `steeringMode`, `followUpMode`, `sessionFile`, `sessionId`, `sessionName`, `autoCompactionEnabled`, `messageCount`, `pendingMessageCount`.+- `get_messages` → all `AgentMessage` objects.+- `set_model` (`provider`, `modelId`) → full Model object.+- `cycle_model` → `{ model, thinkingLevel, isScoped }`, or `null` data with one model.+- `get_available_models` → array of Model objects.+- `set_thinking_level` (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; `xhigh`/`max` only when the model supports them).+- `cycle_thinking_level` → `{ level }`, `null` if the model has no thinking.+- `get_available_thinking_levels` → `{ levels }`; `["off"]` for non-reasoning models.## Queue, Compaction, Retry-- `set_steering_mode`: `all` or `one-at-a-time`.-- `set_follow_up_mode`: `all` or `one-at-a-time`.-- `compact`: manually compact; accepts `customInstructions`.-- `set_auto_compaction`: enable/disable auto compaction.-- `set_auto_retry`: enable/disable transient-error retry.-- `abort_retry`: cancel retry delay and stop retrying.+- `set_steering_mode` / `set_follow_up_mode`: `"all"` or `"one-at-a-time"` (default).+- `compact` with optional `customInstructions` → `{ summary, firstKeptEntryId, tokensBefore, estimatedTokensAfter, usage, details }`. `estimatedTokensAfter` is a heuristic over the rebuilt context, not a provider-exact count; `usage` may be omitted by custom compaction handlers.+- `set_auto_compaction` (`enabled`), `set_auto_retry` (`enabled`), `abort_retry`.## Bash-`bash` executes immediately and returns output. A `BashExecutionMessage` is stored in agent state but no event is emitted for it. The output reaches the LLM on the next `prompt`.--`abort_bash` aborts a running bash command.+`bash` (`command`, optional `id`) executes immediately, streams `bash_execution_update` events, and returns `{ output, exitCode, cancelled, truncated }` plus `fullOutputPath` when truncated. Internally a `BashExecutionMessage` is stored in agent state; it reaches the LLM on the **next** `prompt`, rendered as ``Ran `cmd``` plus a fenced output block. Multiple bash commands before a prompt are all included. `abort_bash` aborts a running command.## Session Commands-- `get_session_stats`: token totals, cost, context usage.-- `export_html`: export current session.-- `switch_session`: load another session; extension can cancel.-- `fork`: create a new fork from an earlier user message.-- `clone`: duplicate active branch into a new session.-- `get_fork_messages`: list forkable user messages.-- `get_last_assistant_text`: last assistant text or null.-- `set_session_name`: set display name.+- `get_session_stats` → session file/id, message counts, `tokens` (`input`, `output`, `cacheRead`, `cacheWrite`, `total`), `cost`, and `contextUsage` (`tokens`, `contextWindow`, `percent`). Totals include tool-reported usage and summary generation. `contextUsage` is omitted without a model/context window; `tokens`/`percent` are `null` right after compaction until a fresh assistant response provides usage.+- `export_html` with optional `outputPath` → `{ path }`.+- `switch_session` (`sessionPath`) → `{ cancelled }`.+- `fork` (`entryId`) → `{ text, cancelled }`; `clone` → `{ cancelled }`. Both can be cancelled by `session_before_fork`.+- `get_fork_messages` → `[{ entryId, text }]`.+- `get_entries` with optional `since` cursor → `{ entries, leafId }`. Includes pre-compaction history and abandoned branches, unlike `get_messages`. Entry ids are durable cursors across client restarts; an unknown `since` returns `success: false`. `leafId` is `null` for an empty session.+- `get_tree` → `{ tree, leafId }` where each node is `{ entry, children, label?, labelTimestamp? }`. Orphaned entries appear as extra roots.+- `get_last_assistant_text` → `{ text }` or `{ text: null }`.+- `set_session_name` (`name`); read it back from `get_state.sessionName`. Set the initial name with `--name`.## Commands Discovery-`get_commands` lists extension commands, prompt templates, and skills. Built-in TUI commands such as `/settings` are interactive-only and are not included.+`get_commands` returns extension commands, prompt templates, and skills (`skill:` prefixed) with `name`, `description`, `source` (`extension` | `prompt` | `skill`), optional `location` (`user` | `project` | `path`), and `path`. Built-in TUI commands such as `/settings` are interactive-only and excluded.## Events-RPC streams the same major events as the SDK/JSON mode: agent, turn, message, tool execution, queue, compaction, retry, and extension errors.+`agent_start`; `agent_end` (`messages`, `willRetry`); `agent_settled` (nothing will continue automatically — no retry, compaction retry, or queued continuation); `turn_start` / `turn_end`; `message_start` / `message_update` / `message_end`; `bash_execution_update`; `tool_execution_start` / `_update` / `_end`; `queue_update`; `compaction_start` / `compaction_end`; `auto_retry_start` / `auto_retry_end`; `summarization_retry_scheduled` / `summarization_retry_attempt_start` / `summarization_retry_finished`; `extension_error`.++`message_update.assistantMessageEvent` types: `start`, `text_start`, `text_delta`, `text_end`, `thinking_start`, `thinking_delta`, `thinking_end`, `toolcall_start`, `toolcall_delta`, `toolcall_end`, `done` (`stop`/`length`/`toolUse`), `error` (`aborted`/`error`).++`compaction_start`/`compaction_end` carry `reason` (`"manual"`, `"threshold"`, `"overflow"`). On overflow success, `willRetry` is `true` and the prompt is retried. Aborted compaction returns `result: null, aborted: true`; failed compaction returns `result: null, aborted: false` plus `errorMessage`. `tool_execution_update.partialResult` is cumulative, so clients can replace their display each update.++## Extension UI Protocol++Extension dialogs (`select`, `confirm`, `input`, `editor`) emit `extension_ui_request` on stdout and block until the client sends `extension_ui_response` on stdin with the matching `id`. Fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `set_editor_text`) emit a request with no response expected. A `timeout` field means the agent auto-resolves when it expires, so clients need not track timeouts.++Responses: `{"type":"extension_ui_response","id":"...","value":"..."}` for select/input/editor, `{"confirmed":true|false}` for confirm, `{"cancelled":true}` to dismiss any dialog.++Degraded in RPC mode: `custom()` returns `undefined`; `setWorkingMessage`, `setWorkingIndicator`, `setFooter`, `setHeader`, `setEditorComponent`, `setToolsExpanded` are no-ops; `getEditorText()` returns `""`; `getToolsExpanded()` returns `false`; `pasteToEditor()` delegates to `setEditorText()`; `getAllThemes()` returns `[]`; `getTheme()` returns `undefined`; `setTheme()` returns `{ success: false, error }`. `ctx.mode` is `"rpc"` and `ctx.hasUI` is `true` — use `ctx.mode === "tui"` to guard real-terminal features.++## Message Types++`UserMessage` (`role`, `content` string or blocks, `timestamp`, `attachments`), `AssistantMessage` (`content` with `text`/`thinking`/`toolCall` blocks, `api`, `provider`, `model`, `usage`, `stopReason` ∈ `stop`/`length`/`toolUse`/`error`/`aborted`, `timestamp`), `ToolResultMessage` (`toolCallId`, `toolName`, `content`, optional `usage` for nested LLM work, `isError`), `BashExecutionMessage` (from the `bash` command, not LLM tool calls), and `Attachment`. Full definitions in `references/session-format.md`.diff --git a/skills/pi-agent/references/sdk.md b/skills/pi-agent/references/sdk.mdindex 3e2a4414..f59bf217 100644--- a/skills/pi-agent/references/sdk.md+++ b/skills/pi-agent/references/sdk.md@@ -2,26 +2,23 @@Source: https://pi.dev/docs/latest/sdk-Install the main package; the SDK is included:+The SDK ships in the main package:```bashnpm install @earendil-works/pi-coding-agent```-Use the SDK to embed Pi in apps, build custom UIs, automate workflows, spawn sub-agents, test behavior, or customize tools/resources in process.+Use it to embed Pi, build custom UIs, automate workflows, spawn sub-agents, test behavior, or customize tools/resources in process.## Quick Start```ts-import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "@earendil-works/pi-coding-agent";--const authStorage = AuthStorage.create();-const modelRegistry = ModelRegistry.create(authStorage);+import { createAgentSession, ModelRuntime, SessionManager } from "@earendil-works/pi-coding-agent";+const modelRuntime = await ModelRuntime.create();const { session } = await createAgentSession({sessionManager: SessionManager.inMemory(),- authStorage,- modelRegistry,+ modelRuntime,});session.subscribe((event) => {@@ -33,62 +30,106 @@ session.subscribe((event) => {await session.prompt("What files are in the current directory?");```+`createAgentSession()` returns `{ session, extensionsResult, modelFallbackMessage? }` and uses `DefaultResourceLoader` when no `resourceLoader` is passed.+## `AgentSession`-Core methods: `prompt`, `steer`, `followUp`, `subscribe`, `setModel`, `setThinkingLevel`, `cycleModel`, `cycleThinkingLevel`, `navigateTree`, `compact`, `abortCompaction`, `abort`, and `dispose`.+Methods: `prompt(text, options?)`, `steer(text)`, `followUp(text)`, `subscribe(listener)` (returns unsubscribe), `setModel`, `setThinkingLevel`, `cycleModel`, `cycleThinkingLevel`, `navigateTree(targetId, { summarize, customInstructions, replaceInstructions, label })`, `compact(customInstructions?)`, `abortCompaction()`, `abort()`, `dispose()`.State: `sessionFile`, `sessionId`, `agent`, `model`, `thinkingLevel`, `messages`, `isStreaming`.-Session replacement (`new`, `resume`, `fork`, import) belongs to `AgentSessionRuntime`, not `AgentSession`.+`session.agent.state` exposes `messages`, `model`, `thinkingLevel`, `systemPrompt`, `tools`, `streamingMessage`, `errorMessage`; `state.messages` and `state.tools` can be replaced (top-level array is copied) and `session.agent.waitForIdle()` waits for completion.++Session replacement (new/resume/fork/clone/import) lives on `AgentSessionRuntime`, not `AgentSession`.## Runtime API-Use `createAgentSessionRuntime()` when replacing the active session and rebuilding cwd-bound services. After `runtime.newSession()`, `runtime.switchSession()`, or `runtime.fork()`, `runtime.session` changes; re-subscribe to events and re-bind extensions if you manage them manually.+```ts+const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {+ const services = await createAgentSessionServices({ cwd });+ return {+ ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })),+ services,+ diagnostics: services.diagnostics,+ };+};++const runtime = await createAgentSessionRuntime(createRuntime, {+ cwd: process.cwd(),+ agentDir: getAgentDir(),+ sessionManager: SessionManager.create(process.cwd()),+});+```++`AgentSessionRuntime` owns `newSession()`, `switchSession(path)`, `fork(entryId)`, clone via `fork(entryId, { position: "at" })`, and `importFromJsonl()`. `runtime.session` changes after each, so re-subscribe to events and call `runtime.session.bindExtensions(...)` again if you manage extensions manually. Creation returns `runtime.diagnostics`; failures throw.## Prompting and Queueing-`PromptOptions` supports `expandPromptTemplates`, `images`, `streamingBehavior` (`steer` or `followUp`), `source`, and `preflightResult`.+```ts+interface PromptOptions {+ expandPromptTemplates?: boolean;+ images?: ImageContent[];+ streamingBehavior?: "steer" | "followUp";+ source?: InputSource;+ preflightResult?: (success: boolean) => void;+}+```++`preflightResult` fires once before `prompt()` resolves: `true` when accepted, queued, or handled immediately; `false` when preflight rejected before acceptance. Failures after acceptance surface through events and messages, not `preflightResult(false)`. `prompt()` resolves only after the full accepted run finishes, including retries.-During streaming, `prompt()` without `streamingBehavior` throws. Use `session.steer()` for steering delivered after current assistant turn tool calls, or `session.followUp()` for after all work finishes. Extension commands execute immediately and cannot be queued by `steer`/`followUp`.+Extension commands execute immediately even during streaming. File-based prompt templates expand before sending or queueing. Calling `prompt()` while streaming without `streamingBehavior` throws — use `session.steer()` (delivered after the current assistant turn's tool calls) or `session.followUp()` (after all work finishes). Both expand templates but error on extension commands.## Events-Subscribe to `AgentSessionEvent` for `message_update` text/thinking deltas, tool execution events, message lifecycle, agent lifecycle, turn lifecycle, queue updates, compaction, and retry events.+`message_update` (with `assistantMessageEvent` deltas such as `text_delta`, `thinking_delta`), `tool_execution_start` / `_update` / `_end`, `message_start` / `message_end`, `agent_start` / `agent_end`, `turn_start` / `turn_end`, `queue_update`, `compaction_start` / `compaction_end`, `auto_retry_start` / `auto_retry_end`, `summarization_retry_scheduled` / `summarization_retry_attempt_start` / `summarization_retry_finished`.## Models and Auth-Use `AuthStorage.create()` and `ModelRegistry.create(authStorage)`. API key priority: runtime overrides, `auth.json`, environment variables, then custom provider fallback from `models.json`.+`ModelRuntime` replaces the older `AuthStorage` + `ModelRegistry` pair (a synchronous `ModelRegistry` facade remains exported for extension compatibility).++```ts+const modelRuntime = await ModelRuntime.create({ authPath, modelsPath, credentials });+modelRuntime.getModel(provider, id); // built-ins + models.json, no auth check+await modelRuntime.getAvailable(); // only models with valid auth+await modelRuntime.checkAuth(providerId);+modelRuntime.getProviders(); // provider.auth methods and status+modelRuntime.setRuntimeApiKey(provider, key); // not persisted+```++Credential priority: runtime overrides → `auth.json` → environment variables → custom fallback from `models.json`. `getModel(provider, id)` from `@earendil-works/pi-ai` looks up built-ins only. Inject any pi-ai `CredentialStore` (for example `InMemoryCredentialStore`) via `credentials`.++To match CLI parsing, use `resolveCliModel({ cliModel, modelRuntime })` (uses all registered models so `--api-key` first-run flows resolve before stored auth exists) and `resolveModelScopeWithDiagnostics(patterns, modelRuntime)` (matches `--models`/`enabledModels` semantics and returns warnings instead of printing).-Use `getModel(provider, id)` for built-in model lookup and `modelRegistry.find(provider, id)` for built-in plus custom. `modelRegistry.getAvailable()` checks auth availability.+Session options also accept `model`, `thinkingLevel` (`off`…`max`), and `scopedModels: [{ model, thinkingLevel }]` for Ctrl+P cycling. With no model: restore from session, then settings default, then first available.## Tools-Built-in names: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`. Defaults: `read`, `bash`, `edit`, `write`. `tools` allowlists tools; `excludeTools` disables specific tools. `noTools: "all"` disables all tools; `noTools: "builtin"` disables built-ins but keeps custom/extension tools.+Built-ins: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`. Defaults: `read`, `bash`, `edit`, `write`. `tools` allowlists, `excludeTools` disables specific names after the allowlist, `noTools: "all"` disables everything, `noTools: "builtin"` keeps extension/custom tools. The `edit` tool returns `details.diff` for the TUI and `details.patch` as a standard unified patch for SDK consumers.-The `edit` tool returns `details.diff` for TUI display and `details.patch` as standard unified patch for SDK consumers.+Define custom tools with `defineTool()` and pass them as `customTools`; include their names in `tools` if you use an allowlist. Tool factories are exported too: `createCodingTools`, `createReadOnlyTools`, `createReadTool`, `createBashTool`, `createEditTool`, `createWriteTool`, `createGrepTool`, `createFindTool`, `createLsTool`.-Define custom tools with `defineTool()` and pass `customTools`; include custom names in `tools` if using an allowlist.+Passing a custom `cwd` makes `createAgentSession()` build the selected built-in tools for that directory.## Resource Loading-`DefaultResourceLoader` discovers extensions, skills, prompts, themes, and context files. It supports additional extension paths, inline extension factories, overrides for skills/prompts/context, and a shared event bus.+`DefaultResourceLoader` discovers extensions, skills, prompts, themes, and context files. Options: `cwd`, `agentDir`, `additionalExtensionPaths`, `extensionFactories` (bare functions or `InlineExtension { name, factory }` so the startup list shows `<inline:my-provider>` instead of `<inline:1>`), `settingsManager`, `systemPromptOverride`, `skillsOverride`, `promptsOverride`, `agentsFilesOverride`, `eventBus` (from `createEventBus()`). Call `await loader.reload()`, then read `getExtensions()`, `getSkills()`, `getPrompts()`, `getThemes()`, `getAgentsFiles().agentsFiles`.-`cwd` controls project discovery and tool path resolution. `agentDir` controls global resources such as `~/.pi/agent`.+`cwd` drives project discovery (`.pi/extensions`, `.pi/skills`, `.agents/skills` up to the git root, `.pi/prompts`, `AGENTS.md` walk-up, session naming); `agentDir` drives global resources (`extensions/`, `skills/`, `~/.agents/skills/`, `prompts/`, `AGENTS.md`, `settings.json`, `models.json`, `auth.json`, `sessions/`). With a custom `ResourceLoader`, `cwd`/`agentDir` still influence session naming and tool path resolution but no longer control discovery.## Sessions and Settings-Use `SessionManager.inMemory()`, `create()`, `continueRecent()`, `open()`, `list()`, and `listAll()`. Tree APIs include `getEntries`, `getTree`, `getPath`, `getLeafEntry`, `getEntry`, `getChildren`, `appendLabelChange`, `branch`, `branchWithSummary`, and `createBranchedSession`.+`SessionManager.inMemory(cwd?)`, `create(cwd)`, `continueRecent(cwd)`, `open(path)`, `list(cwd)`, `listAll(cwd)`. Tree API: `getEntries`, `getTree`, `getPath`, `getLeafEntry`, `getEntry`, `getChildren`, `getLabel`, `appendLabelChange`, `branch`, `branchWithSummary`, `createBranchedSession`. Full API in `references/session-format.md`.-`SettingsManager.create()` loads global plus project settings; `SettingsManager.inMemory()` is useful for tests. Setters persist asynchronously; call `flush()` for durability and `drainErrors()` to report write errors.+`SettingsManager.create(cwd?, agentDir?)` merges global plus project settings; `SettingsManager.inMemory(settings?)` avoids file I/O for tests. `applyOverrides({ compaction, retry, ... })` layers overrides. Getters/setters are synchronous for in-memory state and enqueue writes asynchronously — call `await flush()` for a durability boundary and `drainErrors()` to report write errors yourself (the manager never prints them).## Run Modes-The SDK exports run helpers: `InteractiveMode`, `runPrintMode`, and `runRpcMode`. Use these when building custom launchers while reusing Pi's mode implementations.+`InteractiveMode` (full TUI), `runPrintMode(runtime, { mode: "text", initialMessage, initialImages, messages })`, `runRpcMode(runtime)`. All take an `AgentSessionRuntime`. `InteractiveMode` options include `migratedProviders`, `modelFallbackMessage`, `initialMessage`, `initialImages`, `initialMessages`.## SDK vs RPC-Prefer SDK when you want type safety, same Node.js process, direct state access, or programmatic tools/extensions. Prefer RPC when integrating from another language, needing process isolation, or building a language-agnostic client.+Prefer the SDK for type safety, same-process integration, direct state access, or programmatic tools/extensions. Prefer RPC for other languages, process isolation, or language-agnostic clients.## Important Exports-`createAgentSession`, `createAgentSessionRuntime`, `AgentSessionRuntime`, `AuthStorage`, `ModelRegistry`, `DefaultResourceLoader`, `defineTool`, `getAgentDir`, `SessionManager`, `SettingsManager`, tool factories, and types for options, results, extensions, tools, skills, and prompt templates.+`createAgentSession`, `createAgentSessionRuntime`, `AgentSessionRuntime`, `createAgentSessionServices`, `createAgentSessionFromServices`, `ModelRuntime`, `ModelRegistry`, `resolveCliModel`, `resolveModelScopeWithDiagnostics`, `DefaultResourceLoader`, `ResourceLoader` type, `createEventBus`, `CONFIG_DIR_NAME`, `defineTool`, `getAgentDir`, `getPackageDir`, `getReadmePath`, `getDocsPath`, `getExamplesPath`, `SessionManager`, `SettingsManager`, the tool factories above, `InteractiveMode`, `runPrintMode`, `runRpcMode`, and types for options, results, extensions (`ExtensionAPI`, `ExtensionFactory`, `InlineExtension`), tools, skills, and prompt templates.diff --git a/skills/pi-agent/references/security.md b/skills/pi-agent/references/security.mdindex 51b611cc..073af786 100644--- a/skills/pi-agent/references/security.md+++ b/skills/pi-agent/references/security.md@@ -2,24 +2,51 @@Source: https://pi.dev/docs/latest/security-Pi is a local coding agent. It runs with the permissions of the user account that starts it and treats files writable by that user as inside the local trust boundary.+Pi is a local coding agent. It runs with the permissions of the user account that starts it and treats files writable by that user as inside the same local trust boundary.## Project Trust-Project trust controls whether Pi loads project-local settings, resources, packages, and extensions. It is not a sandbox.+Project trust controls whether Pi loads project-local settings, resources, packages, and extensions. It is not a sandbox and does not restrict what the model can ask tools to do once you are working in a directory.-Trust-gated inputs include `.pi/` in the current directory and `.agents/skills` in the current directory or ancestors. Trusting allows loading `.pi/settings.json`, `.pi` resources, missing project packages, project extensions, and project package-managed extensions.+Pi considers a project to require trust when it finds any of these from the current working directory:-`AGENTS.md` and `CLAUDE.md` context files load regardless of project trust unless context loading is disabled.+- `.pi/settings.json`+- `.pi/extensions`, `.pi/skills`, `.pi/prompts`, or `.pi/themes`+- `.pi/SYSTEM.md` or `.pi/APPEND_SYSTEM.md`+- project `.agents/skills` in the current directory or an ancestor-Non-interactive modes do not prompt. Without a saved trust decision, `defaultProjectTrust: "ask"` and `"never"` ignore trust-gated resources, while `"always"` trusts them. Use `--approve` or `--no-approve` for one-run override.+A bare `.pi` directory does not count.++When an interactive session starts in such a project with no saved decision for the current or a parent directory, Pi follows `defaultProjectTrust` (default `"ask"`). Saved decisions are stored by canonical directory in `~/.pi/agent/trust.json`, and the closest saved decision on the current or parent path applies before the global default.++Trusting a project allows Pi to load `.pi/settings.json`, `.pi` resources (extensions, skills, prompt templates, themes, system prompt files), install missing project packages configured through project settings, and execute project-local and project package-managed extensions.++Declining skips protected resources. `AGENTS.md` and `CLAUDE.md` context files load regardless of trust unless context loading is disabled. Before trust resolves, Pi loads only context files, user/global extensions, and CLI `-e` extensions — those can handle the `project_trust` event, and the first extension returning a yes/no decision owns it.++Non-interactive modes (`-p`, `--mode json`, `--mode rpc`) never prompt. Without an applicable saved decision, `"ask"` and `"never"` ignore trust-gated resources while `"always"` trusts them. `--approve`/`-a` and `--no-approve`/`-na` override for one run.## No Built-in Sandbox-Built-in tools can read, write, edit, and run shell commands with the permissions of the Pi process. Extensions are TypeScript modules with the same permissions. Package installs and developer tools are ordinary local processes.+Built-in tools read, write, edit, and run shell commands with the permissions of the Pi process. Extensions are TypeScript modules with the same permissions. Package installs, shell commands, language servers, and test commands behave as ordinary local processes.++This is intentional: Pi is designed to operate on local source trees, invoke project toolchains, and integrate with an existing development environment. A partial in-process sandbox would be easy to mistake for a security boundary while still depending on the host shell, filesystem, package managers, credentials, and extension code. Real isolation must come from the OS or a virtualization/container boundary.++Project trust is only an input-loading guard. It prevents a repository from silently changing Pi's settings or extensions before you approve it. It does not make untrusted code, prompts, or model output safe. Prompt injection from repository files, comments, documentation, context files, or build output is expected local-agent risk and cannot be reliably prevented.++## Running Untrusted or Unmonitored Work++For untrusted repositories, generated code you will not monitor closely, or unattended automation, run Pi in a contained environment — container, VM, micro-VM, remote sandbox, or policy-controlled sandbox — with only the files and credentials the task needs. Patterns are documented in `references/containerization.md`:++- run the whole `pi` process inside a container/sandbox+- run host Pi while routing built-in tool execution into a Gondolin micro-VM+- mount only the workspace paths the agent should access+- avoid mounting host `~/.pi/agent` unless the container should reach host sessions, settings, and credentials+- pass the minimum required API keys or use short-lived credentials+- restrict network access when the task does not need it+- review diffs and outputs before copying results back to trusted systems-Project trust only guards input loading; it does not make untrusted code, prompts, model output, or build output safe.+Bind-mounting a host workspace read/write means writes from inside the container or VM still modify host files. Use read-only mounts or copy files in and out when you need stronger protection.-## Untrusted Work+## Reporting Security Issues-For untrusted repositories, generated code you will not monitor closely, or unattended automation, run Pi in a contained environment. Use Docker, OpenShell, Gondolin, a VM, micro-VM, or remote sandbox. Mount only needed files, avoid mounting host `~/.pi/agent` unless required, pass minimum credentials, restrict network where possible, and review diffs before copying results to trusted systems.+Follow the repository [Security Policy](https://github.com/earendil-works/pi-mono/blob/main/SECURITY.md); do not open a public issue. Expected local-agent behavior, the absence of a built-in sandbox, prompt injection from untrusted content, and behavior of user-installed extensions or skills are generally outside the security boundary unless the report shows a real privilege-boundary bypass or access the local user did not already have.diff --git a/skills/pi-agent/references/session-format.md b/skills/pi-agent/references/session-format.mdindex 62236edb..7efcc961 100644--- a/skills/pi-agent/references/session-format.md+++ b/skills/pi-agent/references/session-format.md@@ -2,7 +2,7 @@Source: https://pi.dev/docs/latest/session-format-Sessions are JSONL files. Each line is a JSON object with `type`. Entries form a tree through `id` and `parentId`.+Sessions are JSONL files. Each line is a JSON object with a `type`. Entries form a tree through `id` / `parentId`, enabling in-place branching without new files.## Location@@ -10,41 +10,79 @@ Sessions are JSONL files. Each line is a JSON object with `type`. Entries form a~/.pi/agent/sessions/--<path>--/<timestamp>_<uuid>.jsonl```-Existing sessions auto-migrate to current version. Version 3 renamed `hookMessage` role to `custom`.+`<path>` is the working directory with `/` replaced by `-`. Delete sessions by removing the `.jsonl` file, or from `/resume` with Ctrl+D (Pi uses the `trash` CLI when available).-## Message Content+## Versions-Messages use content blocks: `text`, `image`, `thinking`, and `toolCall`. Base roles include `user`, `assistant`, and `toolResult`. Extended roles include `bashExecution`, `custom`, `branchSummary`, and `compactionSummary`.+- v1: linear entry sequence (legacy, auto-migrated on load)+- v2: tree structure with `id`/`parentId`+- v3: renamed the `hookMessage` role to `custom` (extensions unification)-Assistant messages include `api`, `provider`, `model`, `usage`, `stopReason`, optional `errorMessage`, timestamp, and content blocks.+Existing sessions auto-migrate to v3 when loaded.++## Content Blocks++`TextContent { type: "text", text }`, `ImageContent { type: "image", data (base64), mimeType }`, `ThinkingContent { type: "thinking", thinking }`, `ToolCall { type: "toolCall", id, name, arguments }`.++## Message Types++Base (from `pi-ai`):++- `UserMessage` — `role: "user"`, `content` string or `(Text|Image)[]`, `timestamp` (Unix ms)+- `AssistantMessage` — `content: (Text|Thinking|ToolCall)[]`, `api`, `provider`, `model`, `usage`, `stopReason` ∈ `stop`/`length`/`toolUse`/`error`/`aborted`, optional `errorMessage`, `timestamp`+- `ToolResultMessage` — `toolCallId`, `toolName`, `content: (Text|Image)[]`, optional `details`, optional `usage` (nested LLM work performed by the tool), `isError`, `timestamp`+- `Usage` — `input`, `output`, `cacheRead`, `cacheWrite`, `totalTokens`, and `cost` with the same four fields plus `total`++Extended (from `pi-coding-agent`):++- `BashExecutionMessage` — `command`, `output`, `exitCode`, `cancelled`, `truncated`, optional `fullOutputPath`, optional `excludeFromContext` (true for `!!`)+- `CustomMessage` — `customType`, `content`, `display`, optional `details`+- `BranchSummaryMessage` — `summary`, `fromId`+- `CompactionSummaryMessage` — `summary`, `tokensBefore`++`AgentMessage` is the union of all seven.## Entry Types-- `session`: header, first line, metadata only.-- `message`: wraps an `AgentMessage`.-- `model_change`: model switches.-- `thinking_level_change`: thinking level changes.-- `compaction`: summary of earlier messages with `firstKeptEntryId` and `tokensBefore`.-- `branch_summary`: summary of an abandoned branch.-- `custom`: extension state, not sent to LLM.-- `custom_message`: extension-injected message, sent to LLM.-- `label`: user-defined bookmark on an entry.-- `session_info`: display name metadata.+All entries except the header extend `SessionEntryBase { type, id (8-char hex), parentId (null for the first entry), timestamp (ISO string) }`.++- `session` — header, first line, metadata only (no `id`/`parentId`): `version`, `id`, `timestamp`, `cwd`, plus `parentSession` for sessions created via `/fork`, `/clone`, or `newSession({ parentSession })`+- `message` — wraps an `AgentMessage` in `message`+- `model_change` — `provider`, `modelId`+- `thinking_level_change` — `thinkingLevel`+- `compaction` — `summary`, `tokensBefore`, plus optional `usage`, `details`, `fromHook`, `firstKeptEntryId` (old format), and `retainedTail`+- `branch_summary` — `summary`, `fromId`, plus optional `usage`, `details`, `fromHook`+- `custom` — `customType`, `data`; extension state, **not** in LLM context. Renderable in the transcript via `pi.registerEntryRenderer(customType, renderer)`+- `custom_message` — `customType`, `content`, `display`, optional `details`; extension-injected and **in** LLM context+- `label` — `targetId`, `label` (set `label` to `undefined` to clear)+- `session_info` — `name`; set via `/name`, `--name`/`-n`, or `pi.setSessionName()`. Shown in `/resume` instead of the first message++`retainedTail` is a materialized `AgentMessage[]` kept after compaction. Newer harness-generated compactions include it so context rebuilds from that checkpoint without walking entries before the compaction. It is optional only for backward compatibility with sessions that store only `firstKeptEntryId`.## Context Building-`buildSessionContext()` walks from current leaf to root. If a `CompactionEntry` is on the path, Pi emits the summary first, then messages from `firstKeptEntryId`, then later messages.+`buildContextEntries()` walks from the current leaf to the root and produces the active entry list honoring compaction:++1. Collect all entries on the path.+2. If a `CompactionEntry` is on the path: include the compaction entry first; if `retainedTail` is present it acts as a self-contained checkpoint and entries after the compaction are included; otherwise include entries from `firstKeptEntryId` to the compaction, then entries after it.+3. Preserve non-message entries in the selected range so interactive mode can render them.++`buildSessionContext()` builds the LLM message list on top of that: it extracts the current model and thinking level from the full path, then converts entries — `message` → stored `AgentMessage`, `compaction` → `compactionSummary` plus `retainedTail` when present, `branch_summary` → `branchSummary`, `custom_message` → `CustomMessage`, `custom` → no context message.## SessionManager API-Static factories: `create`, `open`, `continueRecent`, `inMemory`, `forkFrom`.+Static creation: `create(cwd, sessionDir?)`, `open(path, sessionDir?)`, `continueRecent(cwd, sessionDir?)`, `inMemory(cwd?)`, `forkFrom(sourcePath, targetCwd, sessionDir?)`.++Static listing: `list(cwd, sessionDir?, onProgress?)`, `listAll(onProgress?)`.++Session management: `newSession({ parentSession? })`, `setSessionFile(path)`, `createBranchedSession(leafId)`.-Listing: `list`, `listAll`.+Appending (each returns an entry ID): `appendMessage`, `appendThinkingLevelChange`, `appendModelChange`, `appendCompaction(summary, firstKeptEntryId, tokensBefore, details?, fromHook?)`, `appendCustomEntry(customType, data?)`, `appendSessionInfo(name)`, `appendCustomMessageEntry(customType, content, display, details?)`, `appendLabelChange(targetId, label)`.-Session management: `newSession`, `setSessionFile`, `createBranchedSession`.+Tree navigation: `getLeafId`, `getLeafEntry`, `getEntry`, `getBranch(fromId?)`, `getTree`, `getChildren`, `getLabel`, `branch(entryId)`, `resetLeaf()`, `branchWithSummary(entryId, summary, details?, fromHook?)`.-Append: `appendMessage`, `appendThinkingLevelChange`, `appendModelChange`, `appendCompaction`, `appendCustomEntry`, `appendSessionInfo`, `appendCustomMessageEntry`, `appendLabelChange`.+Context and info: `buildContextEntries`, `buildSessionContext`, `getEntries`, `getHeader`, `getSessionName`, `getCwd`, `getSessionDir`, `getSessionId`, `getSessionFile` (undefined in memory), `isPersisted`.-Tree: `getLeafId`, `getLeafEntry`, `getEntry`, `getBranch`, `getTree`, `getChildren`, `getLabel`, `branch`, `resetLeaf`, `branchWithSummary`.+## Parsing-Info/context: `buildSessionContext`, `getEntries`, `getHeader`, `getSessionName`, `getCwd`, `getSessionDir`, `getSessionId`, `getSessionFile`, `isPersisted`.+Read the file line by line and switch on `entry.type`; treat `entry.version ?? 1` on the header, and ignore unknown types for forward compatibility. For TypeScript definitions inspect `node_modules/@earendil-works/pi-coding-agent/dist/` and `node_modules/@earendil-works/pi-ai/dist/`.diff --git a/skills/pi-agent/references/sessions.md b/skills/pi-agent/references/sessions.mdindex 3a858e79..c8d9905c 100644--- a/skills/pi-agent/references/sessions.md+++ b/skills/pi-agent/references/sessions.md@@ -7,30 +7,50 @@ Pi auto-saves conversations to `~/.pi/agent/sessions/`, organized by working dir## Session Commands```bash-pi -c-pi -r-pi --no-session-pi --name "my task"-pi --session <path|id>-pi --fork <path|id>+pi -c # continue most recent+pi -r # browse and select+pi --no-session # ephemeral, do not save+pi --name "my task" # display name at startup+pi --session <path|id> # specific file or partial session ID+pi --fork <path|id> # fork into a new session file```-Interactive commands: `/resume`, `/new`, `/name`, `/session`, `/tree`, `/fork`, `/clone`, `/compact [prompt]`, `/export [file]`, `/share`.+Interactive: `/resume`, `/new`, `/name <name>`, `/session` (file, ID, message count, tokens, cost), `/tree`, `/fork`, `/clone`, `/compact [prompt]`, `/export [file]`, `/share`.-## Resuming+## Resuming and Deleting-`/resume` and `pi -r` open a picker. Search by typing; use Ctrl+P to toggle path display, Ctrl+S sort, Ctrl+N named-only filter, Ctrl+R rename, Ctrl+D delete. Pi uses `trash` when available.+`/resume` (and `pi -r`) opens a picker for the current project. Search by typing; Ctrl+P toggles path display, Ctrl+S cycles sort mode, Ctrl+N filters to named sessions, Ctrl+R renames, Ctrl+D deletes with confirmation. Pi uses the `trash` CLI when available instead of permanently removing files.-## Branching+## Branching with `/tree`-Sessions are trees with `id` and `parentId`. `/tree` lets you jump to a previous point and continue without creating a new file. Selecting a user/custom message moves to its parent and puts that message in the editor so it can be edited and resubmitted. Selecting assistant/tool/compaction entries moves the leaf there with an empty editor.+Sessions are trees: every entry has `id` and `parentId`, and the current position is the active leaf. `/tree` jumps to any previous point and continues from there without creating a new file.++| Key | Action |+|---|---|+| ↑/↓ | Navigate visible entries |+| ←/→ | Page up/down |+| Ctrl+←/→ or Alt+←/→ | Fold/unfold or jump between branch segments |+| Shift+L | Set or clear a label on the selected entry |+| Shift+T | Toggle label timestamps |+| Enter | Select entry |+| Escape / Ctrl+C | Cancel |+| Ctrl+O | Cycle filter mode |++Filter modes: default, no-tools, user-only, labeled-only, all. Set the default with `treeFilterMode`.++### Selection Behavior++Selecting a **user or custom** message moves the leaf to that message's parent, puts the message text in the editor, and lets you edit and resubmit — creating a new branch. Selecting an **assistant, tool, compaction, or other non-user** entry moves the leaf there with an empty editor so you continue from that point. Selecting the root user message resets the leaf to an empty conversation with the original prompt in the editor.## Tree vs Fork vs Clone-- `/tree`: same session file, full tree, optional branch summary.-- `/fork`: new session file from an earlier user message.-- `/clone`: new session file duplicating current active branch.+| | `/tree` | `/fork` | `/clone` |+|---|---|---|---|+| Output | Same session file | New session file | New session file |+| View | Full tree | User-message selector | Current active branch |+| Typical use | Explore alternatives in place | Start a new session from an earlier prompt | Duplicate current work before continuing |+| Summary | Optional branch summary | None | None |## Branch Summaries-When switching branches through `/tree`, Pi can summarize the abandoned branch and attach that context at the new position. See `compaction.md` for internals.+When `/tree` switches away from one branch, Pi can summarize the abandoned branch and attach the summary at the new position, preserving context without replaying the branch. When prompted, choose no summary, the default prompt, or custom focus instructions. Internals and extension hooks: `references/compaction.md`. File format and `SessionManager` API: `references/session-format.md`.diff --git a/skills/pi-agent/references/settings.md b/skills/pi-agent/references/settings.mdindex 92415cbb..5c1bea31 100644--- a/skills/pi-agent/references/settings.md+++ b/skills/pi-agent/references/settings.md@@ -2,58 +2,95 @@Source: https://pi.dev/docs/latest/settings-Pi uses JSON settings files. Project settings override global settings; nested objects merge.+Pi uses JSON settings files. Project settings override global settings; nested objects merge key by key. Edit directly or use `/settings` for common options.| Location | Scope ||---|---|| `~/.pi/agent/settings.json` | Global || `.pi/settings.json` | Project |+Resource paths in the global file resolve relative to `~/.pi/agent`; in the project file relative to `.pi`. Absolute paths and `~` work.+## Project Trust-Project settings are trust-gated. Interactive startup asks according to `defaultProjectTrust` when project inputs exist and no saved trust decision applies. Non-interactive modes use `defaultProjectTrust` and do not prompt. `--approve` and `--no-approve` override for one run.+Interactive startup asks before trusting a project folder that has project-local settings, resources, or project `.agents/skills` and no saved decision for that folder or a parent in `~/.pi/agent/trust.json`. Non-interactive modes never prompt and use `defaultProjectTrust` (`"ask"` default, `"never"`, `"always"`); `--approve`/`-a` and `--no-approve`/`-na` override for one run. `/trust` saves a decision (including for the immediate parent folder) but does not reload the current session. `pi config` and package commands follow the same flow; `pi update` never prompts.++## Model and Thinking++| Setting | Default | Notes |+|---|---|---|+| `defaultProvider` | – | Provider id |+| `defaultModel` | – | Model id |+| `defaultThinkingLevel` | – | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |+| `hideThinkingBlock` | `false` | Hide thinking blocks in output |+| `showCacheMissNotices` | `false` | Transcript notices for significant prompt-cache misses |+| `thinkingBudgets` | – | Custom token budgets per thinking level |++## UI and Display++`theme` (`"dark"`), `externalEditor` (Ctrl+G command; takes precedence over `$VISUAL`/`$EDITOR` — use `"code --wait"` for VS Code), `quietStartup` (`false`), `defaultProjectTrust` (`"ask"`, global only), `collapseChangelog` (`false`), `enableInstallTelemetry` (`true`), `enableAnalytics` (`false`, only asked during experimental first-time setup with `PI_EXPERIMENTAL=1`), `trackingId`, `doubleEscapeAction` (`"tree"` | `"fork"` | `"none"`), `treeFilterMode` (`"default"` | `"no-tools"` | `"user-only"` | `"labeled-only"` | `"all"`), `editorPaddingX` (`0`, range 0–3), `outputPad` (`1`, 0 or 1), `autocompleteMaxVisible` (`5`, range 3–20), `showHardwareCursor` (`false`).++## Network, Warnings, Markdown++`httpProxy` (applied as `HTTP_PROXY`/`HTTPS_PROXY`, global only). `warnings.anthropicExtraUsage` (`true`) warns when Anthropic subscription auth may use paid extra usage. `markdown.codeBlockIndent` (`" "`).++## Compaction and Branch Summary++`compaction.enabled` (`true`), `compaction.reserveTokens` (`16384`), `compaction.keepRecentTokens` (`20000`). `branchSummary.reserveTokens` (`16384`), `branchSummary.skipPrompt` (`false`, defaults to no summary).-## Core Settings+## Retry-Model/thinking: `defaultProvider`, `defaultModel`, `defaultThinkingLevel`, `hideThinkingBlock`, `thinkingBudgets`.+`retry.enabled` (`true`), `retry.maxRetries` (`3`), `retry.baseDelayMs` (`2000`, so 2s/4s/8s), `retry.provider.timeoutMs` (SDK default), `retry.provider.maxRetries` (`0`), `retry.provider.maxRetryDelayMs` (`60000`; `0` disables the limit).-UI/display: `theme`, `quietStartup`, `defaultProjectTrust`, `collapseChangelog`, `enableInstallTelemetry`, `doubleEscapeAction`, `treeFilterMode`, `editorPaddingX`, `autocompleteMaxVisible`, `showHardwareCursor`.+Keep `retry.provider.maxRetries` at `0` unless provider-level retries are explicitly needed — above `0`, SDK retries can swallow out-of-usage-limit errors before Pi sees them and block the agent until quota resets. When a provider requests a delay longer than `maxRetryDelayMs`, the request fails immediately with an informative error instead of waiting silently.-Compaction: `compaction.enabled`, `compaction.reserveTokens`, `compaction.keepRecentTokens`.+## Message Delivery-Branch summary: `branchSummary.reserveTokens`, `branchSummary.skipPrompt`.+`steeringMode` / `followUpMode` (`"one-at-a-time"` or `"all"`), `transport` (`"auto"`, `"sse"`, `"websocket"`, `"websocket-cached"`), `httpIdleTimeoutMs` (`300000`, `0` disables), `websocketConnectTimeoutMs` (`15000`, `0` disables).-Retry: `retry.enabled`, `retry.maxRetries`, `retry.baseDelayMs`, `retry.provider.timeoutMs`, `retry.provider.maxRetries`, `retry.provider.maxRetryDelayMs`.+## Terminal and Images-Message delivery: `steeringMode`, `followUpMode`, `transport`, `httpIdleTimeoutMs`, `websocketConnectTimeoutMs`.+`terminal.showImages` (`true`), `terminal.imageWidthCells` (`60`), `terminal.clearOnShrink` (`false`), `images.autoResize` (`true`, 2000×2000 max), `images.blockImages` (`false`).-Terminal/images: `terminal.showImages`, `terminal.imageWidthCells`, `terminal.clearOnShrink`, `images.autoResize`, `images.blockImages`.+## Shell-Shell: `shellPath`, `shellCommandPrefix`, `npmCommand`.+`shellPath` (supports leading `~`), `shellCommandPrefix` (prefix for every bash command), `npmCommand` (argv array, e.g. `["mise", "exec", "node@20", "--", "npm"]`). `npmCommand` covers all npm package-manager operations; user npm packages install under `~/.pi/agent/npm/`, project ones under `.pi/npm/`. When `npmCommand` is configured, git package dependency installs use plain `install` for wrapper compatibility.-Sessions: `sessionDir`; precedence is `--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, then setting.+## Sessions and Model Cycling-Resources: `packages`, `extensions`, `skills`, `prompts`, `themes`, `enableSkillCommands`.+`sessionDir` (absolute, relative, or `~`); precedence is `--session-dir`, then `PI_CODING_AGENT_SESSION_DIR`, then this setting. `enabledModels` is an array of patterns for Ctrl+P cycling, same format as `--models`.++## Resources++`packages` (`[]`), `extensions` (`[]`), `skills` (`[]`), `prompts` (`[]`), `themes` (`[]`), `enableSkillCommands` (`true`, registers `/skill:name`).++Arrays support glob patterns, `!pattern` to exclude, `+path` to force-include an exact path, and `-path` to force-exclude. `packages` accepts strings or objects that filter which resource types load:++```json+{+ "packages": [+ "pi-skills",+ { "source": "npm:my-package", "skills": ["brave-search"], "extensions": [] }+ ]+}+```-## Network/Telemetry+## Telemetry and Update Checks-`enableInstallTelemetry` only controls anonymous install/update ping. Use `PI_SKIP_VERSION_CHECK=1` to disable version checks. Use `--offline` or `PI_OFFLINE=1` to disable startup network operations including update checks, package update checks, and install/update telemetry.+`enableInstallTelemetry` only controls the anonymous install/update ping to `https://pi.dev/api/report-install`. Opting out does not disable update checks, which fetch `https://pi.dev/api/latest-version`. `PI_SKIP_VERSION_CHECK=1` disables the version check; `--offline` or `PI_OFFLINE=1` disables all startup network operations including package update checks and telemetry.## Example```json{"defaultProvider": "anthropic",- "defaultModel": "claude-sonnet-4-5",+ "defaultModel": "claude-sonnet-4-20250514","defaultThinkingLevel": "medium","theme": "dark",- "compaction": {- "enabled": true,- "reserveTokens": 16384,- "keepRecentTokens": 20000- },+ "compaction": { "enabled": true, "reserveTokens": 16384, "keepRecentTokens": 20000 },"retry": { "enabled": true, "maxRetries": 3 },"enabledModels": ["claude-*", "gpt-4o"],+ "warnings": { "anthropicExtraUsage": true },"packages": ["pi-skills"]}```diff --git a/skills/pi-agent/references/shell-aliases.md b/skills/pi-agent/references/shell-aliases.mdindex 2dd48c47..a939491c 100644--- a/skills/pi-agent/references/shell-aliases.md+++ b/skills/pi-agent/references/shell-aliases.md@@ -2,15 +2,14 @@Source: https://pi.dev/docs/latest/shell-aliases-Pi runs bash in non-interactive mode (`bash -c`), so aliases do not expand by default.+Pi runs bash in non-interactive mode (`bash -c`), which does not expand aliases by default.-To enable aliases, set `shellCommandPrefix` in `~/.pi/agent/settings.json`:+To enable your shell aliases, set `shellCommandPrefix` in `~/.pi/agent/settings.json`:```json{- "shellCommandPrefix": "shopt -s expand_aliases-eval "$(grep '^alias ' ~/.zshrc)""+ "shellCommandPrefix": "shopt -s expand_aliases\neval \"$(grep '^alias ' ~/.zshrc)\""}```-Adjust the shell config path for `.zshrc`, `.bashrc`, or your environment.+The value is a JSON string: `\n` is an escaped newline inside the prefix and the inner double quotes are backslash-escaped. Adjust the path (`~/.zshrc`, `~/.bashrc`, …) to match your shell config. The prefix is prepended to every bash command Pi runs.diff --git a/skills/pi-agent/references/skills.md b/skills/pi-agent/references/skills.mdindex 3b2da3c5..6e900675 100644--- a/skills/pi-agent/references/skills.md+++ b/skills/pi-agent/references/skills.md@@ -2,7 +2,7 @@Source: https://pi.dev/docs/latest/skills-Pi implements the Agent Skills standard. Skills are self-contained capability packages loaded on demand. They provide instructions, workflows, scripts, and references.+Pi implements the [Agent Skills standard](https://agentskills.io/specification). Skills are self-contained capability packages loaded on demand, providing workflows, setup instructions, helper scripts, and reference documentation. Pi warns about most spec violations but stays lenient — notably it allows a skill name that differs from its parent directory, because the standard's matching rule is awkward for skill directories shared across harnesses.## Locations@@ -11,30 +11,43 @@ Global:- `~/.pi/agent/skills/`- `~/.agents/skills/`-Project, after project trust:+Project, only after project trust:- `.pi/skills/`-- `.agents/skills/` in cwd and ancestors up to git root or filesystem root+- `.agents/skills/` in cwd and ancestors, up to the git repo root (or filesystem root outside a repo)-CLI `--skill` is repeatable and loads additively even with `--no-skills`.+Also: packages (`skills/` directories or `pi.skills` entries in `package.json`), the `skills` settings array, and CLI `--skill <path>` (repeatable, additive even with `--no-skills`).-## Discovery+Discovery rules:-Directories containing `SKILL.md` are discovered recursively in all skill locations. In `~/.pi/agent/skills/` and `.pi/skills/`, direct root `.md` files are individual skills. In `.agents/skills`, root `.md` files are ignored.+- In `~/.pi/agent/skills/` and `.pi/skills/`, direct root `.md` files are discovered as individual skills.+- In all locations, directories containing `SKILL.md` are discovered recursively.+- In `~/.agents/skills/` and project `.agents/skills/`, root `.md` files are ignored.++To reuse skills from other harnesses, add their directories to settings:++```json+{ "skills": ["~/.claude/skills", "~/.codex/skills"] }+```## How Skills Work-At startup Pi scans skills and extracts names/descriptions. The system prompt includes available skills. The agent should read the full `SKILL.md` when a task matches; users can force with `/skill:name`.+At startup Pi scans skill locations and extracts names and descriptions. The system prompt includes available skills in XML format per the specification. When a task matches, the agent uses `read` to load the full `SKILL.md` (models do not always do this — prompt explicitly or force with `/skill:name`) and follows the instructions using relative paths. Only descriptions stay in context; full instructions load on demand.## Skill Commands-Skills register as `/skill:name`. Arguments after the command are appended as `User: ...`. Enable/disable with `enableSkillCommands`.+Skills register as `/skill:name`; arguments after the command are appended as `User: <args>`. Toggle via `/settings` or `"enableSkillCommands": true`.++```bash+/skill:brave-search+/skill:pdf-tools extract+```## Structure```textmy-skill/- SKILL.md+ SKILL.md # required: frontmatter + instructionsscripts/process.shreferences/api-reference.mdassets/template.json@@ -44,10 +57,27 @@ Use relative paths from the skill directory.## Frontmatter-Required: `name` and `description`. Optional: `license`, `compatibility`, `metadata`, `allowed-tools`, `disable-model-invocation`.+| Field | Required | Constraints |+|---|---|---|+| `name` | Yes | Max 64 chars, lowercase a–z, 0–9, hyphens. Pi does not require it to match the parent directory. |+| `description` | Yes | Max 1024 chars — what the skill does and when to use it. |+| `license` | No | License name or reference to a bundled file. |+| `compatibility` | No | Max 500 chars; environment requirements. |+| `metadata` | No | Arbitrary key-value mapping. |+| `allowed-tools` | No | Space-delimited pre-approved tools (experimental). |+| `disable-model-invocation` | No | `true` hides the skill from the system prompt; users must call `/skill:name`. |-Name rules: 1-64 chars, lowercase letters/numbers/hyphens, no leading/trailing hyphens, no consecutive hyphens. Pi warns on most spec violations but does not require the name to match parent directory. Missing description prevents loading.+Name rules: 1–64 characters, lowercase letters/numbers/hyphens, no leading or trailing hyphen, no consecutive hyphens. Valid: `pdf-processing`. Invalid: `PDF-Processing`, `-pdf`, `pdf--processing`.++## Validation++Most violations warn but still load: over-length or invalid names, leading/trailing/consecutive hyphens, description over 1024 chars. Unknown frontmatter fields are ignored. **Exception:** a missing description prevents loading. Name collisions across locations warn and keep the first skill found.## Security-Skills can instruct the model to perform any action and may include executable code. Review third-party skills before use.+Skills can instruct the model to perform any action and may include executable code the model invokes. Review skill content before use.++## Skill Repositories++- [Anthropic Skills](https://github.com/anthropics/skills) — document processing, web development+- [Pi Skills](https://github.com/badlogic/pi-skills) — web search, browser automation, Google APIs, transcriptiondiff --git a/skills/pi-agent/references/terminal-setup.md b/skills/pi-agent/references/terminal-setup.mdindex a3997aa7..49fc989e 100644--- a/skills/pi-agent/references/terminal-setup.md+++ b/skills/pi-agent/references/terminal-setup.md@@ -2,26 +2,25 @@Source: https://pi.dev/docs/latest/terminal-setup-Pi uses the Kitty keyboard protocol for reliable modifier detection. Most modern terminals support it; some need setup.+Pi uses the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/keyboard-protocol/) for reliable modifier detection. Most modern terminals support it; some need configuration.-## Works Out of Box+## Works Out of the Box-Kitty and iTerm2 work out of the box. Apple Terminal uses enhanced key reporting when available and a local macOS fallback for Shift+Enter when running on the same Mac.+Kitty and iTerm2. Apple Terminal enables enhanced key reporting when available; if it still sends plain Return for `Shift+Enter`, Pi uses a local macOS modifier fallback — which only works when Pi runs on the same Mac, not over SSH. VS Code 1.109.5+ also works by default.## Ghostty-Add:+Config at `~/Library/Application Support/com.mitchellh.ghostty/config` (macOS) or `~/.config/ghostty/config` (Linux):```text-keybind = alt+backspace=text:+keybind = alt+backspace=text:\x1b\x7f```-Remove older `shift+enter=text:-` mappings unless needed for other tools. If keeping that mapping for tmux, add `ctrl+j` to Pi's newline keybinding.+Older Claude Code versions may have added `keybind = shift+enter=text:\n`. That sends a raw linefeed, which inside Pi is indistinguishable from `Ctrl+J`, so tmux and Pi no longer see a real `shift+enter` event. Remove it unless you still need it for Claude Code in tmux. Pi binds `Ctrl+J` as a default newline alias, so `Shift+Enter` keeps working through that remap without extra Pi configuration.## WezTerm-Usually works. To force Kitty keyboard:+Usually works via xterm `modifyOtherKeys`. To force the Kitty protocol, in `~/.wezterm.lua`:```lualocal wezterm = require 'wezterm'@@ -30,20 +29,53 @@ config.enable_kitty_keyboard = truereturn config```-On macOS, remap Option+Enter to send `[13;3u` if you want follow-up queueing.+On macOS `Option+Enter` is bound to fullscreen; to use it for follow-up queueing add to `config.keys`:++```lua+{ key = 'Enter', mods = 'ALT', action = wezterm.action.SendString('\x1b[13;3u') }+```++On WSL, WezTerm may need a visible hardware cursor for IME candidate positioning — set `PI_HARDWARE_CURSOR=1` or `showHardwareCursor: true`.## Alacritty-On macOS, add Alt+Enter binding to send `[13;3u`.+Usually works for `Shift+Enter`. On macOS `Option+Enter` may arrive as plain `Enter`; add to `~/.config/alacritty/alacritty.toml` and restart:++```toml+[[keyboard.bindings]]+key = "Enter"+mods = "Alt"+chars = "\u001b[13;3u"+```## VS Code Integrated Terminal-VS Code 1.109.5+ enables Kitty keyboard by default. Older versions need a Shift+Enter `workbench.action.terminal.sendSequence` keybinding sending `[13;2u`.+1.109.5+ enables the Kitty protocol by default. Older versions need an explicit `keybindings.json` entry (macOS `~/Library/Application Support/Code/User/keybindings.json`, Linux `~/.config/Code/User/keybindings.json`, Windows `%APPDATA%\Code\User\keybindings.json`):++```json+{+ "key": "shift+enter",+ "command": "workbench.action.terminal.sendSequence",+ "args": { "text": "\u001b[13;2u" },+ "when": "terminalFocus"+}+```## Windows Terminal-Add actions for Shift+Enter (`[13;2u`) and Alt+Enter (`[13;3u`). Fully restart if old fullscreen behavior persists.+Add to `settings.json` (Ctrl+Shift+, then Open JSON file) so the modified Enter keys reach Pi:++```json+{+ "actions": [+ { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "keys": "shift+enter" },+ { "command": { "action": "sendInput", "input": "\u001b[13;3u" }, "keys": "alt+enter" }+ ]+}+```++Windows Terminal binds `Alt+Enter` to fullscreen by default, which blocks follow-up queueing; remapping it to `sendInput` forwards the real chord. Fully close and reopen Windows Terminal if the old fullscreen behavior persists.## Limited Terminals-xfce4-terminal, terminator, and IntelliJ's integrated terminal cannot distinguish modified Enter keys reliably. Use a terminal with Kitty keyboard support for the best experience.+xfce4-terminal, terminator, and IntelliJ IDEA's integrated terminal cannot distinguish modified Enter keys from plain Enter, so bindings such as `submit: ["ctrl+enter"]` will not work. Prefer a terminal with Kitty keyboard support: Kitty, Ghostty, WezTerm, iTerm2, or Alacritty compiled with Kitty protocol support. In IntelliJ, set `PI_HARDWARE_CURSOR=1` if you want the hardware cursor visible (off by default for compatibility).diff --git a/skills/pi-agent/references/themes.md b/skills/pi-agent/references/themes.mdindex 74825325..06405cfa 100644--- a/skills/pi-agent/references/themes.md+++ b/skills/pi-agent/references/themes.md@@ -8,27 +8,60 @@ Themes are JSON files defining TUI colors.- Built-in: `dark`, `light`- Global: `~/.pi/agent/themes/*.json`-- Project: `.pi/themes/*.json` after project trust-- Packages: `themes/` or `pi.themes`+- Project: `.pi/themes/*.json` (only after project trust)+- Packages: `themes/` directories or `pi.themes` entries in `package.json`- Settings: `themes` array-- CLI: `--theme`, repeatable+- CLI: `--theme <path>` (repeatable)-Disable with `--no-themes`. Select through `/settings` or `{"theme": "my-theme"}`. Pi detects terminal background on first run.+Disable discovery with `--no-themes`. Select via `/settings` or `{"theme": "my-theme"}`. On first run Pi detects the terminal background and defaults to `dark` or `light`. Editing the active custom theme file hot-reloads it for immediate feedback.## Format-A theme has `$schema`, required `name`, optional `vars`, required `colors`, and optional `export` colors for HTML exports. All 51 color tokens must be defined.+```json+{+ "$schema": "https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",+ "name": "my-theme",+ "vars": { "primary": "#00aaff", "secondary": 242 },+ "colors": { "accent": "primary", "muted": "secondary", "text": "" }+}+```-Color values can be 6-digit hex strings, xterm 256-color indices, variable names from `vars`, or `""` for terminal default.+- `name` is required, must be unique, and must not contain `/`.+- `vars` is optional — reusable colors referenced by name from `colors`.+- `colors` must define all 51 tokens. `thinkingMax` is the only optional one and falls back to `thinkingXhigh`.+- `$schema` enables editor auto-completion and validation.-## Token Groups+## Color Tokens (51)-- Core UI: accent, borders, success/error/warning, muted/dim/text/thinkingText.-- Background/content: selected/user/custom/tool states.-- Markdown: headings, links, code, quote, hr, list bullets.-- Tool diffs: added, removed, context.-- Syntax: comment, keyword, function, variable, string, number, type, operator, punctuation.-- Thinking levels: off, minimal, low, medium, high, xhigh.-- Bash mode.+- **Core UI (11)**: `accent`, `border`, `borderAccent`, `borderMuted`, `success`, `error`, `warning`, `muted`, `dim`, `text`, `thinkingText`+- **Backgrounds & content (11)**: `selectedBg`, `userMessageBg`, `userMessageText`, `customMessageBg`, `customMessageText`, `customMessageLabel`, `toolPendingBg`, `toolSuccessBg`, `toolErrorBg`, `toolTitle`, `toolOutput`+- **Markdown (10)**: `mdHeading`, `mdLink`, `mdLinkUrl`, `mdCode`, `mdCodeBlock`, `mdCodeBlockBorder`, `mdQuote`, `mdQuoteBorder`, `mdHr`, `mdListBullet`+- **Tool diffs (3)**: `toolDiffAdded`, `toolDiffRemoved`, `toolDiffContext`+- **Syntax (9)**: `syntaxComment`, `syntaxKeyword`, `syntaxFunction`, `syntaxVariable`, `syntaxString`, `syntaxNumber`, `syntaxType`, `syntaxOperator`, `syntaxPunctuation`+- **Thinking level borders (6 required + 1 optional)**: `thinkingOff`, `thinkingMinimal`, `thinkingLow`, `thinkingMedium`, `thinkingHigh`, `thinkingXhigh`, and optional `thinkingMax`+- **Bash mode (1)**: `bashMode`-Hot reload applies edits to the active custom theme for immediate feedback.+## HTML Export (optional)++```json+{ "export": { "pageBg": "#18181e", "cardBg": "#1e1e24", "infoBg": "#3c3728" } }+```++Controls `/export` HTML output. If omitted, colors are derived from `userMessageBg`.++## Color Values++| Format | Example | Notes |+|---|---|---|+| Hex | `"#ff0000"` | 6-digit RGB |+| 256-color | `39` | xterm palette index 0–255 |+| Variable | `"primary"` | Reference to a `vars` entry |+| Default | `""` | Terminal default color |++256-color ranges: `0-15` basic ANSI (terminal-dependent), `16-231` the 6×6×6 RGB cube (`16 + 36R + 6G + B`), `232-255` grayscale.++Pi emits 24-bit RGB; older 256-color terminals get the nearest approximation. Check truecolor with `echo $COLORTERM`. In VS Code set `terminal.integrated.minimumContrastRatio` to `1` for accurate colors.++## Tips++Dark terminals want bright saturated colors with higher contrast; light terminals want darker muted colors. Start from a base palette (Nord, Gruvbox, Tokyo Night) in `vars` and reference it consistently. Test against different message types, tool states, markdown, and long wrapped text. Built-in themes to copy: `src/modes/interactive/theme/dark.json` and `light.json`.diff --git a/skills/pi-agent/references/tmux.md b/skills/pi-agent/references/tmux.mdindex c7c98c4a..6ee6592d 100644--- a/skills/pi-agent/references/tmux.md+++ b/skills/pi-agent/references/tmux.md@@ -2,33 +2,43 @@Source: https://pi.dev/docs/latest/tmux-tmux strips modifier information from some keys by default. Without configuration, Shift+Enter and Ctrl+Enter are often indistinguishable from Enter.+tmux strips modifier information from some keys by default, so without configuration `Shift+Enter` and `Ctrl+Enter` are indistinguishable from plain `Enter`.## Recommended Configuration-For tmux 3.5+:+Add to `~/.tmux.conf`:```tmuxset -g extended-keys onset -g extended-keys-format csi-u```-Restart tmux fully:+Then restart tmux fully:```bashtmux kill-servertmux```-With tmux 3.2 through 3.4, omit `extended-keys-format csi-u`; Pi still supports tmux's default xterm modifyOtherKeys format.+Pi requests extended key reporting automatically when the Kitty keyboard protocol is unavailable. `extended-keys-format csi-u` requires **tmux 3.5 or later** (check with `tmux -V`). With tmux 3.2–3.4, omit that line; Pi still supports tmux's default xterm `modifyOtherKeys` format.++## Why csi-u++With only `set -g extended-keys on`, tmux defaults to `extended-keys-format xterm` and forwards modified keys as `modifyOtherKeys` sequences — `Ctrl+C` as `ESC [27;5;99~`, `Ctrl+Enter` as `ESC [27;5;13~`. With `csi-u` the same keys arrive as `ESC [99;5u` and `ESC [13;5u`. Pi supports both formats; `csi-u` is the recommended setup.## What It Fixes-With CSI-u forwarding, modified Enter keys arrive distinctly:+`ESC` below is the escape byte (`0x1b`).++| Key | Without extended keys | With `csi-u` |+|---|---|---|+| Enter | `CR` | `CR` |+| Shift+Enter | `CR` | `ESC [13;2u` |+| Ctrl+Enter | `CR` | `ESC [13;5u` |+| Alt/Option+Enter | `ESC CR` | `ESC [13;3u` |++This affects the default bindings (Enter to submit, Shift+Enter for newline) and any custom keybindings using modified Enter.-- Enter: ` `-- Shift+Enter: `[13;2u`-- Ctrl+Enter: `[13;5u`-- Alt/Option+Enter: `[13;3u`+## Requirements-This affects default Enter submit, Shift+Enter newline, and custom keybindings.+tmux 3.5+ for `extended-keys-format csi-u`, plus a terminal emulator that supports extended keys: Ghostty, Kitty, iTerm2, WezTerm, or Windows Terminal.diff --git a/skills/pi-agent/references/tui.md b/skills/pi-agent/references/tui.mdindex 08f9aa5f..f70ec1e0 100644--- a/skills/pi-agent/references/tui.md+++ b/skills/pi-agent/references/tui.md@@ -2,7 +2,7 @@Source: https://pi.dev/docs/latest/tui-Extensions and custom tools can render custom terminal UI components through `@earendil-works/pi-tui`.+Extensions and custom tools render custom terminal UI through `@earendil-works/pi-tui`.## Component Interface@@ -10,47 +10,88 @@ Extensions and custom tools can render custom terminal UI components through `@einterface Component {render(width: number): string[];handleInput?(data: string): void;- wantsKeyRelease?: boolean;- invalidate(): void;+ wantsKeyRelease?: boolean; // receive key release events (Kitty protocol)+ invalidate(): void; // clear cached render state; called on theme changes}```-`render(width)` returns one string per line; each line must not exceed `width`. The TUI appends style resets at line ends, so reapply styles per line or use helpers that preserve ANSI styles.+Each line from `render(width)` **must not exceed `width`**. The TUI appends a full SGR reset and OSC 8 reset at the end of every rendered line, so styles do not carry across lines — reapply styles per line or use `wrapTextWithAnsi()`.++Width helpers: `visibleWidth(str)` (ignores ANSI), `truncateToWidth(str, width, ellipsis?)`, `wrapTextWithAnsi(str, width)`.## Focusable and IME-Text cursor components that need IME support implement `Focusable` and emit `CURSOR_MARKER` before their fake cursor. Containers with embedded inputs must propagate focus to the child input, or IME candidate windows appear in the wrong place. Hardware cursor visibility is controlled by `showHardwareCursor`, `setShowHardwareCursor(true)`, or `PI_HARDWARE_CURSOR=1`.+Components that draw a text cursor should implement `Focusable { focused: boolean }`. When focused, the TUI sets `focused = true`, scans output for `CURSOR_MARKER` (a zero-width APC sequence emitted right before the fake cursor), and positions the hardware cursor there. The cursor stays hidden by default; some terminals need it visible for IME candidate windows — enable with `showHardwareCursor`, `setShowHardwareCursor(true)`, or `PI_HARDWARE_CURSOR=1`. The built-in `Editor` and `Input` already implement this.-## Usage+Container components (dialogs, selectors) that embed an `Input`/`Editor` must implement `Focusable` and propagate `focused` to the child, or IME candidate windows appear in the wrong place.-In extensions:+## Usage```ts-pi.on("session_start", async (_event, ctx) => {- const handle = ctx.ui.custom(myComponent);- handle.requestRender();- handle.close();-});+const result = await ctx.ui.custom<string | null>((tui, theme, keybindings, done) =>+ new MyComponent({ theme, keybindings, onChange: () => tui.requestRender(), onSelect: done, onCancel: () => done(null) })+);```-In custom tools, use `pi.ui.custom()` inside `execute` and close handles when done.+The same call works inside a custom tool's `execute(toolCallId, params, signal, onUpdate, ctx)`. Returning a plain `{ render, invalidate, handleInput }` object is also fine.## Overlays-Pass `{ overlay: true }` to render on top of existing content. `overlayOptions` controls width, height, anchor, offsets, row/col, margins, and responsive visibility. Overlay handles support focus/unfocus, hide, and visibility toggles. Do not reuse disposed overlay component instances; create fresh ones for each show.+Pass `{ overlay: true }` to render on top of existing content without clearing the screen. `overlayOptions` controls layout:++- Size: `width`, `minWidth`, `maxHeight` (numbers or percentage strings)+- Position: `anchor` (9 positions, default `"center"`), `offsetX`/`offsetY`, or `row`/`col`+- Margins: `margin` (number or `{ top, right, bottom, left }`)+- Responsive: `visible(termWidth, termHeight)`++`onHandle: (handle) => …` gives `focus()` (focus and bring to front), `unfocus()` (release input to the normal fallback), `unfocus({ target })` (hand input to a specific component, or `null` for none), `setHidden(true|false)`, and `hide()` (permanent removal).++A focused visible overlay keeps input ownership across temporary non-overlay UI and can reclaim input when that UI closes. Overlay components are disposed when closed — never reuse a reference; call the show function again to re-show.++## Built-in Components++Import from `@earendil-works/pi-tui`: `Text` (multi-line with word wrapping, `new Text(content, paddingX, paddingY, bgFn?)`, `setText()`), `Box` (padding + background, `addChild`, `setBgFn`), `Container` (vertical grouping, `addChild`/`removeChild`/`clear`), `Spacer(lines)`, `Markdown(text, paddingX, paddingY, theme)`, `Image(base64, mimeType, theme, { maxWidthCells, maxHeightCells })` (Kitty, iTerm2, Ghostty, WezTerm, Warp), `SelectList(items, visibleCount, theme)` with `SelectItem { value, label, description? }`, `SettingsList(items, visibleCount, theme, onChange, onClose, { enableSearch })` with `SettingItem { id, label, currentValue, values }`, plus `AutocompleteItem` types.++From `@earendil-works/pi-coding-agent`: `DynamicBorder`, `BorderedLoader` (spinner + abort signal + `onAbort`), `CustomEditor`, `getMarkdownTheme()`, `getSettingsListTheme()`, `keyHint`/`keyText`/`rawKeyHint`, `highlightCode`, `getLanguageFromPath`.-## Built-ins+## Keyboard Input-Import `Text`, `Box`, `Container`, `Spacer`, `Markdown`, `Input`, `Editor`, `SelectList`, `SettingsList`, `BorderedLoader`, and helpers from `@earendil-works/pi-tui`. Prefer existing components for selectors, settings/toggles, loaders, markdown, and layout before building custom primitives.+```ts+import { matchesKey, Key } from "@earendil-works/pi-tui";++if (matchesKey(data, Key.up)) { /* ... */ }+if (matchesKey(data, Key.ctrl("c"))) { /* ... */ }+```++`Key.enter`, `Key.escape`, `Key.tab`, `Key.space`, `Key.backspace`, `Key.delete`, `Key.home`, `Key.end`, arrows, and modifier helpers `Key.ctrl`, `Key.shift`, `Key.alt`, `Key.ctrlShift`. String literals (`"enter"`, `"ctrl+c"`, `"shift+tab"`) also work.++## Theming-## Theming Rules+Use the `theme` passed into the callback or renderer — never import a global theme. `theme.fg(color, text)` covers general (`text`, `accent`, `muted`, `dim`), status (`success`, `error`, `warning`), borders (`border`, `borderAccent`, `borderMuted`), messages (`userMessageText`, `customMessageText`, `customMessageLabel`), tools (`toolTitle`, `toolOutput`), diffs (`toolDiffAdded`/`Removed`/`Context`), markdown (`md*`), syntax (`syntax*`), thinking levels (`thinkingOff`…`thinkingMax`), and `bashMode`. `theme.bg(color, text)` covers `selectedBg`, `userMessageBg`, `customMessageBg`, `toolPendingBg`, `toolSuccessBg`, `toolErrorBg`. Text styles: `theme.bold`, `theme.italic`, `theme.strikethrough`.-Use the theme object passed into callbacks; do not import a global theme. Implement `invalidate()` so theme changes clear cached styled output. Use explicit color callback parameters such as `(s: string) => theme.fg("accent", s)`.+Components that pre-bake theme colors into cached strings must rebuild that content in `invalidate()` — clearing a render cache is not enough. This applies to `theme.fg`/`theme.bg` strings stored in child components, `highlightCode()` output, and child trees that embed colors. It is unnecessary when you pass theme callbacks that run at render time, for simple containers, or for stateless render.++## Common Patterns++1. **Selection dialog** — `SelectList` framed with `DynamicBorder`, `onSelect`/`onCancel` calling `done`.+2. **Async with cancel** — `BorderedLoader(tui, theme, "Fetching…")`, pass `loader.signal` to the async work, `loader.onAbort = () => done(null)`.+3. **Settings toggles** — `SettingsList` with `getSettingsListTheme()`.+4. **Persistent status** — `ctx.ui.setStatus("my-ext", text)`; clear with `undefined`.+5. **Working indicator** — `ctx.ui.setWorkingIndicator({ frames, intervalMs })`; `{ frames: [] }` hides it, no argument restores the default spinner. Frames render verbatim, so add colors yourself. Compaction and retry loaders keep built-in styling. `setWorkingMessage()` and `setWorkingVisible()` control the loader row.+6. **Widgets** — `ctx.ui.setWidget(key, lines | factory, { placement: "aboveEditor" | "belowEditor" })`; `undefined` clears.+7. **Custom footer** — `ctx.ui.setFooter((tui, theme, footerData) => ({ render, invalidate, dispose }))`. `footerData.getGitBranch()`, `getExtensionStatuses()`, and `onBranchChange(cb)` expose data extensions cannot otherwise reach; token stats come from `ctx.sessionManager.getBranch()` and `ctx.model`. `setFooter(undefined)` restores the default.+8. **Custom editor** — extend `CustomEditor` (not base `Editor`) so app keybindings still work, call `super.handleInput(data)` for keys you do not handle, and install with `ctx.ui.setEditorComponent((tui, theme, keybindings) => new MyEditor(...))`. Capture `ctx.ui.getEditorComponent()` first to wrap another extension's editor; `setEditorComponent(undefined)` restores the default.## Key Rules-- Always respect `render(width)`.-- Implement `invalidate()` on custom components and child trees.-- Propagate focus for embedded inputs.-- Use overlays for temporary panels/dialogs.-- Guard TUI features when running in non-TUI modes.+1. Respect `render(width)` on every line.+2. Always use the `theme` from the callback; type `DynamicBorder` color params explicitly (`(s: string) => theme.fg("accent", s)`).+3. Call `tui.requestRender()` after state changes in `handleInput`.+4. Implement `invalidate()` on custom components and their child trees.+5. Propagate focus to embedded inputs.+6. Reuse `SelectList`, `SettingsList`, and `BorderedLoader` before building primitives.+7. Guard TUI features in non-TUI modes (`ctx.mode === "tui"`).++## Debug Logging++`PI_TUI_WRITE_LOG=/tmp/tui-ansi.log` captures the raw ANSI stream written to stdout.diff --git a/skills/pi-agent/references/usage.md b/skills/pi-agent/references/usage.mdindex 6a43db63..87353869 100644--- a/skills/pi-agent/references/usage.md+++ b/skills/pi-agent/references/usage.md@@ -4,67 +4,122 @@ Source: https://pi.dev/docs/latest/usage## Interface-Interactive mode has a startup header, message area, editor, and footer. The footer shows cwd, session name, token/cache usage, cost, context usage, and current model. The editor border indicates thinking level.+Interactive mode has four areas: startup header (shortcuts, loaded context files, prompt templates, skills, extensions), messages, editor, and footer. The footer shows cwd, session name, token/cache usage, cost, context usage, and current model; totals include assistant responses, usage reported by tools, and summary generation. The editor border indicates thinking level. Built-in UI (`/settings`) or extension UI can temporarily replace the editor.## Editor Features-- Type `@` to fuzzy-search project files.-- Press Tab for path completion.-- Use Shift+Enter, or Ctrl+Enter on Windows Terminal, for multi-line input.-- Paste or drag images in supported terminals.-- Prefix with `!` to run a shell command and include output in context.-- Prefix with `!!` to run a hidden shell command outside model context.-- Ctrl+G opens `$VISUAL` or `$EDITOR`.+| Feature | How |+|---|---|+| File reference | Type `@` to fuzzy-search project files |+| Path completion | Tab |+| Multi-line input | Shift+Enter, or Ctrl+Enter on Windows Terminal |+| Copy response | Ctrl+X copies the last assistant message; in `/tree` it copies the selected message |+| Images | Paste with Ctrl+V (Alt+V on Windows), or drag into the terminal |+| Shell command | `!command` runs and sends output to the model |+| Hidden shell command | `!!command` runs without sending output to the model |+| External editor | Ctrl+G opens `externalEditor`, `$VISUAL`, `$EDITOR`, Notepad on Windows, or `nano` elsewhere |## Slash Commands-Important commands: `/login`, `/logout`, `/model`, `/scoped-models`, `/settings`, `/resume`, `/new`, `/name`, `/session`, `/tree`, `/fork`, `/clone`, `/compact [prompt]`, `/copy`, `/export [file]`, `/share`, `/reload`, `/hotkeys`, `/changelog`, `/quit`.--Skills are available as `/skill:name`; prompt templates expand as `/template-name`; extensions can register custom commands.+| Command | Description |+|---|---|+| `/login`, `/logout` | Manage OAuth or API-key credentials |+| `/llama` | Download, load, unload llama.cpp router models (`references/llama-cpp.md`) |+| `/model` | Switch models |+| `/scoped-models` | Enable/disable models for Ctrl+P cycling |+| `/settings` | Thinking level, theme, message delivery, transport |+| `/resume`, `/new`, `/name <name>`, `/session` | Session management |+| `/tree` | Jump to any point in the session and continue from there |+| `/trust` | Save project trust decision for future sessions |+| `/fork`, `/clone` | New session from a previous user message / duplicate active branch |+| `/compact [prompt]` | Manually compact context, optionally with custom instructions |+| `/copy` | Copy last assistant message to clipboard |+| `/export [file]` | Export session to HTML or JSONL |+| `/import <file>` | Import and resume a session from a JSONL file |+| `/share` | Upload as private GitHub gist with shareable HTML link |+| `/reload` | Reload keybindings, extensions, skills, prompts, themes, context files |+| `/hotkeys`, `/changelog`, `/quit` | Shortcuts, version history, quit |++Skills are available as `/skill:name`; prompt templates expand as `/templatename`; extensions can register custom commands.## Message Queue-- Enter while the agent is running queues a steering message.-- Alt+Enter queues a follow-up message for after all current work finishes.-- Escape aborts and restores queued messages to the editor.-- Alt+Up retrieves queued messages.+- Enter queues a steering message, delivered after the current assistant turn finishes its tool calls.+- Alt+Enter queues a follow-up message, delivered after the agent finishes all work.+- Escape aborts and restores queued messages to the editor; Alt+Up retrieves them.- `steeringMode` and `followUpMode` control one-at-a-time vs all-at-once delivery.+On Windows Terminal, Alt+Enter is fullscreen by default — remap it (`references/terminal-setup.md`).++## Context and System Prompt Files++Pi loads `AGENTS.md` or `CLAUDE.md` from `~/.pi/agent/AGENTS.md`, parent directories walking up from cwd, and the current directory. Disable with `--no-context-files` / `-nc`.++Replace the default system prompt with `.pi/SYSTEM.md` (project) or `~/.pi/agent/SYSTEM.md` (global). Append instead of replacing with `APPEND_SYSTEM.md` in either location.++## Project Trust++Interactive startup asks before trusting a project folder that has project-local settings, resources, or project `.agents/skills` and no saved decision for that folder or a parent in `~/.pi/agent/trust.json`. Before the decision, Pi loads only context files, user/global extensions, and CLI `-e` extensions so they can handle `project_trust`. Non-interactive modes (`-p`, `--mode json`, `--mode rpc`) never prompt and follow `defaultProjectTrust` (`ask` default, `never`, `always`); `--approve`/`-a` and `--no-approve`/`-na` override for one run. `/trust` saves a decision (including for the immediate parent folder) to `trust.json` without reloading the session. `pi config` and package commands use the same flow, except `pi update` never prompts.++## Exporting and Sharing++`/export [file]` writes HTML; `/share` uploads a private GitHub gist with a shareable HTML link. `badlogic/pi-share-hf` publishes sessions to Hugging Face datasets for research.+## CLI Modes```bashpi [options] [@files...] [messages...]-pi -p "prompt"-pi --mode json "prompt"-pi --mode rpc-pi --export [out]+pi -p "prompt" # print and exit+pi --mode json "prompt" # JSONL event stream+pi --mode rpc # RPC over stdin/stdout+pi --export <in> [out] # export a session to HTML```Print mode reads piped stdin and merges it into the initial prompt.-## Common Options+## Package Commands-Model: `--provider`, `--model`, `--api-key`, `--thinking`, `--models`, `--list-models`.+```bash+pi install <source> [-l] # -l writes to project settings+pi remove <source> [-l] # pi uninstall is an alias+pi update [source|self|pi] # update pi only, or one package source+pi update --all # pi + packages; reconcile pinned git refs+pi update --extensions # packages only+pi update --models # refresh model catalogs only+pi update --self # update pi only+pi update --extension <src> # update one package+pi list # list installed packages+pi config # enable/disable package resources+```++## Options++Model: `--provider <name>`, `--model <pattern>` (supports `provider/id` and `:<thinking>`), `--api-key`, `--thinking <off|minimal|low|medium|high|xhigh|max>`, `--models <patterns>`, `--list-models [search]`.-Session: `-c/--continue`, `-r/--resume`, `--session`, `--fork`, `--session-dir`, `--no-session`, `--name/-n`.+Session: `-c/--continue`, `-r/--resume`, `--session <path|id>`, `--fork <path|id>`, `--session-dir`, `--no-session`, `-n/--name`.-Tools: `--tools/-t`, `--exclude-tools/-xt`, `--no-builtin-tools/-nbt`, `--no-tools/-nt`. Built-ins are `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`.+Tools: `-t/--tools`, `-xt/--exclude-tools`, `-nbt/--no-builtin-tools` (keeps extension/custom tools), `-nt/--no-tools`. Built-ins: `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`.-Resources: `-e/--extension`, `--skill`, `--prompt-template`, `--theme`, and corresponding `--no-*` flags. `--no-context-files` disables `AGENTS.md`/`CLAUDE.md` discovery.+Resources: `-e/--extension <source>` (path, npm, or git; repeatable), `--no-extensions`, `--skill`, `--no-skills`, `--prompt-template`, `--no-prompt-templates`, `--theme`, `--no-themes`, `-nc/--no-context-files`. Combine `--no-*` with explicit flags to load exactly what you need: `pi --no-extensions -e ./my-extension.ts`.-Other: `--system-prompt`, `--append-system-prompt`, `--verbose`, `--approve`, `--no-approve`, `--help`, `--version`.+Other: `--system-prompt <text>` (context files and skills are still appended), `--append-system-prompt`, `--verbose`, `-a/--approve`, `-na/--no-approve`, `-h/--help`, `-v/--version`.-## Environment Variables+File arguments: prefix with `@` to include in the message (`pi @code.ts @test.ts "Review these"`).-- `PI_CODING_AGENT_DIR`: config directory, default `~/.pi/agent`.-- `PI_CODING_AGENT_SESSION_DIR`: session storage override.-- `PI_PACKAGE_DIR`: package directory override.-- `PI_OFFLINE`: disable startup network operations.-- `PI_SKIP_VERSION_CHECK`: skip version check.-- `PI_TELEMETRY`: override install/update telemetry and provider attribution headers.-- `PI_CACHE_RETENTION`: set `long` where supported.-- `VISUAL`, `EDITOR`: external editor.+Environment variables are documented separately in `references/environment-variables.md`.++## Examples++```bash+pi "List all .ts files in src/"+pi --name "release audit" -p "Audit this repository"+pi --model openai/gpt-4o "Help me refactor"+pi --model sonnet:high "Solve this complex problem"+pi --models "claude-*,gpt-4o"+pi --tools read,grep,find,ls -p "Review the code"+pi --exclude-tools ask_question+```## Design Principles-Pi intentionally does not include built-in MCP, sub-agents, permission popups, plan mode, to-dos, or background bash. Build or install those workflows as extensions/packages, or use containers/tmux/external tools.+Pi keeps the core small and pushes workflow-specific behavior into extensions, skills, prompt templates, and packages. It intentionally does not include built-in MCP, sub-agents, permission popups, plan mode, to-dos, or background bash. Build or install those workflows as extensions/packages, or use external tools such as containers and tmux.diff --git a/skills/pi-agent/references/windows.md b/skills/pi-agent/references/windows.mdindex f23b20bd..40e159ab 100644--- a/skills/pi-agent/references/windows.md+++ b/skills/pi-agent/references/windows.md@@ -4,16 +4,20 @@ Source: https://pi.dev/docs/latest/windowsPi requires a bash shell on Windows. It checks, in order:-1. Custom path from `~/.pi/agent/settings.json`.-2. Git Bash: `C:\Program Files\Gitinash.exe`.-3. `bash.exe` on PATH, such as Cygwin, MSYS2, or WSL.+1. Custom path from `~/.pi/agent/settings.json`+2. Git Bash (`C:\Program Files\Git\bin\bash.exe`)+3. `bash.exe` on PATH (Cygwin, MSYS2, WSL)-Git for Windows is sufficient for most users.+[Git for Windows](https://git-scm.com/download/win) is sufficient for most users.## Custom Shell Path```json{- "shellPath": "C:\cygwin64\bin\bash.exe"+ "shellPath": "C:\\cygwin64\\bin\\bash.exe"}```++The value is JSON, so each literal backslash in the Windows path must be doubled.++Related Windows notes: Ctrl+Enter for multi-line input, Alt+V to paste images, `app.suspend` has no default binding (`references/keybindings.md`), and Alt+Enter must be remapped away from fullscreen (`references/terminal-setup.md`).