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)
}
Output:
Index ¶
- Variables
- type AfterTurnFunc
- type Agent
- func (a *Agent) Ask(ctx context.Context, sessionID, message string) (string, error)
- func (a *Agent) Close() error
- func (a *Agent) LogPath() string
- func (a *Agent) Model() string
- func (a *Agent) NewSession(ctx context.Context) (string, error)
- func (a *Agent) Run(ctx context.Context, sessionID, message string) iter.Seq2[*session.Event, error]
- func (a *Agent) RunStreaming(ctx context.Context, sessionID, message string) iter.Seq2[*session.Event, error]
- func (a *Agent) SetSessionTitle(sessionID, title string) error
- func (a *Agent) SummarizeSession(ctx context.Context, sessionID string) error
- func (a *Agent) Tools() []adktool.Tool
- func (a *Agent) WorkingDir() string
- type AgentEventFunc
- type BeforeTurnFunc
- type LSPMode
- type Option
- func WithAfterModelCallbacks(cbs ...llmagent.AfterModelCallback) Option
- func WithAfterToolCallbacks(cbs ...llmagent.AfterToolCallback) Option
- func WithAfterTurn(fns ...AfterTurnFunc) Option
- func WithAgentEvents(fn AgentEventFunc) Option
- func WithBeforeModelCallbacks(cbs ...llmagent.BeforeModelCallback) Option
- func WithBeforeToolCallbacks(cbs ...llmagent.BeforeToolCallback) Option
- func WithBeforeTurn(fns ...BeforeTurnFunc) Option
- func WithCompactNotify(fn func(string)) Option
- func WithContextWindow(tokens int64) Option
- func WithExtraInstruction(s string) Option
- func WithExtraSandboxDirs(dirs ...string) Option
- func WithInstruction(s string) Option
- func WithLSP(mode LSPMode) Option
- func WithMemory(enabled bool) Option
- func WithModel(m model.LLM) Option
- func WithPalace(enabled bool) Option
- func WithSessionDir(dir string) Option
- func WithSessionSummary(m model.LLM) Option
- func WithSkills(enabled bool) Option
- func WithSubagents(enabled bool) Option
- func WithSummarizer(m model.LLM) Option
- func WithTools(ts ...tool.Tool) Option
- func WithToolsets(ts ...tool.Toolset) Option
- func WithVersion(v string) Option
- func WithWorkingDir(dir string) Option
- type TurnInfo
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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)
}
Output:
func (*Agent) Ask ¶
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 ¶
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
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) NewSession ¶
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)
}
}
}
}
Output:
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 ¶
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
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 ¶
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 ¶
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 ¶
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.
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()
}
Output:
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()
}
Output:
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
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
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 ¶
WithExtraInstruction appends application-specific text to the assembled system prompt, after the built-in prompt, project rules and skills menu.
func WithExtraSandboxDirs ¶
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 ¶
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 ¶
WithLSP selects the LSP tool surface. Even LSPFull registers nothing when no language server for the workspace is installed.
func WithMemory ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
WithSkills enables or disables skill discovery and the "Available Skills" section of the system prompt. Enabled by default.
func WithSubagents ¶
WithSubagents enables or disables subagent discovery and the tools that spawn them. Enabled by default.
func WithSummarizer ¶ added in v0.1.6
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 WithToolsets ¶
WithToolsets adds toolsets alongside the MCP and A2A toolsets built from configuration.
func WithVersion ¶ added in v0.1.6
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 ¶
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.