adk

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CauseApprovalDenied          = "approval_denied"
	CauseApprovalTimeout         = "approval_timeout"
	CauseApprovalUnavailable     = "approval_unavailable"
	CauseToolNotFound            = "tool_not_found"
	CauseFunctionCallValidation  = "function_call_validation"
	CauseOrchestratorDirectTool  = "orchestrator_direct_tool_call"
	CauseUnknownToolError        = "unknown_tool_error"
	CauseProviderRateLimit       = "provider_rate_limit"
	CauseProviderTransient       = "provider_transient"
	CauseProviderAuth            = "provider_auth"
	CauseProviderConnection      = "provider_connection"
	CauseThoughtSignatureMissing = "thought_signature_missing"
	CauseTimeoutIdle             = "timeout_idle"
	CauseTimeoutHard             = "timeout_hard"
	CauseRepeatedCallSignature   = "repeated_call_signature"
	CauseTurnLimitExceeded       = "turn_limit_exceeded"
	CauseEmptyAfterToolUse       = "empty_after_tool_use"
	CauseInternalRuntimeError    = "internal_runtime_error"
)
View Source
const DefaultTokenBudget = 32000

DefaultTokenBudget is the token budget used when no explicit budget is provided.

Variables

This section is empty.

Functions

func AdaptTool

func AdaptTool(t *agent.Tool) (tool.Tool, error)

AdaptTool converts an internal agent.Tool to an ADK tool.Tool.

func AdaptToolForAgent added in v0.4.0

func AdaptToolForAgent(t *agent.Tool, agentName string) (tool.Tool, error)

AdaptToolForAgent converts an internal agent.Tool to an ADK tool.Tool and injects the given agentName into the context for every handler invocation. This allows downstream hooks and middleware to identify which agent owns the tool call.

func AdaptToolForAgentWithTimeout added in v0.4.0

func AdaptToolForAgentWithTimeout(t *agent.Tool, agentName string, timeout time.Duration) (tool.Tool, error)

AdaptToolForAgentWithTimeout combines agent name injection with a per-call timeout.

func AdaptToolWithTimeout

func AdaptToolWithTimeout(t *agent.Tool, timeout time.Duration) (tool.Tool, error)

AdaptToolWithTimeout converts an internal agent.Tool to an ADK tool.Tool with an enforced per-call timeout. If timeout <= 0, behaves like AdaptTool.

func AgentNameFromContext added in v0.4.0

func AgentNameFromContext(ctx context.Context) string

AgentNameFromContext extracts the agent name stored in ctx. Returns an empty string when no agent name is present.

func LookupModelWindow added in v0.7.0

func LookupModelWindow(modelName string) int

LookupModelWindow returns the context window size for the given model name. Matches by longest prefix. Returns defaultModelWindow (128k) for unknown models.

func ModelTokenBudget

func ModelTokenBudget(modelName string) int

ModelTokenBudget returns an appropriate history token budget for the given model. It uses approximately 50-60% of each model family's context window, leaving room for system prompts, tool definitions, and generated output. Returns DefaultTokenBudget for unknown models.

func NewBeforeToolLoggingPlugin added in v0.7.0

func NewBeforeToolLoggingPlugin() (*plugin.Plugin, error)

NewBeforeToolLoggingPlugin creates a spike plugin that logs tool invocations via BeforeToolCallback. Demonstrates the callback firing for ALL tools (agent-level scope) and shows how blocking would work.

Spike implementation. Not called from app wiring.

func NewEventLoggingPlugin added in v0.7.0

func NewEventLoggingPlugin() (*plugin.Plugin, error)

NewEventLoggingPlugin creates an ADK plugin that logs session events for observability. This is a spike implementation demonstrating OnEventCallback integration.

The plugin logs:

  • Event author and type
  • Delegation transfers (agent-to-agent)
  • Function calls (tool invocations)
  • Text responses

This demonstrates a cross-cutting concern that maps cleanly to ADK's agent-level plugin model — no per-tool scoping needed.

Spike implementation. Not called from app wiring.

func WithAgentName added in v0.4.0

func WithAgentName(ctx context.Context, name string) context.Context

WithAgentName returns a context carrying the given agent name. This delegates to ctxkeys.WithAgentName so that any package importing ctxkeys can read the value without depending on the adk package.

func WithChildSession added in v0.4.0

func WithChildSession(ctx context.Context, info ChildSessionInfo) context.Context

WithChildSession stores child session info in context.

Types

type Agent

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

Agent wraps the ADK runner for integration with Lango.

func NewAgent

func NewAgent(ctx context.Context, tools []tool.Tool, mod model.LLM, systemPrompt string, store internal.Store, opts ...AgentOption) (*Agent, error)

NewAgent creates a new Agent instance.

func NewAgentFromADK

func NewAgentFromADK(adkAgent adk_agent.Agent, store internal.Store, opts ...AgentOption) (*Agent, error)

NewAgentFromADK creates a Lango Agent wrapping a pre-built ADK agent. Used for multi-agent orchestration where the agent tree is built externally.

func (*Agent) ADKAgent

func (a *Agent) ADKAgent() adk_agent.Agent

ADKAgent returns the underlying ADK agent, or nil if not available.

func (*Agent) Run

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

Run executes the agent for a given session and returns an event iterator. It enforces a maximum turn limit to prevent unbounded tool-calling loops.

func (*Agent) RunAndCollect

func (a *Agent) RunAndCollect(ctx context.Context, sessionID, input string, opts ...RunOption) (string, error)

RunAndCollect executes the agent and returns the full text response. If the agent encounters a "failed to find agent" error (hallucinated agent name), it sends a correction message and retries once.

func (*Agent) RunStreaming

func (a *Agent) RunStreaming(ctx context.Context, sessionID, input string, onChunk ChunkCallback, opts ...RunOption) (string, error)

RunStreaming executes the agent and streams partial text chunks via the callback. It returns the full accumulated response text for backward compatibility.

func (*Agent) RunStreamingDetailed added in v0.7.0

func (a *Agent) RunStreamingDetailed(ctx context.Context, sessionID, input string, onChunk ChunkCallback, opts ...RunOption) (RunReport, error)

RunStreamingDetailed executes the agent, streams chunks, and returns structured diagnostics.

func (*Agent) WithErrorFixProvider

func (a *Agent) WithErrorFixProvider(p ErrorFixProvider) *Agent

WithErrorFixProvider sets an optional provider for learning-based error correction. When set, the agent will attempt to apply known fixes on errors before giving up.

func (*Agent) WithMaxTurns

func (a *Agent) WithMaxTurns(n int) *Agent

WithMaxTurns sets the maximum number of tool-calling turns per run. Zero or negative values use the default (50).

type AgentError added in v0.5.0

type AgentError struct {
	Code            ErrorCode
	Message         string        // internal message
	Cause           error         // underlying error
	Partial         string        // accumulated text before failure
	Elapsed         time.Duration // time spent before failure
	CauseClass      string
	CauseDetail     string
	OperatorSummary string
}

AgentError is a structured error type that preserves partial results accumulated before the failure, along with classification metadata.

func (*AgentError) DiagnosticSummary added in v0.7.0

func (e *AgentError) DiagnosticSummary() string

DiagnosticSummary returns an operator-facing summary with cause class and detail.

func (*AgentError) Error added in v0.5.0

func (e *AgentError) Error() string

func (*AgentError) Unwrap added in v0.5.0

func (e *AgentError) Unwrap() error

func (*AgentError) UserMessage added in v0.5.0

func (e *AgentError) UserMessage() string

UserMessage returns a user-facing formatted message with error code and hint.

type AgentOption

type AgentOption func(*agentOptions)

AgentOption configures optional Agent behavior at construction time.

func WithAgentChildLifecycleHook added in v0.7.0

func WithAgentChildLifecycleHook(fn func(internal.SessionLifecycleEvent)) AgentOption

WithAgentChildLifecycleHook records synthetic child-session lifecycle events.

func WithAgentErrorFixProvider

func WithAgentErrorFixProvider(p ErrorFixProvider) AgentOption

WithAgentErrorFixProvider sets a learning-based error correction provider.

func WithAgentIsolatedAgents added in v0.7.0

func WithAgentIsolatedAgents(names []string) AgentOption

WithAgentIsolatedAgents marks agent names that should use child session history routing.

func WithAgentMaxTurns

func WithAgentMaxTurns(n int) AgentOption

WithAgentMaxTurns sets the maximum number of tool-calling turns per run.

func WithAgentRootSessionObserver added in v0.7.0

func WithAgentRootSessionObserver(fn func(string)) AgentOption

WithAgentRootSessionObserver records root session creation events.

func WithAgentTokenBudget

func WithAgentTokenBudget(budget int) AgentOption

WithAgentTokenBudget sets the session history token budget. Use ModelTokenBudget(modelName) to derive an appropriate value.

func WithPlugins added in v0.7.0

func WithPlugins(plugins ...*plugin.Plugin) AgentOption

WithPlugins adds ADK plugins to the runner configuration. Plugins provide agent-level callbacks (BeforeTool, AfterTool, OnEvent, etc.) that are executed by the ADK runner for every tool invocation. Zero plugins preserves current behavior.

type ChildSessionInfo added in v0.4.0

type ChildSessionInfo struct {
	ChildKey  string
	ParentKey string
	AgentName string
}

ChildSessionInfo holds child session metadata in context.

func ChildSessionFromContext added in v0.4.0

func ChildSessionFromContext(ctx context.Context) (ChildSessionInfo, bool)

ChildSessionFromContext retrieves child session info from context.

type ChildSessionServiceAdapter added in v0.4.0

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

ChildSessionServiceAdapter wraps a ChildSessionStore to provide fork/merge/discard operations integrated with ADK's session management.

func NewChildSessionServiceAdapter added in v0.4.0

func NewChildSessionServiceAdapter(childStore session.ChildSessionStore, summarizer Summarizer) *ChildSessionServiceAdapter

NewChildSessionServiceAdapter creates a new adapter.

func (*ChildSessionServiceAdapter) Discard added in v0.4.0

func (a *ChildSessionServiceAdapter) Discard(childKey string) error

Discard removes a child session without merging.

func (*ChildSessionServiceAdapter) Fork added in v0.4.0

func (a *ChildSessionServiceAdapter) Fork(parentKey, agentName string, cfg session.ChildSessionConfig) (*session.ChildSession, error)

Fork creates a child session for a sub-agent.

func (*ChildSessionServiceAdapter) MergeWithSummary added in v0.4.0

func (a *ChildSessionServiceAdapter) MergeWithSummary(childKey string) error

MergeWithSummary merges a child session using the configured summarizer.

type ChunkCallback

type ChunkCallback func(chunk string)

ChunkCallback is called for each streaming text chunk during agent execution.

type ContextAwareModelAdapter

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

ContextAwareModelAdapter wraps a ModelAdapter with context retrieval. Before each LLM call, it retrieves relevant knowledge and injects it into the system instruction.

func NewContextAwareModelAdapter

func NewContextAwareModelAdapter(
	inner *ModelAdapter,
	retriever *knowledge.ContextRetriever,
	builder *prompt.Builder,
	logger *zap.SugaredLogger,
) *ContextAwareModelAdapter

NewContextAwareModelAdapter creates a context-aware model adapter. The builder is used to produce the base system prompt; dynamic context (knowledge, memory, RAG) is still appended at call time.

func (*ContextAwareModelAdapter) GenerateContent

func (m *ContextAwareModelAdapter) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error]

GenerateContent retrieves context and injects an augmented system prompt before delegating to the inner adapter.

func (*ContextAwareModelAdapter) Name

func (m *ContextAwareModelAdapter) Name() string

Name delegates to the inner adapter.

func (*ContextAwareModelAdapter) WithBudgetManager added in v0.7.0

WithBudgetManager sets the context budget manager for per-section token allocation. When set, GenerateContent computes per-section budgets and truncates content to fit.

func (*ContextAwareModelAdapter) WithCoordinator added in v0.7.0

WithCoordinator adds the agentic retrieval coordinator for factual layer retrieval. When set, the coordinator runs in Phase 1 alongside the retriever (non-factual layers) and their results are merged before context assembly.

func (*ContextAwareModelAdapter) WithEventBus added in v0.7.0

WithEventBus sets the event bus for context injection observability. When set, GenerateContent publishes a ContextInjectedEvent after context assembly.

func (*ContextAwareModelAdapter) WithGraphRAG

WithGraphRAG adds graph-enhanced RAG support. When set, graph expansion is performed on vector search results to discover structurally connected context.

func (*ContextAwareModelAdapter) WithMemory

