Skip to content

[BUG] Subagent session isolation #2137

Closed

Description

@dimetron

📋 Prerequisites

  • I have searched the existing issues to avoid creating a duplicate
  • By submitting this issue, you agree to follow our Code of Conduct
  • I am using the latest version of the software
  • I have tried to clear cache/cookies or used incognito mode (if ui-related)
  • I can consistently reproduce this issue

🎯 Affected Service(s)

Not Sure

🚦 Impact/Severity

No impact (Default)

🐛 Bug Description

EP: Per-call session isolation for Agent tools (isolateSessions)

Goal

Let a declarative agent fan out parallel, isolated sub-agent calls. Today every
call the parent makes to a given sub-agent (Agent tool) reuses one A2A
context_id, so all calls land in a single sub-agent session and are processed
as one conversation instead of independent sessions.

Add an opt-in isolateSessions flag on Agent tools. When enabled, each call to that
sub-agent uses a fresh context_id, so every invocation runs in its own isolated
sub-agent session — the Go equivalent of ADK's AgentTool "fresh session/context per
invocation" (the pattern the Python coordinator/dispatcher uses for per-repository
context isolation).

Problem (root cause)

go/adk/pkg/tools/remote_a2a_tool.go generates lastContextID once, at tool
construction (pod startup), and stamps it on every outbound A2A message:

state := &remoteA2AState{ /* ... */ lastContextID: a2atype.NewContextID() }
// ...
message.ContextID = s.lastContextID   // same id for every call, forever

The worker derives its session id straight from that context id
(go/adk/pkg/a2a/executor.go: sessionID := reqCtx.ContextID). So N parallel calls
→ 1 shared worker session, serialized/interleaved rather than N parallel sessions.

Observed: a coordinator emitted 11 sub-agent calls in one model turn; all 11 collapsed
into a single worker session (11 A2A tasks in one context) instead of 11 isolated
sessions.

The Python low-level tool (_remote_a2a_tool.py) has the identical shared-context
behavior; the Python side only gets isolation because a custom dispatcher wraps the
worker in ADK AgentTool, which mints a fresh session per call. This EP brings the
same capability to the Go declarative runtime without a custom agent.

Design

isolateSessions is a per-Agent-tool boolean.

  • false (default): unchanged. One stable context_id per tool for its lifetime
    → session continuity for stateful sub-agents.
  • true: context_id is minted per call via a2atype.NewContextID() → each call
    is an isolated sub-agent session; parallel fan-out no longer shares state/history.

Cross-conversation/turn continuity that stateful workers need does not depend on
the message context_id: it rides the x-kagent-root-context-id header
(lineageHeadersInterceptor), which stays stable per conversation regardless of this
flag. So isolation only changes which sub-agent session a turn is recorded in.

UI linking

The executor pre-stamps outgoing function_call parts with a pre-known
subagent_session_id from a startup map (subagentSessionIDs, keyed by tool name).
With per-call ids there is no single pre-known id, so an isolated tool contributes
no map entry: the UI links each sub-agent card via the per-call
subagent_session_id returned in the tool's function_response (already consumed by
AgentCallDisplay).

Changes

File Change
go/api/v1alpha2/agent_types.go Add IsolateSessions *bool to Tool (+ CEL validation: only for type=Agent)
go/api/adk/types.go Add IsolateSessions bool (isolate_sessions) to RemoteAgentConfig
go/core/internal/controller/translator/agent/compiler.go Copy tool.IsolateSessions → RemoteAgentConfig.IsolateSessions
go/adk/pkg/agent/agent.go Pass flag to NewKAgentRemoteA2ATool; skip stamp-map entry when isolated
go/adk/pkg/tools/remote_a2a_tool.go isolateSessions field; per-call context_id; thread it into processResult
python/packages/kagent-adk/src/kagent/adk/types.py Add isolate_sessions field for config-schema parity (Go runtime honors it)
generated CRD YAML + DeepCopy via make controller-manifests; golden files via UPDATE_GOLDEN=true make -C go test

