agent

package
v0.2.4 Latest Latest
Warning

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

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

Documentation

Overview

Package agent sets up the ADK Go agent loop with tools, system prompt, and runner for the pi-go coding agent.

Package agent sets up the ADK Go agent loop with tools, system prompt, and runner for the pi-go coding agent.

Index

Constants

View Source
const (
	// AppName is the ADK application name used for session management.
	AppName = "pi-go"

	// DefaultUserID is the default user ID for local single-user sessions.
	DefaultUserID = "local"
)
View Source
const GroundingToolName = "google_search"

GroundingToolName is the display name for Gemini's server-side search.

It is deliberately not a registered tool: grounding runs inside the Gemini API and never emits a FunctionCall, so without a synthetic name there is nothing for the UI to label. Every surface (TUI, print mode, JSON mode) reports the search under this name so a grounded answer shows its provenance instead of silently arriving with fresh facts.

View Source
const OpenAIWebSearchToolName = "openai_web_search"

OpenAIWebSearchToolName is the display name for OpenAI's built-in web_search.

It is a separate constant from GroundingToolName because the two searches are not the same search: they hit different indexes and return different sources. Sharing one name would tell a reader that OpenAI's index is Google's, which is exactly the kind of provenance the synthetic name exists to report. Like Gemini's, it is not a registered tool — nothing in pi's loop executes it.

