aller au contenu
FRFlo
Table des matières

The rise of LLM-driven (Large Language Models) coding assistants has profoundly altered how we design, prototype, and maintain software. Yet, most solutions on the market (IDE extensions, proprietary closed-sandbox apps, or naive CLI tools) impose major trade-offs: ephemeral contexts that vanish when a session ends, blocking sequential execution, an inability to interact asynchronously with external systems, and zero guardrails over executed shell commands.

To overcome these constraints, I built a tailored ecosystem centered around Pi Coding Agent (@earendil-works/pi-coding-agent), a modular and extensible coding agent written in TypeScript.

This stack goes far beyond running simple bash commands or editing text files. It embeds a dual-model SQLite persistent memory engine, an asynchronous multiplexed subagent system capable of operating in parallel without blocking the main event loop, a bidirectional real-time Discord bridge for remote mobile orchestration, an advanced MCP gateway tied into my Zero Trust infrastructure, proactive system command safety, and an Antigravity provider harnessing state-of-the-art reasoning models (thinking models) and image generation.

Here is the complete technical deep dive into this architecture.


Architecture Overview

The overall architecture of my Pi stack is structured in interconnected layers, enforcing a strict separation of concerns between orchestration runtime, domain extensions, storage engines, and external interfaces:

flowchart TB
    subgraph UI["User Interfaces & Remote Control"]
        TUI["Pi TUI (Interactive Terminal)"]
        Discord["Discord Mobile / Desktop<br>Interactive Buttons & Webhooks"]
    end

    subgraph Runtime["Pi Coding Agent Core (TypeScript / Node.js)"]
        Core["Pi Orchestrator & State Machine"]
        ExtLoader["Extension & Package Loader"]
        ToolManager["Tool Registry & Guardrails"]
    end

    subgraph LLMProviders["LLM & Provider Layer"]
        Antigravity["pi-antigravity (OAuth Google Cloud Code)<br>Gemini 3.7 Flash Thinking / Pro"]
        Quotas["pi-quotas (Rate Limits & Token Trackers)"]
    end

    subgraph Parallelism["Parallel Execution & Multiplexing"]
        Subagents["interactive-subagents (tmux / psmux)<br>Autonomous Panes & Steer Callbacks"]
        PTYManager["terminal manager (Persistent PTY)<br>Background Sessions & Regex Monitor"]
    end

    subgraph MemoryLayer["Long-Term Persistent Memory"]
        SQLiteDB[("observational-memory.sqlite<br>Branch Ledger & Compaction")]
        Observer["Observer Model (Headless Pi)<br>Atomic Observation Extraction"]
        Consolidator["Consolidator Model<br>Thematic Indexing in .memory/"]
    end

    subgraph SecurityExt["Security & Local Tooling"]
        BashGuard["bash-guard (L7 Interception & Confirmation)"]
        MoveTool["move-tool (AST Relocation & Rollback)"]
        TodoTool["pi-todotools (Phased State Machine)"]
        SearchTools["pi-web-search & Gemini URL Context"]
    end

    subgraph MCPLayer["MCP Gateway (pi-mcp-adapter)"]
        MCPEngine["MCP Client Gateway & mcpScript Runtime"]
        CFAPI["Cloudflare API & Browser MCP"]
        Context7["Context7 (Real-time Docs)"]
        GrepApp["Grep.app (GitHub Code Search)"]
        GitHubMCP["GitHub Copilot MCP (OAuth)"]
    end

    UI <--> Runtime
    Runtime --> LLMProviders
    Runtime --> Parallelism
    Runtime --> MemoryLayer
    Runtime --> SecurityExt
    Runtime --> MCPLayer
    Discord <-->|"pi-bridge (HTTPS / Webhooks)"| Runtime

1. The Model Engine: pi-antigravity & pi-quotas

The foundation of any coding agent lies in the quality of its language models and the resilience of its API transport layer.

pi-antigravity: Google Cloud Code Integration

Rather than relying on generic public APIs burdened with strict rate limits, I use the pi-antigravity extension (updated to v0.7.1). This provider implements direct OAuth authentication with Google Antigravity / Cloud Code internal services.

{
"defaultProvider": "antigravity",
"defaultModel": "gemini-3.7-flash",
"packages": [
"npm:pi-antigravity",
"npm:pi-mcp-adapter",
"git:github.com/FRFlo/pi-quotas",
"git:github.com/FRFlo/pi-web-search"
]
}

This integration delivers several crucial benefits:

  1. Native Access to Thinking Models: First-class support for gemini-3.7-flash and gemini-3-pro with fine-grained thinking levels (off, low, medium, high, max).
  2. Built-in Image Generation (generate_image): Ability for the agent to design UI mockups, visual assets, or architecture diagrams directly using Imagen / Gemini without breaking the development loop.
  3. Automated OAuth Token Lifecycle: Seamless credential renewal without requiring manual API keys scattered across shell environment variables.

pi-quotas: Real-Time Consumption & Limit Tracking

Custom-built for my setup, pi-quotas hooks into Pi’s lifecycle events to inspect response headers, token counters, and remaining rate limits per model in real time. It enables predictive throttling to avoid hitting walls during intensive multi-file refactoring runs.


2. Long-Term Persistent Memory: observational-memory

One of the most persistent hurdles with AI coding agents is context amnesia: as discussions grow, the context window saturates, triggering either destructive truncation or crude summarization that drops subtle architectural choices.

To address this deterministically, my stack integrates Observational Memory, a hierarchical memory architecture backed by SQLite.

flowchart LR
    A["Conversation Chunks<br/><i>Token-based windows</i>"] --> B["Parallel Observers<br/><i>Headless pi instances</i>"]
    B --> C["Atomic Observations<br/><i>{timestamp, content, context}</i>"]
    C --> D["SQLite Master Ledger<br/><i>observational-memory.sqlite</i>"]
    D --> E["Deterministic Compaction<br/><i>Zero-LLM call (no hallucinations)</i>"]
    D --> F["Consolidator Model<br/><i>Dedicated gemini-3.7-flash</i>"]
    F --> G[".memory/&lt;session&gt;/&lt;topic&gt;.md<br/><i>Persistent Markdown files</i>"]

How the Dual-Model (Observer / Consolidator) Architecture Works

  1. The Observer (Asynchronous Observer): In the background, lightweight sub-processes analyze recent dialogue chunks to pull out atomic observations (facts, user preferences, design decisions, bug fixes).
  2. The SQLite Master Ledger: Every observation is committed to a local SQLite database (observational-memory.sqlite). This table structure maps directly to Pi’s session tree (/tree), guaranteeing that if a session branches or rolls back, memory mirrors the active branch.
  3. Deterministic Compaction: Unlike traditional setups where an LLM rewrites the prompt (risking hallucination or data loss), Pi’s compaction compiles validated observations directly into the system context.
  4. The Consolidator (Thematic Topic Archiving): Periodically, the consolidator model clusters older observations into organized Markdown documents inside .memory/<sessionId>/. These documents are easily searchable through fast text retrieval.

3. Asynchronous Subagent Multiplexing: interactive-subagents

Complex engineering tasks frequently demand multiple parallel workstreams: scouring API docs, auditing build logs, running non-regression test suites, and authoring feature code.

The interactive-subagents extension enables spinning up auxiliary agents with complete autonomy without stalling the primary agent.

╭─ Subagents ──────────────────────────── 2 running ─╮
│ 00:23 scout active · bash 7m │
│ 00:45 worker-1 waiting 2m │
╰────────────────────────────────────────────────────╯

Technical Mechanics: tmux / psmux Multiplexing

  • Non-blocking Spawning: Spawning a subagent (subagent({ agent: "scout", task: "..." })) allocates an isolated multiplexer pane (tmux on Linux/macOS, psmux on Windows).
  • Zero Polling Loops: The primary agent never runs sleep loops or polls temporary files. When the subagent completes its job, the Pi harness catches the process exit and injects an asynchronous steer event, instantly waking up the main loop.
  • Bidirectional Steering: The primary agent can issue follow-up instructions to an in-flight subagent or revive a finished session using subagent_message.

