Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cli/azd/cmd/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -581,10 +581,16 @@ func registerCommonDependencies(container *ioc.NestedContainer) {
// AI & LLM components
container.MustRegisterSingleton(llm.NewManager)
container.MustRegisterSingleton(llm.NewModelFactory)
container.MustRegisterSingleton(llm.NewSessionConfigBuilder)
container.MustRegisterSingleton(func() *llm.CopilotClientManager {
return llm.NewCopilotClientManager(nil)
})
container.MustRegisterScoped(agent.NewCopilotAgentFactory)
container.MustRegisterScoped(agent.NewAgentFactory)
container.MustRegisterScoped(consent.NewConsentManager)
container.MustRegisterNamedSingleton("ollama", llm.NewOllamaModelProvider)
container.MustRegisterNamedSingleton("azure", llm.NewAzureOpenAiModelProvider)
container.MustRegisterNamedSingleton("copilot", llm.NewCopilotProvider)
registerGitHubCopilotProvider(container)

// Agent security manager
Expand Down
2 changes: 1 addition & 1 deletion cli/azd/cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@ func promptInitType(
console.Message(ctx, "\nThe azd agent feature has been enabled to support this new experience."+
" To turn off in the future run `azd config unset alpha.llm`.")

err = azdConfig.Set("ai.agent.model.type", "github-copilot")
err = azdConfig.Set("ai.agent.model.type", "copilot")
if err != nil {
return initUnknown, fmt.Errorf("failed to set ai.agent.model.type config: %w", err)
}
Expand Down
2 changes: 2 additions & 0 deletions cli/azd/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,10 @@ require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/github/copilot-sdk/go v0.1.25 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/goph/emperror v0.17.2 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
Expand Down
5 changes: 5 additions & 0 deletions cli/azd/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8
github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=
github.com/getzep/zep-go v1.0.4 h1:09o26bPP2RAPKFjWuVWwUWLbtFDF/S8bfbilxzeZAAg=
github.com/getzep/zep-go v1.0.4/go.mod h1:HC1Gz7oiyrzOTvzeKC4dQKUiUy87zpIJl0ZFXXdHuss=
github.com/github/copilot-sdk/go v0.1.25 h1:SJ/jSoesbpjDEBcvMkoCG+xITvgvnhxnd6oJdmNQnOs=
github.com/github/copilot-sdk/go v0.1.25/go.mod h1:qc2iEF7hdO8kzSvbyGvrcGhuk2fzdW4xTtT0+1EH2ts=
github.com/go-check/check v0.0.0-20180628173108-788fd7840127 h1:0gkP6mzaMqkmpcJYCFOLkIBwI7xFExG03bbkOkCvUPI=
github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
Expand Down Expand Up @@ -223,6 +225,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
Expand Down Expand Up @@ -264,6 +268,7 @@ github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRt
github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
Expand Down
38 changes: 29 additions & 9 deletions cli/azd/internal/agent/agent_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@

// AgentFactory is responsible for creating agent instances
type AgentFactory struct {
consentManager consent.ConsentManager
llmManager *llm.Manager
console input.Console
securityManager *security.Manager
consentManager consent.ConsentManager

Check failure on line 25 in cli/azd/internal/agent/agent_factory.go

View workflow job for this annotation

GitHub Actions / azd-lint (ubuntu-latest)

File is not properly formatted (gofmt)
llmManager *llm.Manager
console input.Console
securityManager *security.Manager
copilotAgentFactory *CopilotAgentFactory
}

// NewAgentFactory creates a new instance of AgentFactory
Expand All @@ -34,17 +35,36 @@
console input.Console,
llmManager *llm.Manager,
securityManager *security.Manager,
copilotAgentFactory *CopilotAgentFactory,
) *AgentFactory {
return &AgentFactory{
consentManager: consentManager,
llmManager: llmManager,
console: console,
securityManager: securityManager,
consentManager: consentManager,
llmManager: llmManager,
console: console,
securityManager: securityManager,
copilotAgentFactory: copilotAgentFactory,
}
}

// CreateAgent creates a new agent instance
func (f *AgentFactory) Create(ctx context.Context, opts ...AgentCreateOption) (Agent, error) {
// Check if the configured model type is 'copilot' — if so, delegate to CopilotAgentFactory
defaultModelContainer, err := f.llmManager.GetDefaultModel(ctx)
if err == nil && defaultModelContainer.Type == llm.LlmTypeCopilot {
log.Println("[agent-factory] Model type is 'copilot', delegating to CopilotAgentFactory")
copilotOpts := []CopilotAgentOption{}
for _, opt := range opts {
base := &agentBase{}
opt(base)
if base.debug {
copilotOpts = append(copilotOpts, WithCopilotDebug(true))
}
}
return f.copilotAgentFactory.Create(ctx, copilotOpts...)
}

log.Printf("[agent-factory] Using langchaingo agent (model type: %s)", defaultModelContainer.Type)

cleanupTasks := map[string]func() error{}

cleanup := func() error {
Expand Down Expand Up @@ -77,7 +97,7 @@
}

// Default model gets the chained handler to expose the UX experience for the agent
defaultModelContainer, err := f.llmManager.GetDefaultModel(ctx, llm.WithLogger(chainedHandler))
defaultModelContainer, err = f.llmManager.GetDefaultModel(ctx, llm.WithLogger(chainedHandler))
if err != nil {
defer cleanup()
return nil, err
Expand Down
270 changes: 270 additions & 0 deletions cli/azd/internal/agent/copilot_agent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package agent

import (
"context"
"fmt"
"log"
"strings"
"time"

copilot "github.com/github/copilot-sdk/go"

"github.com/azure/azure-dev/cli/azd/internal/agent/logging"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/output"
uxlib "github.com/azure/azure-dev/cli/azd/pkg/ux"
"github.com/azure/azure-dev/cli/azd/pkg/watch"
"github.com/fatih/color"
)

// CopilotAgent implements the Agent interface using the GitHub Copilot SDK.
// It manages a copilot.Session for multi-turn conversations and streams
// session events for UX rendering.
type CopilotAgent struct {
session *copilot.Session
console input.Console
thoughtChan chan logging.Thought
cleanupFunc AgentCleanup
debug bool

watchForFileChanges bool
}

// CopilotAgentOption is a functional option for configuring a CopilotAgent.
type CopilotAgentOption func(*CopilotAgent)

// WithCopilotDebug enables debug logging for the Copilot agent.
func WithCopilotDebug(debug bool) CopilotAgentOption {
return func(a *CopilotAgent) { a.debug = debug }
}

// WithCopilotFileWatching enables file change detection after tool execution.
func WithCopilotFileWatching(enabled bool) CopilotAgentOption {
return func(a *CopilotAgent) { a.watchForFileChanges = enabled }
}

// WithCopilotCleanup sets the cleanup function called on Stop().
func WithCopilotCleanup(fn AgentCleanup) CopilotAgentOption {
return func(a *CopilotAgent) { a.cleanupFunc = fn }
}

// WithCopilotThoughtChannel sets the channel for streaming thoughts to the UX layer.
func WithCopilotThoughtChannel(ch chan logging.Thought) CopilotAgentOption {
return func(a *CopilotAgent) { a.thoughtChan = ch }
}

// NewCopilotAgent creates a new CopilotAgent backed by the given copilot.Session.
func NewCopilotAgent(
session *copilot.Session,
console input.Console,
opts ...CopilotAgentOption,
) *CopilotAgent {
agent := &CopilotAgent{
session: session,
console: console,
watchForFileChanges: true,
}

for _, opt := range opts {
opt(agent)
}

return agent
}
Comment on lines +59 to +76
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CopilotAgent and CopilotAgentFactory lack unit tests. These are core components that implement the Agent interface and manage complex lifecycle operations (cleanup ordering, event subscription, context cancellation). Consider adding tests for: CopilotAgent.SendMessage success/error paths, CopilotAgentFactory.Create cleanup on error paths, and proper resource cleanup ordering. The existing agent code has test coverage (e.g., agent_factory_test.go for the langchaingo implementation), so the same standard should apply here.

Copilot uses AI. Check for mistakes.

// SendMessage sends a message to the Copilot agent session and waits for a response.
func (a *CopilotAgent) SendMessage(ctx context.Context, args ...string) (string, error) {
thoughtsCtx, cancelCtx := context.WithCancel(ctx)

var watcher watch.Watcher
if a.watchForFileChanges {
var err error
watcher, err = watch.NewWatcher(ctx)
if err != nil {
cancelCtx()
return "", fmt.Errorf("failed to start watcher: %w", err)
}
}
Comment on lines +82 to +90
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The watcher is created with ctx (line 84) but thoughtsCtx is canceled in the defer (line 98). The watcher goroutine will only stop when the original ctx is done, not when thoughtsCtx is canceled. This could cause the watcher to keep running longer than intended. Consider passing thoughtsCtx to watch.NewWatcher() instead of ctx to ensure the watcher stops when the SendMessage operation completes.

Copilot uses AI. Check for mistakes.

cleanup, err := a.renderThoughts(thoughtsCtx)
if err != nil {
cancelCtx()
return "", err
}

defer func() {
cancelCtx()
time.Sleep(100 * time.Millisecond)
cleanup()
if a.watchForFileChanges {
watcher.PrintChangedFiles(ctx)
}
}()

prompt := strings.Join(args, "\n")
log.Printf("[copilot] SendMessage: sending prompt (%d chars)...", len(prompt))
result, err := a.session.SendAndWait(ctx, copilot.MessageOptions{
Prompt: prompt,
})
if err != nil {
log.Printf("[copilot] SendMessage: error: %v", err)
return "", fmt.Errorf("copilot agent error: %w", err)
}

// Extract the final assistant message content
if result != nil && result.Data.Content != nil {
log.Printf("[copilot] SendMessage: received response (%d chars)", len(*result.Data.Content))
return *result.Data.Content, nil
}

log.Println("[copilot] SendMessage: received empty response")
return "", nil
}

// SendMessageWithRetry sends a message and prompts the user to retry on error.
func (a *CopilotAgent) SendMessageWithRetry(ctx context.Context, args ...string) (string, error) {
for {
agentOutput, err := a.SendMessage(ctx, args...)
if err != nil {
if agentOutput != "" {
a.console.Message(ctx, output.WithMarkdown(agentOutput))
}

if shouldRetry := a.handleErrorWithRetryPrompt(ctx, err); shouldRetry {
continue
}
return "", err
}

return agentOutput, nil
}
}

// Stop terminates the agent and performs cleanup.
func (a *CopilotAgent) Stop() error {
if a.cleanupFunc != nil {
return a.cleanupFunc()
}
return nil
}

func (a *CopilotAgent) handleErrorWithRetryPrompt(ctx context.Context, err error) bool {
a.console.Message(ctx, "")
a.console.Message(ctx, output.WithErrorFormat("Error occurred: %s", err.Error()))
a.console.Message(ctx, "")

retryPrompt := uxlib.NewConfirm(&uxlib.ConfirmOptions{
Message: "Oops, my reply didn't quite fit what was needed. Want me to try again?",
DefaultValue: uxlib.Ptr(true),
HelpMessage: "Choose 'yes' to retry the current step, or 'no' to stop the initialization.",
})

shouldRetry, promptErr := retryPrompt.Ask(ctx)
if promptErr != nil {
return false
}

return shouldRetry != nil && *shouldRetry
}

// renderThoughts reuses the same UX rendering pattern as ConversationalAzdAiAgent,
// reading from the thought channel and displaying spinner + tool completion messages.
func (a *CopilotAgent) renderThoughts(ctx context.Context) (func(), error) {
if a.thoughtChan == nil {
return func() {}, nil
}

var latestThought string

spinner := uxlib.NewSpinner(&uxlib.SpinnerOptions{
Text: "Processing...",
})

canvas := uxlib.NewCanvas(
spinner,
uxlib.NewVisualElement(func(printer uxlib.Printer) error {
printer.Fprintln()
printer.Fprintln()

if latestThought != "" {
printer.Fprintln(color.HiBlackString(latestThought))
printer.Fprintln()
printer.Fprintln()
}

return nil
}))

printToolCompletion := func(action, actionInput, thought string) {
if action == "" {
return
}

completionMsg := fmt.Sprintf("%s Ran %s", color.GreenString("✔︎"), color.MagentaString(action))
if actionInput != "" {
completionMsg += " with " + color.HiBlackString(actionInput)
}
if thought != "" {
completionMsg += color.MagentaString("\n\n◆ agent: ") + thought
}

canvas.Clear()
fmt.Println(completionMsg)
fmt.Println()
}

go func() {
defer canvas.Clear()

var latestAction string
var latestActionInput string
var spinnerText string
var toolStartTime time.Time

for {
select {
case thought := <-a.thoughtChan:
if thought.Action != "" {
if thought.Action != latestAction || thought.ActionInput != latestActionInput {
printToolCompletion(latestAction, latestActionInput, latestThought)
}
latestAction = thought.Action
latestActionInput = thought.ActionInput
toolStartTime = time.Now()
}
if thought.Thought != "" {
latestThought = thought.Thought
}
case <-ctx.Done():
printToolCompletion(latestAction, latestActionInput, latestThought)
return
case <-time.After(200 * time.Millisecond):
}

if latestAction == "" {
spinnerText = "Processing..."
} else {
elapsedSeconds := int(time.Since(toolStartTime).Seconds())
spinnerText = fmt.Sprintf("Running %s tool", color.MagentaString(latestAction))
if latestActionInput != "" {
spinnerText += " with " + color.HiBlackString(latestActionInput)
}
spinnerText += "..."
spinnerText += color.HiBlackString(fmt.Sprintf("\n(%ds, CTRL C to exit agentic mode)", elapsedSeconds))
}

spinner.UpdateText(spinnerText)
canvas.Update()
}
}()

cleanup := func() {
canvas.Clear()
canvas.Close()
}

return cleanup, canvas.Run()
}
Loading
Loading