extension

package
v0.2.9 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

Package extension provides hooks (before/after tool call), skill loading, and MCP tool integration for the pi-go agent.

Index

Constants

This section is empty.

Variables

View Source
var SkillTemplate string

Functions

func BuildAfterToolCallbacks

func BuildAfterToolCallbacks(hooks []HookConfig) []llmagent.AfterToolCallback

BuildAfterToolCallbacks converts HookConfigs with event "after_tool" into ADK AfterToolCallback functions.

func BuildBeforeToolCallbacks

func BuildBeforeToolCallbacks(hooks []HookConfig) []llmagent.BeforeToolCallback

BuildBeforeToolCallbacks converts HookConfigs with event "before_tool" into ADK BeforeToolCallback functions.

func BuildLLMTracingCallbacks added in v0.0.25

func BuildLLMTracingCallbacks(providerName string) ([]llmagent.BeforeModelCallback, []llmagent.AfterModelCallback)

BuildLLMTracingCallbacks returns before/after model callbacks that emit one OTEL span per LLM invocation, named and attributed per the OpenTelemetry GenAI semantic conventions (semconv v1.37.0): `chat <model>`, carrying gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.response.finish_reasons and the gen_ai.usage.* token counts.

providerName is pi-go's provider id ("openai", "anthropic", …); it is mapped onto the semconv enum where one exists and passed through otherwise.

ADK callbacks cannot hand a context back to the framework, so the span cannot be carried between the two callbacks through ctx. It is held in a registry keyed by invocation instead — see llmSpans.

func BuildMCPToolsets

func BuildMCPToolsets(servers []MCPServerConfig) ([]tool.Toolset, error)

BuildMCPToolsets creates ADK Toolsets from MCP server configurations. Each server is launched as a subprocess using CommandTransport. Servers that fail to initialize are logged and skipped rather than failing the entire batch.

func BuildReadImageCallback added in v0.0.47

func BuildReadImageCallback(sb *tools.Sandbox, providerName string) llmagent.BeforeModelCallback

BuildReadImageCallback returns a BeforeModelCallback that finds the newest read_image FunctionResponse in the request and injects the underlying image bytes as an InlineData part on the Content that carried it. This is what makes a screenshot actually visible to a vision-capable model.

The read_image tool returns only the path + metadata (never the bytes), so the bytes never transit the text channel. The callback re-reads the file (sandboxed) and appends a genai.Part{InlineData} alongside the text result.

Two things bound the work, because a BeforeModelCallback runs once per model request — that is once per agentic step, not once per user turn, and ADK rebuilds req.Contents from the session events each step, so nothing injected here survives into the next one:

  • Providers whose adapter drops InlineData get a no-op callback. Reading the file would be pure waste there; see providerForwardsInlineImages.
  • Only the most recent Content carrying read_image results is injected into, not every such Content in the history. Walking the whole history re-read and re-uploaded every screenshot the session had ever taken on every step. The trade is that only the latest image stays visible; an older one is still in context as its textual path + metadata.

func BuildToolCallCallbacks added in v0.0.25

BuildToolCallCallbacks creates ADK before/after tool callbacks that report tool calls to the ACP peer via s. The BeforeToolCallback emits StartToolCall; the AfterToolCallback emits UpdateToolCall with the result or error.

Correlation: ctx.FunctionCallID() is the ADK-assigned unique identifier for each tool invocation. It is the same value in both the before and after callback, so it is used as the key to carry the ACP call ID (returned by OnToolStart) across the two callbacks. Without this, the result of every tool call would be silently dropped because OnToolEnd would receive an empty call ID and treat it as a no-op.

func BuildTracingCallbacks added in v0.0.25

func BuildTracingCallbacks() ([]llmagent.BeforeToolCallback, []llmagent.AfterToolCallback)

BuildTracingCallbacks returns before/after tool callbacks that emit OTEL spans for every tool invocation. The parent span context is propagated from the context passed to the callback, so spans are linked to the agent's trace.

Spans are carried between the two callbacks through a registry keyed by function call id, which is unique per tool call and so stays correct when the model runs several tools in parallel.

func ComposeAfterTool added in v0.1.6

func ComposeAfterTool(cbs []llmagent.AfterToolCallback) llmagent.AfterToolCallback

ComposeAfterTool folds a chain of after-tool callbacks into the single callback handed to ADK.

ADK's own chain (llminternal.Flow.invokeAfterToolCallbacks, adk v2.4.0 internal/llminternal/base_flow.go:1436) returns at the FIRST callback that yields a non-nil result:

for _, callback := range f.AfterToolCallbacks {
    result, err := callback(...)
    if result != nil { return result, nil }
}