Deployment / configuration

apiVersion: kagent.dev/v1alpha2
kind: Agent
metadata:
  name: coordinator
spec:
  declarative:
    runtime: go
    tools:
      - type: Agent
        agent:
          name: worker
        isolateSessions: true   # each worker call = its own isolated session
  • Unset / false → current behavior (one shared sub-agent session).
  • true → fresh sub-agent session per call; enables parallel isolated fan-out.

Scope / non-goals

  • Runtime: honored by the Go declarative runtime. The field is accepted by the
    Python config model (schema parity) but the Python low-level tool is unchanged.
  • Not a concurrency limiter — see max-concurrency.md for capping parallel
    invocations per pod. Isolation and concurrency limiting are complementary.
  • No change to HITL resume: resume still targets the original sub-agent session via
    the context_id stored in the confirmation payload.

Behavior notes & caveats

  • Stateful sub-agents that rely on reused session history across calls must keep
    isolateSessions: false (or key state on x-kagent-root-context-id).
  • With isolation on, a sub-agent's per-call sessions have source='agent' and are
    hidden from the worker's sidebar by design; they render inline in the parent chat.
  • Parallelism is bounded by how many tool calls the parent LLM emits in a turn and by
    any KAGENT_MAX_CONCURRENCY on the worker pod.

🔄 Steps To Reproduce

  1. Create WorkerAgent
  2. Create Coordinator Agent with WorkerAgent as Tool
  3. Ask coordinator agent to call Worker with 3 tasks in parallel

🤔 Expected Behavior

No response

📱 Actual Behavior

No response

💻 Environment

No response

🔧 CLI Bug Report

No response

🔍 Additional Context

No response

📋 Logs

📷 Screenshots

No response

🙋 Are you willing to contribute?

  • I am willing to submit a PR to fix this issue