4. Remote Supervision & Real-Time Discord Mobile Bridge

To stay in full control during long autonomous tasks while away from my workstation, the stack incorporates a real-time bidirectional Discord bridge.

sequenceDiagram
    participant Pi as Pi Coding Agent
    participant Bridge as pi-bridge (API)
    participant Discord as Discord Client (Mobile/Web)

    Pi->>Bridge: POST /ask (Question + Options + Context)
    Bridge->>Discord: Embed Message + ActionRow Buttons
    Note over Discord: User taps an option<br/>or types a custom reply
    Discord->>Bridge: Webhook Interaction (Button Click / Modal)
    Bridge-->>Pi: HTTP Response Resolved (Chosen Option / Text)
    Pi->>Pi: Resumes Execution Flow Immediately

The ask-user-question Tool & Reactive TUI

Whenever an architectural fork or permission check arises, ask_user_question adapts to the current environment:

  1. Interactive TUI Mode: In the terminal, it renders an ANSI keyboard-navigable list (arrow keys, spacebar for multi-select, custom text prompt).
  2. Instant Discord Sync: Concurrently, the payload is forwarded to the pi-bridge service, rendering interactive buttons in a designated Discord channel. Whether I click a button on my phone or select an option in my terminal, the execution loop unblocks immediately.
  3. Proactive Progress Broadcasts (send_discord_message): Build completions, deployment summaries, and test failures are pushed with rich Discord markdown formatting.

5. Persistent PTY Terminal & Proactive Security: terminal & bash-guard

Letting an autonomous agent run arbitrary shell commands on a development machine carries inherent risks: accidental destructive operations, orphaned background processes, and unconstrained resource consumption.

Persistent PTY Management & the monitor Pattern

The terminal extension equips Pi with full pseudo-terminal session management:

  • Background Processes: Long-running dev servers, docker compose services, or heavy builds run without blocking the REPL.
  • Event-Driven Subscriptions (monitor): Instead of actively polling output logs, the agent subscribes to regex patterns (e.g. READY, Compiled successfully, ERROR), waking up only when the pattern matches or the process exits.
  • Interactive REPL Steering: Real-time keystroke and signal injection (ctrl+c, bash_input, bash_resize).

bash-guard: L7 Proactive Security Interceptor

To guard against costly typos or unintended commands, every shell execution passes through bash-guard:

  • Syntax Inspection: Detects high-risk patterns (rm -rf /, raw disk writes, unvetted privilege escalations).
  • Confirmation Floor: Whenever a command crosses safety thresholds, it pauses execution and demands explicit user confirmation (via TUI or Discord).

6. The MCP Gateway (pi-mcp-adapter): Core Tool Hierarchy

The MCP (Model Context Protocol) standard lets the agent interact directly with external platforms. Through pi-mcp-adapter, Pi interfaces with a fleet of local and remote MCP servers.

Not all MCP servers play the same role in the daily workflow: some form essential operational pillars, while others are engaged for specialized tasks.

{
"mcpServers": {
"cloudflare-browser": {
"url": "https://browser.mcp.cloudflare.com/mcp",
"directTools": true
},
"context7": {
"url": "https://mcp.context7.com/mcp",
"directTools": true
},
"grep_app": {
"url": "https://mcp.grep.app",
"directTools": true
},
"cloudflare-api": {
"url": "https://mcp.cloudflare.com/mcp",
"directTools": true
},
"github": {
"url": "https://api.githubcopilot.com/mcp",
"auth": "oauth"
},
"posthog": {
"url": "https://mcp.posthog.com/mcp"
}
}
}

1. cloudflare-browser: Visual Web Access & Headless Scraping (Top Priority)

This is one of the most critical MCPs in the entire stack. Unlike a simple curl or text fetch that falls flat on dynamic JavaScript applications, cloudflare-browser drives a remote Chromium instance hosted on Cloudflare’s Edge:

  • Full SPA & Dynamic Page Rendering: Instant conversion of modern web apps into clean Markdown (get_url_markdown) or raw DOM trees (get_url_html_content).
  • Structured JSON Extraction (get_url_json): Schema-driven extraction powered by AI directly from web pages using natural language prompts.
  • Asynchronous Web Crawls (start_crawl / get_crawl_result): Recursive background crawls across entire documentation hubs.