pi-go registers several after-tool callbacks that each return the result map — hooks, OTEL tracing, LSP, dedup, the compactor, memory recording — so handing ADK the slice runs only the first of them and silently skips the rest. OTEL tracing is registered first and always returns non-nil, so every stage after it, including dedup and the compactor, was dead in production.

The composed semantics are:

  • (nil, nil): result unchanged, chain continues.
  • (m, nil): m becomes the result later callbacks see, and the one returned.
  • (_, err): the chain aborts and err propagates.

If every callback returns nil the composed callback returns (nil, nil), which tells ADK to keep the tool's own result — the same as an empty chain.

Call sites must pass the composed callback as the only entry in the slice.

func ComposeAfterToolChain added in v0.1.6

func ComposeAfterToolChain(cbs []llmagent.AfterToolCallback) []llmagent.AfterToolCallback

ComposeAfterToolChain wraps ComposeAfterTool for the shape ADK expects: a one-element slice, or nil when there is nothing to run.

func DefaultSkillDirs added in v0.0.29

func DefaultSkillDirs() []string

DefaultSkillDirs returns the default skill directories to search. It returns user-level (~/.pi-go/skills) plus project-level directories (.pi-go/skills, .claude/skills, .cursor/skills) found by walking up from the current working directory.

func DefaultSkillDirsIn added in v0.0.29

func DefaultSkillDirsIn(root string) []string

DefaultSkillDirsIn returns skill directories relative to the given root. Installed plugins come first (lowest priority), then the user-level skill directory (~/.pi-go/skills), then the project-level directories (.pi-go/skills, .claude/skills, .cursor/skills) found by walking up from root.

Order is precedence: a later directory overrides an earlier one, so a plugin can never silently replace a skill the user wrote or customized under the same name.

func InstalledPluginSkillDirs added in v0.1.5

func InstalledPluginSkillDirs(piHome string) []string

InstalledPluginSkillDirs returns the skills directories of plugins installed under the given pi-go home. A missing or unreadable registry yields no directories: an installation problem must never stop pi-go from loading the skills it already had.

func LoadBundledSkills added in v0.0.16

func LoadBundledSkills() (map[string][]BundledSkillFile, error)

LoadBundledSkills loads all embedded skill files. Returns a map of skill name → []BundledSkillFile (SKILL.md + supporting files).

func LoadSkillBody added in v0.0.48

func LoadSkillBody(skills []Skill, name string) (string, error)

LoadSkillBody returns the markdown body of a skill on demand. For file-based skills this reads Skill.BodyPath from disk; for bundled skills it looks up the embed-fs cache populated at LoadSkills time. The result is suitable for injection into the system prompt.

Returns an error if the skill name is not present in skills, or if the body cannot be read.

func LoadedToolsetTools added in v0.0.48

func LoadedToolsetTools(toolsets []tool.Toolset) []tool.Tool

LoadedToolsetTools returns the tools already cached by connected MCP toolsets, without triggering a fetch. Callers that need to measure what MCP contributes to the prompt use this rather than Toolset.Tools, which takes an invocation context and can block on a network round-trip — measuring context overhead must never stall startup or a render.

Pending and failed servers contribute nothing, so the figure is a floor: it counts what is loaded, never a guess at what might load later.

func RunLifecycleHook added in v0.0.53

func RunLifecycleHook(ctx context.Context, hook HookConfig, event string, data map[string]any) error

RunLifecycleHook executes a lifecycle hook's shell command with the event name and data as JSON on stdin. Lifecycle hooks (turn_complete, user_input_required) have no tool, so the payload carries the event instead. A non-zero exit or timeout is logged by the caller, never fatal.

func SetHookLogger added in v0.0.53

func SetHookLogger(fn func(string))

SetHookLogger installs a sink for hook-failure diagnostics. Passing nil restores the default (standard logger, i.e. stderr). Hooks run from callback goroutines, so implementations must be goroutine-safe.

func SetInteractiveOAuth added in v0.0.77

func SetInteractiveOAuth(enabled bool)

SetInteractiveOAuth enables or disables the automatic OAuth re-login for MCP servers that answer 401/403. Only a front end with a user and a browser in reach should enable it.

func SkillBodySize added in v0.0.48

func SkillBodySize(skills []Skill, name string) (int, bool)

SkillBodySize returns the size in bytes of a skill's body if it is already loaded (e.g. by a prior LoadSkillBody call or by a slash-activation that rebuilt the agent with this skill active). The second return value is false if the body has not been loaded — callers should use this to avoid triggering I/O just to render a /context display.

For bundled skills the body is always considered loaded (it was read at LoadSkills time).

Types

type AuditMode added in v0.0.10

type AuditMode string

AuditMode controls how skill loading handles audit findings.

const (
	// AuditBlock blocks skills with critical findings (default).
	AuditBlock AuditMode = "block"
	// AuditWarn loads all skills but logs warnings for critical findings.
	AuditWarn AuditMode = "warn"
	// AuditSkip skips scanning entirely (backward compat for tests).
	AuditSkip AuditMode = "skip"
)

