# **pi‑ai in Mode for Process Integration: A Complete Guide to RPC-Based Agent Embedding**

> Learn how to integrate processes with pi-ai in RPC mode for seamless agent embedding. This complete guide covers everything you need to know. Get started today.

- Repository: [Mario Zechner/pi-mono](https://github.com/badlogic/pi-mono)
- Tags: how-to-guide
- Published: 2026-02-16

---

**pi‑ai in Mode for Process Integration: A Complete Guide to RPC-Based Agent Embedding**

When building applications that need to harness the power of AI coding agents programmatically, **pi‑ai in mode for process integration** offers a robust solution through its RPC (Remote Procedure Call) interface. This capability transforms the CLI tool into an embeddable engine that communicates via structured JSON-lines, enabling seamless integration into Node.js applications, custom TUIs, testing frameworks, or any external system requiring automated code generation capabilities.

## Understanding pi‑ai RPC Mode Architecture

The **pi‑ai in mode for process integration** architecture revolves around a parent-child process relationship where the CLI runs as a spawned subprocess. This design decouples the AI agent's execution from your main application while maintaining real-time bidirectional communication through stdin and stdout streams.

| Component | Responsibility | Source Location |
|-----------|---------------|-----------------|
| **CLI entry point** | Parses `--mode rpc`, initializes the agent loop, and manages JSON event streaming to stdout / command ingestion from stdin | [`packages/coding-agent/src/main.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/main.ts) |
| **RPC protocol definition** | Defines all available commands (`prompt`, `steer`, `set_model`), response shapes, and extension UI request types | [`packages/coding-agent/src/modes/rpc/rpc-types.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/rpc/rpc-types.ts) |
| **RPC client library** | Spawns the child process, serializes commands, matches responses using request IDs, buffers events, and exposes typed async methods | [`packages/coding-agent/src/modes/rpc/rpc-client.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/rpc/rpc-client.ts) |
| **Argument parsing** | Recognizes `--mode rpc` and forwards provider flags (`--provider`, `--model`) to the subprocess | [`packages/coding-agent/src/cli/args.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/cli/args.ts) |
| **Reference implementation** | Demonstrates TUI integration using `RpcClient` to drive agent interactions | [`packages/coding-agent/examples/rpc-extension-ui.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/examples/rpc-extension-ui.ts) |

### Data Flow in pi‑ai RPC Mode

The **pi‑ai in mode for process integration** protocol follows a precise request-response lifecycle:

1. The parent process instantiates `RpcClient` and calls `start()`, which spawns `node <dist/cli.js> --mode rpc`
2. The child process writes agent events (such as `assistant_start`, `assistant_message`, `tool_call`) as JSON lines to **stdout**
3. The child reads JSON commands (like `{type:"prompt", message:"...", id:"req_1"}`) from **stdin**
4. `RpcClient` parses each line: matching `response` objects resolve pending promises via incrementing request IDs (`req_1`, `req_2`, etc.), while other events route to `onEvent` listeners
5. Each request enforces a **30-second timeout** with exact-once delivery guarantees

## Implementing pi‑ai in Mode for Process Integration

### Basic Node.js Script Implementation

For developers embedding **pi‑ai in mode for process integration** without graphical interfaces, the `RpcClient` class provides immediate API access:

```

import { RpcClient } from "@mariozechner/pi-ai";

async function main() {
  const client = new RpcClient({
    cliPath: "dist/cli.js",
    provider: "openai",
    model: "gpt-4o-mini"
  });

  await client.start();

  // Subscribe to streaming agent events
  const unsubscribe = client.onEvent((ev) => {
    console.log("EVENT →", ev);
  });

  // Execute prompt and await completion
  await client.prompt("Write a TypeScript function that adds two numbers.");
  await client.waitForIdle();

  // Retrieve final execution state
  const state = await client.getState();
  console.log("FINAL STATE →", state);

  unsubscribe();
  await client.stop();
}

main().catch((e) => {
  console.error("RPC error:", e);
  process.exit(1);
});

```

Key implementation details for **pi‑ai in mode for process integration**:
- `RpcClient.start()` launches the agent subprocess with `--mode rpc`
- `client.prompt()` returns immediately while streaming output arrives via `onEvent`
- `client.waitForIdle()` resolves upon receiving the `agent_end` event

### Custom TUI Integration

For applications requiring visual interfaces, **pi‑ai in mode for process integration** supports sophisticated UI bindings:

```

import { RpcClient } from "@mariozechner/pi-ai";
import { TUI, Input, Container, ProcessTerminal } from "@mariozechner/pi-tui";

async function runTui() {
  const client = new RpcClient({ model: "claude-3-5-sonnet" });
  await client.start();

  const tui = new TUI();
  const output = new ProcessTerminal();
  const input = new Input();

  client.onEvent((ev) => output.write(JSON.stringify(ev) + "\n"));

  input.onSubmit = async (msg) => {
    await client.prompt(msg);
    await client.waitForIdle();
    input.clear();
  };

  const root = new Container([output, input]);
  tui.setRoot(root);
  await tui.run();
}

runTui().catch(console.error);

```

This pattern from [`packages/coding-agent/examples/rpc-extension-ui.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/examples/rpc-extension-ui.ts) demonstrates bridging UI components to the RPC client for real-time agent visualization.

### Handling Extension UI Requests

Advanced **pi‑ai in mode for process integration** implementations can programmatically respond to UI interaction requests:

```

client.onEvent((ev) => {
  if (ev.type === "extension_ui_request") {
    if (ev.method === "confirm") {
      client.send({ 
        type: "extension_ui_response", 
        id: ev.id, 
        confirmed: true 
      });
    }
  }
});

```

The `RpcExtensionUIRequest` and `RpcExtensionUIResponse` types in [`rpc-types.ts`](https://github.com/badlogic/pi-mono/blob/main/rpc-types.ts) define all possible interaction patterns for automated confirmation workflows.

## Essential Files for pi‑ai RPC Development

| File | Purpose | Direct Link |
|------|---------|-----------|
| [`packages/coding-agent/src/modes/rpc/rpc-types.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/rpc/rpc-types.ts) | Complete protocol specification including commands, responses, events, and UI requests | [View Source](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/rpc/rpc-types.ts) |
| [`packages/coding-agent/src/modes/rpc/rpc-client.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/rpc/rpc-client.ts) | Production-ready client implementing request/response matching and event streaming | [View Source](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/modes/rpc/rpc-client.ts) |
| [`packages/coding-agent/src/cli/args.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/cli/args.ts) | CLI argument parser supporting `--mode rpc` and provider configuration | [View Source](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/cli/args.ts) |
| [`packages/coding-agent/src/main.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/main.ts) | Application entry point switching to stream-based JSON line mode when RPC flag present | [View Source](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/src/main.ts) |
| [`packages/coding-agent/examples/rpc-extension-ui.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/examples/rpc-extension-ui.ts) | Working TUI example serving as integration reference | [View Source](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/examples/rpc-extension-ui.ts) |
| [`packages/ai/src/index.ts`](https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/index.ts) | Public API exports making `RpcClient` available via `@mariozechner/pi-ai` | [View Source](https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/index.ts) |

## Conclusion

**pi‑ai in mode for process integration** provides a type-safe, provider-agnostic mechanism for embedding full-featured AI coding agents into any JavaScript runtime environment. By leveraging structured JSON-lines communication through `RpcClient`, developers can orchestrate complex agent workflows across OpenAI, Anthropic, and Google models while maintaining precise control over execution flow, event streaming, and state management.