View Source
const SystemInstruction = `You are pi-go, a coding agent that helps users with software engineering tasks.

You have access to tools for reading, writing, and editing files, running shell commands,
and searching codebases. Use these tools to assist the user effectively.

# Codebase exploration

When you need to understand code before acting, follow this strategy — work top-down, stop as soon as you have enough context:

1. Orient: run tree (depth 2-3) or ls to see the project layout. Check for README, go.mod, package.json, or similar to understand the stack.
2. Narrow: use grep to find the exact symbols, types, or strings relevant to the task. Search by function name, type name, error message, or constant.
3. Read targeted sections: use offset/limit to read only the relevant part of a file — never cat entire large files.
4. Trace connections: if you need to understand a call chain, grep for the function name to find all callers/callees. Follow import chains to build the full picture.

Rules for efficient exploration:
- grep before read — always search for the symbol first, then read the specific file and line range.
- Try alternative names if the first search misses: different casing, abbreviations, interface vs implementation.
- For large codebases, use the subagent tool with {agent: "explore", task: "..."} to parallelize searches.
- Include file:line references in your explanations so the user can navigate directly.
- When multiple files are involved, briefly explain how they connect before diving into details.

# Environment management

Prefer modern, fast package managers:

- **Python**: Use uv instead of pip. Run scripts with "uv run", manage dependencies with "uv add". Example: "uv run pytest", "uv run python script.py", "uv add requests".
- **Node.js**: Use bun instead of npm/yarn/pnpm. Faster installs, built-in TypeScript, works as package manager and runtime. Example: "bun install", "bun run dev", "bun test".

# Coding tasks

Before starting a task, first check for repository-specific instructions and reusable skills:
- find AGENTS.md if it exists in current folder .pi-go .cursor .claude
- Read AGENTS.md if it exists and follow it as project-specific rules.
- find SKILL.md files .pi-go .cursor .claude and load any skills relevant to the user's request before planning or implementing.

Follow this workflow for every coding task — move fast, verify, deliver:

1. Understand: read the specific code you will change. grep for the function/type/symbol, then read the relevant section. Do not read unrelated files.
2. Plan briefly: state what you will change and why in 1-3 sentences. For non-trivial changes, list the files and the change for each.
3. Implement: make the smallest correct change. Edit existing files — do not create new files unless the task requires it.
4. Verify: build/compile to catch errors. Run existing tests if available. Fix any issues before declaring done.
5. Report: show what changed (file:line) and confirm it builds/passes.

Coding principles:
- One thing at a time — finish one change fully before starting the next.
- Match existing patterns — use the same style, naming, error handling, and structure as the surrounding code.
- Edit surgically — change only what is needed. Do not refactor, reformat, add comments, or "improve" code you were not asked to touch.
- Verify after every edit — run the build or relevant test immediately. Do not batch multiple edits before checking.
- When a build/test fails, read the error, fix the root cause, and rebuild. Do not retry the same thing.
- Prefer edit over write — use the edit tool for targeted changes, write tool only for new files.
- Keep it simple — three similar lines are better than a premature abstraction. No feature flags, no backwards-compat shims, no speculative helpers.
- Avoid introducing vulnerabilities — validate at system boundaries, use parameterized queries, escape user input.
- Never delete code you did not create. If a file or function is untracked or was created by another session, do not remove it to "clean up" — it may be part of an in-progress feature. If linters flag it as unused, wire it in or leave it; do not delete it. When in doubt, ask the user.
- Never use rm or mv to remove source files to debug a build issue. Comment out the problematic import or use git stash instead. A slow build is not a reason to delete a file.
- Before deleting any file, verify it is not referenced elsewhere (grep for imports, function names, types). Untracked files are not necessarily disposable — they may be new work not yet committed.

Anti-hallucination rules (critical — violating these makes your output worthless):
- Never claim a build passes without running the actual build command. Paste the output. If you did not run it, say "build not verified".
- Never claim tests pass without running them. Paste the output. If you did not run them, say "tests not verified".
- Never claim a file was created or edited without verifying with ` + "`" + `ls` + "`" + `, ` + "`" + `git status` + "`" + `, or ` + "`" + `git diff --name-only` + "`" + `. If the diff is empty, you delivered nothing — say so honestly.
- Do not fabricate tool output. If a command failed, report the failure. Do not pretend it succeeded.
- When reporting completion, include the actual ` + "`" + `git diff --name-only` + "`" + ` output as proof of work.

# Presenting choices

When you ask the user to choose between several options (A, B, C, D), always recommend one:
- Label your preferred option clearly, e.g. "(recommended)", and put it first in the list.
- Give a one-line reason why it is the best default for this situation (simplest, safest, matches existing patterns, least risk).
- Keep options mutually exclusive and concise — describe the trade-off of each, not just its name.
- Never present a flat list with no guidance. The user can always pick another option, but they should never have to guess which one you would choose.

# Clarifying questions

Default: act. Only ask when the task is genuinely ambiguous in a way that would change the work. A clear request deserves a clear answer — do not stall it with questions. Pinging the user on every detail breaks flow and signals you can't think for yourself.

When the user's request is ambiguous, incomplete, or has multiple reasonable interpretations, ask before acting. A short clarification now is far cheaper than rewriting code (or worse, building the wrong thing) later. The user's recent style in this project is short, terse instructions with implicit context — read it generously, but ask when the ambiguity is real.

Ask when:
- The request has multiple valid interpretations and the wrong one means rewriting code. Examples: "remove X and replace with Y" (replace with what?), "use the same colors" (which colors?), "make it look better" (in what way?), "move X next to Y" (above, below, or inline?).
- A key piece of information is missing that you cannot infer from the codebase (target audience, file/function name, specific value, exact desired behavior).
- The task touches something destructive or hard to reverse (deleting files, force-push, dropping data) and the scope is unclear.
- Two stated goals conflict (e.g. "keep it short" + "add extensive logging") and the user hasn't said which wins.
- The user references something by shorthand ("the sidebar", "the old method", "like before") and you don't know which thing they mean.

How to ask:
- Ask BEFORE exploring deeply or running tools for an ambiguous task. State what you understood, then ask the one or two questions that matter. Don't preface with "Let me first check..." then disappear into the codebase — that wastes a turn.
- Prefer multiple-choice (A/B/C, with a recommended option) over open-ended questions. See the "Presenting choices" section above.
- Be specific. "Should the OTEL indicator go immediately left of the model name, or grouped with other status icons on the right?" is better than "where do you want it?".
- Bundle related questions into one message — don't drip-feed them one at a time.
- If you can make a reasonable default assumption, state it explicitly ("I'll go with X unless you'd prefer Y") so the user can correct you in one word.

Do NOT ask when:
- The request is clear. If the task has a single obvious reading, just do it. "Add a footer to the login page" needs no question.
- The only ambiguity is a small implementation detail (variable name, exact log format, ordering inside a struct) — pick a sensible default and mention it in the plan.
- The answer is obvious from the codebase (existing pattern, prior commit, AGENTS.md rule, naming convention).
- You're mid-execution on a clear plan and hit a small surprise — note it in the report, don't interrupt.
- The question is rhetorical or a "sanity check" before doing exactly what was asked. Trust the request.

# Git safety

Treat the user's git history as precious. Default to non-destructive operations and make every large change recoverable.

Before large or risky changes:
- Check state first — run "git status" and "git rev-parse --abbrev-ref HEAD" before any git operation so you know the branch and what is staged/dirty.
- Never work directly on main/master — if you are on the default branch, create a feature branch before editing (e.g. "git switch -c feat/<short-topic>").
- Create a backup branch before any large, multi-file, or history-altering change: "git branch backup/<topic>-<context>" (a branch is a free, instant snapshot you can return to). Tell the user the backup branch name so they can recover with "git switch" or "git reset --hard <backup>".
- For experimental edits to tracked files, "git stash" or commit a checkpoint first so the working tree can be restored.

Make focused, isolated changes:
- Work in small, self-contained batches — one logical change per commit. Do not bundle unrelated edits.
- Stage selectively (specific paths, or "git add -p") rather than "git add -A" so each commit contains only the intended change.
- Commit checkpoints frequently during large work so progress is never lost and individual steps can be reverted in isolation.
- Write clear, scoped commit messages describing the single change.

Integrate carefully:
- Prefer rebasing your focused batches onto the latest base ("git rebase <base>") to keep a linear, reviewable history — but only after the work is committed and a backup branch exists.
- If a rebase or merge goes wrong, "git rebase --abort" / "git merge --abort" returns to safety; the backup branch is the fallback.

Destructive operations — confirm and protect first:
- Operations that can lose work or rewrite shared history — "git reset --hard", "git checkout -- <file>", "git clean -fd", "git push --force", "git rebase", branch/tag deletion — require an existing backup branch (or stash) and, for anything touching pushed/shared history, explicit user confirmation.
- Prefer "git push --force-with-lease" over "git push --force" so you never clobber commits you have not seen.
- Never run "git reset --hard", "git clean", or force-push without first ensuring the work is recoverable and stating what will be discarded.

# Context management

Be aware of context window pressure. Follow these rules to keep output quality high:
- When a tool returns a very large result (>200 lines), summarize the key findings and note where the full output can be found. Do not paste large outputs verbatim into your response.
- Prefer targeted reads (offset/limit) over full-file reads. Only read the lines you actually need.
- If you notice your responses becoming repetitive or losing track of earlier details, proactively suggest compaction or summarize your current understanding before continuing.
- Keep your working context focused: when switching between unrelated topics, briefly restate the current goal.

# Multi-step tasks

For non-trivial tasks involving multiple files or phases, plan vertically, not horizontally:
- Vertical (preferred): implement one complete slice end-to-end (e.g., type + handler + test), verify it works, then move to the next slice.
- Horizontal (avoid): implementing all types first, then all handlers, then all tests — this delays verification and compounds errors.
- After each vertical slice, run the build and tests to confirm correctness before proceeding.

# Parallel execution

You can call multiple tools in a single response when they are independent. For example:
- Read multiple files simultaneously
- Run grep searches in parallel
- Spawn multiple subagents at once
The TUI tracks all active tools and shows them in the status bar. Only parallelize when operations are truly independent — do not parallelize edits to the same file or dependent operations.

# Diagrams

When a response benefits from a visual diagram, use these three styles as appropriate:

- **Mermaid ` + "`" + `mindmap` + "`" + `** — for showing hierarchy, grouping, or "what belongs to what" (e.g. a toolbelt, a category tree). No directional flow; branches radiate from a center node.
- **Mermaid ` + "`" + `flowchart` + "`" + `** (` + "`" + `TD` + "`" + ` or ` + "`" + `LR` + "`" + `) — for showing a process, pipeline, or decision flow with arrows. Use ` + "`" + `TD` + "`" + ` (top-down) for sequential steps, ` + "`" + `LR` + "`" + ` (left-right) for pipelines with feedback loops.
- **ASCII tree** — for showing file/directory structure, nested config, or anything naturally tree-shaped. Use box-drawing characters (` + "`" + `├──` + "`" + `, ` + "`" + `└──` + "`" + `, ` + "`" + `│` + "`" + `) with optional emoji annotations.

Prefer the simplest style that communicates the idea. Do not mix styles within a single diagram. Use markdown tables to compare or summarize when a diagram is not needed — except for CI and check status, which has its own format below.

# CI status tables

When reporting the state of CI stages — check runs, test gates, coverage gates,
or any set of named checks — draw a box-drawing table. Do not use a markdown
table for this: the TUI renders the response as text, so a markdown table
arrives as raw pipes and dashes, while a box-drawing table renders as the grid
you drew.

Rules:
- Pad every cell so the column rules line up. The table is only readable if the
  vertical bars align down the whole grid; count display width, remembering an
  emoji occupies two columns.
- One row per check, with a separator row between rows.
- Write the status as emoji plus word — ✅ pass, ❌ fail, ⏳ running — so the
  state still reads where emoji do not render.
- Include a Before column only when you changed something and know both states.
  For a single snapshot, drop it and show the current status alone.
- Never invent a status. A check you have not actually observed is unknown:
  say so or leave the row out. Report what the CI output said, not what you
  expect it to say once it finishes.

Example shape:

    ┌─────────────────┬─────────┬────────────┐
    │      Check      │ Before  │    Now     │
    ├─────────────────┼─────────┼────────────┤
    │ codecov/patch   │ ❌ fail │ ✅ pass    │
    ├─────────────────┼─────────┼────────────┤
    │ codecov/project │ ❌ fail │ ✅ pass    │
    ├─────────────────┼─────────┼────────────┤
    │ Test (Windows)  │ ❌ fail │ ⏳ running │
    ├─────────────────┼─────────┼────────────┤
    │ Test            │ pass    │ ⏳ running │
    └─────────────────┴─────────┴────────────┘

# Internal tools

- restart — Restarts the pi process (re-exec with same binary and args). Call this tool after successfully rebuilding the pi binary to apply changes. The process will restart with the updated binary.

# JSON String Escaping

When sending tool parameters that contain file paths or strings with special characters:
- Always escape backslashes in JSON: use ` + "`" + `\\` + "`" + ` not ` + "`" + `\` + "`" + `
- For Windows paths like C:\Users\test, send as "C:\\Users\\test" in JSON
- Verify paths are properly escaped before calling tools that require file_path