2. context7: Up-to-Date Official Framework Docs

Pre-trained LLM weights naturally freeze at their training cutoff and frequently hallucinate newer APIs or major framework redesigns. context7 bridges this gap:

  • Accurate Library Resolution (context7_resolve-library-id): Maps package identifiers to exact library versions.
  • Concept-Scoped Docs Querying (context7_query-docs): Pulls official, verified code samples and current documentation chunks directly into context.

3. grep_app: Searching Real-World Code Across GitHub

Official guides often stop at simplified “hello world” demos. grep_app gives the agent direct visibility into how production codebases use libraries in the wild:

  • Literal Pattern & Regular Expression Searches (grep_app_searchGitHub) indexing over one million public repositories.
  • Pattern Verification: Validates function signatures, real-world error handling patterns, advanced TypeScript configurations, and multi-library interop.

4. Infrastructure & Ecosystem MCPs

  • cloudflare-api: OpenAPI spec lookups and execution across Workers, D1 databases, KV namespaces, R2 buckets, DNS, and WAF rulesets.
  • github & posthog: Dedicated connectors for GitHub Copilot endpoints and analytics telemetry.

The mcpScript Batching Engine

To minimize token churn and round-trip latency during multi-step tool calls, pi-mcp-adapter provides mcpScript. It allows the agent to author and execute trusted JavaScript that chains multiple MCP calls (filtering, loops, fan-outs) in a single request, eliminating costly conversational ping-pongs.


7. Specialized Tooling: Refactoring, Tasks & Context

Alongside the core extensions, the stack incorporates several purpose-built utilities:

Package / Module Role & Key Features
move-tool Safely relocates code blocks between files with automated indentation adjustment, preview dry_run, and instant rollback.
pi-todotools Phased deterministic task tracker backed by a state machine (Foundation, Implementation, Verification).
pi-nested-agents-md Recursively detects local AGENTS.md and CLAUDE.md context files to adapt behaviors dynamically per folder.
pi-apply-patch Surgical application of unified Git patches.

8. Specialized Skill System

Skills deliver modular sets of domain-specific guidelines and checklists loaded dynamically based on project requirements:

  • Cloudflare Architecture: cloudflare, wrangler, durable-objects, agents-sdk, sandbox-sdk, cloudflare-one.
  • Design Engineering & UI/UX: impeccable (visual hierarchy, accessibility, typographic scale), make-interfaces-feel-better (physics, transitions, micro-interactions), responsive-craft.
  • Code Quality Guidelines: karpathy-guidelines (averting LLM overcomplication, surgical changes, verifiable test gates).
  • Performance & Debugging: web-perf (Core Web Vitals), web-debug (live Playwright DOM & network tracing).

Daily Workflow & Engineering Impact

Integrating these components into a single coherent system transforms daily development:

  1. Mission Initialization: Starting a Pi session in a codebase prompts pi-nested-agents-md to load project rules, while todo lays out a structured roadmap.
  2. Exploration & Concurrency: While the main agent tackles core logic, a background scout subagent is spawned to investigate real-world usage on grep_app or query context7 for docs.
  3. Safety & Mobile Steering: If a high-stakes decision or sensitive shell command is reached while I am away, an interactive notification pings Discord. A single tap confirms the operation and the agent proceeds.
  4. Cognitive Persistence: Through observational-memory, key learnings (resolved edge cases, library quirks, API conventions) are committed to SQLite, continuously refining future sessions.

Conclusion

The true leverage of an AI coding agent does not hinge solely on the parameter count of the foundational LLM, but on the depth, responsiveness, and safety of its execution environment.

By unifying deterministic persistent memory, asynchronous concurrency, a Zero Trust MCP gateway, multi-channel interactivity (TUI + Discord), and proactive guardrails, this stack elevates Pi into a genuine autonomous engineering partner built for production software development.