WithMemory adds observational memory support to the adapter. The session key is resolved at call time from the request context via session.SessionKeyFromContext.

func (*ContextAwareModelAdapter) WithMemoryLimits

func (m *ContextAwareModelAdapter) WithMemoryLimits(maxReflections, maxObservations int) *ContextAwareModelAdapter

WithMemoryLimits sets the maximum number of reflections and observations to include in the LLM context. Zero means unlimited (existing behavior).

func (*ContextAwareModelAdapter) WithMemoryTokenBudget

func (m *ContextAwareModelAdapter) WithMemoryTokenBudget(budget int) *ContextAwareModelAdapter

WithMemoryTokenBudget sets the maximum token budget for the memory section injected into the system prompt. Reflections are prioritized first (higher information density), then observations fill the remaining budget. Zero means use default (4000 tokens).

func (*ContextAwareModelAdapter) WithRAG

WithRAG adds RAG (retrieval-augmented generation) support.

func (*ContextAwareModelAdapter) WithRunSummaryProvider added in v0.7.0

func (m *ContextAwareModelAdapter) WithRunSummaryProvider(provider RunSummaryProvider) *ContextAwareModelAdapter

WithRunSummaryProvider adds RunLedger command-context injection support.

func (*ContextAwareModelAdapter) WithRuntimeAdapter

WithRuntimeAdapter adds runtime context support to the adapter.

type ContextBudgetManager added in v0.7.0

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

ContextBudgetManager allocates available context window tokens across prompt sections.

func NewContextBudgetManager added in v0.7.0

func NewContextBudgetManager(modelWindow, responseReserve, basePromptTokens int, alloc SectionAllocation) (*ContextBudgetManager, error)

NewContextBudgetManager creates a budget manager with validated allocation. The allocation sum must equal 1.0 (within 0.001 tolerance). responseReserve is clamped to [1024, 25% of modelWindow].

func (*ContextBudgetManager) ModelWindow added in v0.7.0

func (bm *ContextBudgetManager) ModelWindow() int

ModelWindow returns the configured model window size.

func (*ContextBudgetManager) ReallocateBudgets added in v0.7.0

func (bm *ContextBudgetManager) ReallocateBudgets(measured SectionTokens) SectionBudgets

ReallocateBudgets computes per-section budgets with empty-section redistribution. Sections with measured token count of 0 donate their entire budget proportionally to sections that have content. Non-empty sections keep their full initial budget plus a proportional share of the surplus. Headroom is never redistributed.

No recursive redistribution: surplus is distributed once. Excess in non-empty sections is simply unused.

All sections empty: returns all-zero budgets with Degraded=false.

func (*ContextBudgetManager) SectionBudgets added in v0.7.0

func (bm *ContextBudgetManager) SectionBudgets() SectionBudgets

SectionBudgets computes per-section token budgets. Returns zero budgets (unlimited) when available budget is zero or negative (degradation). Check Degraded field on the result to know if budget enforcement was skipped.

type ErrorCode added in v0.5.0

type ErrorCode string

ErrorCode identifies the category of an agent error.

const (
	ErrTimeout           ErrorCode = "E001"
	ErrModelError        ErrorCode = "E002"
	ErrToolError         ErrorCode = "E003"
	ErrTurnLimit         ErrorCode = "E004"
	ErrInternal          ErrorCode = "E005"
	ErrIdleTimeout       ErrorCode = "E006"
	ErrToolChurn         ErrorCode = "E007"
	ErrEmptyAfterToolUse ErrorCode = "E008"
)

type ErrorFixProvider

type ErrorFixProvider interface {
	GetFixForError(ctx context.Context, toolName string, err error) (string, bool)
}

ErrorFixProvider returns a known fix for a tool error if one exists. Implemented by learning.Engine.

type EventsAdapter

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

EventsAdapter adapts internal history to adk events. Uses token-budget truncation: includes messages from most recent until the budget is exhausted. Truncated history and converted events are lazily cached for O(1) repeated access.

func (*EventsAdapter) All

func (e *EventsAdapter) All() iter.Seq[*session.Event]

func (*EventsAdapter) At

func (e *EventsAdapter) At(i int) *session.Event

At returns the i-th event. The full event list is built once on first call and cached, making subsequent At calls O(1) instead of O(n).

func (*EventsAdapter) Len