Example INCORRECT (will cause tool errors):
{"file_path": "C:\Users\test\file.go"}

Example CORRECT:
{"file_path": "C:\\Users\\test\\file.go"}

# Subagents

You can spawn subagents using the subagent tool to parallelize work. The sidebar shows running agent names, status, and total count.

## When to use agents

Use agents for any task that benefits from parallel or independent work:

- **Research & exploration**: spawn explore agents to search multiple code areas simultaneously. For example, to understand a feature, spawn parallel explores for "find all callers of FooService" and "find the config and initialization for FooService".
- **Repository analysis**: for broad questions ("how does auth work?", "what changed recently?"), spawn 2-3 explore agents targeting different aspects in parallel rather than searching sequentially yourself.
- **Implementation**: use task/designer agents for isolated coding in worktrees, or worker/quick-task agents for edits in the main tree.
- **Review**: use code-reviewer for diff review, spec-reviewer for design document review.
- **Planning**: use the plan agent to produce vertically-sliced implementation plans from codebase research.

## Worktree agents

- "task" and "designer" run in isolated git worktrees. A normal subagent call returns the agent's output; its worktree edits are not automatically applied to the current tree unless a separate workflow keeps and merges that worktree.
- For user-requested changes that must land in this session, either edit the current tree yourself, use "worker"/"quick-task" for main-tree edits, or ask a worktree agent to return an exact patch/file list that you can review and apply.
- When delegating worktree edits, give the agent clear ownership of specific files or directories, expected verification commands, and the final handoff format. Do not send multiple worktree agents to edit the same files.

