Skip to content
Open
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
72 changes: 19 additions & 53 deletions cli/azd/extensions/azure.ai.agents/internal/cmd/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"fmt"
"io"
"log"
"maps"
"net/http"
"net/url"
"os"
Expand All @@ -24,7 +23,6 @@ import (
"azureaiagent/internal/pkg/agents/agent_api"
"azureaiagent/internal/pkg/agents/agent_yaml"
"azureaiagent/internal/pkg/paths"
"azureaiagent/internal/pkg/projectconfig"
projectpkg "azureaiagent/internal/project"

"github.com/azure/azure-dev/cli/azd/pkg/azdext"
Expand Down Expand Up @@ -941,10 +939,11 @@ func resolveAgentServiceFromProject(

// ServiceRunContext holds the resolved context needed for local development.
type ServiceRunContext struct {
ServiceName string // the resolved service name (from azure.yaml)
ProjectDir string // absolute path to the service source directory
StartupCommand string // startupCommand from AdditionalProperties (may be empty)
Environment map[string]string
ServiceName string // the resolved service name (from azure.yaml)
ProjectDir string // absolute path to the service source directory
StartupCommand string // startupCommand from AdditionalProperties (may be empty)
ServiceEnvironment map[string]string // values already expanded by azd core
HasServiceEnvironment bool // service declares env: even when empty
// Definition is the resolved agent definition (from the inline azure.yaml
// entry or a legacy agent.yaml). It is nil when no definition can be resolved.
Definition *agent_yaml.ContainerAgent
Expand Down Expand Up @@ -982,28 +981,10 @@ func resolveServiceRunContext(ctx context.Context, azdClient *azdext.AzdClient,
}

var startupCmd string
serviceEnv := map[string]string{}
if agentConfig, cfgErr := projectpkg.LoadServiceTargetAgentConfig(
svc,
); cfgErr == nil {
startupCmd = agentConfig.StartupCommand
maps.Copy(serviceEnv, agentConfig.Environment)
}
serviceEnv, err = loadServiceRunEnvironment(
project.Path,
svc,
serviceEnv,
)
if err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidServiceConfig,
fmt.Sprintf(
"failed to load environment for %s: %s",
svc.Name,
err,
),
"fix the service env configuration in azure.yaml",
)
}

var definition *agent_yaml.ContainerAgent
Expand All @@ -1014,39 +995,24 @@ func resolveServiceRunContext(ctx context.Context, azdClient *azdext.AzdClient,
}
}

hasServiceEnvironment := false
if resp, envErr := azdClient.Project().GetServiceConfigValue(
ctx,
&azdext.GetServiceConfigValueRequest{ServiceName: svc.Name, Path: "env"},
); envErr == nil {
hasServiceEnvironment = resp.GetFound()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

On a GetServiceConfigValue error this leaves hasServiceEnvironment false, so mergeAgentRunEnvironment takes the legacy branch and injects the full azd environment, the exact leak this commit is closing. The routines and toolboxes targets in this same change fail closed by returning the error from serviceEnvDeclared. Do the same here and only trust Found after a successful call.

}
Comment on lines +998 to +1004

return &ServiceRunContext{
ServiceName: svc.Name,
ProjectDir: projectDir,
StartupCommand: startupCmd,
Environment: serviceEnv,
Definition: definition,
ServiceName: svc.Name,
ProjectDir: projectDir,
StartupCommand: startupCmd,
ServiceEnvironment: svc.GetEnvironment(),
HasServiceEnvironment: hasServiceEnvironment,
Definition: definition,
}, nil
}

func loadServiceRunEnvironment(
projectRoot string,
svc *azdext.ServiceConfig,
base map[string]string,
) (map[string]string, error) {
env := maps.Clone(base)
if env == nil {
env = map[string]string{}
}
raw, err := projectconfig.LoadServiceEnvironment(
projectRoot,
svc.GetName(),
)
if err != nil {
return nil, err
}
if raw == nil {
maps.Copy(env, svc.GetEnvironment())
} else {
maps.Copy(env, raw)
}
return env, nil
}

