TaskFlow
DashboardFreewriteWhiteboardsProjectsCRMTasksNotificationsSettingsAgent TowerAPI Docs
OpenClaw Docs
?

User

Member

Caricamento in corso...

Home
Progetti
Task
Notifiche
CRM

    OpenClaw

    Documentation Mirror

    Documentation Overview

    Docs

    Auth credential semantics
    Scheduled tasks
    Hooks
    Automation & tasks
    Standing orders
    Task flow
    Background tasks
    BlueBubbles
    Broadcast groups
    Channel routing
    Discord
    Feishu
    Google Chat
    Group messages
    Groups
    iMessage
    Chat channels
    IRC
    LINE
    Channel location parsing
    Matrix
    Matrix migration
    Matrix push rules for quiet previews
    Mattermost
    Microsoft Teams
    Nextcloud Talk
    Nostr
    Pairing
    QA channel
    QQ bot
    Signal
    Slack
    Synology Chat
    Telegram
    Tlon
    Channel troubleshooting
    Twitch
    WeChat
    WhatsApp
    Yuanbao
    Zalo
    Zalo personal
    CI pipeline
    ACP
    Agent
    Agents
    Approvals
    Backup
    Browser
    Channels
    Clawbot
    `openclaw commitments`
    Completion
    Config
    Configure
    Cron
    Daemon
    Dashboard
    Devices
    Directory
    DNS
    Docs
    Doctor
    Flows (redirect)
    Gateway
    Health
    Hooks
    CLI reference
    Inference CLI
    Logs
    MCP
    Memory
    Message
    Migrate
    Models
    Node
    Nodes
    Onboard
    Pairing
    Plugins
    Proxy
    QR
    Reset
    Sandbox CLI
    Secrets
    Security
    Sessions
    Setup
    Skills
    Status
    System
    `openclaw tasks`
    TUI
    Uninstall
    Update
    Voicecall
    Webhooks
    Wiki
    Active memory
    Agent runtime
    Agent loop
    Agent runtimes
    Agent workspace
    Gateway architecture
    Channel docking
    Inferred commitments
    Compaction
    Context
    Context engine
    Delegate architecture
    Dreaming
    Experimental features
    Features
    Markdown formatting
    Memory overview
    Builtin memory engine
    Honcho memory
    QMD memory engine
    Memory search
    Messages
    Model failover
    Model providers
    Models CLI
    Multi-agent routing
    OAuth
    OpenClaw App SDK
    Presence
    QA overview
    Matrix QA
    Command queue
    Steering queue
    Retry policy
    Session management
    Session pruning
    Session tools
    SOUL.md personality guide
    Streaming and chunking
    System prompt
    Timezones
    TypeBox
    Typing indicators
    Usage tracking
    Date and time
    Node + tsx crash
    Diagnostics flags
    Authentication
    Background exec and process tool
    Bonjour discovery
    Bridge protocol
    CLI backends
    Configuration — agents
    Configuration — channels
    Configuration — tools and custom providers
    Configuration
    Configuration examples
    Configuration reference
    Diagnostics export
    Discovery and transports
    Doctor
    Gateway lock
    Health checks
    Heartbeat
    Gateway runbook
    Local models
    Gateway logging
    Multiple gateways
    Network model
    OpenAI chat completions
    OpenResponses API
    OpenShell
    OpenTelemetry export
    Gateway-owned pairing
    Prometheus metrics
    Gateway protocol
    Remote access
    Remote gateway setup
    Sandbox vs tool policy vs elevated
    Sandboxing
    Secrets management
    Secrets apply plan contract
    Security audit checks
    Security
    Tailscale
    Tools invoke API
    Troubleshooting
    Trusted proxy auth
    Debugging
    Environment variables
    FAQ
    FAQ: first-run setup
    FAQ: models and auth
    GPT-5.5 / Codex agentic parity
    GPT-5.5 / Codex parity maintainer notes
    Help
    Scripts
    Testing
    Testing: live suites
    General troubleshooting
    OpenClaw
    Ansible
    Azure
    Bun (experimental)
    ClawDock
    Release channels
    DigitalOcean
    Docker
    Docker VM runtime
    exe.dev
    Fly.io
    GCP
    Hetzner
    Hostinger
    Install
    Installer internals
    Kubernetes
    macOS VMs
    Migration guide
    Migrating from Claude
    Migrating from Hermes
    Nix
    Node.js
    Northflank
    Oracle Cloud
    Podman
    Railway
    Raspberry Pi
    Render
    Uninstall
    Updating
    Logging
    Network
    Audio and voice notes
    Camera capture
    Image and media support
    Nodes
    Location command
    Media understanding
    Talk mode
    Node troubleshooting
    Voice wake
    Pi integration architecture
    Pi development workflow
    Android app
    Platforms
    iOS app
    Linux app
    Gateway on macOS
    Canvas
    Gateway lifecycle
    macOS dev setup
    Health checks (macOS)
    Menu bar icon
    macOS logging
    Menu bar
    Peekaboo bridge
    macOS permissions
    Remote control
    macOS signing
    Skills (macOS)
    Voice overlay
    Voice wake (macOS)
    WebChat (macOS)
    macOS IPC
    macOS app
    Windows
    Plugin internals
    Plugin architecture internals
    Building plugins
    Plugin bundles
    Codex Computer Use
    Codex harness
    Community plugins
    Plugin compatibility
    Google Meet plugin
    Plugin hooks
    Plugin manifest
    Memory LanceDB
    Memory wiki
    Message presentation
    Agent harness plugins
    Building channel plugins
    Channel turn kernel
    Plugin entry points
    Plugin SDK migration
    Plugin SDK overview
    Building provider plugins
    Plugin runtime helpers
    Plugin setup and config
    Plugin SDK subpaths
    Plugin testing
    Skill workshop plugin
    Voice call plugin
    Webhooks plugin
    Zalo personal plugin
    OpenProse
    Alibaba Model Studio
    Anthropic
    Arcee AI
    Azure Speech
    Amazon Bedrock
    Amazon Bedrock Mantle
    Chutes
    Claude Max API proxy
    Cloudflare AI gateway
    ComfyUI
    Deepgram
    Deepinfra
    DeepSeek
    ElevenLabs
    Fal
    Fireworks
    GitHub Copilot
    GLM (Zhipu)
    Google (Gemini)
    Gradium
    Groq
    Hugging Face (inference)
    Provider directory
    Inferrs
    Inworld
    Kilocode
    LiteLLM
    LM Studio
    MiniMax
    Mistral
    Model provider quickstart
    Moonshot AI
    NVIDIA
    Ollama
    OpenAI
    OpenCode
    OpenCode Go
    OpenRouter
    Perplexity
    Qianfan
    Qwen
    Runway
    SGLang
    StepFun
    Synthetic
    Tencent Cloud (TokenHub)
    Together AI
    Venice AI
    Vercel AI gateway
    vLLM
    Volcengine (Doubao)
    Vydra
    xAI
    Xiaomi MiMo
    Z.AI
    Default AGENTS.md
    Release policy
    API usage and costs
    Credits
    Device model database
    Full release validation
    Memory configuration reference
    OpenClaw App SDK API design
    Prompt caching
    Rich output protocol
    RPC adapters
    SecretRef credential surface
    Session management deep dive
    AGENTS.md template
    BOOT.md template
    BOOTSTRAP.md template
    HEARTBEAT.md template
    IDENTITY template
    SOUL.md template
    TOOLS.md template
    USER template
    Tests
    Token use and costs
    Transcript hygiene
    Onboarding reference
    Contributing to the threat model
    Threat model (MITRE ATLAS)
    Formal verification (security models)
    Network proxy
    Agent bootstrapping
    Docs directory
    Getting started
    Docs hubs
    OpenClaw lore
    Onboarding (macOS app)
    Onboarding overview
    Personal assistant setup
    Setup
    Showcase
    Onboarding (CLI)
    CLI automation
    CLI setup reference
    ACP agents
    ACP agents — setup
    Agent send
    apply_patch tool
    Brave search
    Browser (OpenClaw-managed)
    Browser control API
    Browser troubleshooting
    Browser login
    WSL2 + Windows + remote Chrome CDP troubleshooting
    BTW side questions
    ClawHub
    Code execution
    Creating skills
    Diffs
    DuckDuckGo search
    Elevated mode
    Exa search
    Exec tool
    Exec approvals
    Exec approvals — advanced
    Firecrawl
    Gemini search
    Grok search
    Image generation
    Tools and plugins
    Kimi search
    LLM task
    Lobster
    Tool-loop detection
    Media overview
    MiniMax search
    Multi-agent sandbox and tools
    Music generation
    Ollama web search
    PDF tool
    Perplexity search
    Plugins
    Reactions
    SearXNG search
    Skills
    Skills config
    Slash commands
    Sub-agents
    Tavily
    Thinking levels
    Tokenjuice
    Trajectory bundles
    Text-to-speech
    Video generation
    Web search
    Web fetch
    Linux server
    Control UI
    Dashboard
    Web
    TUI
    WebChat

    OpenAPI Specs

    openapi
    TaskFlow
    docs/openclaw
    Original Docs

    Real-time Synchronized Documentation

    Last sync: 01/05/2026 07:00:29

    Note: This content is mirrored from docs.openclaw.ai and is subject to their terms and conditions.

    OpenClaw Docs

    v2.4.0 Production

    Last synced: Today, 22:00

    Technical reference for the OpenClaw framework. Real-time synchronization with the official documentation engine.

    Use this file to discover all available pages before exploring further.

    Pi integration architecture

    OpenClaw integrates with pi-coding-agent and its sibling packages (

    text
    pi-ai
    ,
    text
    pi-agent-core
    ,
    text
    pi-tui
    ) to power its AI agent capabilities.

    Overview

    OpenClaw uses the pi SDK to embed an AI coding agent into its messaging gateway architecture. Instead of spawning pi as a subprocess or using RPC mode, OpenClaw directly imports and instantiates pi's

    text
    AgentSession
    via
    text
    createAgentSession()
    . This embedded approach provides:

    • Full control over session lifecycle and event handling
    • Custom tool injection (messaging, sandbox, channel-specific actions)
    • System prompt customization per channel/context
    • Session persistence with branching/compaction support
    • Multi-account auth profile rotation with failover
    • Provider-agnostic model switching

    Package dependencies

    json
    { "@mariozechner/pi-agent-core": "0.70.2", "@mariozechner/pi-ai": "0.70.2", "@mariozechner/pi-coding-agent": "0.70.2", "@mariozechner/pi-tui": "0.70.2" }
    PackagePurpose
    text
    pi-ai
    Core LLM abstractions:
    text
    Model
    ,
    text
    streamSimple
    , message types, provider APIs
    text
    pi-agent-core
    Agent loop, tool execution,
    text
    AgentMessage
    types
    text
    pi-coding-agent
    High-level SDK:
    text
    createAgentSession
    ,
    text
    SessionManager
    ,
    text
    AuthStorage
    ,
    text
    ModelRegistry
    , built-in tools
    text
    pi-tui
    Terminal UI components (used in OpenClaw's local TUI mode)

    File structure

    text
    src/agents/ ├── pi-embedded-runner.ts # Re-exports from pi-embedded-runner/ ├── pi-embedded-runner/ │ ├── run.ts # Main entry: runEmbeddedPiAgent() │ ├── run/ │ │ ├── attempt.ts # Single attempt logic with session setup │ │ ├── params.ts # RunEmbeddedPiAgentParams type │ │ ├── payloads.ts # Build response payloads from run results │ │ ├── images.ts # Vision model image injection │ │ └── types.ts # EmbeddedRunAttemptResult │ ├── abort.ts # Abort error detection │ ├── cache-ttl.ts # Cache TTL tracking for context pruning │ ├── compact.ts # Manual/auto compaction logic │ ├── extensions.ts # Load pi extensions for embedded runs │ ├── extra-params.ts # Provider-specific stream params │ ├── google.ts # Google/Gemini turn ordering fixes │ ├── history.ts # History limiting (DM vs group) │ ├── lanes.ts # Session/global command lanes │ ├── logger.ts # Subsystem logger │ ├── model.ts # Model resolution via ModelRegistry │ ├── runs.ts # Active run tracking, abort, queue │ ├── sandbox-info.ts # Sandbox info for system prompt │ ├── session-manager-cache.ts # SessionManager instance caching │ ├── session-manager-init.ts # Session file initialization │ ├── system-prompt.ts # System prompt builder │ ├── tool-split.ts # Split tools into builtIn vs custom │ ├── types.ts # EmbeddedPiAgentMeta, EmbeddedPiRunResult │ └── utils.ts # ThinkLevel mapping, error description ├── pi-embedded-subscribe.ts # Session event subscription/dispatch ├── pi-embedded-subscribe.types.ts # SubscribeEmbeddedPiSessionParams ├── pi-embedded-subscribe.handlers.ts # Event handler factory ├── pi-embedded-subscribe.handlers.lifecycle.ts ├── pi-embedded-subscribe.handlers.types.ts ├── pi-embedded-block-chunker.ts # Streaming block reply chunking ├── pi-embedded-messaging.ts # Messaging tool sent tracking ├── pi-embedded-helpers.ts # Error classification, turn validation ├── pi-embedded-helpers/ # Helper modules ├── pi-embedded-utils.ts # Formatting utilities ├── pi-tools.ts # createOpenClawCodingTools() ├── pi-tools.abort.ts # AbortSignal wrapping for tools ├── pi-tools.policy.ts # Tool allowlist/denylist policy ├── pi-tools.read.ts # Read tool customizations ├── pi-tools.schema.ts # Tool schema normalization ├── pi-tools.types.ts # AnyAgentTool type alias ├── pi-tool-definition-adapter.ts # AgentTool -> ToolDefinition adapter ├── pi-settings.ts # Settings overrides ├── pi-hooks/ # Custom pi hooks │ ├── compaction-safeguard.ts # Safeguard extension │ ├── compaction-safeguard-runtime.ts │ ├── context-pruning.ts # Cache-TTL context pruning extension │ └── context-pruning/ ├── model-auth.ts # Auth profile resolution ├── auth-profiles.ts # Profile store, cooldown, failover ├── model-selection.ts # Default model resolution ├── models-config.ts # models.json generation ├── model-catalog.ts # Model catalog cache ├── context-window-guard.ts # Context window validation ├── failover-error.ts # FailoverError class ├── defaults.ts # DEFAULT_PROVIDER, DEFAULT_MODEL ├── system-prompt.ts # buildAgentSystemPrompt() ├── system-prompt-params.ts # System prompt parameter resolution ├── system-prompt-report.ts # Debug report generation ├── tool-summaries.ts # Tool description summaries ├── tool-policy.ts # Tool policy resolution ├── transcript-policy.ts # Transcript validation policy ├── skills.ts # Skill snapshot/prompt building ├── skills/ # Skill subsystem ├── sandbox.ts # Sandbox context resolution ├── sandbox/ # Sandbox subsystem ├── channel-tools.ts # Channel-specific tool injection ├── openclaw-tools.ts # OpenClaw-specific tools ├── bash-tools.ts # exec/process tools ├── apply-patch.ts # apply_patch tool (OpenAI) ├── tools/ # Individual tool implementations │ ├── browser-tool.ts │ ├── canvas-tool.ts │ ├── cron-tool.ts │ ├── gateway-tool.ts │ ├── image-tool.ts │ ├── message-tool.ts │ ├── nodes-tool.ts │ ├── session*.ts │ ├── web-*.ts │ └── ... └── ...

    Channel-specific message action runtimes now live in the plugin-owned extension directories instead of under

    text
    src/agents/tools
    , for example:

    • the Discord plugin action runtime files
    • the Slack plugin action runtime file
    • the Telegram plugin action runtime file
    • the WhatsApp plugin action runtime file

    Core integration flow

    1. Running an Embedded Agent

    The main entry point is

    text
    runEmbeddedPiAgent()
    in
    text
    pi-embedded-runner/run.ts
    :

    typescript
    import { runEmbeddedPiAgent } from "./agents/pi-embedded-runner.js"; const result = await runEmbeddedPiAgent({ sessionId: "user-123", sessionKey: "main:whatsapp:+1234567890", sessionFile: "/path/to/session.jsonl", workspaceDir: "/path/to/workspace", config: openclawConfig, prompt: "Hello, how are you?", provider: "anthropic", model: "claude-sonnet-4-6", timeoutMs: 120_000, runId: "run-abc", onBlockReply: async (payload) => { await sendToChannel(payload.text, payload.mediaUrls); }, });

    2. Session Creation

    Inside

    text
    runEmbeddedAttempt()
    (called by
    text
    runEmbeddedPiAgent()
    ), the pi SDK is used:

    typescript
    import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager, } from "@mariozechner/pi-coding-agent"; const resourceLoader = new DefaultResourceLoader({ cwd: resolvedWorkspace, agentDir, settingsManager, additionalExtensionPaths, }); await resourceLoader.reload(); const { session } = await createAgentSession({ cwd: resolvedWorkspace, agentDir, authStorage: params.authStorage, modelRegistry: params.modelRegistry, model: params.model, thinkingLevel: mapThinkingLevel(params.thinkLevel), tools: builtInTools, customTools: allCustomTools, sessionManager, settingsManager, resourceLoader, }); applySystemPromptOverrideToSession(session, systemPromptOverride);

    3. Event Subscription

    text
    subscribeEmbeddedPiSession()
    subscribes to pi's
    text
    AgentSession
    events:

    typescript
    const subscription = subscribeEmbeddedPiSession({ session: activeSession, runId: params.runId, verboseLevel: params.verboseLevel, reasoningMode: params.reasoningLevel, toolResultFormat: params.toolResultFormat, onToolResult: params.onToolResult, onReasoningStream: params.onReasoningStream, onBlockReply: params.onBlockReply, onPartialReply: params.onPartialReply, onAgentEvent: params.onAgentEvent, });

    Events handled include:

    • text
      message_start
      /
      text
      message_end
      /
      text
      message_update
      (streaming text/thinking)
    • text
      tool_execution_start
      /
      text
      tool_execution_update
      /
      text
      tool_execution_end
    • text
      turn_start
      /
      text
      turn_end
    • text
      agent_start
      /
      text
      agent_end
    • text
      compaction_start
      /
      text
      compaction_end

    4. Prompting

    After setup, the session is prompted:

    typescript
    await session.prompt(effectivePrompt, { images: imageResult.images });

    The SDK handles the full agent loop: sending to LLM, executing tool calls, streaming responses.

    Image injection is prompt-local: OpenClaw loads image refs from the current prompt and passes them via

    text
    images
    for that turn only. It does not re-scan older history turns to re-inject image payloads.

    Tool architecture

    Tool pipeline

    1. Base Tools: pi's
      text
      codingTools
      (read, bash, edit, write)
    2. Custom Replacements: OpenClaw replaces bash with
      text
      exec
      /
      text
      process
      , customizes read/edit/write for sandbox
    3. OpenClaw Tools: messaging, browser, canvas, sessions, cron, gateway, etc.
    4. Channel Tools: Discord/Telegram/Slack/WhatsApp-specific action tools
    5. Policy Filtering: Tools filtered by profile, provider, agent, group, sandbox policies
    6. Schema Normalization: Schemas cleaned for Gemini/OpenAI quirks
    7. AbortSignal Wrapping: Tools wrapped to respect abort signals

    Tool definition adapter

    pi-agent-core's

    text
    AgentTool
    has a different
    text
    execute
    signature than pi-coding-agent's
    text
    ToolDefinition
    . The adapter in
    text
    pi-tool-definition-adapter.ts
    bridges this:

    typescript
    export function toToolDefinitions(tools: AnyAgentTool[]): ToolDefinition[] { return tools.map((tool) => ({ name: tool.name, label: tool.label ?? name, description: tool.description ?? "", parameters: tool.parameters, execute: async (toolCallId, params, onUpdate, _ctx, signal) => { // pi-coding-agent signature differs from pi-agent-core return await tool.execute(toolCallId, params, signal, onUpdate); }, })); }

    Tool split strategy

    text
    splitSdkTools()
    passes all tools via
    text
    customTools
    :

    typescript
    export function splitSdkTools(options: { tools: AnyAgentTool[]; sandboxEnabled: boolean }) { return { builtInTools: [], // Empty. We override everything customTools: toToolDefinitions(options.tools), }; }

    This ensures OpenClaw's policy filtering, sandbox integration, and extended toolset remain consistent across providers.

    System prompt construction

    The system prompt is built in

    text
    buildAgentSystemPrompt()
    (
    text
    system-prompt.ts
    ). It assembles a full prompt with sections including Tooling, Tool Call Style, Safety guardrails, OpenClaw CLI reference, Skills, Docs, Workspace, Sandbox, Messaging, Reply Tags, Voice, Silent Replies, Heartbeats, Runtime metadata, plus Memory and Reactions when enabled, and optional context files and extra system prompt content. Sections are trimmed for minimal prompt mode used by subagents.

    The prompt is applied after session creation via

    text
    applySystemPromptOverrideToSession()
    :

    typescript
    const systemPromptOverride = createSystemPromptOverride(appendPrompt); applySystemPromptOverrideToSession(session, systemPromptOverride);

    Session management

    Session files

    Sessions are JSONL files with tree structure (id/parentId linking). Pi's

    text
    SessionManager
    handles persistence:

    typescript
    const sessionManager = SessionManager.open(params.sessionFile);

    OpenClaw wraps this with

    text
    guardSessionManager()
    for tool result safety.

    Session caching

    text
    session-manager-cache.ts
    caches SessionManager instances to avoid repeated file parsing:

    typescript
    await prewarmSessionFile(params.sessionFile); sessionManager = SessionManager.open(params.sessionFile); trackSessionManagerAccess(params.sessionFile);

    History limiting

    text
    limitHistoryTurns()
    trims conversation history based on channel type (DM vs group).

    Compaction

    Auto-compaction triggers on context overflow. Common overflow signatures include

    text
    request_too_large
    ,
    text
    context length exceeded
    ,
    text
    input exceeds the maximum number of tokens
    ,
    text
    input token count exceeds the maximum number of input tokens
    ,
    text
    input is too long for the model
    , and
    text
    ollama error: context length exceeded
    .
    text
    compactEmbeddedPiSessionDirect()
    handles manual compaction:

    typescript
    const compactResult = await compactEmbeddedPiSessionDirect({ sessionId, sessionFile, provider, model, ... });

    Authentication & Model Resolution

    Auth profiles

    OpenClaw maintains an auth profile store with multiple API keys per provider:

    typescript
    const authStore = ensureAuthProfileStore(agentDir, { allowKeychainPrompt: false }); const profileOrder = resolveAuthProfileOrder({ cfg, store: authStore, provider, preferredProfile });

    Profiles rotate on failures with cooldown tracking:

    typescript
    await markAuthProfileFailure({ store, profileId, reason, cfg, agentDir }); const rotated = await advanceAuthProfile();

    Model resolution

    typescript
    import { resolveModel } from "./pi-embedded-runner/model.js"; const { model, error, authStorage, modelRegistry } = resolveModel( provider, modelId, agentDir, config, ); // Uses pi's ModelRegistry and AuthStorage authStorage.setRuntimeApiKey(model.provider, apiKeyInfo.apiKey);

    Failover

    text
    FailoverError
    triggers model fallback when configured:

    typescript
    if (fallbackConfigured && isFailoverErrorMessage(errorText)) { throw new FailoverError(errorText, { reason: promptFailoverReason ?? "unknown", provider, model: modelId, profileId, status: resolveFailoverStatus(promptFailoverReason), }); }

    Pi extensions

    OpenClaw loads custom pi extensions for specialized behavior:

    Compaction safeguard

    text
    src/agents/pi-hooks/compaction-safeguard.ts
    adds guardrails to compaction, including adaptive token budgeting plus tool failure and file operation summaries:

    typescript
    if (resolveCompactionMode(params.cfg) === "safeguard") { setCompactionSafeguardRuntime(params.sessionManager, { maxHistoryShare }); paths.push(resolvePiExtensionPath("compaction-safeguard")); }

    Context pruning

    text
    src/agents/pi-hooks/context-pruning.ts
    implements cache-TTL based context pruning:

    typescript
    if (cfg?.agents?.defaults?.contextPruning?.mode === "cache-ttl") { setContextPruningRuntime(params.sessionManager, { settings, contextWindowTokens, isToolPrunable, lastCacheTouchAt, }); paths.push(resolvePiExtensionPath("context-pruning")); }

    Streaming & Block Replies

    Block chunking

    text
    EmbeddedBlockChunker
    manages streaming text into discrete reply blocks:

    typescript
    const blockChunker = blockChunking ? new EmbeddedBlockChunker(blockChunking) : null;

    Thinking/Final Tag Stripping

    Streaming output is processed to strip

    text
    <think>
    /
    text
    <thinking>
    blocks and extract
    text
    <final>
    content:

    typescript
    const stripBlockTags = (text: string, state: { thinking: boolean; final: boolean }) => { // Strip <think>...</think> content // If enforceFinalTag, only return <final>...</final> content };

    Reply directives

    Reply directives like

    text
    [[media:url]]
    ,
    text
    [[voice]]
    ,
    text
    [[reply:id]]
    are parsed and extracted:

    typescript
    const { text: cleanedText, mediaUrls, audioAsVoice, replyToId } = consumeReplyDirectives(chunk);

    Error handling

    Error classification

    text
    pi-embedded-helpers.ts
    classifies errors for appropriate handling:

    typescript
    isContextOverflowError(errorText) // Context too large isCompactionFailureError(errorText) // Compaction failed isAuthAssistantError(lastAssistant) // Auth failure isRateLimitAssistantError(...) // Rate limited isFailoverAssistantError(...) // Should failover classifyFailoverReason(errorText) // "auth" | "rate_limit" | "quota" | "timeout" | ...

    Thinking level fallback

    If a thinking level is unsupported, it falls back:

    typescript
    const fallbackThinking = pickFallbackThinkingLevel({ message: errorText, attempted: attemptedThinking, }); if (fallbackThinking) { thinkLevel = fallbackThinking; continue; }

    Sandbox integration

    When sandbox mode is enabled, tools and paths are constrained:

    typescript
    const sandbox = await resolveSandboxContext({ config: params.config, sessionKey: sandboxSessionKey, workspaceDir: resolvedWorkspace, }); if (sandboxRoot) { // Use sandboxed read/edit/write tools // Exec runs in container // Browser uses bridge URL }

    Provider-Specific Handling

    Anthropic

    • Refusal magic string scrubbing
    • Turn validation for consecutive roles
    • Strict upstream Pi tool parameter validation

    Google/Gemini

    • Plugin-owned tool schema sanitization

    OpenAI

    • text
      apply_patch
      tool for Codex models
    • Thinking level downgrade handling

    TUI Integration

    OpenClaw also has a local TUI mode that uses pi-tui components directly:

    typescript
    // src/tui/tui.ts import { ... } from "@mariozechner/pi-tui";

    This provides the interactive terminal experience similar to pi's native mode.

    Key differences from Pi CLI

    AspectPi CLIOpenClaw Embedded
    Invocation
    text
    pi
    command / RPC
    SDK via
    text
    createAgentSession()
    ToolsDefault coding toolsCustom OpenClaw tool suite
    System promptAGENTS.md + promptsDynamic per-channel/context
    Session storage
    text
    ~/.pi/agent/sessions/
    text
    ~/.openclaw/agents/<agentId>/sessions/
    (or
    text
    $OPENCLAW_STATE_DIR/agents/<agentId>/sessions/
    )
    AuthSingle credentialMulti-profile with rotation
    ExtensionsLoaded from diskProgrammatic + disk paths
    Event handlingTUI renderingCallback-based (onBlockReply, etc.)

    Future considerations

    Areas for potential rework:

    1. Tool signature alignment: Currently adapting between pi-agent-core and pi-coding-agent signatures
    2. Session manager wrapping:
      text
      guardSessionManager
      adds safety but increases complexity
    3. Extension loading: Could use pi's
      text
      ResourceLoader
      more directly
    4. Streaming handler complexity:
      text
      subscribeEmbeddedPiSession
      has grown large
    5. Provider quirks: Many provider-specific codepaths that pi could potentially handle

    Tests

    Pi integration coverage spans these suites:

    • text
      src/agents/pi-*.test.ts
    • text
      src/agents/pi-auth-json.test.ts
    • text
      src/agents/pi-embedded-*.test.ts
    • text
      src/agents/pi-embedded-helpers*.test.ts
    • text
      src/agents/pi-embedded-runner*.test.ts
    • text
      src/agents/pi-embedded-runner/**/*.test.ts
    • text
      src/agents/pi-embedded-subscribe*.test.ts
    • text
      src/agents/pi-tools*.test.ts
    • text
      src/agents/pi-tool-definition-adapter*.test.ts
    • text
      src/agents/pi-settings.test.ts
    • text
      src/agents/pi-hooks/**/*.test.ts

    Live/opt-in:

    • text
      src/agents/pi-embedded-runner-extraparams.live.test.ts
      (enable
      text
      OPENCLAW_LIVE_TEST=1
      )

    For current run commands, see Pi Development Workflow.

    Related

    • Pi development workflow
    • Install overview

    © 2024 TaskFlow Mirror

    Powered by TaskFlow Sync Engine