## Rules

- Maximum 8 concurrent subagents. Do not spawn more than needed.
- Each subagent runs in its own process with its own context and tools.
- Give each subagent a specific, focused task description — not the full ticket. The clearer the input, the better the output.
- **Prefer parallel over sequential**: when researching a topic, spawn 2-4 explore agents with different search angles rather than one agent doing everything.
- **Prefer agents over manual multi-step search**: if finding the answer requires reading 3+ files across different packages, delegate to an explore agent instead of doing it yourself.
- Chain mode passes results between agents: use it when step 2 depends on step 1's output (e.g., explore → plan → task).

# Diagram style

For diagrams of packages, modules, or folders, use an ASCII tree with
category-grouped emojis — not Mermaid. Mermaid is still fine for flowcharts and
process; ASCII + emoji is for structure.

Rules:
- Print the root directory with a leading emoji and a bucket label (e.g. internal/).
- Group first-level children under a blank line beginning with the tree char, the emoji, and the category, then list the package(s) under it indented with the tree chars.
- Use one emoji per category, reused consistently across diagrams.
- Keep descriptions on the same line, terse.
- Prefer the last-item tree char for the final item in a group; use the mid-item char otherwise.

Example shape (tree chars shown literally):

    internal/
    ├── 🤖 agent runtime
    │   ├── agent/          Agent, run loop, callbacks, eventstream
    │   └── subagent/       Orchestrator, worktree mgmt, spawn/cancel
    ├── 🧠 model pipeline
    │   ├── provider/       9 backends + modeldata/ + list_models
    │   └── (pimodels/)     public façade — at repo root
    └── 🧰 tools
        ├── tools/          read·write·edit·bash·grep·find·git·lsp·mem
        └── lsp/            Manager, language servers, protocol
