Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(agent): add Pi agent runtime support (#1064)

Bohan Jiang8c518c350ad5
diff --git a/CLI_INSTALL.md b/CLI_INSTALL.md
index 3207b6c068..5d080b4ce9 100644
--- a/CLI_INSTALL.md
+++ b/CLI_INSTALL.md
@@ -165,12 +165,12 @@ Wait 3 seconds, then verify:
multica daemon status
```
-Expected output should show `running` status with detected agents (e.g. `claude`, `codex`, `opencode`, `openclaw`, `hermes`).
+Expected output should show `running` status with detected agents (e.g. `claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, `pi`).
**If daemon fails to start:**
- Check logs: `multica daemon logs`
- If a port conflict occurs, the daemon may already be running under a different profile.
-- If no agents are detected, ensure at least one AI CLI (`claude`, `codex`, `opencode`, `openclaw`, or `hermes`) is installed and on the `$PATH`.
+- If no agents are detected, ensure at least one AI CLI (`claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, or `pi`) is installed and on the `$PATH`.
---
@@ -184,12 +184,12 @@ multica daemon status
Confirm:
1. Status is `running`
-2. At least one agent is listed (e.g. `claude`, `codex`, `opencode`, `openclaw`, or `hermes`)
+2. At least one agent is listed (e.g. `claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, or `pi`)
3. At least one workspace is being watched
If the agents list is empty, tell the user:
-> "The Multica daemon is running but no AI agent CLIs were detected. Please install at least one supported CLI (`claude`, `codex`, `opencode`, `openclaw`, or `hermes`), then restart the daemon with `multica daemon stop && multica daemon start`."
+> "The Multica daemon is running but no AI agent CLIs were detected. Please install at least one supported CLI (`claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, or `pi`), then restart the daemon with `multica daemon stop && multica daemon start`."
---
diff --git a/README.md b/README.md
index bab5000da5..2e4773b490 100644
--- a/README.md
+++ b/README.md
@@ -97,7 +97,7 @@ multica setup # Connect to Multica Cloud, log in, start daemon
multica setup # Configure, authenticate, and start the daemon
```
-The daemon runs in the background and auto-detects agent CLIs (`claude`, `codex`, `openclaw`, `opencode`) on your PATH.
+The daemon runs in the background and auto-detects agent CLIs (`claude`, `codex`, `openclaw`, `opencode`, `hermes`, `gemini`, `pi`) on your PATH.
### 2. Verify your runtime
diff --git a/README.zh-CN.md b/README.zh-CN.md
index e82623a549..a3239084f5 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -99,7 +99,7 @@ multica setup # 连接 Multica Cloud,登录,启动 daemon
multica setup # 配置、认证、启动 daemon(一条命令搞定)
```
-daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动检测 PATH 中可用的 Agent CLI(`claude`、`codex`、`openclaw`、`opencode`)。
+daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动检测 PATH 中可用的 Agent CLI(`claude`、`codex`、`openclaw`、`opencode`、`hermes`、`gemini`、`pi`)。
### 2. 确认运行时已连接
diff --git a/apps/docs/content/docs/cli/installation.mdx b/apps/docs/content/docs/cli/installation.mdx
index 5f66e0e60c..d5df65adc1 100644
--- a/apps/docs/content/docs/cli/installation.mdx
+++ b/apps/docs/content/docs/cli/installation.mdx
@@ -78,7 +78,7 @@ multica daemon status
Confirm:
1. Status is `running`
-2. At least one agent is listed (e.g. `claude`, `codex`, `gemini`, `opencode`, `openclaw`, or `hermes`)
+2. At least one agent is listed (e.g. `claude`, `codex`, `gemini`, `opencode`, `openclaw`, `hermes`, or `pi`)
3. At least one workspace is being watched
If the agents list is empty, install at least one supported AI agent CLI:
diff --git a/apps/docs/content/docs/getting-started/cloud-quickstart.mdx b/apps/docs/content/docs/getting-started/cloud-quickstart.mdx
index 6df9526723..a4cca9f5a5 100644
--- a/apps/docs/content/docs/getting-started/cloud-quickstart.mdx
+++ b/apps/docs/content/docs/getting-started/cloud-quickstart.mdx
@@ -45,7 +45,7 @@ Then configure, authenticate, and start the daemon:
multica setup
```
-The daemon auto-detects available agent CLIs (`claude`, `codex`, `gemini`, `openclaw`, `opencode`, `hermes`) on your PATH. When an agent is assigned a task, the daemon creates an isolated environment, runs the agent, and reports results back.
+The daemon auto-detects available agent CLIs (`claude`, `codex`, `gemini`, `openclaw`, `opencode`, `hermes`, `pi`) on your PATH. When an agent is assigned a task, the daemon creates an isolated environment, runs the agent, and reports results back.
## 3. Verify your runtime
diff --git a/apps/docs/content/docs/guides/quickstart.mdx b/apps/docs/content/docs/guides/quickstart.mdx
index 646659a949..8fdfaf49ac 100644
--- a/apps/docs/content/docs/guides/quickstart.mdx
+++ b/apps/docs/content/docs/guides/quickstart.mdx
@@ -11,7 +11,7 @@ Once you have the CLI installed (or signed up for [Multica Cloud](https://multic
multica setup # Configure, authenticate, and start the daemon
```
-This configures the CLI, opens your browser for login, discovers your workspaces, and starts the agent daemon in the background. It auto-detects agent CLIs (`claude`, `codex`, `gemini`, `openclaw`, `opencode`, `hermes`) available on your PATH.
+This configures the CLI, opens your browser for login, discovers your workspaces, and starts the agent daemon in the background. It auto-detects agent CLIs (`claude`, `codex`, `gemini`, `openclaw`, `opencode`, `hermes`, `pi`) available on your PATH.
## 2. Verify your runtime
diff --git a/packages/views/issues/components/agent-transcript-dialog.tsx b/packages/views/issues/components/agent-transcript-dialog.tsx
index cc769d15b9..0ac191232a 100644
--- a/packages/views/issues/components/agent-transcript-dialog.tsx
+++ b/packages/views/issues/components/agent-transcript-dialog.tsx
@@ -422,6 +422,7 @@ function formatProvider(provider: string): string {
claude: "Claude Code",
"claude-code": "Claude Code",
codex: "Codex",
+ pi: "Pi",
};
return map[provider.toLowerCase()] ?? provider;
}
diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsx
index c184350168..36d1d9c918 100644
--- a/packages/views/runtimes/components/provider-logo.tsx
+++ b/packages/views/runtimes/components/provider-logo.tsx
@@ -73,6 +73,26 @@ function HermesLogo({ className }: { className: string }) {
);
}
+// Pi — Greek letter π mark, styled in Pi brand teal
+function PiLogo({ className }: { className: string }) {
+ return (
+ <svg viewBox="0 0 16 16" fill="none" className={className}>
+ <rect width="16" height="16" rx="3" fill="#0D9488" />
+ <text
+ x="8"
+ y="12.5"
+ textAnchor="middle"
+ fontFamily="serif"
+ fontSize="12"
+ fontWeight="bold"
+ fill="white"
+ >
+ π
+ </text>
+ </svg>
+ );
+}
+
export function ProviderLogo({
provider,
className = "h-4 w-4",
@@ -91,6 +111,8 @@ export function ProviderLogo({
return <OpenClawLogo className={className} />;
case "hermes":
return <HermesLogo className={className} />;
+ case "pi":
+ return <PiLogo className={className} />;
default:
return <Monitor className={className} />;
}
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index e66f4cecdf..cd1e5e9488 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -33,7 +33,7 @@ type Config struct {
CLIVersion string // multica CLI version (e.g. "0.1.13")
LaunchedBy string // "desktop" when spawned by the Electron app, empty for standalone
Profile string // profile name (empty = default)
- Agents map[string]AgentEntry // keyed by provider: claude, codex, opencode, openclaw, hermes, gemini
+ Agents map[string]AgentEntry // keyed by provider: claude, codex, opencode, openclaw, hermes, gemini, pi
WorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)
KeepEnvAfterTask bool // preserve env after task for debugging
HealthPort int // local HTTP port for health checks (default: 19514)
@@ -120,8 +120,15 @@ func LoadConfig(overrides Overrides) (Config, error) {
Model: strings.TrimSpace(os.Getenv("MULTICA_GEMINI_MODEL")),
}
}
+ piPath := envOrDefault("MULTICA_PI_PATH", "pi")
+ if _, err := exec.LookPath(piPath); err == nil {
+ agents["pi"] = AgentEntry{
+ Path: piPath,
+ Model: strings.TrimSpace(os.Getenv("MULTICA_PI_MODEL")),
+ }
+ }
if len(agents) == 0 {
- return Config{}, fmt.Errorf("no agent CLI found: install claude, codex, opencode, openclaw, hermes, or gemini and ensure it is on PATH")
+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codex, opencode, openclaw, hermes, gemini, or pi and ensure it is on PATH")
}
// Host info
diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.go
index f0bd453f52..5a9cf91c7f 100644
--- a/server/internal/daemon/execenv/context.go
+++ b/server/internal/daemon/execenv/context.go
@@ -14,6 +14,7 @@ import (
// Claude: skills → {workDir}/.claude/skills/{name}/SKILL.md (native discovery)
// Codex: skills → handled separately in Prepare via codex-home
// OpenCode: skills → {workDir}/.config/opencode/skills/{name}/SKILL.md (native discovery)
+// Pi: skills → {workDir}/.pi/agent/skills/{name}/SKILL.md (native discovery)
// Default: skills → {workDir}/.agent_context/skills/{name}/SKILL.md
func writeContextFiles(workDir, provider string, ctx TaskContextForEnv) error {
contextDir := filepath.Join(workDir, ".agent_context")
@@ -54,6 +55,9 @@ func resolveSkillsDir(workDir, provider string) (string, error) {
case "opencode":
// OpenCode natively discovers skills from .config/opencode/skills/ in the workdir.
skillsDir = filepath.Join(workDir, ".config", "opencode", "skills")
+ case "pi":
+ // Pi natively discovers skills from .pi/agent/skills/ in the workdir.
+ skillsDir = filepath.Join(workDir, ".pi", "agent", "skills")
default:
// Fallback: write to .agent_context/skills/ (referenced by meta config).
skillsDir = filepath.Join(workDir, ".agent_context", "skills")
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.go
index 3ac8bc7e87..c8a5542ff7 100644
--- a/server/internal/daemon/execenv/runtime_config.go
+++ b/server/internal/daemon/execenv/runtime_config.go
@@ -15,13 +15,14 @@ import (
// For OpenCode: writes {workDir}/AGENTS.md (skills discovered natively from .config/opencode/skills/)
// For OpenClaw: writes {workDir}/AGENTS.md (skills discovered natively from .openclaw/skills/)
// For Gemini: writes {workDir}/GEMINI.md (discovered natively by the Gemini CLI)
+// For Pi: writes {workDir}/AGENTS.md (skills discovered natively from ~/.pi/agent/skills/)
func InjectRuntimeConfig(workDir, provider string, ctx TaskContextForEnv) error {
content := buildMetaSkillContent(provider, ctx)
switch provider {
case "claude":
return os.WriteFile(filepath.Join(workDir, "CLAUDE.md"), []byte(content), 0o644)
- case "codex", "opencode", "openclaw":
+ case "codex", "opencode", "openclaw", "pi":
return os.WriteFile(filepath.Join(workDir, "AGENTS.md"), []byte(content), 0o644)
case "gemini":
return os.WriteFile(filepath.Join(workDir, "GEMINI.md"), []byte(content), 0o644)
@@ -140,8 +141,8 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {
case "claude":
// Claude discovers skills natively from .claude/skills/ — just list names.
b.WriteString("You have the following skills installed (discovered automatically):\n\n")
- case "codex", "opencode", "openclaw":
- // Codex, OpenCode, and OpenClaw discover skills natively from their respective paths — just list names.
+ case "codex", "opencode", "openclaw", "pi":
+ // Codex, OpenCode, OpenClaw, and Pi discover skills natively from their respective paths — just list names.
b.WriteString("You have the following skills installed (discovered automatically):\n\n")
case "gemini":
// Gemini reads GEMINI.md directly; point it at the fallback skills dir.
diff --git a/server/internal/daemon/usage/pi.go b/server/internal/daemon/usage/pi.go
new file mode 100644
index 0000000000..8aa9527fa4
--- /dev/null
+++ b/server/internal/daemon/usage/pi.go
@@ -0,0 +1,126 @@
+package usage
+
+import (
+ "bufio"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// scanPi reads Pi session JSONL logs produced by the multica daemon and
+// extracts token usage from assistant `message` events.
+//
+// The agent backend writes every run's session file into
+// ~/.multica/pi-sessions/ (see agent.PiSessionDir). Pi appends events to
+// the file as it runs; each assistant `message` event carries cumulative
+// usage for that turn in the shape:
+//
+// {"type":"message","timestamp":"...",
+// "message":{"role":"assistant","model":"...",
+// "usage":{"input":N,"output":N,"cacheRead":N,"cacheWrite":N,...}}}
+func (s *Scanner) scanPi() []Record {
+ root, err := agent.PiSessionDir()
+ if err != nil || root == "" {
+ return nil
+ }
+ if info, err := os.Stat(root); err != nil || !info.IsDir() {
+ return nil
+ }
+
+ files, err := filepath.Glob(filepath.Join(root, "*.jsonl"))
+ if err != nil {
+ s.logger.Debug("pi glob error", "error", err)
+ return nil
+ }
+
+ var records []Record
+ for _, f := range files {
+ records = append(records, s.parsePiFile(f)...)
+ }
+ return mergeRecords(records)
+}
+
+type piSessionLine struct {
+ Type string `json:"type"`
+ Timestamp string `json:"timestamp"`
+ Message *struct {
+ Role string `json:"role"`
+ Model string `json:"model"`
+ Usage *struct {
+ Input int64 `json:"input"`
+ Output int64 `json:"output"`
+ CacheRead int64 `json:"cacheRead"`
+ CacheWrite int64 `json:"cacheWrite"`
+ } `json:"usage"`
+ } `json:"message"`
+}
+
+// parsePiFile walks a single session file and emits one Record per
+// assistant message with non-zero usage. Each assistant message carries
+// the cost for that specific turn (not cumulative), so they can be
+// summed by mergeRecords downstream.
+func (s *Scanner) parsePiFile(path string) []Record {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil
+ }
+ defer f.Close()
+
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 256*1024), 8*1024*1024)
+
+ var records []Record
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if !bytesContains(line, `"usage"`) {
+ continue
+ }
+ var entry piSessionLine
+ if err := json.Unmarshal(line, &entry); err != nil {
+ continue
+ }
+ if entry.Type != "message" || entry.Message == nil || entry.Message.Usage == nil {
+ continue
+ }
+ if entry.Message.Role != "assistant" {
+ continue
+ }
+ u := entry.Message.Usage
+ if u.Input == 0 && u.Output == 0 && u.CacheRead == 0 && u.CacheWrite == 0 {
+ continue
+ }
+
+ date := ""
+ if entry.Timestamp != "" {
+ if ts, err := time.Parse(time.RFC3339Nano, entry.Timestamp); err == nil {
+ date = ts.Local().Format("2006-01-02")
+ }
+ }
+ if date == "" {
+ info, err := os.Stat(path)
+ if err != nil {
+ continue
+ }
+ date = info.ModTime().Local().Format("2006-01-02")
+ }
+
+ model := entry.Message.Model
+ if model == "" {
+ model = "unknown"
+ }
+
+ records = append(records, Record{
+ Date: date,
+ Provider: "pi",
+ Model: model,
+ InputTokens: u.Input,
+ OutputTokens: u.Output,
+ CacheReadTokens: u.CacheRead,
+ CacheWriteTokens: u.CacheWrite,
+ })
+ }
+ return records
+}
diff --git a/server/internal/daemon/usage/scanner.go b/server/internal/daemon/usage/scanner.go
index 50ce0ab0d5..52bac64667 100644
--- a/server/internal/daemon/usage/scanner.go
+++ b/server/internal/daemon/usage/scanner.go
@@ -27,7 +27,8 @@ func NewScanner(logger *slog.Logger) *Scanner {
// Scan reads local log files for all supported agent runtimes (Claude Code,
// Codex, OpenCode, OpenClaw, Hermes) and returns aggregated usage records
-// keyed by (date, provider, model).
+// keyed by (date, provider, model). Supports Claude Code, Codex, OpenCode,
+// OpenClaw, Hermes, and Pi.
func (s *Scanner) Scan() []Record {
var records []Record
@@ -46,6 +47,9 @@ func (s *Scanner) Scan() []Record {
hermesRecords := s.scanHermes()
records = append(records, hermesRecords...)
+ piRecords := s.scanPi()
+ records = append(records, piRecords...)
+
return records
}
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 9565e6abc5..99a9d1f7e0 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -1,5 +1,5 @@
// Package agent provides a unified interface for executing prompts via
-// coding agents (Claude Code, Codex, OpenCode, OpenClaw, Hermes). It mirrors the happy-cli AgentBackend
+// coding agents (Claude Code, Codex, OpenCode, OpenClaw, Hermes, Pi). It mirrors the happy-cli AgentBackend
// pattern, translated to idiomatic Go.
package agent
@@ -83,13 +83,13 @@ type Result struct {
// Config configures a Backend instance.
type Config struct {
- ExecutablePath string // path to CLI binary (claude, codex, opencode, openclaw, hermes, or gemini)
+ ExecutablePath string // path to CLI binary (claude, codex, opencode, openclaw, hermes, gemini, or pi)
Env map[string]string // extra environment variables
Logger *slog.Logger
}
// New creates a Backend for the given agent type.
-// Supported types: "claude", "codex", "opencode", "openclaw", "hermes", "gemini".
+// Supported types: "claude", "codex", "opencode", "openclaw", "hermes", "gemini", "pi".
func New(agentType string, cfg Config) (Backend, error) {
if cfg.Logger == nil {
cfg.Logger = slog.Default()
@@ -108,8 +108,10 @@ func New(agentType string, cfg Config) (Backend, error) {
return &hermesBackend{cfg: cfg}, nil
case "gemini":
return &geminiBackend{cfg: cfg}, nil
+ case "pi":
+ return &piBackend{cfg: cfg}, nil
default:
- return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codex, opencode, openclaw, hermes, gemini)", agentType)
+ return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codex, opencode, openclaw, hermes, gemini, pi)", agentType)
}
}
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
new file mode 100644
index 0000000000..3e41dc747a
--- /dev/null
+++ b/server/pkg/agent/pi.go
@@ -0,0 +1,397 @@
+package agent
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+)
+
+// piBackend implements Backend by spawning the Pi CLI in non-interactive
+// JSON mode (`pi -p --mode json --session <path>`) and parsing its event
+// stream on stdout.
+type piBackend struct {
+ cfg Config
+}
+
+func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
+ execPath := b.cfg.ExecutablePath
+ if execPath == "" {
+ execPath = "pi"
+ }
+ if _, err := exec.LookPath(execPath); err != nil {
+ return nil, fmt.Errorf("pi executable not found at %q: %w", execPath, err)
+ }
+
+ timeout := opts.Timeout
+ if timeout == 0 {
+ timeout = 20 * time.Minute
+ }
+
+ // Pi's --session flag expects a file path where events are appended.
+ // The path doubles as our opaque session identifier: we return it as
+ // SessionID and expect it back as ResumeSessionID on the next turn.
+ sessionPath := opts.ResumeSessionID
+ if sessionPath == "" {
+ p, err := newPiSessionPath()
+ if err != nil {
+ return nil, fmt.Errorf("pi session path: %w", err)
+ }
+ sessionPath = p
+ }
+ if err := ensurePiSessionFile(sessionPath); err != nil {
+ return nil, fmt.Errorf("pi session file: %w", err)
+ }
+
+ runCtx, cancel := context.WithTimeout(ctx, timeout)
+
+ args := buildPiArgs(prompt, sessionPath, opts, b.cfg.Logger)
+
+ cmd := exec.CommandContext(runCtx, execPath, args...)
+ cmd.WaitDelay = 10 * time.Second
+ if opts.Cwd != "" {
+ cmd.Dir = opts.Cwd
+ }
+ cmd.Env = buildEnv(b.cfg.Env)
+
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("pi stdout pipe: %w", err)
+ }
+ cmd.Stderr = newLogWriter(b.cfg.Logger, "[pi:stderr] ")
+
+ if err := cmd.Start(); err != nil {
+ cancel()
+ return nil, fmt.Errorf("start pi: %w", err)
+ }
+
+ b.cfg.Logger.Info("pi started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
+
+ msgCh := make(chan Message, 256)
+ resCh := make(chan Result, 1)
+
+ // Close stdout when the context is cancelled so scanner.Scan() unblocks.
+ go func() {
+ <-runCtx.Done()
+ _ = stdout.Close()
+ }()
+
+ go func() {
+ defer cancel()
+ defer close(msgCh)
+ defer close(resCh)
+
+ startTime := time.Now()
+ var output strings.Builder
+ finalStatus := "completed"
+ var finalError string
+ usage := make(map[string]TokenUsage)
+
+ scanner := bufio.NewScanner(stdout)
+ // Pi message_update events can be large (they embed the full message
+ // partial on each delta), so give the scanner generous headroom.
+ scanner.Buffer(make([]byte, 0, 1024*1024), 32*1024*1024)
+
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" {
+ continue
+ }
+ var evt piStreamEvent
+ if err := json.Unmarshal([]byte(line), &evt); err != nil {
+ continue
+ }
+
+ switch evt.Type {
+ case "agent_start":
+ trySend(msgCh, Message{Type: MessageStatus, Status: "running"})
+
+ case "message_update":
+ if evt.AssistantMessageEvent == nil {
+ continue
+ }
+ switch evt.AssistantMessageEvent.Type {
+ case "text_delta":
+ if d := evt.AssistantMessageEvent.Delta; d != "" {
+ output.WriteString(d)
+ trySend(msgCh, Message{Type: MessageText, Content: d})
+ }
+ case "thinking_delta":
+ if d := evt.AssistantMessageEvent.Delta; d != "" {
+ trySend(msgCh, Message{Type: MessageThinking, Content: d})
+ }
+ }
+
+ case "tool_execution_start":
+ var params map[string]any
+ if len(evt.Args) > 0 {
+ _ = json.Unmarshal(evt.Args, &params)
+ }
+ trySend(msgCh, Message{
+ Type: MessageToolUse,
+ Tool: evt.ToolName,
+ CallID: evt.ToolCallID,
+ Input: params,
+ })
+
+ case "tool_execution_end":
+ trySend(msgCh, Message{
+ Type: MessageToolResult,
+ CallID: evt.ToolCallID,
+ Output: decodePiResult(evt.Result),
+ })
+
+ case "turn_end":
+ if msg := decodePiMessage(evt.Message); msg != nil && msg.Usage != nil {
+ model := msg.Model
+ if model == "" {
+ model = opts.Model
+ }
+ if model == "" {
+ model = "unknown"
+ }
+ u := usage[model]
+ u.InputTokens += msg.Usage.Input
+ u.OutputTokens += msg.Usage.Output
+ u.CacheReadTokens += msg.Usage.CacheRead
+ u.CacheWriteTokens += msg.Usage.CacheWrite
+ usage[model] = u
+ }
+
+ case "error":
+ errText := decodePiString(evt.Message)
+ trySend(msgCh, Message{Type: MessageError, Content: errText})
+ if finalStatus == "completed" {
+ finalStatus = "failed"
+ finalError = errText
+ }
+
+ case "auto_retry_end":
+ if !evt.Success && finalStatus == "completed" {
+ finalStatus = "failed"
+ if evt.FinalError != "" {
+ finalError = evt.FinalError
+ } else {
+ finalError = "pi exhausted automatic retries"
+ }
+ }
+ }
+ }
+
+ waitErr := cmd.Wait()
+ duration := time.Since(startTime)
+
+ if runCtx.Err() == context.DeadlineExceeded {
+ finalStatus = "timeout"
+ finalError = fmt.Sprintf("pi timed out after %s", timeout)
+ } else if runCtx.Err() == context.Canceled {
+ finalStatus = "aborted"
+ finalError = "execution cancelled"
+ } else if waitErr != nil && finalStatus == "completed" {
+ finalStatus = "failed"
+ finalError = fmt.Sprintf("pi exited with error: %v", waitErr)
+ }
+
+ b.cfg.Logger.Info("pi finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+
+ resCh <- Result{
+ Status: finalStatus,
+ Output: output.String(),
+ Error: finalError,
+ DurationMs: duration.Milliseconds(),
+ SessionID: sessionPath,
+ Usage: usage,
+ }
+ }()
+
+ return &Session{Messages: msgCh, Result: resCh}, nil
+}
+
+// ── Pi event types ──
+
+// piStreamEvent is the union of fields we consume from Pi's JSON event
+// stream. Fields that can be either string or object across event types
+// (e.g. `message`, `result`) are held as json.RawMessage and decoded on
+// demand by the switch arms.
+type piStreamEvent struct {
+ Type string `json:"type"`
+
+ // message_update
+ AssistantMessageEvent *piAssistantMessageEvent `json:"assistantMessageEvent,omitempty"`
+
+ // tool_execution_start / tool_execution_end
+ ToolCallID string `json:"toolCallId,omitempty"`
+ ToolName string `json:"toolName,omitempty"`
+ Args json.RawMessage `json:"args,omitempty"`
+ Result json.RawMessage `json:"result,omitempty"`
+ IsError bool `json:"isError,omitempty"`
+
+ // error: Message is a string. turn_end: Message is an object.
+ Message json.RawMessage `json:"message,omitempty"`
+
+ // auto_retry_end
+ Success bool `json:"success,omitempty"`
+ FinalError string `json:"finalError,omitempty"`
+}
+
+type piAssistantMessageEvent struct {
+ Type string `json:"type"`
+ Delta string `json:"delta,omitempty"`
+}
+
+type piMessage struct {
+ Role string `json:"role,omitempty"`
+ Model string `json:"model,omitempty"`
+ Usage *piUsage `json:"usage,omitempty"`
+}
+
+type piUsage struct {
+ Input int64 `json:"input"`
+ Output int64 `json:"output"`
+ CacheRead int64 `json:"cacheRead"`
+ CacheWrite int64 `json:"cacheWrite"`
+ TotalTokens int64 `json:"totalTokens"`
+}
+
+func decodePiMessage(raw json.RawMessage) *piMessage {
+ if len(raw) == 0 {
+ return nil
+ }
+ var m piMessage
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return nil
+ }
+ return &m
+}
+
+func decodePiString(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var s string
+ if err := json.Unmarshal(raw, &s); err == nil {
+ return s
+ }
+ return strings.Trim(string(raw), `"`)
+}
+
+func decodePiResult(raw json.RawMessage) string {
+ if len(raw) == 0 {
+ return ""
+ }
+ var s string
+ if err := json.Unmarshal(raw, &s); err == nil {
+ return s
+ }
+ return string(raw)
+}
+
+// ── Arg builder ──
+
+// piBlockedArgs are flags hardcoded by the daemon that must not be
+// overridden by user-configured custom_args. Overriding these would
+// break the daemon↔Pi communication protocol.
+var piBlockedArgs = map[string]blockedArgMode{
+ "-p": blockedStandalone, // non-interactive mode
+ "--print": blockedStandalone, // alias for -p
+ "--mode": blockedWithValue, // "json" event stream protocol
+ "--session": blockedWithValue, // daemon manages the session path
+}
+
+// buildPiArgs assembles the argv for a one-shot Pi invocation.
+//
+// Flags:
+//
+// -p non-interactive mode (prompt is positional)
+// --mode json emit one JSON event per line on stdout
+// --session <path> session log file (created upfront, reused on resume)
+// --provider <name> provider, when Model is "provider/id"
+// --model <id> model identifier
+// --tools read,bash,... explicit tool allowlist (pi has no --yolo)
+// --append-system-prompt <s> extra system instructions
+//
+// Custom args appended before the positional prompt. The prompt is a
+// positional argument and must be last.
+func buildPiArgs(prompt, sessionPath string, opts ExecOptions, logger *slog.Logger) []string {
+ args := []string{
+ "-p",
+ "--mode", "json",
+ }
+ if sessionPath != "" {
+ args = append(args, "--session", sessionPath)
+ }
+ if opts.Model != "" {
+ provider, model := splitPiModel(opts.Model)
+ if provider != "" {
+ args = append(args, "--provider", provider)
+ }
+ if model != "" {
+ args = append(args, "--model", model)
+ }
+ }
+ args = append(args, "--tools", "read,bash,edit,write,grep,find,ls")
+ if opts.SystemPrompt != "" {
+ args = append(args, "--append-system-prompt", opts.SystemPrompt)
+ }
+ args = append(args, filterCustomArgs(opts.CustomArgs, piBlockedArgs, logger)...)
+ args = append(args, prompt)
+ return args
+}
+
+// splitPiModel parses a "provider/model" string into its parts. Plain
+// "model" strings pass through as (provider="", model="model").
+func splitPiModel(s string) (provider, model string) {
+ s = strings.TrimSpace(s)
+ if i := strings.Index(s, "/"); i >= 0 {
+ return strings.TrimSpace(s[:i]), strings.TrimSpace(s[i+1:])
+ }
+ return "", s
+}
+
+// ── Session path ──
+
+// piSessionDir returns the directory where Pi session JSONL files live.
+// Exported via a helper so the usage scanner (package usage) can point at
+// the same location without duplicating the path construction.
+func piSessionDir() (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ".multica", "pi-sessions"), nil
+}
+
+func newPiSessionPath() (string, error) {
+ dir, err := piSessionDir()
+ if err != nil {
+ return "", err
+ }
+ name := fmt.Sprintf("%s.jsonl", time.Now().UTC().Format("20060102T150405.000000000"))
+ return filepath.Join(dir, name), nil
+}
+
+// ensurePiSessionFile creates an empty session file if one does not yet
+// exist at path. Pi refuses to start when --session points at a missing
+// file; paths that already exist (a resumed session) are left untouched.
+func ensurePiSessionFile(path string) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644)
+ if err != nil {
+ return err
+ }
+ return f.Close()
+}
+
+// PiSessionDir exposes piSessionDir to other packages in this module.
+func PiSessionDir() (string, error) {
+ return piSessionDir()
+}