type BundledSkillFile added in v0.0.16

type BundledSkillFile struct {
	SkillName string
	RelPath   string
	Content   []byte
}

BundledSkillFile represents a skill loaded from the embedded filesystem.

type HookConfig

type HookConfig struct {
	// Event is "before_tool" or "after_tool".
	Event string `json:"event"`
	// Command is the shell command to execute.
	Command string `json:"command"`
	// Tools optionally restricts this hook to specific tool names.
	// If empty, the hook fires for all tools.
	Tools []string `json:"tools,omitempty"`
	// Timeout in seconds for hook execution. Default: 10.
	Timeout int `json:"timeout,omitempty"`
}

HookConfig defines a shell command hook that runs before or after tool calls.

type LoadOptions added in v0.0.10

type LoadOptions struct {
	AuditMode AuditMode
}

LoadOptions controls skill loading behavior.

type MCPServerConfig

type MCPServerConfig struct {
	Name    string            `json:"name"`
	Command string            `json:"command,omitempty"`
	Args    []string          `json:"args,omitempty"`
	URL     string            `json:"url,omitempty"`     // HTTP transport (Streamable HTTP)
	Headers map[string]string `json:"headers,omitempty"` // Custom HTTP headers for the URL transport
	OAuth   bool              `json:"oauth,omitempty"`   // run the OAuth authorization-code flow on first connect
}

MCPServerConfig matches the config.MCPServer structure.

type MCPServerStatus added in v0.0.22

type MCPServerStatus struct {
	Name      string
	Connected bool   // true if Tools() succeeded at least once
	Failed    bool   // true if Tools() timed out or returned an error
	ToolCount int    // number of tools reported; 0 if not yet loaded
	Status    string // "connected", "failed", "pending"
}

func ToolsetStatuses added in v0.0.22

func ToolsetStatuses(toolsets []tool.Toolset) []MCPServerStatus

ToolsetStatuses returns the current status for each toolset that was created by BuildMCPToolsets. Toolsets that haven't been queried yet are reported as "pending".

type MCPToolEntry added in v0.0.22

type MCPToolEntry struct {
	Server string
	Tool   string
}

MCPToolEntry is a single resolved tool from a named MCP server.

func BuildMCPToolEntries added in v0.0.22

func BuildMCPToolEntries(toolsets []tool.Toolset) []MCPToolEntry

BuildMCPToolEntries returns a flat list of {Server, Tool} pairs for all connected MCP toolsets. Only toolsets whose tools have already been loaded (via a previous Tools() call) contribute entries — pending/failed servers are silently skipped.

type Skill

type Skill struct {
	// Name is the skill's identifier (derived from directory name).
	Name string
	// Description is a one-line description from frontmatter.
	Description string
	// Instruction is the markdown body (the system prompt to inject).
	// Empty after LoadSkills/parseSkillFile; use LoadSkillBody to read it.
	Instruction string
	// BodyPath is the on-disk path to the SKILL.md file used to read the body
	// on demand. Empty for bundled skills (their body is read from the
	// embedded filesystem via the bundledSkillsFS key).
	BodyPath string
	// Tools lists tool names this skill is allowed to use (from frontmatter).
	Tools []string
	// Source is where the skill came from: "bundled", "user", or "project".
	Source string
}

Skill represents a loaded skill from a SKILL.md file.

func FindSkill

func FindSkill(skills []Skill, name string) (Skill, bool)

FindSkill looks up a skill by name from a slice of loaded skills.

func LoadSkills

func LoadSkills(dirs ...string) ([]Skill, error)

LoadSkills discovers and loads skills from the given directories. It searches for <dir>/<skill-name>/SKILL.md subdirectories. Later directories override earlier ones (project overrides global). Skills with critical audit findings are blocked when AuditMode is "block" (default).

func LoadSkillsWithOptions added in v0.0.10

func LoadSkillsWithOptions(opts LoadOptions, dirs ...string) ([]Skill, error)

LoadSkillsWithOptions discovers and loads skills with configurable audit behavior. Bundled skills (embedded in the binary) are loaded first and can be overridden by user or project skills.

type ToolCallReporter added in v0.0.25

type ToolCallReporter interface {
	OnToolStart(ctx context.Context, name string, args map[string]any) (string, error)
	OnToolEnd(ctx context.Context, callID string, args map[string]any, result any, runErr error) error
}

ToolCallReporter is the interface that adapter.Stream exposes for reporting tool call lifecycle events to the ACP peer. This allows BuildToolCallCallbacks to bridge ADK Before/AfterToolCallbacks → ACP StartToolCall/UpdateToolCall.

Jump to

Keyboard shortcuts

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