`

SystemInstruction is the default system prompt for the coding agent.

Variables

This section is empty.

Functions

func AppendActiveSkill added in v0.0.48

func AppendActiveSkill(prompt string, skill extension.Skill, body string) string

AppendActiveSkill returns prompt with an "# Active Skill" section appended for the given skill body. Use this on top of a prompt produced by LoadInstruction to activate a skill for one turn (Level-2 injection).

The format is:

\n\n# Active Skill: <name>\n\n<body>\n

func EventError added in v0.0.46

func EventError(ev *session.Event) error

EventError extracts a provider-level failure from an event, or nil if the event is fine.

Providers report LLM failures (HTTP 4xx/5xx, stream aborts, guardrail rejections) by yielding an event that carries ErrorCode/ErrorMessage with a *nil* Go error and no Content. ADK then ends the turn normally, so every consumer that only guards on `err != nil` and `ev.Content == nil` drops the failure on the floor and shows the user an empty response. Call this right after the nil-event check, before the Content guard, so the error reaches the surface instead of being swallowed.

func GatewayRouteSpeaksGemini added in v0.2.0

func GatewayRouteSpeaksGemini(modelName string) bool

GatewayRouteSpeaksGemini reports whether an agentgateway model name resolves to a route whose upstream speaks Gemini's native generateContent protocol.

The gateway fronts every provider behind one endpoint, so the provider name alone cannot say whether Gemini's server-side search is available — the ROUTE decides. The convention mirrored here is the one the gateway's own config.yaml follows: gemini/* and gemini-* are Gemini routes.

This is deliberately a second implementation of internal/provider.GatewayRoutesToGemini rather than a call into it, and the reason is a hard constraint rather than a preference: piagent imports this package, and TestPiagentStaysIsolated forbids internal/provider anywhere in piagent's transitive graph, so importing it here would break the embedder. The two lists are pinned together by TestGatewayRouteSpeaksGeminiAgreesWithProvider, which fails the moment either one changes alone — that test is what makes the duplication safe.

func GeminiGroundingTool added in v0.0.41

func GeminiGroundingTool(providerName, modelName string) (tool.Tool, bool)

GeminiGroundingTool returns the geminitool.GoogleSearch tool if and only if the active provider is served by Gemini (see GroundsViaGemini) and grounding has not been disabled by the PI_NO_GROUNDING env var. It returns (nil, false) otherwise. Callers append the returned tool to the agent's Tools slice only when the second return value is true.

modelName may be empty; a caller that has already established the provider is "gemini" does not need it. It is required for the agentgateway case, where the provider name alone does not say which upstream the route reaches.

func GroundingQuery added in v0.0.41

func GroundingQuery(gm *genai.GroundingMetadata) string

GroundingQuery renders the searched queries as a single human-readable string.

func GroundingQueryKey added in v0.0.41

func GroundingQueryKey(queries []string) string

GroundingQueryKey identifies a search by its query set. GroundingMetadata is repeated on every streamed chunk of the response it grounds, so callers key on this to report each search exactly once per turn.

func GroundingSources added in v0.0.41

func GroundingSources(gm *genai.GroundingMetadata) string

GroundingSources returns every source as "label — uri", uncapped. This is the full-fidelity form for the trace log and session record, where width does not matter and the redirect URIs are worth keeping.

func GroundingSummary added in v0.0.41

func GroundingSummary(gm *genai.GroundingMetadata) string

GroundingSummary lists every source a search returned, one per line.

Sources are deduplicated by label. Gemini commonly cites several distinct pages from the same site, and since it sets Title to the site's domain, those arrive as identical labels — printing them verbatim gave "kyivindependent.com kyivindependent.com kyivindependent.com". A repeated label is instead shown once with a count: "kyivindependent.com (3)".

Only the source *label* is shown, not its URI. Google Search grounding does not return the real source URL: it returns an opaque ~200-character vertexaisearch.cloud.google.com/grounding-api-redirect/... link. Printing that tells the reader nothing, soft-wraps across several rows, and shreds the chat panel's layout. The full URIs are still written to the trace log via GroundingSources, so nothing is lost.

func GroundingToolNameFor added in v0.1.8

func GroundingToolNameFor(providerName string) string

GroundingToolNameFor returns the display name for a server-side search run by the given provider. Gemini grounds with Google Search and OpenAI with its own web_search; anything else returning GroundingMetadata is treated as the Gemini shape, which is where the convention started.

Azure is included with OpenAI because it serves the same model and the same Responses API.

func GroundsViaGemini added in v0.2.0

func GroundsViaGemini(providerName, modelName string) bool

GroundsViaGemini reports whether a resolved provider/model pair is served by Gemini, and so may carry Gemini's server-side search.

Two shapes reach Gemini and they are not the same provider:

  • "gemini" — the AI Studio API directly, where the provider name is the whole answer.
  • "agentgateway" — the local gateway, but only for a route whose upstream speaks native Gemini. The gateway also fronts OpenAI, Anthropic and Ollama, and a grounding tool registered for one of those is dropped in conversion rather than rejected: {"type":"google_search"} simply disappears and the model then answers from its own priors. So the model name has to agree, and this is the same question internal/provider asks before choosing the native client.

The model name is therefore required for the gateway case and optional for the direct one, so a caller that knows only the provider still works.

func LoadInstruction

func LoadInstruction(baseInstruction string) string

LoadInstruction appends discovered project context files and a summary of discovered skills to the base instruction. Context files (AGENT.md, AGENTS.md, CLAUDE.md, or .pi-go/AGENTS.md; first match per directory) are discovered by walking from the working directory up to the filesystem root; a global ~/.pi-go/AGENTS.md is included first when present.

func WithRetry

func WithRetry(cfg RetryConfig, runFn func() iter.Seq2[*session.Event, error]) iter.Seq2[*session.Event, error]

WithRetry wraps an agent run function with retry logic for transient errors. If the iterator yields a transient error, it sleeps and retries the entire run. Non-transient errors are yielded immediately without retry.

This is the coarse net. It can only replay a run that produced nothing, so it does not help once a turn is underway — by the time a mid-turn request fails, tool calls have already been yielded and re-running them is not safe. The finer net is in internal/provider, which retries the single failed HTTP request without disturbing the turn around it.

func WithRetryContext added in v0.0.76

func WithRetryContext(ctx context.Context, cfg RetryConfig, runFn func() iter.Seq2[*session.Event, error]) iter.Seq2[*session.Event, error]

WithRetryContext is WithRetry with a context: each retry is announced to the retry.Notifier carried on ctx (see retry.WithNotifier), so the front-end can show that it is waiting on a retry rather than on the model, and the backoff sleep ends early if ctx is canceled.

Types

type AfterModelCallback added in v0.0.25

type AfterModelCallback = llmagent.AfterModelCallback

re-export callback types for use by CLI without importing llmagent directly.

type AfterToolCallback

type AfterToolCallback = llmagent.AfterToolCallback

re-export callback types for use by CLI without importing llmagent directly.

type Agent

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

Agent wraps an ADK Runner and session management for the coding agent.

func New

func New(cfg Config) (*Agent, error)

New creates a new Agent with the given configuration.

func (*Agent) CreateSession

func (a *Agent) CreateSession(ctx context.Context) (sessionID, defaultTitle string, err error)

CreateSession creates a new session and returns its ID together with the default title that was applied (git repo name, or CWD basename) — or "" if no title was set. The title is metadata only; the TUI seeds its terminal window/tab title from it so users see a sensible label before the first user prompt arrives.

func (*Agent) HasPreTurnHook added in v0.1.0

func (a *Agent) HasPreTurnHook() bool

HasPreTurnHook reports whether a pre-turn hook is installed. It exists so a caller can assert that compaction was actually wired: every entry point installs the hook conditionally, and an entry point that quietly declined to would show no symptom until a transcript outgrew its context window.

func (*Agent) OpenSession added in v0.0.92

func (a *Agent) OpenSession(ctx context.Context, sessionID string) (resumed bool, err error)

OpenSession resumes the session persisted under sessionID, creating it when the session service has no record of that id. It reports whether an existing transcript was found. This is how a server hosting a session for an external client — an ACP editor, an A2A gateway — continues a conversation across its own restarts: the client keeps the id, and the transcript lives under it.

func (*Agent) RebuildWithInstruction

func (a *Agent) RebuildWithInstruction(instruction string) error

RebuildWithInstruction recreates the agent's internal runner with a new system instruction while preserving all other configuration (tools, callbacks, etc.). The session service is reused so existing sessions remain accessible.

func (*Agent) RebuildWithModel added in v0.0.34

func (a *Agent) RebuildWithModel(llm model.LLM) error

RebuildWithModel recreates the agent's internal runner with a new LLM while preserving all other configuration (tools, callbacks, instruction, session). The session service is reused so existing sessions remain accessible.

func (*Agent) Run

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

Run sends a user message and returns an iterator over agent events. The caller should iterate over the returned sequence to process events.

func (*Agent) RunStreaming

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

RunStreaming sends a user message with SSE streaming enabled.

func (*Agent) SetPreTurnHook added in v0.0.48

func (a *Agent) SetPreTurnHook(h PreTurnHook)

SetPreTurnHook installs a hook that runs before every turn. Passing nil removes it.

func (*Agent) SetSessionTitle added in v0.0.43

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

SetSessionTitle records a title for the given session via the session service when it supports it. Services without the title capability (e.g. the ADK in-memory service) silently no-op — the title is metadata that is safe to lose for ephemeral sessions.

type BeforeModelCallback added in v0.0.25

type BeforeModelCallback = llmagent.BeforeModelCallback

re-export callback types for use by CLI without importing llmagent directly.

type BeforeToolCallback

type BeforeToolCallback = llmagent.BeforeToolCallback

re-export callback types for use by CLI without importing llmagent directly.

type Config

type Config struct {
	// Model is the LLM provider to use (implements model.LLM).
	Model model.LLM

	// Tools are the tools available to the agent.
	Tools []tool.Tool

	// Toolsets are additional tool providers (e.g. MCP toolsets).
	Toolsets []tool.Toolset

	// Instruction overrides the default system instruction.
	// If empty, SystemInstruction is used.
	Instruction string

	// SessionService overrides the default in-memory session service.
	// If nil, an in-memory service is created.
	SessionService session.Service

	// BeforeToolCallbacks run before each tool execution.
	BeforeToolCallbacks []BeforeToolCallback

	// AfterToolCallbacks run after each tool execution.
	AfterToolCallbacks []AfterToolCallback

	// BeforeModelCallbacks run before each LLM invocation.
	BeforeModelCallbacks []BeforeModelCallback

	// AfterModelCallbacks run after each LLM invocation.
	AfterModelCallbacks []AfterModelCallback

	// WorkingDir, when non-empty, is the directory reported to the model as
	// the current working directory. Empty means the process's, which is
	// right for the CLI but wrong for an embedder driving a directory it was
	// not started in.
	WorkingDir string

	// Version is the pi-go build string recorded in the session's metadata
	// (e.g. "1.4.2+a1b2c3d"), so a transcript can be tied to the build that
	// produced it. Empty means the field is left out of meta.json. It is a
	// caller-supplied string rather than a lookup because the CLI stamps the
	// version through -ldflags and an embedder may carry a different one.
	Version string

	// Logger, if non-nil, receives non-fatal diagnostics such as unresolved
	// instruction placeholders. These are written to the session log rather
	// than stderr: stderr would paint over the TUI alt-screen. Its methods
	// are nil-safe, so a nil Logger silently discards.
	Logger *logger.Logger
}

Config holds configuration for creating a new Agent.

type InstructionParts added in v0.0.48

type InstructionParts struct {
	// Base is the built-in system prompt.
	Base string
	// Rules is the concatenated AGENTS.md / CLAUDE.md project context.
	Rules string
	// Skills is the "# Available Skills" menu.
	Skills string
}

InstructionParts is the system prompt broken into the sections it is assembled from. Callers that only need the finished prompt use LoadInstruction; the parts exist so the TUI can attribute context usage to each section instead of reporting one opaque total.

func LoadInstructionParts added in v0.0.48

func LoadInstructionParts(baseInstruction string) InstructionParts

LoadInstructionParts resolves the system prompt and returns it broken into its sections.

func LoadInstructionPartsFor added in v0.0.73

func LoadInstructionPartsFor(baseInstruction, cwd string) InstructionParts

LoadInstructionPartsFor resolves the system prompt for an explicit working directory instead of the process's, and returns it broken into its sections. Callers that drive the agent over a directory they were not started in — the public piagent package, for one — need this; LoadInstructionParts is the os.Getwd() convenience on top of it.

func (InstructionParts) String added in v0.0.48

func (p InstructionParts) String() string

String reassembles the parts into the prompt the model receives. Keeping composition here means the breakdown can never drift from the real prompt: LoadInstruction returns exactly this.

type PreTurnHook added in v0.0.48

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

PreTurnHook runs before a turn is dispatched to the runner. Returning an error aborts the turn.

type RetryConfig

type RetryConfig = retry.Config

RetryConfig controls retry behavior for transient LLM errors.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns sensible defaults for retry behavior.

type StreamDedup added in v0.0.46

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

StreamDedup suppresses the duplicate copy of assistant text that SSE streaming produces.

Under StreamingModeSSE, ADK yields each chunk as a Partial event and then re-yields the whole turn once more as a non-partial aggregate. A consumer that emits every text part it sees therefore emits the reply twice — which is what `pi --mode print` and `--mode json` did until this existed.

Usage, once per run:

var dedup agent.StreamDedup
for ev := range events {
    dedup.BeginEvent(ev)          // once per event, before its parts
    for _, part := range ev.Content.Parts {
        if part.Text != "" && dedup.SkipText(ev) {
            continue              // aggregate re-send; deltas already went out
        }
        ...
    }
}

The zero value is ready to use. Not safe for concurrent use; one value tracks one event stream.

func (*StreamDedup) BeginEvent added in v0.0.46

func (d *StreamDedup) BeginEvent(ev *session.Event)

BeginEvent starts a new turn's bookkeeping when ev is not model-authored. A user or tool-result event means the next model turn may arrive as a bare aggregate with no deltas in front of it, and that aggregate must pass through. Call once per event, before walking its parts.

func (*StreamDedup) SkipText added in v0.0.46

func (d *StreamDedup) SkipText(ev *session.Event) bool

SkipText reports whether the non-empty text part currently being walked is the aggregate re-send of text already emitted as deltas. Call it only for parts with non-empty text: it is what records that deltas were seen, so calling it for empty parts would suppress the following aggregate even when nothing was emitted.

Jump to

Keyboard shortcuts

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