func (e *EventsAdapter) Len() int

type FailureClassification added in v0.7.0

type FailureClassification struct {
	Code            ErrorCode
	CauseClass      string
	CauseDetail     string
	OperatorSummary string
}

FailureClassification is the operator-facing classification for a terminal failure.

type MemoryProvider

type MemoryProvider interface {
	ListObservations(ctx context.Context, sessionKey string) ([]memory.Observation, error)
	ListReflections(ctx context.Context, sessionKey string) ([]memory.Reflection, error)
	ListRecentReflections(ctx context.Context, sessionKey string, limit int) ([]memory.Reflection, error)
	ListRecentObservations(ctx context.Context, sessionKey string, limit int) ([]memory.Observation, error)
}

MemoryProvider retrieves observations and reflections for a session.

type ModelAdapter

type ModelAdapter struct {
	OnTokenUsage TokenUsageCallback
	// contains filtered or unexported fields
}

func NewModelAdapter

func NewModelAdapter(p provider.Provider, model string) *ModelAdapter

func (*ModelAdapter) GenerateContent

func (m *ModelAdapter) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error]

func (*ModelAdapter) Name

func (m *ModelAdapter) Name() string

type PIIRedactingModelAdapter

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

PIIRedactingModelAdapter wraps an LLM and redacts PII from user messages before forwarding them to the underlying model. It also scans tool results and model responses for known secret values.

func NewPIIRedactingModelAdapter

func NewPIIRedactingModelAdapter(
	inner model.LLM,
	redactor *agent.PIIRedactor,
	scanner *agent.SecretScanner,
) *PIIRedactingModelAdapter

NewPIIRedactingModelAdapter creates a PII-redacting model adapter. If scanner is nil, output scanning is disabled.

func (*PIIRedactingModelAdapter) GenerateContent

func (m *PIIRedactingModelAdapter) GenerateContent(
	ctx context.Context,
	req *model.LLMRequest,
	stream bool,
) iter.Seq2[*model.LLMResponse, error]

GenerateContent redacts PII from user messages, scans tool results for secrets, and wraps the response iterator to scan model output.

func (*PIIRedactingModelAdapter) Name

func (m *PIIRedactingModelAdapter) Name() string

Name delegates to the inner adapter.

type RecoveryInfo added in v0.7.0

type RecoveryInfo struct {
	Action    string
	AgentName string
	Error     string
}

RecoveryInfo captures a structured recovery action observed during a run.

type RunDiagnostics added in v0.7.0

type RunDiagnostics struct {
	VisibleTextCount        int
	ToolCallCount           int
	ToolResultCount         int
	DelegationCount         int
	DirectRootToolCallCount int
}

RunDiagnostics captures high-level runtime facts about a single agent turn.

type RunHooks added in v0.7.0

type RunHooks struct {
	OnActivity func()
	OnEvent    func(*session.Event)
	OnRecovery func(RecoveryInfo)
	OnFinish   func()
}

RunHooks is the exported view of parsed RunOptions for tests and adapters.

func ResolveRunHooks added in v0.7.0

func ResolveRunHooks(opts ...RunOption) RunHooks

ResolveRunHooks applies RunOptions and returns the resulting hooks.

type RunOption added in v0.5.0

type RunOption func(*runOptions)

RunOption configures optional behavior for a single agent run.

func ChainOnEvent added in v0.7.0

func ChainOnEvent(fn func(*session.Event)) RunOption

ChainOnEvent appends an event handler after any existing one, instead of replacing. Use this when wrapping an executor that may already have an OnEvent handler set.

func WithOnActivity added in v0.5.0

func WithOnActivity(fn func()) RunOption

WithOnActivity sets a callback that is invoked whenever the agent produces activity (text chunks, function calls). Useful for extending deadlines.

func WithOnEvent added in v0.7.0

func WithOnEvent(fn func(*session.Event)) RunOption

WithOnEvent receives each event observed by the detailed collectors.

func WithOnFinish added in v0.7.0

func WithOnFinish(fn func()) RunOption

WithOnFinish registers a callback fired when collection completes.

func WithOnRecovery added in v0.7.0

func WithOnRecovery(fn func(RecoveryInfo)) RunOption

WithOnRecovery receives each structured recovery action observed by runtime wrappers.

type RunReport added in v0.7.0

