piacp

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 37 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

acp-go-pi

acp-go-pi exposes the pi coding agent as an Agent Client Protocol agent. It launches one pi --mode rpc process per ACP session, maps ACP requests onto pi's JSONL RPC, and streams ACP session updates back to the client.

pi inherits the adapter's environment and keeps sessions in its own home. A session started over ACP can be continued natively:

acp-go-pi              # host runs a session in /work
cd /work && pi --session NATIVE_SESSION_ID

New, load, and resume responses and session-list entries expose the current native ID as _meta.pi.nativeSessionId. Use it for native CLI continuation. ACP requests continue to use the stable ACP sessionId. The store's configuration record saves both IDs with the matching native history.

Install

go install github.com/savid/acp-go-pi/cmd/acp-go-pi@latest

pi is found on PATH or named with -path.

Run

acp-go-pi [-path pi] [-home DIR] [-scratch-dir DIR] [-model provider/id] [-seed-file rel=host]... [-debug]
Flag Meaning
-path pi executable; a bare name is searched on PATH
-home pi config root, passed as PI_CODING_AGENT_DIR; empty inherits pi's own resolution
-scratch-dir parent for ephemeral adapter state; empty means the system temp directory
-model default model for new sessions as provider/id
-seed-file <relpath>=<hostpath> written into pi's config root before launch; repeatable
-debug debug logs to stderr
-version print the adapter version

OpenTelemetry exporters are configured from the standard OTEL_* variables.

Embed

err := piacp.Serve(ctx, os.Stdin, os.Stdout,
    piacp.WithHome("/srv/pi"),
    piacp.WithSessionStore(store),
)

Options: WithExecutablePath, WithHome, WithScratchDir, WithInputHandoffRoot, WithDefaultModel, WithConfiguredModels, WithEnv, WithSeedFiles, WithSessionStore, WithConcurrencyLimits, WithImageLimits, WithLogger, WithTracerProvider, WithMeterProvider, WithTextMapPropagator, WithAgentName, WithAgentTitle, WithAgentVersion.

Session options

_meta.pi.options on session/new, session/load, and session/resume, or WithSessionPiOptions from Go:

Field Meaning
model provider/id for the session
env environment overlay for the session's pi process
extraPathDirs absolute directories prepended to PATH, in order
thinkingLevel reasoning level passed to pi
permission ask (default) requests permission per tool call; allow auto-allows
autoRetry opt in to pi's native retry of transient provider errors

_meta.pi.rawEvent.enabled forwards every native pi event on the _pi/rawEvent notification.

Config options

