Documentation
¶
Overview ¶
Package execution: git resource materialization for the per-task workspace.
Git resources let task authors check out a clean copy of a local git repository into the workspace before the agent runs. This is useful when developing skills that live inside the same repo whose code they need to reason about (e.g. azure-sdk-for-rust): rather than hand-crafting fixtures, the task can point at the local clone and get an isolated checkout for each run.
Currently only the "worktree" strategy is supported. It uses `git worktree add --detach` against the local source repo, which is cheap (shares the same .git object store) and does not require network access. Additional strategies (HTTPS clone, ssh, submodules) can be added later behind the same GitResource interface.
Index ¶
- func EvaluationSessionStats(entry models.EvaluationSessionUsage) *models.UsageStats
- func IsSkillAvailable(skillDirs []string, skillName string) bool
- func MergeResponseUsage(resp, follow *ExecutionResponse)
- func ResolveAgentDefinition(skillDirs []string, skillName string) (string, *skill.AgentFrontmatter, error)
- func ResolveWorkDir(workspaceDir, workDir string) (string, error)
- func ShutdownSharedClient(_ context.Context) error
- func UpdateOutcomeUsage(outcome *models.EvaluationOutcome, engine AgentEngine)
- type AgentEngine
- type CommandMockFinalizer
- type CopilotClient
- type CopilotEngine
- func (e *CopilotEngine) CopilotClient() CopilotClient
- func (e *CopilotEngine) DeleteSession(ctx context.Context, sessionID string) error
- func (e *CopilotEngine) Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResponse, error)
- func (e *CopilotEngine) FinalizeCommandMocks(workspace string) ([]models.CommandInvocation, error)
- func (e *CopilotEngine) Initialize(ctx context.Context) error
- func (e *CopilotEngine) ListModels(ctx context.Context) ([]copilot.ModelInfo, error)
- func (e *CopilotEngine) SessionEventModelObservation(id string) SessionEventModelObservation
- func (e *CopilotEngine) SessionUsage(sessionID string) *models.UsageStats
- func (e *CopilotEngine) SessionUsageObservation(id string) SessionUsageObservation
- func (e *CopilotEngine) SessionUsageRevision(sessionID string) uint64
- func (e *CopilotEngine) SetKeepWorkspace(keep bool)
- func (e *CopilotEngine) Shutdown(ctx context.Context) error
- type CopilotEngineBuilder
- type CopilotEngineBuilderOptions
- type CopilotSession
- type DiagnosticCode
- type DiagnosticError
- type DiagnosticStage
- type EvidenceJudgeExecutor
- type ExecutionDiagnostic
- type ExecutionRequest
- type ExecutionResponse
- type GitResource
- type InstructionFile
- type MessageMode
- type MockEngine
- func (m *MockEngine) Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResponse, error)
- func (m *MockEngine) Initialize(ctx context.Context) error
- func (m *MockEngine) SessionUsage(sessionID string) *models.UsageStats
- func (m *MockEngine) SetKeepWorkspace(keep bool)
- func (m *MockEngine) Shutdown(ctx context.Context) error
- type ResourceFile
- type SessionEventModelObservation
- type SessionEventsCollector
- func (coll *SessionEventsCollector) Done() <-chan struct{}
- func (coll *SessionEventsCollector) ErrorMessage() string
- func (coll *SessionEventsCollector) FirstEvent() <-chan struct{}
- func (coll *SessionEventsCollector) On(event copilot.SessionEvent)
- func (coll *SessionEventsCollector) OutputParts() []string
- func (coll *SessionEventsCollector) SessionEvents() []copilot.SessionEvent
- func (coll *SessionEventsCollector) SetOnSkillInvoked(fn func(SkillInvocation))
- func (coll *SessionEventsCollector) ToolCalls() []models.ToolCall
- type SessionUsageCollector
- func (s *SessionUsageCollector) EventModelObservation() SessionEventModelObservation
- func (s *SessionUsageCollector) Observation() SessionUsageObservation
- func (s *SessionUsageCollector) On(event copilot.SessionEvent)
- func (s *SessionUsageCollector) SetMetrics(metrics *rpc.UsageGetMetricsResult)
- func (s *SessionUsageCollector) UsageStats() *models.UsageStats
- type SessionUsageObservation
- type SharedClientOptions
- type SkillInvocation
- type ToolPolicy
- type ToolPolicyDenial
- type ToolPolicyMode
- type UsageAccumulator
- type UsageScope
- type WorkspaceKeeper
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EvaluationSessionStats ¶ added in v0.38.9
func EvaluationSessionStats(entry models.EvaluationSessionUsage) *models.UsageStats
EvaluationSessionStats removes a prior evaluation's cumulative counters. Missing baselines and resets keep billing unavailable, not a partial total.
func IsSkillAvailable ¶ added in v0.38.8
IsSkillAvailable reports whether the target skill can be discovered from the effective skill directories passed to the engine.
func MergeResponseUsage ¶ added in v0.38.9
func MergeResponseUsage(resp, follow *ExecutionResponse)
func ResolveAgentDefinition ¶ added in v0.38.8
func ResolveAgentDefinition(skillDirs []string, skillName string) (string, *skill.AgentFrontmatter, error)
ResolveAgentDefinition uses the same selection and SKILL.md precedence as system-message injection, including nested directories and fallback names.
func ResolveWorkDir ¶ added in v0.37.0
ResolveWorkDir returns the effective working directory for the agent session. When workDir is empty, the workspace root is returned. Otherwise workDir is joined under workspaceDir and verified not to escape it via path traversal. `..` segments are rejected outright (even if they would resolve to a path still inside the workspace) so callers cannot rely on filesystem normalization to hide intent.
func ShutdownSharedClient ¶ added in v0.37.0
ShutdownSharedClient stops the underlying Copilot SDK process if a shared client was ever constructed. Safe to call multiple times. Should be invoked once from the top-level command after all engines have been Shutdown and all graders have completed.
func UpdateOutcomeUsage ¶
func UpdateOutcomeUsage(outcome *models.EvaluationOutcome, engine AgentEngine)
UpdateOutcomeUsage replaces fallback per-turn usage data in the outcome with authoritative post-shutdown usage data from the engine, then re-aggregates the digest-level usage totals. Call after engine.Shutdown().
Types ¶
type AgentEngine ¶
type AgentEngine interface {
// Initialize sets up the engine
Initialize(ctx context.Context) error
// Execute runs a test with the given stimulus. The caller controls
// cancellation and deadlines through ctx.
Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResponse, error)
// Shutdown cleans up resources. It is safe to call multiple times;
// subsequent calls after the first are no-ops. After Shutdown returns,
// SessionUsage results include data from session termination events.
Shutdown(ctx context.Context) error
// SessionUsage returns the final usage stats for a session, including
// data from session.shutdown events that fire during Shutdown().
// Returns nil if no usage data is available for the given session.
SessionUsage(sessionID string) *models.UsageStats
}
AgentEngine is the interface for executing test prompts
type CommandMockFinalizer ¶ added in v0.38.9
type CommandMockFinalizer interface {
FinalizeCommandMocks(workspace string) ([]models.CommandInvocation, error)
}
CommandMockFinalizer collects task-level command records and checks expected call counts after the final agent turn has completed.
type CopilotClient ¶
type CopilotClient interface {
// CreateSession maps to [copilot.Client.CreateSession]
CreateSession(ctx context.Context, config *copilot.SessionConfig) (CopilotSession, error)
// GetAuthStatus maps to [copilot.Client.GetAuthStatus]
GetAuthStatus(ctx context.Context) (*copilot.GetAuthStatusResponse, error)
// Start maps to [copilot.Client.Start]
Start(ctx context.Context) error
// Stop maps to [copilot.Client.Stop]
Stop() error
// ResumeSessionWithOptions maps to [copilot.Client.ResumeSessionWithOptions]
ResumeSessionWithOptions(ctx context.Context, sessionID string, config *copilot.ResumeSessionConfig) (CopilotSession, error)
// DeleteSession maps to [copilot.Client.DeleteSession]
DeleteSession(ctx context.Context, sessionID string) error
// ListModels maps to [copilot.Client.ListModels]
ListModels(ctx context.Context) ([]copilot.ModelInfo, error)
}
CopilotClient is just an interface over *copilot.Client
func NewOwnedCopilotClient ¶ added in v0.39.0
func NewOwnedCopilotClient(clientOptions *copilot.ClientOptions) CopilotClient
NewOwnedCopilotClient constructs a dedicated SDK client. Supply this factory through CopilotEngineBuilderOptions.NewCopilotClient to avoid SharedClient; the engine then owns and stops the client.
func SharedClient ¶ added in v0.37.0
func SharedClient(opts SharedClientOptions) CopilotClient
SharedClient returns a lazily-constructed, process-wide CopilotClient.
Rationale (#135 R2): the embedded Copilot CLI process is expensive to spawn / tear down. Now that all per-call state (workdir, model, MCP servers, skill dirs, system message) is provided to CreateSession and ResumeSessionWithOptions, a single SDK client can serve compatible CopilotEngine instances and graders within a `waza run`. Startup-only CLIArgs (for example --model) are part of the compatibility key.
The client is started lazily on first use by CopilotEngine.Initialize (or by an explicit [Start] caller) and is stopped exactly once via ShutdownSharedClient. Engines built on top of the shared client must not call client.Stop() themselves.
Tests that need an isolated client can either construct one directly with [newCopilotClient] (package-private) or pass a custom NewCopilotClient factory via CopilotEngineBuilderOptions.
type CopilotEngine ¶
type CopilotEngine struct {
// contains filtered or unexported fields
}
CopilotEngine integrates with GitHub Copilot SDK
func (*CopilotEngine) CopilotClient ¶ added in v0.37.0
func (e *CopilotEngine) CopilotClient() CopilotClient
CopilotClient returns the underlying Copilot SDK client backing this engine. Graders that need to spin up their own grading session (e.g. prompt graders) can use this to avoid spawning a fresh SDK process per invocation. Callers must NOT call Stop() on the returned client.
func (*CopilotEngine) DeleteSession ¶ added in v0.37.0
func (e *CopilotEngine) DeleteSession(ctx context.Context, sessionID string) error
DeleteSession removes a persistent session created via Execute (with EphemeralSession=false) and stops tracking it for shutdown cleanup. It is used by callers that own a long-lived session, such as the responder, to tear it down promptly rather than waiting for engine Shutdown.
func (*CopilotEngine) Execute ¶
func (e *CopilotEngine) Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResponse, error)
Execute runs a test with Copilot SDK
func (*CopilotEngine) FinalizeCommandMocks ¶ added in v0.38.9
func (e *CopilotEngine) FinalizeCommandMocks(workspace string) ([]models.CommandInvocation, error)
FinalizeCommandMocks closes the task's command-mock state after all turns.
func (*CopilotEngine) Initialize ¶
func (e *CopilotEngine) Initialize(ctx context.Context) error
Initialize sets up the Copilot client
func (*CopilotEngine) ListModels ¶ added in v0.28.0
ListModels returns the available models from the Copilot backend.
func (*CopilotEngine) SessionEventModelObservation ¶ added in v0.39.0
func (e *CopilotEngine) SessionEventModelObservation(id string) SessionEventModelObservation
func (*CopilotEngine) SessionUsage ¶
func (e *CopilotEngine) SessionUsage(sessionID string) *models.UsageStats
SessionUsage returns the final usage stats for a session. Call after Shutdown() to get data from session.shutdown events (ModelMetrics, TotalPremiumRequests). When BYOK was active for this session, the returned stats include sanitized provider metadata so downstream consumers can label PremiumRequests accurately (custom endpoint vs Copilot MaaS).
func (*CopilotEngine) SessionUsageObservation ¶ added in v0.39.0
func (e *CopilotEngine) SessionUsageObservation(id string) SessionUsageObservation
func (*CopilotEngine) SessionUsageRevision ¶ added in v0.38.9
func (e *CopilotEngine) SessionUsageRevision(sessionID string) uint64
SessionUsageRevision identifies the last execution contributing to a snapshot, preventing an older evaluation from absorbing a later resumed turn.
func (*CopilotEngine) SetKeepWorkspace ¶ added in v0.29.0
func (e *CopilotEngine) SetKeepWorkspace(keep bool)
SetKeepWorkspace enables or disables workspace preservation on shutdown.
type CopilotEngineBuilder ¶
type CopilotEngineBuilder struct {
// contains filtered or unexported fields
}
CopilotEngineBuilder builds a CopilotEngine with options
func NewCopilotEngineBuilder ¶
func NewCopilotEngineBuilder(defaultModelID string, options *CopilotEngineBuilderOptions) *CopilotEngineBuilder
NewCopilotEngineBuilder creates a builder for CopilotEngine
- defaultModelID - used if no model ID is specified in session creation. Can be blank, which means the copilot CLI will choose its own fallback model.
Unless OwnClient is selected, when `options.NewCopilotClient` is nil the engine is wired to the process-wide shared client returned by SharedClient. The caller MUST invoke ShutdownSharedClient once at the top level after every engine has been Shutdown — engines built on top of the shared client will not stop it themselves. See docs/design/135-improve-concurrency.md (R2).
OwnClient resolves the same explicit/embedded CLI options for a fresh production client. A supplied NewCopilotClient factory also selects ownership. Both owned paths stop their client during Shutdown.
func (*CopilotEngineBuilder) Build ¶
func (b *CopilotEngineBuilder) Build() *CopilotEngine
type CopilotEngineBuilderOptions ¶
type CopilotEngineBuilderOptions struct {
NewCopilotClient func(clientOptions *copilot.ClientOptions) CopilotClient
// OwnClient selects a fresh production client instead of SharedClient.
OwnClient bool
// DisableCommandMocks omits the shim registry and rejects command mocks.
// Requires OwnClient or a supplied NewCopilotClient factory.
DisableCommandMocks bool
// DiagnosticObserver enables sanitized, failure-retaining lifecycle diagnostics.
// Calls are serialized outside engine state locks. Observers must not reenter
// engine lifecycle methods (including Execute, Initialize, DeleteSession, Shutdown).
DiagnosticObserver func(ExecutionDiagnostic) error
}
type CopilotSession ¶
type CopilotSession interface {
// Disconnect maps to [copilot.Session.Disconnect]. It closes the session and releases resources, however it
// doesn't delete data and the session is still resumable until deleted via [copilot.Client.DeleteSession].
Disconnect() error
// On maps to [copilot.Session.On]
On(handler copilot.SessionEventHandler) func()
// SendAndWait maps to [copilot.Session.SendAndWait]
SendAndWait(ctx context.Context, options copilot.MessageOptions) (*copilot.SessionEvent, error)
// SessionID returns [copilot.Session.SessionID]
SessionID() string
UsageMetrics(ctx context.Context) (*rpc.UsageGetMetricsResult, error)
ShutdownUsage(ctx context.Context) (*copilot.SessionShutdownData, error)
}
CopilotSession is just an interface over *copilot.Session
type DiagnosticCode ¶ added in v0.39.0
type DiagnosticCode string
const ( CodeProvider DiagnosticCode = "provider_failed" CodeStart DiagnosticCode = "start_failed" CodeAuth DiagnosticCode = "auth_failed" CodeCreate DiagnosticCode = "create_failed" CodeResume DiagnosticCode = "resume_failed" CodeSend DiagnosticCode = "send_failed" CodeExecute DiagnosticCode = "execute_failed" CodeCleanup DiagnosticCode = "cleanup_failed" CodeExpectedSkillCancellation DiagnosticCode = "expected_skill_cancellation" CodeUsageMissingOrPartial DiagnosticCode = "usage_missing_or_partial" CodeModelAttributionMissing DiagnosticCode = "model_attribution_missing" CodeShutdownRPC DiagnosticCode = "shutdown_rpc_failed" CodeHistory DiagnosticCode = "history_failed" CodeFallbackDisconnect DiagnosticCode = "fallback_disconnect_failed" CodeObserverFailed DiagnosticCode = "observer_failed" CodeClosed DiagnosticCode = "engine_closed" CodeSessionBusy DiagnosticCode = "session_busy" )
type DiagnosticError ¶ added in v0.39.0
type DiagnosticError struct{ Diagnostic ExecutionDiagnostic }
DiagnosticError deliberately does not unwrap provider or observer causes.
func (*DiagnosticError) Error ¶ added in v0.39.0
func (e *DiagnosticError) Error() string
type DiagnosticStage ¶ added in v0.39.0
type DiagnosticStage string
const ( StageInitialize DiagnosticStage = "initialize" StageExecute DiagnosticStage = "execute" StageDisconnect DiagnosticStage = "disconnect" StageEphemeralDelete DiagnosticStage = "ephemeral_delete" StageUsageMetrics DiagnosticStage = "usage_metrics" StageShutdownUsage DiagnosticStage = "shutdown_usage" StageShutdownDelete DiagnosticStage = "shutdown_delete" StageClientStop DiagnosticStage = "client_stop" StageCommandMockCleanup DiagnosticStage = "commandmock_cleanup" StageGitCleanup DiagnosticStage = "git_cleanup" StageWorkspaceCleanup DiagnosticStage = "workspace_cleanup" )
type EvidenceJudgeExecutor ¶ added in v0.39.0
type EvidenceJudgeExecutor struct {
// contains filtered or unexported fields
}
EvidenceJudgeExecutor owns a separate empty runtime for every Execute. It does not share actor state or retain a client/session after the call returns. This is a runtime capability/discovery boundary, not an OS sandbox.
func NewEvidenceJudgeExecutor ¶ added in v0.39.0
func NewEvidenceJudgeExecutor() *EvidenceJudgeExecutor
NewEvidenceJudgeExecutor is lazy; construction performs no I/O.
func (*EvidenceJudgeExecutor) Execute ¶ added in v0.39.0
func (e *EvidenceJudgeExecutor) Execute(parent context.Context, req *ExecutionRequest) (resp *ExecutionResponse, resultErr error)
Execute returns final observed usage even when execution, submission, policy, or finalization fails. No external Shutdown or Close is necessary.
type ExecutionDiagnostic ¶ added in v0.39.0
type ExecutionDiagnostic struct {
Stage DiagnosticStage `json:"stage"`
Code DiagnosticCode `json:"code"`
SessionID string `json:"-"`
}
ExecutionDiagnostic contains only allowlisted classifications. SessionID is available for internal correlation but never serialized.
type ExecutionRequest ¶
type ExecutionRequest struct {
ModelID string
ReasoningEffort string
Message string
Context map[string]any
Resources []ResourceFile
GitResources []models.GitResource
WorkDir string
Instructions []InstructionFile
Tools []copilot.Tool
MessageMode MessageMode
Streaming bool
// FirstEventTimeout bounds how long Execute waits for the FIRST session
// event before treating the run as a session-start hang and aborting it
// with a distinct error. It is intentionally much shorter than the overall
// turn deadline (the ctx passed to Execute), which must be sized for the
// slowest legitimate full turn and therefore cannot also catch a
// no-first-turn wedge quickly. Zero disables the check (the prior behavior).
FirstEventTimeout time.Duration
// EphemeralSession keeps one-off sessions out of engine shutdown tracking.
// New ephemeral sessions are deleted at the end of Execute. Resumed
// ephemeral sessions are only disconnected because the caller does not own
// the original session data.
EphemeralSession bool
// SkipWorkspaceCapture avoids post-run workspace snapshots for callers that
// only need model/tool output, such as prompt graders.
SkipWorkspaceCapture bool
// CaptureJudgeFiles freezes explicitly reviewed files before disconnect can
// restore the actor workspace. The callback never runs in a judge session.
CaptureJudgeFiles func(string) *models.JudgeFileCapture `json:"-"`
SessionID string
WorkspaceDir string // Reuse an existing workspace directory (for follow-up prompts)
SkillName string
// TaskName and TaskDescription carry test-case metadata so mock engines can
// echo them, enabling output_contains expectations that reference task-level
// concepts (e.g., "recursive") without a real model.
TaskName string
TaskDescription string
SourceDir string // used when looking for workspace items via relative path, like skills.
SkillPaths []string // Directories to search for skills
NoSkills bool // When true, skip all skill loading
// SuppressSkillBody prevents full target skill content from being appended
// while still allowing skill discovery and compact summaries.
SuppressSkillBody bool
// TriggerSkillRouting appends an eval-only routing instruction that asks
// the agent to invoke the target skill tool when the task falls within that
// skill's scope. It is intended for trigger-precision evals where the skill
// body is suppressed.
TriggerSkillRouting bool
// MCPServers configures MCP servers for the session. Keys are server names,
// values follow the copilot SDK MCPServerConfig format (type/command/args).
MCPServers map[string]copilot.MCPServerConfig
CommandMocks []models.CommandMockConfig
CommandMocksBaseDir string
// PermissionHandler called when the copilot SDK wants to determine if a tool can be used.
// Default: allows all tools.
PermissionHandler copilot.PermissionHandlerFunc
// CancelOnSkillInvocation, when true, causes the execution context to be
// canceled as soon as a SkillInvoked event is received. This allows trigger
// tests to terminate early once the skill invocation they care about has been
// detected, avoiding unnecessary wait for the agent to finish its full turn.
CancelOnSkillInvocation bool
// ToolPolicy is the resolved tool-capability boundary derived from the
// target .agent.md `tools:` declaration (see [NewToolPolicy]). Nil means
// no policy was resolved and preserves the pre-existing unrestricted
// behavior. Engines that support it (currently CopilotEngine) apply it to
// both the native SDK session tool configuration and a fail-closed
// OnPermissionRequest wrapper.
ToolPolicy *ToolPolicy
}
ExecutionRequest represents a test execution request
type ExecutionResponse ¶
type ExecutionResponse struct {
FinalOutput string
Events []agentevent.Event
ModelID string
SkillInvocations []SkillInvocation
DurationMs int64
ToolCalls []models.ToolCall
ErrorMsg string
Success bool
WorkspaceDir string // Path to workspace directory (for file grading)
WorkspaceFiles map[string][]byte // Post-execution workspace file contents captured before session disconnect
JudgeFiles *models.JudgeFileCapture
SessionID string // Copilot session ID
Usage *models.UsageStats
// UsageIsCumulative distinguishes a session snapshot from per-execution
// usage. Engines that report per-turn usage leave this false.
UsageIsCumulative bool
UsageRevision uint64
GraderSessions []models.SessionDigest
// ToolPolicyMode is the effective ToolPolicy mode applied to this
// execution ("unrestricted", "deny_all", or "allow_list"), empty when no
// policy was resolved for the request.
ToolPolicyMode string
// ToolPolicyDenials records every tool-execution attempt the engine
// denied under an active ToolPolicy. Empty when the policy was
// unrestricted or no tool was ever denied.
ToolPolicyDenials []ToolPolicyDenial
CommandInvocations []models.CommandInvocation
// contains filtered or unexported fields
}
ExecutionResponse represents the result of an execution.
Events carries engine-neutral agentevent.Event values rather than a concrete SDK type so additional agent engines (Claude Code, Codex, generic CLI) can plug in without leaking their native event types through this API. The Copilot engine wraps each SDK event into an Event via internal/copilotevents.FromSDK at the engine boundary; consumers that still need SDK-typed access unwrap via copilotevents.ToSDK or copilotevents.AsSDKEvent.
func ExecuteRecorded ¶ added in v0.38.9
func ExecuteRecorded(ctx context.Context, executor usageExecutor, req *ExecutionRequest) (*ExecutionResponse, error)
ExecuteRecorded preserves the executor's response/error contract, including responses returned with errors. Without a scope it simply executes.
func (*ExecutionResponse) ContainsText ¶
func (r *ExecutionResponse) ContainsText(text string) bool
ContainsText checks if output contains text (case-insensitive)
func (*ExecutionResponse) ExtractMessages ¶
func (r *ExecutionResponse) ExtractMessages() []string
ExtractMessages gets all non-empty assistant messages from events.
Copilot SDK events are unwrapped through copilotevents.AsSDKEvent so the existing Content helper can extract structured fields. Events produced by other engines fall back to agentevent.Event.Text, which delegates to the engine payload's optional agentevent.TextProvider implementation. This keeps ExtractMessages truly engine-neutral: a non-Copilot engine that emits KindAssistantMessage with a TextProvider payload will surface here instead of being silently dropped.
type GitResource ¶ added in v0.37.0
type GitResource interface {
// Cleanup removes the materialized resource (e.g. `git worktree
// remove`). It is safe to call multiple times; subsequent calls are
// no-ops.
Cleanup(ctx context.Context) error
}
GitResource represents a materialized git resource that must be cleaned up when the engine shuts down. Implementations are returned from CloneGitResources.
func CloneGitResources ¶ added in v0.37.0
func CloneGitResources(ctx context.Context, resources []models.GitResource, workspaceDir string) ([]GitResource, error)
CloneGitResources materializes each git resource into workspaceDir and returns handles that the caller is responsible for cleaning up via Cleanup(). If any resource fails to materialize, previously created resources in this call are cleaned up before returning the error.
The caller must clean up resources before removing workspaceDir, because some strategies (worktree) keep bookkeeping inside the source repository's .git/worktrees/ that needs `git worktree remove` to invalidate cleanly.
type InstructionFile ¶ added in v0.33.0
InstructionFile represents a file whose content should be applied as agent instructions.
type MessageMode ¶ added in v0.33.0
type MessageMode string
MessageMode controls how a prompt is submitted to an existing session.
const ( // MessageModeEnqueue sends the prompt using the Copilot SDK's enqueue mode. MessageModeEnqueue MessageMode = "enqueue" )
type MockEngine ¶
type MockEngine struct {
// contains filtered or unexported fields
}
MockEngine is a simple mock implementation for testing
func NewMockEngine ¶
func NewMockEngine(modelID string) *MockEngine
NewMockEngine creates a new mock engine
func (*MockEngine) Execute ¶
func (m *MockEngine) Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResponse, error)
func (*MockEngine) Initialize ¶
func (m *MockEngine) Initialize(ctx context.Context) error
func (*MockEngine) SessionUsage ¶
func (m *MockEngine) SessionUsage(sessionID string) *models.UsageStats
func (*MockEngine) SetKeepWorkspace ¶ added in v0.29.0
func (m *MockEngine) SetKeepWorkspace(keep bool)
SetKeepWorkspace enables or disables workspace preservation on shutdown.
type ResourceFile ¶
ResourceFile represents a file resource
type SessionEventModelObservation ¶ added in v0.39.0
type SessionEventModelObservation struct {
Models []string `json:"models"`
EventsObserved uint64 `json:"events_observed"`
Complete bool `json:"complete"`
}
SessionEventModelObservation describes received SDK model attribution, independently of authoritative usage snapshots. Complete requires at least one supported attribution event and usable IDs in every such received event. It does not guarantee exhaustive event delivery or establish billed usage.
func ObserveSessionEventModels ¶ added in v0.39.0
func ObserveSessionEventModels(event copilot.SessionEvent) SessionEventModelObservation
ObserveSessionEventModels extracts the collector's supported model observations from one SDK event without collecting usage or inferring missing identities. Retained native evidence uses this same contract to reconcile canonical events.
type SessionEventsCollector ¶
type SessionEventsCollector struct {
// SkillInvocations is a chronological list of skills invoked during the session
SkillInvocations []SkillInvocation
// contains filtered or unexported fields
}
func NewSessionEventsCollector ¶
func NewSessionEventsCollector() *SessionEventsCollector
NewSessionEventsCollector creates a new SessionEvents.
func (*SessionEventsCollector) Done ¶
func (coll *SessionEventsCollector) Done() <-chan struct{}
Done returns the channel that is closed when the session completes.
func (*SessionEventsCollector) ErrorMessage ¶
func (coll *SessionEventsCollector) ErrorMessage() string
ErrorMessage returns the error message, if any.
func (*SessionEventsCollector) FirstEvent ¶ added in v0.37.0
func (coll *SessionEventsCollector) FirstEvent() <-chan struct{}
FirstEvent returns a channel that is closed when the FIRST session event of any type is received. A healthy session emits events promptly once the agent starts its first turn; a session-start hang (the embedded engine launches but never produces a turn) emits nothing at all. Callers use this to arm a short "time to first event" deadline distinct from the overall turn timeout, so a no-first-turn wedge is caught in seconds instead of running out the full (necessarily large) turn budget.
func (*SessionEventsCollector) On ¶
func (coll *SessionEventsCollector) On(event copilot.SessionEvent)
On is a callback, intended to be passed to copilot.Session.On to receive events in real-time.
func (*SessionEventsCollector) OutputParts ¶
func (coll *SessionEventsCollector) OutputParts() []string
OutputParts returns the collected output text parts.
func (*SessionEventsCollector) SessionEvents ¶
func (coll *SessionEventsCollector) SessionEvents() []copilot.SessionEvent
SessionEvents returns the collected session events.
func (*SessionEventsCollector) SetOnSkillInvoked ¶ added in v0.28.0
func (coll *SessionEventsCollector) SetOnSkillInvoked(fn func(SkillInvocation))
SetOnSkillInvoked registers a callback that fires every time a SkillInvoked event is received. The callback runs synchronously inside On(), so it can safely cancel a context to abort an in-flight SendAndWait.
func (*SessionEventsCollector) ToolCalls ¶
func (coll *SessionEventsCollector) ToolCalls() []models.ToolCall
ToolCalls goes through the list of session events and correlates tool starts with Success. The resulting tool calls are not cached - if you're going to use it repeatedly you should store it locally.
type SessionUsageCollector ¶
type SessionUsageCollector struct {
// contains filtered or unexported fields
}
SessionUsageCollector tracks token, AI-credit, and request usage from Copilot SDK session events. Its On method implements copilot.SessionEventHandler and should be registered via session.On(collector.On).
Usage data arrives through three channels:
- The accumulated session.usage.getMetrics RPC — authoritative.
- Per-turn events (AssistantUsage) — accumulated as a fallback.
- SessionShutdown events — totals that override per-turn data when the RPC is unavailable. Shutdown metrics carry the final nano-AI-unit totals GitHub billed for the session, both overall and per model; those are recorded as AI credits and are never reconstructed from a local token-rate table.
func NewSessionUsageCollector ¶
func NewSessionUsageCollector() *SessionUsageCollector
func (*SessionUsageCollector) EventModelObservation ¶ added in v0.39.0
func (s *SessionUsageCollector) EventModelObservation() SessionEventModelObservation
EventModelObservation is cumulative for this collector's session lifetime; RPC snapshots, shutdown totals and beginTurn never replace received evidence.
func (*SessionUsageCollector) Observation ¶ added in v0.39.0
func (s *SessionUsageCollector) Observation() SessionUsageObservation
Observation reports completeness of the same authoritative source selected by UsageStats. Per-turn data remains partial; credits are never inferred.
func (*SessionUsageCollector) On ¶
func (s *SessionUsageCollector) On(event copilot.SessionEvent)
On handles a single session event, extracting any usage data it carries. Pass this method to session.On as a copilot.SessionEventHandler.
func (*SessionUsageCollector) SetMetrics ¶ added in v0.38.9
func (s *SessionUsageCollector) SetMetrics(metrics *rpc.UsageGetMetricsResult)
SetMetrics records the accumulated RPC snapshot, authoritative over events.
func (*SessionUsageCollector) UsageStats ¶
func (s *SessionUsageCollector) UsageStats() *models.UsageStats
UsageStats returns the collected usage statistics. Returns nil if no usage data was collected. The accumulated RPC snapshot is authoritative, with SessionShutdown data then per-turn accumulated data (from AssistantUsage) as fallback.
type SessionUsageObservation ¶ added in v0.39.0
type SessionUsageObservation struct {
Source string `json:"source"`
Complete bool `json:"complete"`
ModelAttributionComplete bool `json:"model_attribution_complete"`
Models []string `json:"models"`
}
SessionUsageObservation describes presence before SDK pointer fields are flattened into UsageStats. Models are observed SDK keys, never requested IDs. Complete describes usage presence, not lifecycle success; consumers must also reject observations affected by execution or engine-lifecycle diagnostics.
type SharedClientOptions ¶ added in v0.37.0
type SharedClientOptions struct {
// "error" when blank.
LogLevel string
// same CLIArgs share one process; calls with different CLIArgs get separate
// processes because CLIArgs are startup-only.
CLIArgs []string
}
SharedClientOptions configures a lazily-constructed process-wide Copilot SDK client returned by SharedClient. Clients are shared by CLIArgs key; within each key, only the first call wins and subsequent calls receive the already-built client regardless of options.
type SkillInvocation ¶
type ToolPolicy ¶ added in v0.38.8
type ToolPolicy struct {
Mode ToolPolicyMode
// contains filtered or unexported fields
}
ToolPolicy is the resolved runtime tool-capability boundary for a session. It is derived from an .agent.md `tools:` declaration (see NewToolPolicy) and then applied to a Copilot SDK session in three ways:
- Declaratively, via SessionConfig/ResumeSessionConfig.AvailableTools (see ToolPolicy.SessionToolFilter), so the SDK itself never exposes denied tools to the model when it supports the filter.
- As defense in depth, via a fail-closed OnPermissionRequest handler (see enforceToolPolicy in copilot.go) that denies any tool-execution attempt the policy does not explicitly allow -- including requests the policy resolver cannot recognize.
- A pre-tool-use hook denies undeclared calls even when the tool does not request permission. Source selection relies on the SDK filter because hook and transcript tool names do not include source metadata.
Tool-name matching is exact and case-insensitive (not regex based), plus a small fixed alias table (see models.CanonicalToolName), matching the semantics used by the tool_constraint grader's allow_only field (see internal/orchestration/agent_graders.go) so runtime enforcement and post-run grading agree on what a declared tool name means.
func NewToolPolicy ¶ added in v0.38.8
func NewToolPolicy(tools *[]string) *ToolPolicy
NewToolPolicy converts the tri-state `.agent.md` `tools:` declaration into an explicit ToolPolicy:
- nil (key absent): ToolPolicyUnrestricted.
- empty (`tools: []`): ToolPolicyDenyAll.
- populated: ToolPolicyAllowList, with the given names as the allowed set.
func (*ToolPolicy) Active ¶ added in v0.38.8
func (p *ToolPolicy) Active() bool
Active reports whether the policy imposes any restriction at all, i.e. enforcement (the OnPermissionRequest wrapper) needs to run.
func (*ToolPolicy) IsAllowed ¶ added in v0.38.8
func (p *ToolPolicy) IsAllowed(name string) bool
IsAllowed reports whether the given tool name is permitted under the policy. A nil *ToolPolicy is treated as unrestricted (preserves prior behavior for callers that never opted in to policy enforcement).
func (*ToolPolicy) SessionToolFilter ¶ added in v0.38.8
func (p *ToolPolicy) SessionToolFilter() []string
SessionToolFilter returns the value to assign to the Copilot SDK's SessionConfig/ResumeSessionConfig.AvailableTools field:
- nil for ToolPolicyUnrestricted: no filter is applied.
- a non-nil empty slice for ToolPolicyDenyAll: the SDK exposes no tools.
- declared names for ToolPolicyAllowList, with built-in aliases translated to native SDK tool names. MCP/custom case and source qualifiers are preserved.
A nil receiver returns nil (unrestricted), matching ToolPolicy.IsAllowed.
type ToolPolicyDenial ¶ added in v0.38.8
type ToolPolicyDenial struct {
// Tool is the canonical tool name the policy evaluated (empty when the
// request kind/shape could not be resolved to a tool name at all).
Tool string
// Kind is the underlying Copilot SDK permission request kind (e.g.
// "shell", "url", "mcp", "custom-tool", "workflow").
Kind string
// Reason explains why the request was denied.
Reason string
}
ToolPolicyDenial records a single tool-execution attempt that was denied by an active ToolPolicy. Captured on ExecutionResponse so callers can surface the effective policy and every denial in session logs and results.json.
type ToolPolicyMode ¶ added in v0.38.8
type ToolPolicyMode string
ToolPolicyMode describes the tool-capability boundary derived from an .agent.md `tools:` declaration. See NewToolPolicy for the tri-state mapping from the declaration to a mode.
const ( // ToolPolicyUnrestricted means the agent did not declare a `tools:` key. // Tools provided by the Copilot runtime may be used without restriction // (the pre-existing default behavior). ToolPolicyUnrestricted ToolPolicyMode = "unrestricted" // ToolPolicyDenyAll means the agent declared `tools: []`. No // model-initiated tool execution is permitted. ToolPolicyDenyAll ToolPolicyMode = "deny_all" // ToolPolicyAllowList means the agent declared one or more tool names. // Only those tools (matched exactly, case-insensitively) are permitted; // every other tool is denied before it executes. ToolPolicyAllowList ToolPolicyMode = "allow_list" )
type UsageAccumulator ¶ added in v0.38.9
type UsageAccumulator struct {
// contains filtered or unexported fields
}
UsageAccumulator combines responses without double-counting cumulative snapshots. Anonymous responses are independent executions.
func (*UsageAccumulator) Add ¶ added in v0.38.9
func (a *UsageAccumulator) Add(resp *ExecutionResponse)
func (*UsageAccumulator) Usage ¶ added in v0.38.9
func (a *UsageAccumulator) Usage() *models.UsageStats
type UsageScope ¶ added in v0.38.9
type UsageScope struct {
// contains filtered or unexported fields
}
UsageScope records executions rather than final task results, so discarded retries and auxiliary sessions remain billable and cache hits do not. A scope belongs to one evaluation pass and its engine.
func NewUsageScope ¶ added in v0.38.9
func NewUsageScope(ctx context.Context) (context.Context, *UsageScope)
func (*UsageScope) Snapshot ¶ added in v0.38.9
func (s *UsageScope) Snapshot() *models.EvaluationUsage
type WorkspaceKeeper ¶ added in v0.29.0
type WorkspaceKeeper interface {
SetKeepWorkspace(keep bool)
}
WorkspaceKeeper is an optional interface that engines can implement to support preserving temp workspaces after execution (for debugging).