type RunReport struct {
	TraceID     string
	Response    string
	Diagnostics RunDiagnostics
}

RunReport is the structured result returned by detailed run helpers.

type RunSummaryContext added in v0.7.0

type RunSummaryContext struct {
	RunID          string
	Goal           string
	Status         string
	CurrentStep    string
	CurrentBlocker string
}

RunSummaryContext is the compact command-context view injected from RunLedger.

type RunSummaryProvider added in v0.7.0

type RunSummaryProvider interface {
	ListRunSummaries(ctx context.Context, sessionKey string, limit int) ([]RunSummaryContext, error)
	MaxJournalSeqForSession(ctx context.Context, sessionKey string) (int64, error)
}

RunSummaryProvider retrieves active RunLedger summaries for a session.

type RuntimeContextAdapter

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

RuntimeContextAdapter provides runtime session/system state.

func NewRuntimeContextAdapter

func NewRuntimeContextAdapter(toolCount int, encryption, knowledgeEnabled, memoryEnabled bool) *RuntimeContextAdapter

NewRuntimeContextAdapter creates a RuntimeContextAdapter with static system info.

func (*RuntimeContextAdapter) GetRuntimeContext

func (a *RuntimeContextAdapter) GetRuntimeContext() knowledge.RuntimeContext

GetRuntimeContext returns a snapshot of the current runtime context.

func (*RuntimeContextAdapter) SetSession

func (a *RuntimeContextAdapter) SetSession(sessionKey string)

SetSession updates the session key and derives the channel type.

type SectionAllocation added in v0.7.0

type SectionAllocation struct {
	Knowledge  float64
	RAG        float64
	Memory     float64
	RunSummary float64
	Headroom   float64
}

SectionAllocation defines the ratio of available context budget allocated to each section. All values must sum to 1.0 (within tolerance of 0.001).

func DefaultAllocation added in v0.7.0

func DefaultAllocation() SectionAllocation

DefaultAllocation returns the default section allocation ratios.

type SectionBudgets added in v0.7.0

type SectionBudgets struct {
	Knowledge  int
	RAG        int
	Memory     int
	RunSummary int
	Degraded   bool
}

SectionBudgets holds computed per-section token budgets. A value of 0 means unlimited (no budget enforcement). Degraded is true when available budget was zero or negative.

type SectionTokens added in v0.7.0

type SectionTokens struct {
	Knowledge  int
	RAG        int
	Memory     int
	RunSummary int
}

SectionTokens represents measured token counts per section before truncation. Used as input to ReallocateBudgets for empty-section redistribution.

type SessionAdapter

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

SessionAdapter adapts internal.Session to adk.Session

func NewSessionAdapter

func NewSessionAdapter(s *internal.Session, store internal.Store, rootAgentName string) *SessionAdapter

func (*SessionAdapter) AppName

func (s *SessionAdapter) AppName() string

func (*SessionAdapter) Events

func (s *SessionAdapter) Events() session.Events

func (*SessionAdapter) EventsWithTokenBudget

func (s *SessionAdapter) EventsWithTokenBudget(budget int) session.Events

EventsWithTokenBudget returns an EventsAdapter that uses token-budget truncation.

func (*SessionAdapter) ID

func (s *SessionAdapter) ID() string

func (*SessionAdapter) LastUpdateTime

func (s *SessionAdapter) LastUpdateTime() time.Time

func (*SessionAdapter) State

func (s *SessionAdapter) State() session.State

func (*SessionAdapter) UserID

func (s *SessionAdapter) UserID() string

type SessionServiceAdapter

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

func NewSessionServiceAdapter

func NewSessionServiceAdapter(store internal.Store, rootAgentName string) *SessionServiceAdapter

func (*SessionServiceAdapter) AppendEvent

func (s *SessionServiceAdapter) AppendEvent(ctx context.Context, sess session.Session, evt *session.Event) error

func (*SessionServiceAdapter) CleanupFailedTurn added in v0.7.0

func (s *SessionServiceAdapter) CleanupFailedTurn(sessionID, reason string) error

CleanupFailedTurn discards any active isolated child state and closes dangling parent-visible tool calls before the session is retried or reused.

func (*SessionServiceAdapter) CloseActiveChild added in v0.7.0

func (s *SessionServiceAdapter) CloseActiveChild(sessionID string) error