Activity

  1. added theissue type on Jul 2, 2026
  2. dimetron commented on Jul 2, 2026

    @dimetron
    CollaboratorAuthor

    In addition child sessions, when Coordinator Agent -> Worker Agent
    on worker we do not see sessions from A2A in ListSessionsForAgent filter source != 'agent'

  3. dimetron commented on Jul 10, 2026

    @dimetron
    CollaboratorAuthor

    EP 2153: Per-call session isolation + robust sub-agent session reporting

    Status: implemented
    Upstream: #2153
    (fix(go-adk): add per-call session isolation for Agent tools)

    Goal

    Let a declarative agent fan out parallel, isolated sub-agent calls, and make
    each of those calls observable in the UI by always reporting the sub-agent
    session it ran in.

    Two capabilities, delivered together:

    1. Per-call session isolation (isolateSessions) — mint a fresh A2A
      context_id per sub-agent call so parallel fan-out no longer collapses into
      one shared sub-agent session.
    2. A single typed response contract — every remote A2A tool outcome
      (success, input_required, failure) returns the per-call context_id as
      subagent_session_id, so the UI can always link a sub-agent card to the
      session that produced it.

    Problem

    Shared sub-agent session (isolation)

    go/adk/pkg/tools/remote_a2a_tool.go used to generate one context_id once,
    at tool construction (pod startup), and stamp it on every outbound A2A
    message:

    state := &remoteA2AState{ /* ... */ lastContextID: a2atype.NewContextID() }
    // ...
    message.ContextID = s.lastContextID   // same id for every call, forever

    The worker derives its session id straight from that context id
    (go/adk/pkg/a2a/executor.go: sessionID := reqCtx.ContextID). So N parallel
    calls → 1 shared worker session, serialized/interleaved rather than N parallel
    sessions.

    Observed: a coordinator emitted 11 sub-agent calls in one model turn; all 11
    collapsed into a single worker session (11 A2A tasks in one context) instead of
    11 isolated sessions.

    Session id silently dropped on some branches (reporting)

    The tool returned each outcome as an ad-hoc map[string]any literal, built
    independently per branch. Nothing forced a branch to include
    subagent_session_id, and several omitted it (direct-message result,
    input_required, and the no-result fallback). With isolation on there is no
    stable, pre-known session id to fall back to, so any branch that drops the
    per-call id leaves the UI unable to link that sub-agent card to a session.

    Design

    isolateSessions flag

    A per-Agent-tool boolean.

    • false (default): one stable context_id per tool for its lifetime →
      session continuity for stateful sub-agents. Unchanged behavior.
    • true: context_id is minted per call via a2atype.NewContextID() →
      each call is an isolated sub-agent session; parallel fan-out no longer shares
      state/history.
    // contextIDForCall returns the A2A context_id (== sub-agent session id) to stamp
    // on this call. With isolation enabled every call gets a fresh id; otherwise the
    // stable per-tool id is reused.
    func (s *remoteA2AState) contextIDForCall() string {
    	if s.isolateSessions {
    		return a2atype.NewContextID()
    	}
    	return s.lastContextID
    }

    Cross-conversation/turn continuity that stateful workers need does not
    depend on the message context_id: it rides the x-kagent-root-context-id
    header (lineageHeadersInterceptor), which stays stable per conversation
    regardless of this flag. So isolation only changes which sub-agent session a
    turn is recorded in.

    UI linking

    The executor can pre-stamp outgoing function_call parts with a pre-known
    subagent_session_id from a startup map (subagentSessionIDs, keyed by tool
    name). That model only works when a tool has exactly one session for its whole
    lifetime — it breaks down under isolateSessions, where the real session is
    per call. So an isolated tool contributes no map entry (its constructor
    returns an empty stamp id), and the UI links each sub-agent card via the
    per-call subagent_session_id returned in the tool's function_response
    (consumed by AgentCallDisplay).

    For this to hold, that response field must be present on every branch — see
    below.

    Typed response contract (the reporting fix)

    Every outcome returns one shared struct instead of a per-branch map literal, so
    SubagentSessionID (the per-call context_id) is a field every path sets and
    cannot be forgotten in one branch while present in another:

    // remoteA2AResponse is the single typed return value for every remote A2A tool
    // outcome — success, input_required, and failure alike. functiontool.New infers
    // the tool's output schema from this type.
    type remoteA2AResponse struct {
    	Result              string         `json:"result,omitempty"`
    	Error               string         `json:"error,omitempty"`
    	ErrorType           string         `json:"error_type,omitempty"`
    	ErrorStep           string         `json:"error_step,omitempty"`
    	ErrorMessage        string         `json:"error_message,omitempty"`
    	RemediationHint     string         `json:"remediation_hint,omitempty"`
    	Retryable           *bool          `json:"retryable,omitempty"`
    	Status              string         `json:"status,omitempty"`
    	WaitingFor          string         `json:"waiting_for,omitempty"`
    	Subagent            string         `json:"subagent,omitempty"`
    	SubagentSessionID   string         `json:"subagent_session_id,omitempty"`
    	SubagentTaskID      string         `json:"subagent_task_id,omitempty"`
    	SubagentTaskState   string         `json:"subagent_task_state,omitempty"`
    	KAgentUsageMetadata map[string]any `json:"kagent_usage_metadata,omitempty"`
    }

    subagent_session_id reporting per branch:

    Outcome Reported session id
    completed per-call context_id
    direct *Message result (unary and streaming) per-call context_id
    input_required (incl. nil-task guard) paused task's context_id, else per-call
    failed / canceled / rejected task's context_id, else per-call
    non-terminal after call end per-call context_id
    request / stream error, timeout per-call context_id
    no result returned per-call context_id

    Retryable is a *bool so subagent_timeout can report an explicit false
    that survives JSON omitempty (a plain false would be dropped). Child-provided
    structured failure fields (error_type, error_step, error_message,
    remediation_hint) are overlaid onto the struct, with the child's value winning
    over the generic subagent_<state> default.

    Relationship to PR #2153 and local divergences

    PR #2153 is the upstream origin of both ideas. This repo had already implemented
    a superset of the PR's isolation feature (adding streaming relay, per-call
    timeout + tasks/cancel, and a per-invocation concurrency limiter), so the PR
    could not be cherry-picked as-is. Only the PR's response-contract idea was
    missing here, and it was adopted — but adapted, keeping the local implementation
    where it is superior:

    Aspect Upstream PR #2153 This repo (kept) Why local wins
    Typed remoteA2AResponse + always report subagent_session_id ✅ introduced ✅ adopted Structural guarantee beats per-branch map literals
    Tool constructor positional params NewKAgentRemoteA2ATool(RemoteA2AToolConfig) Config-struct convention; fields can't be misordered
    subagentSessionIDs stamp-map plumbing removed entirely retained (empty for isolated tools) Still serves non-isolated tools; removal is a separate, larger cleanup
    Streaming relay / per-call timeout / concurrency cap not present present Real child progress + bounded fan-out

    Net: the typed response is the one place the PR was ahead, and it is now in; the
    rest of the PR would have been a regression against the local code.

    Changes

    File Change
    go/api/v1alpha2/agent_types.go IsolateSessions *bool on Tool (CEL: type=Agent only)
    go/api/adk/types.go IsolateSessions bool (isolate_sessions) on RemoteAgentConfig
    go/core/internal/controller/translator/agent/compiler.go Copy tool.IsolateSessions → RemoteAgentConfig.IsolateSessions
    go/adk/pkg/agent/agent.go Pass flag via RemoteA2AToolConfig; skip stamp-map entry when isolated
    go/adk/pkg/tools/remote_a2a_tool.go isolateSessions field + contextIDForCall; typed remoteA2AResponse on every branch, always setting subagent_session_id
    python/packages/kagent-adk/src/kagent/adk/types.py isolate_sessions field for config-schema parity (Go runtime honors it)
    generated CRD YAML + DeepCopy via make controller-manifests; golden files via UPDATE_GOLDEN=true make -C go test

    Deployment / configuration

    apiVersion: kagent.dev/v1alpha2
    kind: Agent
    metadata:
      name: coordinator
    spec:
      declarative:
        runtime: go
        tools:
          - type: Agent
            agent:
              name: worker
            isolateSessions: true   # each worker call = its own isolated session
    • Unset / false → current behavior (one shared sub-agent session).
    • true → fresh sub-agent session per call; enables parallel isolated fan-out.

    Scope / non-goals

    • Runtime: honored by the Go declarative runtime. The field is accepted
      by the Python config model (schema parity) but the Python low-level tool is
      unchanged.
    • Not a concurrency limiter — capping parallel invocations per pod is a
      separate mechanism. Isolation and concurrency limiting are complementary.
    • No change to HITL resume: resume still targets the original sub-agent session
      via the context_id stored in the confirmation payload.

    Behavior notes & caveats

    • Stateful sub-agents that rely on reused session history across calls must
      keep isolateSessions: false (or key state on x-kagent-root-context-id).
    • With isolation on, a sub-agent's per-call sessions have source='agent' and
      are hidden from the worker's sidebar by design; they render inline in the
      parent chat.
    • The per-call subagent_session_id in the function_response is now the
      single source of truth for UI linkage on both isolated and non-isolated tools.

    Testing

    • Unit: contextIDForCall — shared reuses one id, isolated mints a fresh
      non-empty id per call.
    • Unit: every processResult branch (message, completed, input_required,
      failed/canceled/rejected, non-terminal, no-result) returns a non-empty
      subagent_session_id; sendStreaming terminal-message path reports it too.
    • Unit: structured failure passthrough (data part, JSON text, fenced JSON,
      plain text default, synthesized empty text); timeoutResult reports explicit
      retryable=false plus linkage fields.
    • Regression: existing lineage-header, stream-consume, and translator
      isolateSessions tests stay green.
  4. added a commit that references this issue on Jul 31, 2026
    986a79b
  5. added a commit that references this issue on Jul 31, 2026
    4ecfca8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions