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
14 changes: 8 additions & 6 deletions go/api/v1alpha3/agenttemplate_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ type MCPToolBinding struct {
RequireApproval bool `json:"requireApproval,omitempty"`
}

// SubAgentToolBinding exposes a same-namespace AgentTemplate as a logical tool.
// SubAgentToolBinding exposes a same-namespace AgentTemplate or Agent as a logical tool.
// +kubebuilder:validation:XValidation:rule="has(self.templateRef) != has(self.agentRef)",message="exactly one of templateRef or agentRef must be specified"
type SubAgentToolBinding struct {
// +kubebuilder:validation:MinLength=1
// +required
Expand All @@ -82,11 +83,12 @@ type SubAgentToolBinding struct {
Description string `json:"description"`
// TemplateRef selects a Shared subagent compiled into the parent's runtime using its Harness.
// +kubebuilder:validation:XValidation:rule="has(self.name) && self.name != ''",message="templateRef.name must not be empty"
// +required
TemplateRef *corev1.LocalObjectReference `json:"templateRef"`

// Deferred until Dedicated subagents can create and invoke their own Session.
// AgentRef *corev1.LocalObjectReference `json:"agentRef,omitempty"`
// +optional
TemplateRef *corev1.LocalObjectReference `json:"templateRef,omitempty"`
// AgentRef selects a Dedicated subagent with its own Harness and Session, invoked over A2A.
// +kubebuilder:validation:XValidation:rule="has(self.name) && self.name != ''",message="agentRef.name must not be empty"
// +optional
AgentRef *corev1.LocalObjectReference `json:"agentRef,omitempty"`
}

// ToolBinding selects exactly one MCP or subagent tool source.
Expand Down
7 changes: 6 additions & 1 deletion go/api/v1alpha3/configuration_crd_cel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,13 @@ func TestConfigurationCRDValidation(t *testing.T) {
wantReject string
}{
{name: "template-ref", binding: SubAgentToolBinding{TemplateRef: &corev1.LocalObjectReference{Name: "context"}}},
{name: "missing-template-ref", wantReject: "templateRef: Required value"},
{name: "agent-ref", binding: SubAgentToolBinding{AgentRef: &corev1.LocalObjectReference{Name: "peer"}}},
{name: "both-refs", binding: SubAgentToolBinding{
TemplateRef: &corev1.LocalObjectReference{Name: "context"}, AgentRef: &corev1.LocalObjectReference{Name: "peer"},
}, wantReject: "exactly one of templateRef or agentRef must be specified"},
{name: "neither-ref", wantReject: "exactly one of templateRef or agentRef must be specified"},
{name: "empty-template-ref", binding: SubAgentToolBinding{TemplateRef: &corev1.LocalObjectReference{}}, wantReject: "templateRef.name must not be empty"},
{name: "empty-agent-ref", binding: SubAgentToolBinding{AgentRef: &corev1.LocalObjectReference{}}, wantReject: "agentRef.name must not be empty"},
} {
for _, inline := range []bool{false, true} {
name := fmt.Sprintf("subagent-%s-inline-%t", tc.name, inline)
Expand Down
5 changes: 5 additions & 0 deletions go/api/v1alpha3/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions go/core/internal/egress/destination.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,34 @@ func ParseOrigin(raw string) (*url.URL, error) {
return u, nil
}

// Covers reports whether origin falls under one of the granted origins. A
// grant covers an origin with the same scheme, port and host; a wildcard grant
// (https://*.example.com) covers hosts with exactly one more leftmost label,
// the semantics ParseOrigin accepts and Substrate enforces.
func Covers(grants []string, origin string) bool {
target, err := ParseOrigin(origin)
if err != nil {
return false
}
for _, raw := range grants {
grant, err := ParseOrigin(raw)
if err != nil || grant.Scheme != target.Scheme || grant.Port() != target.Port() {
continue
}
if rest, wildcard := strings.CutPrefix(grant.Hostname(), "*."); wildcard {
label, parent, found := strings.Cut(target.Hostname(), ".")
if found && label != "" && parent == rest {
return true
}
continue
}
if grant.Hostname() == target.Hostname() {
return true
}
}
return false
}

// Access is a compiled network grant. It contains references,
// never Secret values.
type Access struct {
Expand Down
25 changes: 25 additions & 0 deletions go/core/internal/egress/destination_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,28 @@ func TestOrigin(t *testing.T) {
})
}
}

func TestCovers(t *testing.T) {
for _, tc := range []struct {
name string
grants []string
origin string
want bool
}{
{name: "no grants", origin: "http://a.example.com:80"},
{name: "exact", grants: []string{"http://a.example.com:80"}, origin: "http://a.example.com:80", want: true},
{name: "default port is explicit", grants: []string{"https://a.example.com"}, origin: "https://a.example.com:443", want: true},
{name: "other scheme", grants: []string{"https://a.example.com:80"}, origin: "http://a.example.com:80"},
{name: "other port", grants: []string{"http://a.example.com:8080"}, origin: "http://a.example.com:80"},
{name: "other host", grants: []string{"http://b.example.com:80"}, origin: "http://a.example.com:80"},
{name: "wildcard covers one label", grants: []string{"https://*.example.com"}, origin: "https://a.example.com:443", want: true},
{name: "wildcard does not cover the apex", grants: []string{"https://*.example.com"}, origin: "https://example.com:443"},
{name: "wildcard does not cover two labels", grants: []string{"https://*.example.com"}, origin: "https://a.b.example.com:443"},
{name: "wildcard keeps the port", grants: []string{"https://*.example.com:8443"}, origin: "https://a.example.com:443"},
{name: "second grant matches", grants: []string{"http://b.example.com:80", "http://a.example.com:80"}, origin: "http://a.example.com:80", want: true},
} {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, Covers(tc.grants, tc.origin))
})
}
}
20 changes: 17 additions & 3 deletions go/core/internal/runtimeauth/delegation.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,14 @@ func (d *PeerDelegator) DelegatePeer(ctx context.Context, target types.Namespace
return auth.AuthSessionTo(ctx, delegatedSession{owner: actor.owner, agent: callerNamespace + "/" + callerName, sessionID: actor.sessionID}), nil
}