session/set_config_option accepts model (provider/id, from pi's catalog plus any WithConfiguredModels entries) and thought_level (off, minimal, low, medium, high, xhigh, max).

Image input

Images are accepted as inline data or through WithInputHandoffRoot. Pi's native prompt has separate text and image fields. Put all text, resource links, and text resources before the images; images alone and multiple images are accepted. Forwarded text after the first image fails with {"error":"unsupported","field":"prompt"} before native dispatch. User-only text excluded from native input does not affect ordering.

Response identity and usage

Agent text, thought, and image chunks carry the id the model gateway returned for their response (gen-…, chatcmpl-…, msg_…, resp_…) as ACP messageId, live and on session/load replay. The usage_update reporting a finished response carries its token breakdown as acp-go-core's wire.CallUsage, with the same id as responseId. pi's RPC stream omits the streaming message, so the bridge extension relays the id from the first update that holds it. A response pi holds no id for, such as one that failed before the gateway answered, carries neither.

Session store

WithSessionStore mirrors pi's session JSONL rows under the main subpath and the adapter's session record under config, format pi-session-jsonl-v2. The record names pi's session file as nativePath and carries the session title, so session/list reads only records. session/load and session/resume prefer pi's own file when it exists and materialize it from the store otherwise. A restore, and a relaunch after pi exited, first cut any bytes after the file's last complete line, so a line a killed process left half-written never becomes a row. Native rows and session configuration commit as one store generation through acp-go-core's sessionlog.Mirror: after the first generation, a commit reads only the lines pi appended since the last one and appends them, rewriting the record only when it changed, and writes nothing when neither changed. A configuration change is durable even when no native rows were added, and an established conversation with no native history yet commits its configuration with an empty main record. Replay decodes every stored image, user or assistant, through the same output gate as live image output, so a stored image that gate refuses fails the whole restore rather than leaving a hole.

Development

make test
make lint
make audit
make test-integration-smoke   # needs pi installed, spends no tokens
make test-integration-live    # spends model tokens

Unit tests run the test binary as a scripted fake pi and need no installed pi, credentials, or network.

Account usage

AccountUsageMethod (_pi/accountUsage) accepts sessionId and providerId (opencode-go, openrouter, openai-codex, or anthropic). A provider pi holds no native account for is read through the gateways extension-registered providers route to, when such a gateway publishes a usage report. Reads hold the session's foreground gate and spend no model tokens. The session extension resolves effective credentials, model endpoints, and authentication headers from Pi's native model registry. Credentials travel only over an authenticated loopback endpoint and never enter the conversation or ACP events.

Official provider routes use github.com/savid/acp-go-core/usage to read Go percentage windows, OpenRouter USD balances and request counts, ChatGPT subscription windows, and Claude subscription windows and reported spending. ChatGPT account IDs come from the same native access token used for inference. Subscription credits are not treated as dollars. Custom provider implementations and unverified routes report not_reported. Missing credentials report not_authenticated. The adapter revalidates the native binding after each read.

Context compaction

Reports starts, completions, failures, and cancellations, including an overflow recovery failure without a start. The native trigger and before/after context counts are included when reported; contextAfter is Pi's native estimate.

Notifications carry acp-go.dev/compaction on the notification’s _meta, with an otherwise empty session_info_update. The value is acp-go-core wire.Compaction: a required compactionId and status, and optional trigger, contextBefore, and contextAfter. A start and its outcome share an ID. Unknown facts are omitted. These are live notifications; historical replay emits none. Usage accounting is independent.

A session/cancel or session/close that arrives while pi compacts waits for the compaction to end, up to five minutes, before it aborts the run or stops the process, so the summary pi is generating is kept. A cancelled turn then has five seconds to settle before its process is stopped.

Documentation

Overview

Package piacp exposes the pi coding agent CLI as an Agent Client Protocol agent.

Most hosts run the agent over a pair of JSON-RPC streams using Serve. Serve starts one `pi --mode rpc` process per ACP session, maps ACP requests onto pi's JSONL RPC, and streams ACP session updates back to the client. pi inherits the adapter's environment and keeps its sessions in its own home, so a session started over ACP can be continued natively with `pi --resume` after the adapter closes.

Hosts that need durable remote resume provide WithSessionStore. The store is the durability boundary for session/list, session/load and session/resume; pi's own session file is the native copy an operator can continue outside ACP.

Hosts that need adapter telemetry provide OpenTelemetry providers with WithTracerProvider and WithMeterProvider; the package never configures global providers.

Index

Examples

Constants

View Source
const (
	// RawEventMethod is the notification carrying one raw pi event when a
	// session opted in through _meta.pi.rawEvent.enabled.
	RawEventMethod = "_pi/rawEvent"
	// AccountUsageMethod reads one provider's account allowance through a session.
	AccountUsageMethod = "_pi/accountUsage"
	// SessionStoreFormat identifies the store layout this package writes: raw
	// pi session JSONL rows under the main subpath plus the adapter's session
	// record under the config subpath.
	SessionStoreFormat = "pi-session-jsonl-v2"
)

Variables

This section is empty.

Functions

func Serve

func Serve(ctx context.Context, input io.Reader, output io.Writer, opts ...Option) (returnErr error)

Serve runs an ACP agent over the provided streams. It blocks until the context is cancelled or the peer closes the connection, then closes the agent.

Example (Initialize)

ExampleServe_initialize embeds the agent over a pair of pipes, the same wiring a host uses for stdio, and reads the capabilities the handshake advertises.

package main

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"io"

	piacp "github.com/savid/acp-go-pi"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	clientToAgentReader, clientToAgentWriter := io.Pipe()
	agentToClientReader, agentToClientWriter := io.Pipe()

	done := make(chan error, 1)

	go func() {
		done <- piacp.Serve(ctx, clientToAgentReader, agentToClientWriter)
	}()

	_, _ = fmt.Fprintln(clientToAgentWriter,
		`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}`)

	line, _ := bufio.NewReader(agentToClientReader).ReadString('\n')

	cancel()
	_ = clientToAgentWriter.Close()
	<-done

	var response struct {
		Result struct {
			AuthMethods       []any `json:"authMethods"`
			AgentCapabilities struct {
				LoadSession         bool           `json:"loadSession"`
				SessionCapabilities map[string]any `json:"sessionCapabilities"`
			} `json:"agentCapabilities"`
		} `json:"result"`
	}

	_ = json.Unmarshal([]byte(line), &response)

	fmt.Println(len(response.Result.AuthMethods))
	fmt.Println(response.Result.AgentCapabilities.LoadSession)
	fmt.Println(len(response.Result.AgentCapabilities.SessionCapabilities))
}
Output:
0
true
5

func SetModelRequest

func SetModelRequest(sessionID acp.SessionId, model string) acp.SetSessionConfigOptionRequest

SetModelRequest constructs a model selector update as "provider/id".

func ValidatePiSessionMeta added in v0.2.0

func ValidatePiSessionMeta(meta map[string]any) error

ValidatePiSessionMeta runs the owned-namespace parsing of a session lifecycle request's _meta without an Agent and returns the same refusal.

func WithSessionPiOptions

func WithSessionPiOptions(options PiOptions) wire.SessionRequestOption

WithSessionPiOptions merges pi-specific options into _meta.pi.options.

func WithSessionRawEvents

func WithSessionRawEvents(enabled bool) wire.SessionRequestOption

WithSessionRawEvents toggles raw pi event emission for the session.

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent exposes the pi coding agent through ACP.

func NewAgent

func NewAgent(opts ...Option) *Agent

NewAgent creates an ACP agent for the pi coding agent CLI. Construction never fails; a refused option is reported by Initialize and every session-establishing method as pi_invalid_options.

func (*Agent) Authenticate

func (a *Agent) Authenticate(_ context.Context, params acp.AuthenticateRequest) (acp.AuthenticateResponse, error)

Authenticate exists because the SDK interface requires it. The harness authenticates itself in its own home, outside ACP.

func (*Agent) Cancel

func (a *Agent) Cancel(ctx context.Context, params acp.CancelNotification) (err error)

Cancel interrupts the session's in-flight turn. It is wire-silent on an unknown session or with no turn in flight.

func (*Agent) Close

func (a *Agent) Close() error

Close runs the shutdown ladder for every session and refuses every later request.

func (*Agent) CloseSession

func (a *Agent) CloseSession(ctx context.Context, params acp.CloseSessionRequest) (resp acp.CloseSessionResponse, err error)

CloseSession runs the shutdown ladder for one session.

func (*Agent) HandleExtensionMethod

func (a *Agent) HandleExtensionMethod(ctx context.Context, method string, params json.RawMessage) (any, error)

HandleExtensionMethod serves the account-usage read; every other extension method is method-not-found.

func (*Agent) Initialize

func (a *Agent) Initialize(ctx context.Context, params acp.InitializeRequest) (resp acp.InitializeResponse, err error)

Initialize implements ACP initialize.

func (*Agent) ListSessions

func (a *Agent) ListSessions(ctx context.Context, params acp.ListSessionsRequest) (resp acp.ListSessionsResponse, err error)

ListSessions lists live sessions and stored sessions, newest first.

func (*Agent) LoadSession

func (a *Agent) LoadSession(ctx context.Context, params acp.LoadSessionRequest) (resp acp.LoadSessionResponse, err error)

LoadSession restores a session and replays its history.

func (*Agent) Logout

func (a *Agent) Logout(_ context.Context, params acp.LogoutRequest) (acp.LogoutResponse, error)

Logout exists because the SDK interface requires it.

func (*Agent) NewSession

func (a *Agent) NewSession(ctx context.Context, params acp.NewSessionRequest) (resp acp.NewSessionResponse, err error)

NewSession creates and starts a pi session.

func (*Agent) Prompt

func (a *Agent) Prompt(ctx context.Context, params acp.PromptRequest) (resp acp.PromptResponse, err error)

Prompt sends one turn to pi and streams updates until it settles.

func (*Agent) ResumeSession

func (a *Agent) ResumeSession(ctx context.Context, params acp.ResumeSessionRequest) (resp acp.ResumeSessionResponse, err error)

ResumeSession restores a session without replaying its history.

func (*Agent) SetSessionConfigOption

func (a *Agent) SetSessionConfigOption(ctx context.Context, params acp.SetSessionConfigOptionRequest) (resp acp.SetSessionConfigOptionResponse, err error)

SetSessionConfigOption applies one select value.

func (*Agent) SetSessionMode

SetSessionMode exists because the SDK interface requires it. Native modes are config options, never ACP session modes.

func (*Agent) UnstableDeleteSession

func (a *Agent) UnstableDeleteSession(ctx context.Context, params acp.UnstableDeleteSessionRequest) (resp acp.UnstableDeleteSessionResponse, err error)

UnstableDeleteSession tombstones the session first, then closes any live session with the same id. Native state stays in pi's home.

type ConcurrencyLimits

type ConcurrencyLimits struct {
	MaxActiveSessions        int
	MaxConcurrentClientCalls int
}

ConcurrencyLimits controls per-agent backpressure. Zero fields use defaults.

type ImageLimits

type ImageLimits struct {
	MaxInputBytesPerImage     int64
	MaxInputBytesPerPrompt    int64
	MaxOutputBytesPerImage    int64
	MaxOutputBytesPerToolCall int64
}

ImageLimits bounds decoded image bytes. A zero field disables that policy limit; the frame clamp still applies.

type Option

type Option func(*Options)

Option configures the pi ACP agent.

func WithAgentName

func WithAgentName(name string) Option

WithAgentName sets the protocol identifier advertised during ACP initialize.

func WithAgentTitle

func WithAgentTitle(title string) Option

WithAgentTitle sets the human-readable agent name advertised during ACP initialize.

func WithAgentVersion

func WithAgentVersion(version string) Option

WithAgentVersion sets the agent version advertised during ACP initialize.

func WithConcurrencyLimits

func WithConcurrencyLimits(limits ConcurrencyLimits) Option

WithConcurrencyLimits sets process-local backpressure limits.

func WithConfiguredModels added in v0.2.0

func WithConfiguredModels(ids []string) Option

WithConfiguredModels names the models the host lists explicitly.

func WithDefaultModel

func WithDefaultModel(model string) Option

WithDefaultModel selects the model for new sessions as "provider/id".

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv sets the static agent-scoped environment overlay applied to every pi process after the inherited environment and before the session env.

func WithExecutablePath

func WithExecutablePath(path string) Option

WithExecutablePath selects the pi executable.

func WithHome added in v0.2.0

func WithHome(path string) Option

WithHome sets pi's native config root, passed to every session as PI_CODING_AGENT_DIR.

func WithImageLimits

func WithImageLimits(limits ImageLimits) Option

WithImageLimits bounds decoded image bytes. A zero field disables that policy limit; a negative field fails construction.

func WithInputHandoffRoot

func WithInputHandoffRoot(dir string) Option

WithInputHandoffRoot sets the absolute directory under which handoff-form prompt images are read. The adapter never writes there.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger configures structured diagnostic logging.

func WithMeterProvider

func WithMeterProvider(provider metric.MeterProvider) Option

WithMeterProvider configures the OpenTelemetry meter provider.

func WithScratchDir

func WithScratchDir(dir string) Option

WithScratchDir sets the parent directory for ephemeral adapter state.

func WithSeedFiles

func WithSeedFiles(files map[string]string) Option

WithSeedFiles registers files written into pi's config root before each launch. Keys are paths relative to that root; values are the contents.

func WithSessionStore

func WithSessionStore(store acpcore.SessionStore) Option

WithSessionStore configures the session store.

func WithTextMapPropagator

func WithTextMapPropagator(propagator propagation.TextMapPropagator) Option

WithTextMapPropagator configures trace-context extraction from ACP _meta.

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) Option

WithTracerProvider configures the OpenTelemetry tracer provider.

type Options

type Options struct {
	// AgentName is the protocol identifier advertised during ACP initialize.
	AgentName string
	// AgentTitle is the human-readable agent name advertised during ACP initialize.
	AgentTitle string
	// AgentVersion is the agent version advertised during ACP initialize.
	AgentVersion string

	// ExecutablePath selects the pi executable. A bare name is searched on the
	// base PATH; a path containing a separator is used as given. Empty means
	// "pi".
	ExecutablePath string
	// Home is pi's native config, auth, and runtime root, passed to every
	// session as PI_CODING_AGENT_DIR. Empty leaves pi to resolve its home from
	// the inherited environment exactly as it would from a shell.
	Home string
	// ScratchDir is the parent directory for ephemeral adapter state. Empty
	// means the system temp directory.
	ScratchDir string
	// InputHandoffRoot is the absolute directory under which handoff-form
	// prompt images are read. Empty rejects the handoff form.
	InputHandoffRoot string
	// DefaultModel selects the model for new sessions as "provider/id".
	DefaultModel string
	// ConfiguredModels are the model ids the host lists explicitly, each as
	// "provider/id".
	ConfiguredModels []string
	// Env is the static agent-scoped overlay on the inherited process
	// environment every pi process runs with.
	Env map[string]string

	// Logger receives structured diagnostic logs. If nil, the default logger is used.
	Logger *slog.Logger
	// TracerProvider records adapter spans. If nil, tracing is a no-op.
	TracerProvider trace.TracerProvider
	// MeterProvider records adapter metrics. If nil, metrics are no-ops.
	MeterProvider metric.MeterProvider
	// TextMapPropagator extracts trace context from ACP _meta. If nil, W3C
	// trace context plus baggage propagation is used.
	TextMapPropagator propagation.TextMapPropagator

	// SessionStore is the durability boundary for session rows. Nil installs a
	// fresh in-memory store.
	SessionStore acpcore.SessionStore
	// ConcurrencyLimits controls process-local backpressure.
	ConcurrencyLimits ConcurrencyLimits
	// SeedFiles maps paths relative to pi's config root to file contents
	// written there before each launch.
	SeedFiles map[string]string
	// ImageLimits bounds decoded image bytes on prompt input and emitted
	// output. Every field defaults to 6 MiB when the option is omitted.
	ImageLimits ImageLimits
	// contains filtered or unexported fields
}

Options configures the ACP agent process and the pi RPC-mode sessions it starts.

type PiOption

type PiOption func(*PiOptions)

PiOption configures PiOptions values.

func WithPiAutoRetry

func WithPiAutoRetry(enabled bool) PiOption

WithPiAutoRetry opts the session in to pi's native automatic retry.

func WithPiEnv

func WithPiEnv(env map[string]string) PiOption

WithPiEnv configures the session environment overlay.

func WithPiExtraPathDirs

func WithPiExtraPathDirs(dirs ...string) PiOption

WithPiExtraPathDirs configures the directories prepended to the session PATH.

func WithPiModel

func WithPiModel(model string) PiOption

WithPiModel configures the session model as "provider/id".

func WithPiPermission

func WithPiPermission(mode string) PiOption

WithPiPermission configures the permission mode: "ask" or "allow".

func WithPiThinkingLevel

func WithPiThinkingLevel(level string) PiOption

WithPiThinkingLevel configures the reasoning level passed to pi.

type PiOptions

type PiOptions struct {
	// Model selects the pi model for this session as "provider/id".
	Model string `json:"model,omitempty"`
	// Env overlays the session's pi process environment.
	Env map[string]string `json:"env,omitempty"`
	// ExtraPathDirs are absolute directories prepended, in order, to the PATH
	// of this session's pi process.
	ExtraPathDirs []string `json:"extraPathDirs,omitempty"`
	// ThinkingLevel is a reasoning-level value passed unchanged to pi.
	ThinkingLevel string `json:"thinkingLevel,omitempty"`
	// Permission selects the permission mode: "ask" (the default) raises a
	// permission request per tool call, "allow" auto-allows every tool call.
	Permission string `json:"permission,omitempty"`
	// AutoRetry opts the session in to pi's native retry of transient
	// provider errors.
	AutoRetry bool `json:"autoRetry,omitempty"`
	// contains filtered or unexported fields
}

PiOptions is the per-session options struct carried at _meta.pi.options.

func NewPiOptions

func NewPiOptions(opts ...PiOption) PiOptions

NewPiOptions constructs PiOptions from functional options.

Example
package main

import (
	"fmt"

	piacp "github.com/savid/acp-go-pi"
)

func main() {
	options := piacp.NewPiOptions(
		piacp.WithPiModel("provider/model"),
		piacp.WithPiThinkingLevel("high"),
		piacp.WithPiPermission("ask"),
	)

	fmt.Println(options.Model)
	fmt.Println(options.ThinkingLevel)
	fmt.Println(options.Permission)
}
Output:
provider/model
high
ask

func (PiOptions) Meta

func (options PiOptions) Meta() map[string]any

Meta returns exactly {"pi": {"options": {...}}}, including an explicit false autoRetry.

Directories

Path Synopsis
cmd
acp-go-pi command
Package integration holds the tests that run against an installed pi.
Package integration holds the tests that run against an installed pi.
internal
pi
Package pi implements the native boundary to the pi coding agent CLI: the launch arguments of one `pi --mode rpc` process, its LF-delimited JSONL RPC, the wrapper-owned extensions it loads, and the session-file layout pi keeps in its own home.
Package pi implements the native boundary to the pi coding agent CLI: the launch arguments of one `pi --mode rpc` process, its LF-delimited JSONL RPC, the wrapper-owned extensions it loads, and the session-file layout pi keeps in its own home.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址