piagent

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 28 Imported by: 0

README

piagent

Embed pi-go's coding agent in your own Go program.

Every other package in this module is under internal/, so piagent is the only importable surface. It assembles the same agent the pi CLI runs headlessly (--mode print), minus the terminal UI.

go get github.com/dimetron/pi-go

The model comes from outside

piagent never constructs a provider. The model arrives through WithModel as an ADK model.LLM — the interface the agent already runs on — and New returns ErrNoModel without one. pi-go's providers (credentials, base URLs, transport options, thinking level, token metering) live in a separate package:

m, err := pimodels.FromConfig(ctx, "")            // the model a pi session picks
ag, err := piagent.New(ctx, piagent.WithModel(m)) // the agent

Neither package imports the other, and piagent/isolation_test.go fails the build if that ever changes. A change to provider handling is therefore not a breaking change here — and a fake model.LLM drives a whole turn in a test with no network.

Minimal embed

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/dimetron/pi-go/piagent"
)

func main() {
	ctx := context.Background()

	m, err := pimodels.FromConfig(ctx, "")
	if err != nil {
		log.Fatal(err)
	}

	ag, err := piagent.New(ctx, piagent.WithModel(m))
	if err != nil {
		log.Fatal(err)
	}
	defer ag.Close()

	sessionID, err := ag.NewSession(ctx)
	if err != nil {
		log.Fatal(err)
	}

	answer, err := ag.Ask(ctx, sessionID, "what does this repository do?")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(answer)
}

What that one option buys

Concern Behaviour
Config Hooks, MCP, A2A, memory, palace and compactor settings from ~/.pi-go/config.json plus any project override
Filesystem Sandbox rooted at the working directory, plus ~/.pi-go
Tools read, write, edit, bash (+ supervisor and control tools), grep, find, ls, tree, git tools, session-stats
Skills .pi-go/skills/, the user directory and the bundled set, summarized into the prompt
Subagents .pi-go/agents plus the bundled set, exposed as tools
Project rules AGENT.md / AGENTS.md / CLAUDE.md / .pi-go/AGENTS.md, discovered upward from the working directory
Toolsets MCP servers and A2A agents from configuration
Memory Off by default — see below. WithMemory(true) opts in
Palace Off by default. Once on, tools register only when it holds drawers
LSP Registered only when a language server is installed; two tools by default
Sessions Persisted under ~/.pi-go/sessions, so pi --resume can pick one up

Options

ag, err := piagent.New(ctx,
	piagent.WithModel(m),
	piagent.WithWorkingDir("/srv/checkout"),
	piagent.WithExtraInstruction("Answer as a release engineer."),
	piagent.WithLSP(piagent.LSPOff),
	piagent.WithMemory(false),
	piagent.WithPalace(false),
)
Option Purpose
WithWorkingDir(dir) Directory to work in; sandbox root and discovery anchor
WithExtraSandboxDirs(dirs...) Grant file access outside the working directory
WithSessionDir(dir) Where sessions are persisted
WithModel(m) Required. The ADK model.LLM the agent runs on
WithInstruction(s) Replace the built-in system prompt
WithExtraInstruction(s) Append your own text to the assembled prompt
WithTools(...) / WithToolsets(...) Add your own tools
WithBeforeTurn(...) / WithAfterTurn(...) Bracket whole turns — admission control and metrics
WithBeforeToolCallbacks(...) / WithAfterToolCallbacks(...) Observe or rewrite tool calls
WithBeforeModelCallbacks(...) / WithAfterModelCallbacks(...) Observe or rewrite LLM calls
WithLSP(mode) LSPOff, LSPMin (default) or LSPFull
WithMemory(bool) / WithPalace(bool) Opt in to the shared ~/.pi-go stores (off by default)
WithSkills(bool) / WithSubagents(bool) Toggle discovery (on by default)
WithAgentEvents(fn) Receive subagent and background-bash progress
WithSummarizer(m) Model that writes compaction summaries (default: the session model)
WithCompactNotify(fn) Be told when auto-compaction runs, or fails
WithSessionSummary(m) Write an end-of-session summary into the memory store

Auto-compaction is observable and retargetable

Compaction discards conversation history, so two things about it are worth controlling.

Which model summarizes. Summarizing a transcript is a different job from holding the conversation, and a small fast model often does it better and for less:

cheap, _ := pimodels.New(ctx, "gemini-3.8-flash")
ag, _ := piagent.New(ctx,
    piagent.WithModel(m),
    piagent.WithSummarizer(cheap),
)

Whether you are told. Without a notifier the outcome is silent, and "silent" is not the same as "discoverable" — the session log is the stated fallback, so Agent.LogPath() exists to make it reachable:

ag, _ := piagent.New(ctx, piagent.WithModel(m),
    piagent.WithCompactNotify(func(msg string) {
        log.Printf("compaction: %s", msg)
    }),
)
fmt.Println("session log:", ag.LogPath()) // "" when no log could be created

The notifier runs on the goroutine driving the turn, so keep it quick.

Callbacks

ADK ends its after-tool callback chain at the first callback returning a non-nil result. pi-go registers several that all return the result map, so a plain slice would run only the first — a defect that silently disabled the compactor, dedup, the LSP hook and memory recording for months.

piagent composes the whole chain into one ADK callback with explicit semantics:

func(ctx agent.Context, t tool.Tool, args, result map[string]any, toolErr error) (map[string]any, error)
  • (nil, nil) — leave the result unchanged, continue the chain.
  • (m, nil) — m becomes the result for every later callback and for the model.
  • (_, err) — abort the chain; the error surfaces on the turn.

Your callbacks run after pi-go's, so they see the compacted and deduplicated result. Before-tool and model callbacks are handed to ADK as slices, where "run until one intervenes" is already the semantics you want.

Testing an embed

WithModel takes any google.golang.org/adk/v2/model.LLM, so a fake model drives a whole turn without a network:

ag, err := piagent.New(ctx,
	piagent.WithModel(&fakeLLM{reply: "hello"}),
	piagent.WithWorkingDir(t.TempDir()),
	piagent.WithSessionDir(t.TempDir()),
	piagent.WithMemory(false),
	piagent.WithPalace(false),
	piagent.WithSubagents(false),
	piagent.WithLSP(piagent.LSPOff),
)

Nothing wraps the model on the way in — metering, retries and transport belong to whoever built it.

Lifetime

Close() releases the sandbox, any backgrounded process trees, the subagent orchestrator, the LSP manager, the memory worker and store, the palace, and the session log. Always defer it.

Not included

  • Provider construction, in any form. No model-name, base-URL, API-key or credential option exists here — each would drag provider resolution into this package's public surface.
  • The CLI's two-stage auto-compaction pre-turn hook. It lives in internal/cli and would have to be extracted first; install your own via ADK if you need it.
  • A process-global HTTP trace sink. A library has no business claiming one.
  • The daily-token guardrail, which wraps the model rather than the agent.
  • Config-driven shell hooks as a programmatic option. They still load from ~/.pi-go/config.json, but an embedder writing Go gets a Go func rather than a subprocess.
  • The subagent orchestrator. Subagents are reachable as tools; direct orchestration would be a much larger compatibility commitment.

Turn hooks

Tool and model callbacks fire inside a turn. WithBeforeTurn and WithAfterTurn bracket the whole thing, which is the level metrics, audit trails and admission control actually work at.

piagent.New(ctx,
	piagent.WithModel(m),

	// Admission control: returning an error aborts the turn before it
	// reaches the model.
	piagent.WithBeforeTurn(func(ctx context.Context, sessionID, message string) error {
		return budget.Check(sessionID)
	}),

	// Metrics and audit. Cannot change the outcome.
	piagent.WithAfterTurn(func(ctx context.Context, i piagent.TurnInfo) {
		metrics.Record(i.SessionID, i.Duration, i.ToolCalls, i.Err)
	}),
)

TurnInfo carries SessionID, Message, Duration, Events, ToolCalls, Err and Abandoned.

Three behaviours worth knowing, because each is a bug if you assume otherwise:

  • They fire on iteration, not on the Run call. A sequence nobody ranges over is not a turn, and recording one would put a turn that never happened into your metrics.
  • An abandoned turn still reports. Break out of the range loop and the after-turn hook still runs, with Abandoned: true — a caller that stops consuming has still spent the tokens.
  • An aborted turn does not. If a before-turn hook denies the turn, no request is made and there is nothing to report, so the after-turn hook is not called.

This is the headless equivalent of pi-go's turn_complete lifecycle hook, which is otherwise dispatched only from the TUI.

One deliberate difference from the CLI

Memory and palace are off by default here. The CLI has both on, and this is the only place piagent departs from it.

They are the only subsystems that write to state shared with the user: ~/.pi-go/memory/claude-mem.db and ~/.pi-go/palace.db are the same stores a real pi session reads and writes. An embedder's process is not a pi session, and quietly interleaving its observations with the user's is a surprise documentation cannot undo. Opt in when your embed is meant to contribute:

piagent.New(ctx, piagent.WithModel(m), piagent.WithMemory(true))

Skills and subagent discovery stay on. Those read .pi-go/, which is the whole reason to embed this agent rather than write your own. Reading a convention and writing to someone's store are different things.

Session summaries

With memory on, the agent records observations as it works. Nothing summarizes them unless you ask, because summarizing means a model call and that is your budget to spend:

piagent.New(ctx,
	piagent.WithModel(m),
	piagent.WithMemory(true),
	piagent.WithSessionSummary(m), // may be a cheaper model
)

Close then writes one summary per session the agent created, and marks those sessions completed. Call ag.SummarizeSession(ctx, sessionID) yourself if you would rather choose the moment — a long-lived agent may want a summary per unit of work rather than per process.

WithSessionSummary is deliberately distinct from WithSummarizer, which configures the compaction summary. They answer different questions and reach different stores: compaction asks "what does the next model need to continue?", a session summary asks "what happened here, for someone reading the memory database later?".

Sessions are marked completed even when no summary model is configured. Leaving them active is what let the shared store accumulate thousands of rows that no reader could tell apart from a session still in progress.

Finding the provider behind a model

Two things need to know which provider a model talks to: the OpenTelemetry gen_ai.provider.name span attribute, and whether Gemini's server-side grounding tool is worth registering. piagent asks the model:

if p, ok := m.(interface{ Provider() string }); ok { ... }

The shape, never a named type from another package — that is what keeps the dependency on ADK alone. Models from pimodels satisfy it. A model that cannot answer falls back to a prefix match on its name, and an unrecognized name gets neither the span attribute nor the grounding tool. Both degrade quietly; nothing else depends on it.

Documentation

Overview

Package piagent embeds pi-go's coding agent in a third-party Go program.

Every other package in this module lives under internal/ and is therefore unreachable from outside. piagent is the one importable façade: it assembles the same agent the pi CLI runs in its headless (--mode print) path, minus the terminal UI, and hands it back as a small type you can drive from your own code.

The model comes from outside

piagent never constructs a provider. The model arrives through WithModel as a google.golang.org/adk/v2/model.LLM — the interface the agent already runs on — and New returns ErrNoModel without one. pi-go's own providers (credentials, base URLs, transport options, thinking level, token metering) live in a separate package that builds one:

m, err := pimodels.FromConfig(ctx, "")   // the model a pi session would pick
if err != nil {
	return err
}

ag, err := piagent.New(ctx, piagent.WithModel(m))
if err != nil {
	return err
}
defer ag.Close()

sid, err := ag.NewSession(ctx)
if err != nil {
	return err
}
answer, err := ag.Ask(ctx, sid, "what does this repo do?")

Keeping the seam at ADK's interface means neither package imports the other, a change to provider handling is not a breaking change here, and a fake model.LLM drives a whole turn in a test with no network.

What one option buys

That single option aside, everything else is resolved from pi-go's conventions:

  • Hooks, MCP servers, A2A agents, memory, palace and compactor settings from ~/.pi-go/config.json plus any project override.
  • A filesystem sandbox rooted at the working directory (plus ~/.pi-go), and the core tool set: read, write, edit, bash with its supervisor and the bash control tools, search, and the rest of pi-go's built-ins.
  • Skills discovered from .pi-go/skills/, the user directory and the bundled set, summarized into the system prompt.
  • Subagents discovered from .pi-go/agents plus the bundled set, wired to an orchestrator and exposed as tools.
  • Project context files (AGENT.md, AGENTS.md, CLAUDE.md, .pi-go/AGENTS.md) discovered from the working directory up to the filesystem root.
  • MCP servers and A2A agents as ADK toolsets.
  • Sessions persisted under ~/.pi-go/sessions, so a session started by an embedder is visible to `pi --resume` and vice versa.

One deliberate difference from the CLI

Observation memory and the memory palace are OFF by default here, where the CLI has both on. They are the only subsystems that write to state shared with the user: ~/.pi-go/memory/claude-mem.db and ~/.pi-go/palace.db are the same stores a real pi session reads and writes. An embedder's process is not a pi session, and silently interleaving its observations with the user's is a surprise that documentation cannot undo — so it is opt-in, via WithMemory and WithPalace.

Skills and subagent discovery stay on. Those read .pi-go/, which is the whole reason to embed this agent instead of writing your own. Reading a convention and writing to someone's store are different things.

Gated subsystems

Tool declarations are billed on every request — roughly 7.4k tokens before gating — so two groups only register when they can pay for themselves, and piagent keeps those gates rather than turning everything on:

  • LSP tools register only when WithLSP is not LSPOff and a language server for the workspace is actually installed. The default mode is LSPMin, which advertises two tools (symbols and diagnostics); LSPFull advertises all seven. The after-tool LSP hook is wired either way and costs nothing when no server starts.
  • Palace tools, once WithPalace is on, register only when the palace database exists and holds at least one drawer. An empty palace still gets opened, so the observation bridge can fill it and the tools appear on a later run.

Callback composition

ADK ends its after-tool callback chain at the first callback that returns a non-nil result. pi-go's own after-tool callbacks all return the result map, so handing ADK a slice of them silently runs only the first. piagent therefore composes every after-tool callback — its own and yours — into a single ADK callback with explicit semantics:

  • returning (nil, nil) leaves the result unchanged and continues the chain;
  • returning (m, nil) makes m the result seen by every later callback and, ultimately, by the model;
  • returning a non-nil error aborts the chain and surfaces the error.

Callbacks supplied through WithAfterToolCallbacks run after pi-go's, so they observe the compacted and deduplicated result rather than the raw one.

Before-tool and model callbacks are passed to ADK as slices: for those, ADK's "run until one intervenes" semantics are already what you want.

Turn hooks

Tool and model callbacks fire inside a turn. WithBeforeTurn and WithAfterTurn bracket the whole turn instead, which is the level metrics, audit trails and admission control actually work at:

  • A before-turn hook sees the session ID and the outgoing message, and returning an error aborts the turn before it reaches the model. Budget checks, rate limits and moderation belong here.
  • An after-turn hook receives a TurnInfo — duration, event and tool-call counts, the failure if there was one, and whether the caller abandoned the turn by breaking out of the loop early.

Both fire when the caller starts iterating, not when Run returns: a sequence nobody ranges over is not a turn, and recording one would be a lie in whatever the hook writes down. An abandoned turn still reports, because a caller that stops consuming has still spent the tokens.

This is the headless equivalent of pi-go's turn_complete lifecycle hook, which is otherwise dispatched only from the TUI.

Lifetime

Agent.Close releases everything New acquired — sandbox, bash supervisor and any backgrounded process trees, subagent orchestrator, LSP manager, memory worker and store, palace, and the session log. Always defer it.

Deliberately not included

Provider construction, in any form: no model name, base URL, API key or credential option exists here, because each one would drag provider resolution into this package's public surface.

A process-global HTTP trace sink, because a library has no business claiming one.

Config-driven shell hooks as a programmatic option. Those still load from ~/.pi-go/config.json and run for tool calls, but an embedder writing Go gets a Go func rather than a subprocess: WithBeforeTurn and WithAfterToolCallbacks do the same work without the fork.

The daily-token guardrail, which wraps the model rather than the agent and so belongs with whoever built the model. piagent does wrap the model in an unlimited tracker, but only to measure: nothing here caps an embedder's spend.

Auto-compaction

The two-stage compaction the CLI runs — shed superseded tool results at the lower threshold, summarize the transcript at the upper one — is installed here too, as a pre-turn hook. An embedded agent re-sends its whole transcript on every turn exactly as an interactive one does, so a long session outgrows its context window just as fast.

It reads its thresholds from the auto_compact block of ~/.pi-go/config.json and is on by default. Two things switch it off: setting auto_compact.enabled to false, and a context window that cannot be resolved. The window comes from the embedded model catalog, because piagent is handed a finished model and never learns its base URL; set context_window in config.json when the catalog does not know the model.

Finding the provider behind a model

Two things need to know which provider a model talks to: the OpenTelemetry gen_ai.provider.name span attribute, and whether Gemini's server-side grounding tool is worth registering. piagent asks the model itself, by asserting the shape interface{ Provider() string } — the shape, never a named type from another package, so the dependency stays on ADK alone. A model that cannot answer falls back to a prefix match on its name, and an unrecognized name simply gets neither the attribute nor the tool.

Example

Example is the whole embed: bring a model, build an agent, ask a question. Tools, skills, project rules, subagents and sessions all come from pi-go's own conventions.

package main

import (
	"context"
	"fmt"
	"log"

	"google.golang.org/adk/v2/model"

	"github.com/dimetron/pi-go/piagent"
)

// newModel stands in for pimodels.FromConfig. piagent takes any ADK model.LLM
// and never builds one itself, so the examples below say nothing about where
// yours comes from.
func newModel(context.Context, string) (model.LLM, error) { return nil, nil }

func main() {
	ctx := context.Background()

	m, err := newModel(ctx, "") // pimodels.FromConfig(ctx, "")
	if err != nil {
		log.Fatal(err)
	}

	ag, err := piagent.New(ctx, piagent.WithModel(m))
	if err != nil {
		log.Fatal(err)
	}
	defer ag.Close()

	sessionID, err := ag.NewSession(ctx)
	if err != nil {
		log.Fatal(err)
	}

	answer, err := ag.Ask(ctx, sessionID, "summarize this repository in one sentence")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(answer)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNoModel = errors.New("piagent: no model supplied — pass WithModel(m) with an ADK model.LLM (pi-go's providers are in the pimodels package)")

ErrNoModel is returned by New when no model was supplied. piagent does not construct providers, so there is nothing to fall back to.

Functions

This section is empty.

Types

type AfterTurnFunc

type AfterTurnFunc func(ctx context.Context, info TurnInfo)

AfterTurnFunc runs once a turn has finished, whether it succeeded, failed or was abandoned. It cannot change the outcome; it is for metrics, audit logs and persistence.

type Agent

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

Agent is an embedded pi-go coding agent: an ADK runner assembled with pi-go's tools, prompt, skills, subagents and memory. Create one with New and release it with [Close].

An Agent is safe for concurrent use across sessions; a single session should be driven by one goroutine at a time, since turns append to shared history.

func New

func New(ctx context.Context, opts ...Option) (*Agent, error)

New assembles an embedded agent around the model given to WithModel, which is the one required option. Everything else — working directory, tools, skills, subagents, project rules, toolsets, memory and palace — is resolved from pi-go's conventions; see the package documentation.

The returned Agent owns a sandbox, a process supervisor, a subagent orchestrator and possibly an LSP manager, a memory worker and a palace. Always defer Agent.Close.

Example (Options)

ExampleNew_options shows the knobs an embedder usually reaches for: a specific directory, an application-specific instruction, and the optional subsystems turned off to keep the run cheap and self-contained.

package main

import (
	"context"
	"fmt"
	"log"

	"google.golang.org/adk/v2/model"

	"github.com/dimetron/pi-go/piagent"
)

// newModel stands in for pimodels.FromConfig. piagent takes any ADK model.LLM
// and never builds one itself, so the examples below say nothing about where
// yours comes from.
func newModel(context.Context, string) (model.LLM, error) { return nil, nil }

func main() {
	ctx := context.Background()

	m, err := newModel(ctx, "claude-sonnet-5")
	if err != nil {
		log.Fatal(err)
	}

	ag, err := piagent.New(ctx,
		piagent.WithModel(m),
		piagent.WithWorkingDir("/srv/checkout"),
		piagent.WithExtraInstruction("Answer as a release engineer. Never modify files under /srv/checkout/vendor."),
		piagent.WithLSP(piagent.LSPOff),
		piagent.WithMemory(true), // opt in to the shared ~/.pi-go stores
	)
	if err != nil {
		log.Fatal(err)
	}
	defer ag.Close()

	fmt.Println(len(ag.Tools()) > 0)
}

func (*Agent) Ask

func (a *Agent) Ask(ctx context.Context, sessionID, message string) (string, error)

Ask runs one turn and returns the assistant's text, discarding tool calls, tool results and thinking. It is the shortest path from a question to an answer; use Agent.Run when you need to observe the turn.

func (*Agent) Close

func (a *Agent) Close() error

Close releases every resource the agent acquired: the sandbox, backgrounded processes, the subagent orchestrator, the LSP manager, the memory worker and store, the palace, and the session log. It is safe to call more than once.

When a session summarizer is configured, Close writes a summary for every session this agent created and marks those sessions completed. Both happen inside the memory closer, after the observation worker has drained and before the store is closed — see setupMemory for why that order is required. Summarization is best-effort: a failure is logged and does not prevent any resource from being released.

func (*Agent) LogPath added in v0.1.6

func (a *Agent) LogPath() string

LogPath returns the file the agent writes its session log to — the same JSONL stream a `pi` session produces, with tool calls, model output and any auto-compaction outcome in it.

It returns "" when no log could be created, which is not fatal: the agent runs without one. Callers should treat "" as "no log" rather than as an error.

The path is fixed at construction and the file is created then, so this is safe to call from the moment New returns.

func (*Agent) Model

func (a *Agent) Model() string

Model returns the name reported by the model the agent runs on.

func (*Agent) NewSession

func (a *Agent) NewSession(ctx context.Context) (string, error)

NewSession creates a session and returns its ID. Sessions persist under the session directory, so the pi CLI can resume one an embedder started.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, sessionID, message string) iter.Seq2[*session.Event, error]

Run sends a message and returns the turn's ADK events. Iterate the sequence to completion, or stop early to abandon the turn.

Example

ExampleAgent_Run streams a turn's events instead of waiting for the final text, which is what a UI wants.

package main

import (
	"context"
	"fmt"
	"log"

	"google.golang.org/adk/v2/model"

	"github.com/dimetron/pi-go/piagent"
)

// newModel stands in for pimodels.FromConfig. piagent takes any ADK model.LLM
// and never builds one itself, so the examples below say nothing about where
// yours comes from.
func newModel(context.Context, string) (model.LLM, error) { return nil, nil }

func main() {
	ctx := context.Background()

	m, err := newModel(ctx, "claude-sonnet-5")
	if err != nil {
		log.Fatal(err)
	}

	ag, err := piagent.New(ctx, piagent.WithModel(m))
	if err != nil {
		log.Fatal(err)
	}
	defer ag.Close()

	sessionID, err := ag.NewSession(ctx)
	if err != nil {
		log.Fatal(err)
	}

	for ev, err := range ag.Run(ctx, sessionID, "run the tests and report failures") {
		if err != nil {
			log.Fatal(err)
		}
		if ev == nil || ev.Content == nil {
			continue
		}
		for _, part := range ev.Content.Parts {
			switch {
			case part.FunctionCall != nil:
				fmt.Printf("calling %s\n", part.FunctionCall.Name)
			case part.Text != "":
				fmt.Print(part.Text)
			}
		}
	}
}

func (*Agent) RunStreaming

func (a *Agent) RunStreaming(ctx context.Context, sessionID, message string) iter.Seq2[*session.Event, error]

RunStreaming is Agent.Run with SSE streaming, so text arrives as deltas. The final aggregate event repeats the whole reply; a caller that prints deltas must skip it.

func (*Agent) SetSessionTitle

func (a *Agent) SetSessionTitle(sessionID, title string) error

SetSessionTitle records a human-readable label for a session. It is metadata only, used by the CLI's session listing.

func (*Agent) SummarizeSession added in v0.1.6

func (a *Agent) SummarizeSession(ctx context.Context, sessionID string) error

SummarizeSession summarizes one session's recorded observations and stores the result, so it can be read back with `pi memory recent`.

It is exported for embedders that want to choose the moment rather than wait for Agent.Close — a long-lived agent may want a summary per logical unit of work, not per process. Agent.Close calls it for every session the agent created.

It returns an error when memory is off, when no summarizer was configured, or when the session has no observations. A session with no observations is not an error in the "something broke" sense, but there is no summary to write, so it is reported rather than silently succeeding.

func (*Agent) Tools

func (a *Agent) Tools() []adktool.Tool

Tools returns the tools registered with the model, in the order they were declared. Toolsets (MCP, A2A) resolve their tools per request and are not included.

func (*Agent) WorkingDir

func (a *Agent) WorkingDir() string

WorkingDir returns the absolute directory the agent operates in.

type AgentEventFunc

type AgentEventFunc func(id, kind, content string)

AgentEventFunc receives progress from subagents and from backgrounded bash commands: an identifier for the emitter, a kind ("text", "tool", "done", …) and the payload. It is called from the agent's goroutines, so it must be safe for concurrent use and must not block.

type BeforeTurnFunc

type BeforeTurnFunc func(ctx context.Context, sessionID, message string) error

BeforeTurnFunc runs before a turn is dispatched. Returning an error aborts the turn: no request reaches the model, and the error surfaces through the event sequence like any other turn failure.

This is the seam for admission control — budget checks, rate limiting, moderation of the outgoing message, injecting session state.

type LSPMode

type LSPMode string

LSPMode selects how much of the LSP tool surface is advertised to the model. The declarations are billed on every request, so the default is deliberately narrow.

const (
	// LSPOff registers no LSP tools.
	LSPOff LSPMode = "off"
	// LSPMin registers symbols and diagnostics only. This is the default, and
	// covers ~90% of the LSP calls observed in practice.
	LSPMin LSPMode = "min"
	// LSPFull registers all seven LSP tools.
	LSPFull LSPMode = "full"
)

type Option

type Option func(*options)

Option configures New.

func WithAfterModelCallbacks

func WithAfterModelCallbacks(cbs ...llmagent.AfterModelCallback) Option

WithAfterModelCallbacks adds after-model callbacks after pi-go's own.

func WithAfterToolCallbacks

func WithAfterToolCallbacks(cbs ...llmagent.AfterToolCallback) Option

WithAfterToolCallbacks adds after-tool callbacks after pi-go's own, so they see the compacted and deduplicated result.

These do not get ADK's first-non-nil-wins semantics. piagent composes the whole chain into one callback: return (nil, nil) to leave the result alone, (m, nil) to replace it for every later callback and for the model, or a non-nil error to abort the turn. See the package documentation for why.

Example

ExampleWithAfterToolCallbacks audits every tool call. The callback returns nil to leave the result untouched; returning a map would replace the result for every later callback and for the model.

package main

import (
	"context"
	"log"

	adkagent "google.golang.org/adk/v2/agent"
	"google.golang.org/adk/v2/model"

	adktool "google.golang.org/adk/v2/tool"

	"github.com/dimetron/pi-go/piagent"
)

// newModel stands in for pimodels.FromConfig. piagent takes any ADK model.LLM
// and never builds one itself, so the examples below say nothing about where
// yours comes from.
func newModel(context.Context, string) (model.LLM, error) { return nil, nil }

func main() {
	ctx := context.Background()

	audit := func(_ adkagent.Context, t adktool.Tool, args, result map[string]any, toolErr error) (map[string]any, error) {
		if toolErr != nil {
			log.Printf("tool %s failed: %v", t.Name(), toolErr)
			return nil, nil
		}
		log.Printf("tool %s: %d args, %d result fields", t.Name(), len(args), len(result))
		return nil, nil
	}

	m, err := newModel(ctx, "claude-sonnet-5")
	if err != nil {
		log.Fatal(err)
	}

	ag, err := piagent.New(ctx, piagent.WithModel(m), piagent.WithAfterToolCallbacks(audit))
	if err != nil {
		log.Fatal(err)
	}
	defer ag.Close()
}

func WithAfterTurn

func WithAfterTurn(fns ...AfterTurnFunc) Option

WithAfterTurn adds hooks that run once a turn has finished — including when it failed, and when the caller broke out of the loop early, which TurnInfo.Abandoned reports. They cannot change the outcome.

Use it for metrics, audit trails and persistence. This is the headless equivalent of pi-go's turn_complete lifecycle hook, which otherwise fires only from the TUI.

Example

ExampleWithAfterTurn brackets whole turns rather than individual tool calls, which is the level metrics and audit logs work at. The before-turn hook is admission control: returning an error aborts the turn before it reaches the model.

package main

import (
	"context"
	"fmt"
	"log"
	"sync/atomic"

	"google.golang.org/adk/v2/model"

	"github.com/dimetron/pi-go/piagent"
)

// newModel stands in for pimodels.FromConfig. piagent takes any ADK model.LLM
// and never builds one itself, so the examples below say nothing about where
// yours comes from.
func newModel(context.Context, string) (model.LLM, error) { return nil, nil }

func main() {
	ctx := context.Background()

	var spent atomic.Int64
	const budget = 500

	m, err := newModel(ctx, "")
	if err != nil {
		log.Fatal(err)
	}

	ag, err := piagent.New(ctx,
		piagent.WithModel(m),
		piagent.WithBeforeTurn(func(_ context.Context, sessionID, message string) error {
			if spent.Load() >= budget {
				return fmt.Errorf("session %s is over its %d-turn budget", sessionID, budget)
			}
			return nil
		}),
		piagent.WithAfterTurn(func(_ context.Context, info piagent.TurnInfo) {
			spent.Add(1)
			log.Printf("turn: session=%s tools=%d events=%d took=%s abandoned=%t err=%v",
				info.SessionID, info.ToolCalls, info.Events, info.Duration, info.Abandoned, info.Err)
		}),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer ag.Close()
}

func WithAgentEvents

func WithAgentEvents(fn AgentEventFunc) Option

WithAgentEvents installs a sink for subagent and background-bash progress. Without one those events are discarded.

func WithBeforeModelCallbacks

func WithBeforeModelCallbacks(cbs ...llmagent.BeforeModelCallback) Option

WithBeforeModelCallbacks adds before-model callbacks after pi-go's own. Returning a non-nil response from one skips the LLM call.

func WithBeforeToolCallbacks

func WithBeforeToolCallbacks(cbs ...llmagent.BeforeToolCallback) Option

WithBeforeToolCallbacks adds before-tool callbacks after pi-go's own. ADK runs them in order until one returns a non-nil result, which short-circuits the tool call and becomes its result.

func WithBeforeTurn

func WithBeforeTurn(fns ...BeforeTurnFunc) Option

WithBeforeTurn adds hooks that run before each turn is dispatched, in the order given. The first to return an error aborts the turn — nothing reaches the model, and the error surfaces through the event sequence.

Use it for admission control: budget and quota checks, rate limiting, moderating the outgoing message, or seeding session state.

A hook runs when the caller starts iterating, not when Run returns. A sequence nobody ranges over is not a turn.

func WithCompactNotify added in v0.1.6

func WithCompactNotify(fn func(string)) Option

WithCompactNotify receives a line of text whenever auto-compaction runs — or fails to.

Compaction discards conversation history, which is not something an embedder should have to infer from a shrinking transcript. Without this the outcome is silent: piagent passes no notifier, on the grounds that an embedder can read the session log, and the session log is not reachable from outside the module.

The callback runs on the goroutine driving the turn, so keep it quick and do not block on I/O.

func WithContextWindow added in v0.1.0

func WithContextWindow(tokens int64) Option

WithContextWindow states the model's context window in tokens, which is what switches auto-compaction on.

piagent cannot look this up. Resolving a window means consulting pi-go's model catalog, and this package is deliberately kept off provider construction — so the number is stated by whoever built the model. An embedder using pimodels has it to hand:

m, _ := pimodels.New(ctx, "gemini-3.8-flash")
ag, _ := piagent.New(ctx,
	piagent.WithModel(m),
	piagent.WithContextWindow(provider.ContextWindowSizeFor("gemini", m.Name())),
)

Without it, and without context_window in ~/.pi-go/config.json, the window is unknown and compaction never fires — the transcript grows until the provider rejects it. A non-positive size is ignored.

func WithExtraInstruction

func WithExtraInstruction(s string) Option

WithExtraInstruction appends application-specific text to the assembled system prompt, after the built-in prompt, project rules and skills menu.

func WithExtraSandboxDirs

func WithExtraSandboxDirs(dirs ...string) Option

WithExtraSandboxDirs grants the agent's file tools access to directories outside the working directory. Without this, everything outside the sandbox root (and ~/.pi-go, which is always added) is denied.

func WithInstruction

func WithInstruction(s string) Option

WithInstruction replaces pi-go's built-in system prompt. Project context files and the skills menu are still appended, so the conventions survive. Most embedders want WithExtraInstruction instead.

func WithLSP

func WithLSP(mode LSPMode) Option

WithLSP selects the LSP tool surface. Even LSPFull registers nothing when no language server for the workspace is installed.

func WithMemory

func WithMemory(enabled bool) Option

WithMemory turns on observation memory — the SQLite store under ~/.pi-go/memory, its background worker, and the memory search tools.

Off by default, unlike the CLI. That store is shared with the user's real pi sessions, and an embedder's process is not one of them; opt in when the embedder is meant to contribute to it.

func WithModel

func WithModel(m model.LLM) Option

WithModel supplies the model the agent runs on. It is required: piagent never constructs a provider, so there is no default to fall back to and New returns ErrNoModel without it.

Any ADK model works. pi-go's own providers — credentials, base URLs, transport options, thinking level, token metering — live in a separate package that builds one for you:

m, err := pimodels.FromConfig(ctx, "")   // the model a pi session would pick
ag, err := piagent.New(ctx, piagent.WithModel(m))

Keeping the seam at ADK's interface means neither package depends on the other, and a change to provider handling is not a breaking change here. It is also what makes an embed testable: a fake model.LLM drives a whole turn with no network.

func WithPalace

func WithPalace(enabled bool) Option

WithPalace turns on the memory palace. Off by default for the same reason as WithMemory — ~/.pi-go/palace.db is the user's. Once on, its tools still only register when the palace holds at least one drawer.

func WithSessionDir

func WithSessionDir(dir string) Option

WithSessionDir overrides where sessions are persisted. The default, ~/.pi-go/sessions, is what the pi CLI reads, so leaving it alone lets `pi --resume` pick up a session an embedder started.

func WithSessionSummary added in v0.1.6

func WithSessionSummary(m model.LLM) Option

WithSessionSummary sets the model that writes the end-of-session summary for the observation memory store, and turns the feature on.

It is separate from WithSummarizer, which writes the auto-compaction handoff summary for the conversation. The two reach different stores and answer different questions: compaction asks "what does the next model need to continue?", session summary asks "what happened in this session, for someone reading the memory database later?".

Summaries are written on Agent.Close, because that is the only point at which a session is known to be over — an embedder may run turns for hours, and a summary written mid-session would describe work that had not happened yet. Close is also the wrong place to spend much time, so the write is one model call with a short budget and a failure is logged rather than returned.

Without this option no summary is written, which is also the behavior when memory is off. Agent.SummarizeSession can be called directly instead when the embedder would rather choose the moment.

func WithSkills

func WithSkills(enabled bool) Option

WithSkills enables or disables skill discovery and the "Available Skills" section of the system prompt. Enabled by default.

func WithSubagents

func WithSubagents(enabled bool) Option

WithSubagents enables or disables subagent discovery and the tools that spawn them. Enabled by default.

func WithSummarizer added in v0.1.6

func WithSummarizer(m model.LLM) Option

WithSummarizer sets the model that writes the handoff summary when auto-compaction triggers. Without it, the session's own model does the work.

A summarizer is a different job from the conversation: it reads a transcript and emits prose, so a cheaper or faster model often does it better and for less. This is the headless equivalent of replacing the compaction strategy.

The model is used as-is — nothing is wrapped or metered here, and it is not used for anything but summarization.

func WithTools

func WithTools(ts ...tool.Tool) Option

WithTools adds tools alongside pi-go's core set.

func WithToolsets

func WithToolsets(ts ...tool.Toolset) Option

WithToolsets adds toolsets alongside the MCP and A2A toolsets built from configuration.

func WithVersion added in v0.1.6

func WithVersion(v string) Option

WithVersion records the version string an embedder wants stamped into the sessions it creates via [Agent.CreateSession], so a transcript can be tied back to the build that produced it. The CLI passes its -ldflags-stamped version; an embedder passes its own, or nothing.

Without this option the session's "version" field is omitted, which is correct for a library that has no version of its own to claim.

func WithWorkingDir

func WithWorkingDir(dir string) Option

WithWorkingDir sets the directory the agent works in. It becomes the sandbox root, the starting point for project-context and skill discovery, and the repository root reported to subagents. Defaults to the process working directory.

type TurnInfo

type TurnInfo struct {
	// SessionID is the session the turn belonged to.
	SessionID string

	// Message is the user message that opened the turn.
	Message string

	// Duration covers the whole turn, from the first iteration to the last
	// event — including time the caller spent inside its own loop body.
	Duration time.Duration

	// Events counts the events the turn produced. Streaming turns report far
	// more than non-streaming ones for the same reply, because SSE delivers
	// text as deltas and then repeats it as an aggregate.
	Events int

	// ToolCalls counts the tool invocations the model requested.
	ToolCalls int

	// Err is the failure that ended the turn, or nil. It covers both an
	// iteration error and a provider failure reported on an ordinary event,
	// which are different channels for the same thing.
	Err error

	// Abandoned reports that the caller stopped iterating before the turn
	// finished — a break in the range loop, or a canceled context. The
	// counts describe what was consumed, not what the model produced.
	Abandoned bool
}

TurnInfo describes a turn that has finished, and is what an AfterTurnFunc receives. It is a snapshot: the hook may keep it, but must not assume the agent is idle by the time it runs.

Jump to

Keyboard shortcuts

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