// declares reports whether the caller Agent, or the AgentTemplate it references, lists peer in AgentRefsAnnotation.
// declares reports whether the caller Agent, or the AgentTemplate it references, declares peer: either in
// AgentRefsAnnotation or as a Dedicated subAgent.agentRef tool binding of its effective template.
func (d *PeerDelegator) declares(ctx context.Context, caller types.NamespacedName, peer string) (bool, error) {
var agent v1alpha3.Agent
if err := d.kube.Get(ctx, caller, &agent); err != nil {
return false, client.IgnoreNotFound(err)
}
if listed(agent.GetAnnotations()[AgentRefsAnnotation], peer) {
if listed(agent.GetAnnotations()[AgentRefsAnnotation], peer) || bindsAgentRef(agent.Spec.Template.Inline, peer) {
return true, nil
}
ref := agent.Spec.Template.Ref
Expand All @@ -103,7 +104,20 @@ func (d *PeerDelegator) declares(ctx context.Context, caller types.NamespacedNam
}
return false, fmt.Errorf("read AgentTemplate %s/%s: %w", caller.Namespace, ref.Name, err)
}
return listed(template.GetAnnotations()[AgentRefsAnnotation], peer), nil
return listed(template.GetAnnotations()[AgentRefsAnnotation], peer) || bindsAgentRef(&template.Spec, peer), nil
}

// bindsAgentRef reports whether the template has a Dedicated subagent tool that references peer.
func bindsAgentRef(template *v1alpha3.AgentTemplateSpec, peer string) bool {
if template == nil {
return false
}
for _, tool := range template.Tools {
if tool.SubAgent != nil && tool.SubAgent.AgentRef != nil && tool.SubAgent.AgentRef.Name == peer {
return true
}
}
return false
}

func listed(value, name string) bool {
Expand Down
42 changes: 42 additions & 0 deletions go/core/internal/runtimeauth/delegation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,48 @@ func TestDeclaredPeerIsDelegatedToTheSessionOwner(t *testing.T) {
}
}

func agentRefTool(peer string) v1alpha3.ToolBinding {
return v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{
Name: "peer_tool", Description: "peer", AgentRef: &corev1.LocalObjectReference{Name: peer},
}}
}

// A Dedicated subAgent.agentRef binding is a declaration, next to the annotation.
func TestAgentRefBindingIsADeclaration(t *testing.T) {
f := newDelegationFixture(t)
inline := func(tools ...v1alpha3.ToolBinding) *v1alpha3.Agent {
agent := callerAgent(nil, "")
agent.Spec.Template.Inline = &v1alpha3.AgentTemplateSpec{Tools: tools}
return agent
}
referenced := func(tools ...v1alpha3.ToolBinding) *v1alpha3.AgentTemplate {
tpl := template("coordinator", nil)
tpl.Spec.Tools = tools
return tpl
}
peer := types.NamespacedName{Namespace: "team-a", Name: "peer"}
for name, test := range map[string]struct {
reader client.Reader
wantDelegated bool
}{
"inline agentRef": {kube(t, inline(agentRefTool("peer"))), true},
"referenced-template agentRef": {kube(t, callerAgent(nil, "coordinator"), referenced(agentRefTool("peer"))), true},
"agentRef to another name": {kube(t, inline(agentRefTool("peer-2"))), false},
"shared templateRef is no peer": {kube(t, inline(v1alpha3.ToolBinding{SubAgent: &v1alpha3.SubAgentToolBinding{Name: "peer", Description: "d", TemplateRef: &corev1.LocalObjectReference{Name: "peer"}}})), false},
"planeo annotation still declares": {kube(t, callerAgent(map[string]string{runtimeauth.AgentRefsAnnotation: "peer"}, "")), true},
} {
t.Run(name, func(t *testing.T) {
principal := delegate(t, f, test.reader, peer)
if test.wantDelegated {
require.Nil(t, principal.RuntimeBinding, "a delegated call is not an actor any more")
require.Equal(t, "owner", principal.ID)
return
}
require.NotNil(t, principal.RuntimeBinding, "stays an actor, so upstream's actor policy decides")
})
}
}