// toServiceKey converts a service name into the env var key format (uppercase, underscores).
func toServiceKey(serviceName string) string {
key := strings.ReplaceAll(serviceName, " ", "_")
Expand Down
38 changes: 0 additions & 38 deletions cli/azd/extensions/azure.ai.agents/internal/cmd/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -956,41 +956,3 @@ func TestResolveAgentProtocol_MultipleServicesPromptsOnce(t *testing.T) {
require.Equal(t, int32(1), promptServer.selectCalls.Load(),
"resolveAgentProtocol should trigger exactly one prompt")
}

func TestLoadServiceRunEnvironmentUsesRawValues(t *testing.T) {
t.Parallel()

root := t.TempDir()
require.NoError(t, os.WriteFile(
filepath.Join(root, "azure.yaml"),
[]byte(`services:
agent:
host: azure.ai.agent
env:
PROJECT: ${{project.endpoint}}
ENABLED: true
SHARED: direct
`),
0o600,
))
svc := &azdext.ServiceConfig{
Name: "agent",
Environment: map[string]string{
"PROJECT": "",
"ENABLED": "",
"SHARED": "expanded",
},
}

env, err := loadServiceRunEnvironment(
root,
svc,
map[string]string{"CONFIG_ONLY": "config", "SHARED": "config"},
)

require.NoError(t, err)
require.Equal(t, "${{project.endpoint}}", env["PROJECT"])
require.Equal(t, "true", env["ENABLED"])
require.Equal(t, "direct", env["SHARED"])
require.Equal(t, "config", env["CONFIG_ONLY"])
}
9 changes: 9 additions & 0 deletions cli/azd/extensions/azure.ai.agents/internal/cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2935,6 +2935,7 @@ func (a *InitAction) addToProject(ctx context.Context, targetDir string, agentMa
if err != nil {
return err
}
agentEnvironment := project.AgentEnvironment(containerDef)

serviceConfig := &azdext.ServiceConfig{
Name: a.serviceNameOverride,
Expand Down Expand Up @@ -2968,6 +2969,14 @@ func (a *InitAction) addToProject(ctx context.Context, targetDir string, agentMa
if _, err := a.azdClient.Project().AddService(ctx, req); err != nil {
return fmt.Errorf("adding agent service to project: %w", err)
}
if err := setServiceEnvironment(
ctx,
a.azdClient,
a.serviceNameOverride,
agentEnvironment,
); err != nil {
return err
}

// Emit the sibling Foundry resource services (project + deployments,
// connections, toolboxes) and wire the agent's uses: to them. A selected
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,7 @@ func (a *InitFromCodeAction) addToProject(
if err != nil {
return err
}
agentEnvironment := project.AgentEnvironment(*definition)

language := "python"
if !isCodeDeploy {
Expand All @@ -840,8 +841,9 @@ func (a *InitFromCodeAction) addToProject(
language = "csharp"
}

agentServiceName := strings.ReplaceAll(agentName, " ", "")
serviceConfig := &azdext.ServiceConfig{
Name: strings.ReplaceAll(agentName, " ", ""),
Name: agentServiceName,
RelativePath: targetDir,
Host: AiAgentHost,
Language: language,
Expand All @@ -868,11 +870,18 @@ func (a *InitFromCodeAction) addToProject(
if _, err := a.azdClient.Project().AddService(ctx, req); err != nil {
return fmt.Errorf("adding agent service to project: %w", err)
}
if err := setServiceEnvironment(
ctx,
a.azdClient,
agentServiceName,
agentEnvironment,
); err != nil {
return err
}

// Emit the sibling azure.ai.project service carrying the model deployments
// and wire the agent's uses: to it. A selected existing project contributes
// its endpoint so provision reuses it instead of creating a new project.
agentServiceName := strings.ReplaceAll(agentName, " ", "")
if err := emitResourceServices(
ctx, a.azdClient, agentServiceName,
projectNameHint(ctx, a.azdClient, a.environment.Name, a.selectedFoundryProject),
Expand Down
10 changes: 10 additions & 0 deletions cli/azd/extensions/azure.ai.agents/internal/cmd/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,9 @@ func TestAddToProjectPreBuiltImageWritesServiceImage(t *testing.T) {
Protocols: []agent_yaml.ProtocolVersionRecord{
{Protocol: "responses", Version: "2.0.0"},
},
EnvironmentVariables: &[]agent_yaml.EnvironmentVariable{
{Name: "LOG_LEVEL", Value: "info"},
},
},
}

Expand All @@ -446,9 +449,16 @@ func TestAddToProjectPreBuiltImageWritesServiceImage(t *testing.T) {
require.Equal(t, "docker", agentService.GetLanguage())
require.NotNil(t, agentService.GetDocker())
require.NotNil(t, agentService.GetAdditionalProperties())
require.Empty(t, agentService.GetEnvironment())
require.Equal(t, map[string]any{
"LOG_LEVEL": "info",
}, server.env["my-agent"])

_, hasInlineImage := agentService.GetAdditionalProperties().GetFields()["image"]
require.False(t, hasInlineImage, "pre-built image must ride on the top-level service image field")
_, hasInlineEnvironment := agentService.GetAdditionalProperties().
GetFields()["environmentVariables"]
require.False(t, hasInlineEnvironment)
}

func TestValidateInitAgentName(t *testing.T) {
Expand Down
Loading
Loading