CloseActiveChild merges any active synthetic child session for the parent session.

func (*SessionServiceAdapter) Create

func (*SessionServiceAdapter) Delete

func (*SessionServiceAdapter) DiscardActiveChild added in v0.7.0

func (s *SessionServiceAdapter) DiscardActiveChild(sessionID string) error

DiscardActiveChild discards the current synthetic child session for the parent session.

func (*SessionServiceAdapter) DiscardActiveChildWithReason added in v0.7.0

func (s *SessionServiceAdapter) DiscardActiveChildWithReason(sessionID, reason string) error

DiscardActiveChildWithReason discards the current synthetic child session and leaves a compact root-authored note in the parent history.

func (*SessionServiceAdapter) Get

Get retrieves a session by ID.

CONTRACT DEVIATION: ADK's session.Service.Get() contract expects an error for missing sessions. This implementation auto-creates missing sessions and auto-renews expired sessions instead of returning an error. This is intentional because lango's session lifecycle is self-managing — the caller should not need to handle "not found" as a special case. The auto-create/renew behavior is preserved for backward compatibility and must not be changed without updating all callers.

func (*SessionServiceAdapter) List

func (*SessionServiceAdapter) WithChildLifecycleHook added in v0.7.0

func (s *SessionServiceAdapter) WithChildLifecycleHook(h func(internal.SessionLifecycleEvent)) *SessionServiceAdapter

WithChildLifecycleHook enables synthetic child-session lifecycle tracking.

func (*SessionServiceAdapter) WithIsolatedAgents added in v0.7.0

func (s *SessionServiceAdapter) WithIsolatedAgents(names []string) *SessionServiceAdapter

WithIsolatedAgents marks the agent names that should write to child session history.

func (*SessionServiceAdapter) WithRootSessionObserver added in v0.7.0

func (s *SessionServiceAdapter) WithRootSessionObserver(fn func(string)) *SessionServiceAdapter

WithRootSessionObserver records root session creation events.

func (*SessionServiceAdapter) WithTokenBudget

func (s *SessionServiceAdapter) WithTokenBudget(budget int) *SessionServiceAdapter

WithTokenBudget sets the token budget for history truncation. Use ModelTokenBudget(modelName) to derive an appropriate budget from the model name.

type StateAdapter

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

StateAdapter adapts internal.Session.Metadata to adk.State

func (*StateAdapter) All

func (s *StateAdapter) All() iter.Seq2[string, any]

func (*StateAdapter) Get

func (s *StateAdapter) Get(key string) (any, error)

func (*StateAdapter) Set

func (s *StateAdapter) Set(key string, val any) error

type StructuredSummarizer added in v0.4.0

type StructuredSummarizer struct{}

StructuredSummarizer extracts the last assistant response as the summary. This is the default zero-cost summarizer that avoids LLM calls.

func (*StructuredSummarizer) Summarize added in v0.4.0

func (s *StructuredSummarizer) Summarize(messages []session.Message) (string, error)

Summarize returns the last assistant message content as the summary. If no assistant message is found, returns an empty string.

type Summarizer added in v0.4.0

type Summarizer interface {
	Summarize(messages []session.Message) (string, error)
}

Summarizer produces a summary string from a child session's messages.

type TokenUsageCallback added in v0.5.0

type TokenUsageCallback func(providerID, model string, input, output, total, cache int64)

TokenUsageCallback is called when a provider returns token usage data.

type ToolRegistryAdapter

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

ToolRegistryAdapter adapts []*agent.Tool to knowledge.ToolRegistryProvider.

func NewToolRegistryAdapter

func NewToolRegistryAdapter(tools []*agent.Tool) *ToolRegistryAdapter

NewToolRegistryAdapter creates a ToolRegistryAdapter from agent tools. The input slice is copied to prevent caller mutation.

func (*ToolRegistryAdapter) ListTools

func (a *ToolRegistryAdapter) ListTools() []knowledge.ToolDescriptor

ListTools returns all available tools.

func (*ToolRegistryAdapter) SearchTools

func (a *ToolRegistryAdapter) SearchTools(query string, limit int) []knowledge.ToolDescriptor

SearchTools returns tools whose name, aliases, category, search hints, or description contains the query (case-insensitive substring match).

Jump to

Keyboard shortcuts

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