func TestUndeclaredCrossNamespaceAndSelfStayActors(t *testing.T) {
f := newDelegationFixture(t)
declared := map[string]string{runtimeauth.AgentRefsAnnotation: "peer"}
Expand Down
53 changes: 51 additions & 2 deletions go/core/internal/translator/adkconfig/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,23 @@ type provenanceEntry struct {

// Builder assembles resolved inputs into an ADK agent configuration.
type Builder struct {
ctx krt.HandlerContext
collections translator.Collections
ctx krt.HandlerContext
collections translator.Collections
controlPlaneURL string
}

// NewBuilder constructs an ADK configuration builder.
func NewBuilder(ctx krt.HandlerContext, collections translator.Collections) *Builder {
return &Builder{ctx: ctx, collections: collections}
}

// WithControlPlaneURL sets the controller origin that Dedicated subagents call
// through the A2A gateway.
func (c *Builder) WithControlPlaneURL(url string) *Builder {
c.controlPlaneURL = url
return c
}

type Result struct {
Config *configv1.ADKAgentConfig
Models []*translator.ResolvedModelConfig
Expand Down Expand Up @@ -88,12 +96,53 @@ func (c *Builder) Build(ctx context.Context, input *translator.HarnessInput) (*R
return nil, err
}
}
if err := c.applyRemoteAgents(result, input); err != nil {
return nil, err
}
// The Python runtime needs an async SQLite driver; the Go runtime accepts
// this URL and strips the driver before opening the same durable database.
result.Config.SessionDbUrl = "sqlite+aiosqlite:////data/sessions.db"
return result, nil
}

// applyRemoteAgents adds the root agent's Dedicated subagents and the external
// A2A agents declared by annotation (which grant no egress themselves). Binding names are unique across all three
// kinds of subagent because each becomes a tool of the same name.
func (c *Builder) applyRemoteAgents(result *Result, input *translator.HarnessInput) error {
if len(input.Root.Dedicated) > 0 && c.controlPlaneURL == "" {
return fmt.Errorf("control plane URL is required for Dedicated subagents")
}
remote := DedicatedRemoteAgents(c.controlPlaneURL, input.Root.Template.Namespace, input.Root.Dedicated)
external, err := ExternalRemoteAgents(c.controlPlaneURL, input.Annotations)
if err != nil {
return translator.NewValidationError("%w", err)
}
// An annotation is not an authorization: external origins must already be
// granted by an EgressPolicy the Agent references.
for _, agent := range external {
target, err := url.Parse(agent.Url)
if err != nil {
return translator.NewValidationError("remote agent %q: %w", agent.Name, err)
}
if origin := egress.Origin(target); !egress.Covers(input.EgressGrants, origin) {
return translator.NewValidationError("remote agent %q needs egress to %s, which must be granted by an EgressPolicy in spec.egressPolicyRefs", agent.Name, origin)
}
}
remote = append(remote, external...)
taken := map[string]struct{}{}
for _, child := range result.Config.SubAgents {
taken[child.Name] = struct{}{}
}
for _, agent := range remote {
if _, ok := taken[agent.Name]; ok {
return translator.NewValidationError("duplicate subagent binding name %q", agent.Name)
}
taken[agent.Name] = struct{}{}
}
result.Config.RemoteAgents = remote
return nil
}

func (c *Builder) compileAgent(ctx context.Context, input *translator.AgentInput) (*Result, error) {
modelRuntime := &modelRuntime{}
var modelConfig *v1alpha3.ModelConfig
Expand Down
38 changes: 38 additions & 0 deletions go/core/internal/translator/adkconfig/dedicated.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package adkconfig

import (
"strings"
"time"

"google.golang.org/protobuf/types/known/durationpb"

configv1 "github.com/kagent-dev/kagent/go/api/gen/kagent/config/v1"
"github.com/kagent-dev/kagent/go/core/internal/translator"
)

// remoteAgentTimeout bounds one call to a peer Agent. A peer runs a full agent
// loop, so the bound is generous; it matches the kagent 0.10 default.
const remoteAgentTimeout = 30 * time.Minute

// DedicatedRemoteAgents turns subAgent.agentRef bindings into ADK remote A2A
// agents that call the peer through the controller's A2A gateway.
//
// The card URL carries the gateway path, which a2a-go fetches verbatim
// (kagent#3275). The compiled output depends only on the parent's own spec: a
// missing peer surfaces at call time as a gateway 404.
func DedicatedRemoteAgents(controlPlaneURL, namespace string, bindings []translator.DedicatedBinding) []*configv1.ADKRemoteAgentConfig {
if len(bindings) == 0 {
return nil
}
base := strings.TrimRight(controlPlaneURL, "/")
agents := make([]*configv1.ADKRemoteAgentConfig, 0, len(bindings))
for _, binding := range bindings {
agents = append(agents, &configv1.ADKRemoteAgentConfig{
Name: binding.Name,
Description: binding.Description,
Url: base + "/agents/" + namespace + "/" + binding.AgentRef.Name + "/.well-known/agent-card.json",
Timeout: durationpb.New(remoteAgentTimeout),
})
}
return agents
}
34 changes: 34 additions & 0 deletions go/core/internal/translator/adkconfig/dedicated_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package adkconfig

import (
"testing"
"time"

"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"

"github.com/kagent-dev/kagent/go/core/internal/translator"
)

func TestDedicatedRemoteAgents(t *testing.T) {
const controlPlane = "http://kagent-v1-controller.kagent-v1.svc.cluster.local:8083"

require.Nil(t, DedicatedRemoteAgents(controlPlane, "troubleshooting", nil))

agents := DedicatedRemoteAgents(controlPlane, "troubleshooting", []translator.DedicatedBinding{{
Name: "telemetry_agent", Description: "T", AgentRef: corev1.LocalObjectReference{Name: "telemetry-agent"},
}})
require.Len(t, agents, 1)
require.Equal(t, "telemetry_agent", agents[0].Name)
require.Equal(t, "T", agents[0].Description)
require.Equal(t, controlPlane+"/agents/troubleshooting/telemetry-agent/.well-known/agent-card.json", agents[0].Url)
require.Equal(t, 30*time.Minute, agents[0].Timeout.AsDuration())
require.False(t, agents[0].IsolateSessions)
}

func TestDedicatedRemoteAgentsToleratesTrailingSlash(t *testing.T) {
agents := DedicatedRemoteAgents("http://controller:8083/", "ns", []translator.DedicatedBinding{{
Name: "peer", Description: "d", AgentRef: corev1.LocalObjectReference{Name: "peer-agent"},
}})
require.Equal(t, "http://controller:8083/agents/ns/peer-agent/.well-known/agent-card.json", agents[0].Url)
}
Loading
Loading