fix(go-adk): add per-call session isolation for Agent tools - #2153
Conversation
There was a problem hiding this comment.
Pull request overview
Adds an opt-in isolateSessions flag for Agent-type tools so each sub-agent invocation can use a fresh A2A context_id (and therefore a distinct sub-agent session), fixing the “parallel fan-out collapses into one shared worker session” bug described in #2137.
Changes:
- Introduces
Tool.IsolateSessions(CRD + CEL validation) and threads it through translation intoRemoteAgentConfig.IsolateSessions. - Updates the Go remote A2A tool to mint per-call
context_idwhen isolation is enabled and to avoid pre-stamping a single subagent session id for isolated tools. - Adds translation fixture coverage and a unit test for the new context-id selection logic; adds Python schema parity field.
Reviewed changes
Copilot reviewed 13 out of 14 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| python/packages/kagent-adk/src/kagent/adk/types.py | Adds isolate_sessions field for config/schema parity (no runtime behavior change in Python). |
| helm/kagent-crds/templates/kagent.dev_sandboxagents.yaml | Regenerates CRD template to include isolateSessions and CEL rule. |
| helm/kagent-crds/templates/kagent.dev_agents.yaml | Regenerates CRD template to include isolateSessions and CEL rule. |
| go/core/internal/controller/translator/agent/testdata/outputs/agent_with_isolated_session_tool.json | Adds golden output asserting isolate_sessions: true is emitted into config.json. |
| go/core/internal/controller/translator/agent/testdata/inputs/agent_with_isolated_session_tool.yaml | Adds translator input fixture exercising isolateSessions: true. |
| go/core/internal/controller/translator/agent/compiler.go | Threads tool.IsolateSessions into RemoteAgentConfig.IsolateSessions. |
| go/api/v1alpha2/zz_generated.deepcopy.go | Regenerates deepcopy to include Tool.IsolateSessions. |
| go/api/v1alpha2/agent_types.go | Adds Tool.IsolateSessions *bool and CEL validation restricting it to Agent tools. |
| go/api/config/crd/bases/kagent.dev_sandboxagents.yaml | Regenerates CRD base to include isolateSessions schema + validation. |
| go/api/config/crd/bases/kagent.dev_agents.yaml | Regenerates CRD base to include isolateSessions schema + validation. |
| go/api/adk/types.go | Adds RemoteAgentConfig.IsolateSessions (isolate_sessions) to runtime config. |
| go/adk/pkg/tools/remote_a2a_tool.go | Implements per-call context id minting for isolated tools and reports back per-call session id. |
| go/adk/pkg/tools/remote_a2a_tool_test.go | Adds unit test for nextContextID() isolation semantics. |
| go/adk/pkg/agent/agent.go | Passes isolation flag into tool creation and skips pre-stamp map entry when isolated. |
Files not reviewed (1)
- go/api/v1alpha2/zz_generated.deepcopy.go: Generated file
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| // session that actually ran the call — critical when isolateSessions is true | ||
| // and every call has a different id. | ||
| func (s *remoteA2AState) processResult(ctx adkagent.ToolContext, contextID string, result a2atype.SendMessageResult) (map[string]any, error) { | ||
| switch r := result.(type) { | ||
| case *a2atype.Message: |
|
PTAL @EItanya |
EItanya
left a comment
There was a problem hiding this comment.
Thanks so much for the contribution, however I did find a bug we need to fix and clean up
I think the current approach fixes the session-collision issue, but it also highlights an existing design smell: we have two different mechanisms for linking an AgentCall card to subagent activity.
Today we pre-generate a subagent context_id when constructing the remote tool, return that from NewKAgentRemoteA2ATool, store it in subagentSessionIDs, and stamp it onto the function_call metadata so the UI can show the nested Activity panel. With isolateSessions, that model no longer fits because the actual subagent session is per invocation, not per tool instance. Returning "" from the constructor for isolated tools is a sign that the constructor-time session ID is the wrong abstraction.
I’d suggest simplifying this so both shared and isolated modes use the same UI path:
- Stop treating the constructor-time context ID as UI metadata.
- Don’t return a subagent session ID from
NewKAgentRemoteA2ATool. - Don’t special-case isolated tools in
CreateGoogleADKAgentWithSubagentSessionIDs. - Always return the actual invocation’s subagent session ID from the tool result:
return remoteA2AResponse{
Result: text,
SubagentSessionID: contextID,
}- Also include it for
input_required/ HITL:
return remoteA2AResponse{
Status: "pending",
WaitingFor: "subagent_approval",
Subagent: s.name,
SubagentSessionID: task.ContextID,
}Then the UI can use one source of truth for both modes: function_response.response.subagent_session_id. That ID is the actual remote A2A context_id used by the subagent session.
This also lets the Go code be simpler:
type remoteA2AState struct {
// ...
sharedContextID string
isolateSessions bool
}
func (s *remoteA2AState) contextIDForCall() string {
if s.isolateSessions {
return a2atype.NewContextID()
}
return s.sharedContextID
}lastContextID should probably be renamed to sharedContextID, since it is not really “last”; in shared mode it is a stable session ID, and in isolated mode it should not be used.
While touching this path, I’d also prefer replacing the ad-hoc map[string]any tool responses with a typed response struct. Right now fields like result, error, status, waiting_for, subagent, subagent_session_id, and kagent_usage_metadata are implicit string keys spread across several branches. That makes it easy to forget subagent_session_id in one path, which is exactly the kind of issue this PR risks for input_required.
Something like:
type remoteA2AResponse struct {
Result string `json:"result,omitempty"`
Error string `json:"error,omitempty"`
Status string `json:"status,omitempty"`
WaitingFor string `json:"waiting_for,omitempty"`
Subagent string `json:"subagent,omitempty"`
SubagentSessionID string `json:"subagent_session_id,omitempty"`
KAgentUsageMetadata map[string]any `json:"kagent_usage_metadata,omitempty"`
}Each path can return the same typed shape, and subagent_session_id becomes an explicit field rather than a magic map key. That would make this change safer and easier to review.
The one behavior change is that the nested Activity panel would appear once the tool response/pending response exists, rather than being pre-linked from the initial function_call event. I think that is the cleaner and more honest model. If we need live subagent activity before a response exists, that should be modeled explicitly with a per-invocation “tool started”/running event that carries the generated context ID. Constructor-time pre-stamping only works for shared sessions and is exactly what breaks down here.
6a90619 to
babc9cb
Compare
|
Thanks for the thorough review, makes sense. Pushed a follow up commit for this:
Also added TestProcessResult_SetsSubagentSessionIDOnEveryBranch to cover the branches that were missing the field before. |
|
Thank you @yashrajshuklaaa for taking care of #2137 some additional changes I've discovered during my testing Additional Required changes1. [required] Response struct is missing failure-linkage and structured fieldsThe PR struct carries only
Without these, a failed sub-agent is not debuggable from the parent session 2. [required]
|
|
@yashrajshuklaaa just for the reference #2202 |
Addresses review feedback on kagent-dev#2153 Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
babc9cb to
d9048f8
Compare
|
These are good additions, thanks for testing it out @dimetron. I think it's a separate concern from what #2137 asked for (session isolation vs structured failure reporting) so my plan is to pick these up in a focused follow up PR once this one lands and link back to this thread when I open it. |
|
Also keeps git log/blame cleaner, a commit called "add per-call session isolation" quietly also adding a failure reporting schema would be confusing to trace back later. |
|
@EItanya PTAL |
supreme-gg-gg
left a comment
There was a problem hiding this comment.
@yashrajshuklaaa the changes look good overall, pls resolve the merge conflict and I'll take another look / approve. A few follow ups:
- I agree we need to address @dimetron's comments regarding terminal state handling and failure fields
- I think it's a fair tradeoff to drop constructor-time pre-stamping of session ID for a single response-based UI path, with that, we should get rid of the dead plumbings like
stampSubagentSessionID,subsagentSessionIDsthreading inagent.go, executor.go, converter.go
There's a regression regarding how HITL activity is supposed to work that is quite important to address. Without pre-stamped IDs, subagent activity panels will not open until a function_response supplies the session ID. HITL events surfaced from subagents returns this function_response containing status: "pending" + subagent_session_id, but it is currently skipped in the UI since it wasn't needed before due to pre-stamping IDs. One of the key motivations of having subagent activity viewing is for the user to know what the subagent is doing before approving its tool calls, which no longer works.
kagent/ui/src/lib/messageHandlers.ts
Lines 940 to 950 in eed7287
A simple fix that I came up with is to check if it comes from a pending subagent and do not skip it:
} else if (partType === "function_response") {
const responseData = (data as { response?: Record<string, unknown> })?.response;
const responseStatus = responseData?.status as string | undefined;
- if (responseStatus === "confirmation_requested" || responseStatus === "pending") {
+ const toolData = data as unknown as ToolResponseData;
+ const isPendingAgentSession =
+ responseStatus === "pending" &&
+ isAgentToolName(toolData.name) &&
+ typeof responseData?.subagent_session_id === "string";
+ if (
+ (responseStatus === "confirmation_requested" || responseStatus === "pending") &&
+ !isPendingAgentSession
+ ) {
continue;
}
- const toolData = data as unknown as ToolResponseData;
const source = getSourceFromMetadata(adkMetadata, defaultAgentSource);
processFunctionResponsePart(toolData, statusUpdate.contextId, statusUpdate.taskId, source);
}I've tried this out and it preserves the old behaviour where when a subagent requires an approval, the user can view its activity.
Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
Addresses review feedback on kagent-dev#2153 Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
be0ed2d to
cee0670
Compare
|
Hey there, unit tests are failing |
The committed fixture had ghcr.io/kagent-dev/kagent/app@sha256:test-app baked in, but DefaultImageConfig.Tag resolves from version.Get().Version at package init, which is unlinked (falls back to dev) under the Makefile's actual test invocation (go test, no -ldflags). Regenerated via the same command CI uses (go test -skip 'TestE2E.*' with UPDATE_GOLDEN=true) so the fixture now matches what CI actually produces. Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
|
@supreme-gg-gg @EItanya thanks for the review! |
…plumbing Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
3723e3a to
1afefb4
Compare
|
@supreme-gg-gg @EItanya removed the dead plumbing |
supreme-gg-gg
left a comment
There was a problem hiding this comment.
This looks great! One nit and this is good to merge
…o CreateGoogleADKAgent Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com>
ab8d7b2 to
54f8775
Compare
supreme-gg-gg
left a comment
There was a problem hiding this comment.
lgtm, thanks for the PR!
|
This will need to be backported to make it into 0.10 |
…ev#2153) ## Summary Fixes kagent-dev#2137 The bug : every call a parent agent makes to a sub-agent (Agent tool) reuses the same A2A **context_id** since it's minted once when the tool is built. worker just uses that **context_id** as its session id directly ( **executor.go: sessionID := reqCtx.ContextID** ) so if a coordinator fires off N parallel calls to the same sub-agent in one turn , they all pile into a single shared session instead of getting their own. Fix is an opt-in **IsolateSessions** flag on Agent-type tools : ```yaml spec: declarative: tools: - type: Agent agent: name: worker isolateSessions: true # each call to worker gets its own session ``` Default behavior (flag unset/false) doesn't change one **context_id** for the tool's whole lifetime so stateful sub-agents keep their session continuity. with the flag on we mint a fresh **context_id** on every call so each invocation is isolated. Doesn't touch the **x-kagent-root-context-id** header stuff. that's still what carries cross-turn continuity and it stays stable either way. ## What changed - `agent_types.go`: added `Tool.IsolateSessions *bool` plus a CEL rule so it can only be set when `type: Agent` - `adk/types.go`: `RemoteAgentConfig.IsolateSessions bool` - `compiler.go`: passes the flag through into `RemoteAgentConfig` - `agent.go`: forwards the flag to `NewKAgentRemoteA2ATool`. also skips adding an entry to `subagentSessionIDs` when isolated since there's no single session id to pre-stamp function_call parts with anymore - `remote_a2a_tool.go`: added `isolateSessions` plus a small `nextContextID()` helper that either returns the stable id or mints a new one. This gets reported back as `subagent_session_id` - Python `types.py`: added `isolate_sessions` for schema parity only, it doesn't do anything on that side yet (matches what the issue scoped out) - Regenerated CRDs/deepcopy with `make controller-manifests` - Added a test for the new context-id logic and a golden fixture (`agent_with_isolated_session_tool`) to check it flows through the whole translation pipeline ## About the UI Isolated tools don't have one fixed session id, so the executor can't pre-populate the stamp map for them at startup. Instead the UI grabs the session id per call from `subagent_session_id` in the function_response. `AgentCallDisplay` already reads that field, so nothing new needed there. ## Not doing in this PR - Not a concurrency limiter, that's separate (`max-concurrency.md`) - HITL resume is unaffected, it still uses the context_id from the confirmation payload - Only the Go runtime respects this flag right now. Python accepts it for config parity but the low-level tool doesn't use it yet ## Tests Ran `go test ./adk/pkg/tools/... ./adk/pkg/agent/... ./api/...` and the golden translator tests. Everything passes. Confirmed `isolate_sessions: true` shows up correctly in the generated `config.json` for the new fixture. ## One small thing I noticed In `handleResume`, `processResult` now sets `subagent_session_id` from the contextID I pass in, but there's older code right after it that sets the same key again with a fallback to `lastContextID`. Not wrong, just a bit redundant now since it writes the same value twice in the normal case. Left it as is since it's harmless but flagging it in case someone wants it cleaned up. --------- Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com> Co-authored-by: Eitan Yarmush <eitan.yarmush@solo.io> Signed-off-by: Jet Chiang <pokyuen.jetchiang-ext@solo.io>
#2153 Signed-off-by: Yashraj Shukla <shuklayashraj68@gmail.com> Signed-off-by: Jet Chiang <pokyuen.jetchiang-ext@solo.io> Co-authored-by: yashraj S <shuklayashraj68@gmail.com> Co-authored-by: Eitan Yarmush <eitan.yarmush@solo.io>
This PR changes A2A output to be now artifact-based rather than assistant-message/history-based. Consumers should render `Task.Artifacts`; transient progress remains in task status updates. ## Motivation This refactor aligns kagent’s A2A usage with the protocol’s separation between task state and task output, as A2A [protocol specification](https://a2a-protocol.org/latest/specification/#37-messages-and-artifacts) noted: > Messages SHOULD NOT be used to deliver task outputs. Results SHOULD BE returned using Artifacts associated with a Task. This separation allows for a clear distinction between communication (Messages) and data output (Artifacts). Previously, streamed assistant text and tool data were carried in `WORKING` status messages, with an artifact emitted only at the end of the task. That made status updates serve two roles and required clients to reconstruct the response from transient state. Task output is now emitted as `TaskArtifactUpdateEvents` throughout execution. Status updates communicate only task lifecycle, HITL, failures, etc. A terminal status closes the task, while `lastChunk` closes an individual artifact. **This is a breaking wire-level change for consumers that read assistant output from status messages or task history.** Consumers should instead render `Task.Artifacts` and process artifact updates as they arrive. ## Change surfaces ADK/BYO: - Go ADK: replaced the custom executor flow with the upstream ADK A2A executor, configured for `OutputArtifactPerEvent`, so ADK events become A2A artifact updates. Subsequently, cleanup all kagent specific partial event handling logic since upstream supports it now. Partial events and emitted as artifacts with `append=true`. - Python ADK: Similar refactor as Go. Python still uses custom executor, but in a follow up PR we will bump python-adk to 2.0 which allows upstreaming executor - Applies the same A2A change to BYO harness and improves them (CrewAI, OpenAI Agents SDK) by making their converters / event handlers return appropriate tool calling / agent delegation data parts UI/CLI: - UI: use task status updates for working/progress and HITL instead of canonical assistant response, which is now moved to artifact part updates, and adds relevant buffering and flushing mechanisms for handling streaming cases (similarly for CLI, except that the Go TUI does not support streaming messages) - UI cleanup: subagent session IDs are now taken from function-response data, cleanup following #2153 --------- Signed-off-by: Jet Chiang <pokyuen.jetchiang-ext@solo.io>
## Summary - honor the existing `isolate_sessions` configuration in the Python remote A2A tool runtime - mint a fresh sub-agent context for each isolated invocation while preserving shared-session defaults - return the actual invocation context in completed and HITL-pending responses This is a Python runtime follow-up to the accepted Go implementation in #2153. It does not change the CRD, UI, lineage headers, concurrency limits, or HITL resume routing. ## Testing - `cd python && uv run pytest -q packages/kagent-adk/tests/unittests/test_remote_a2a_tool.py packages/kagent-adk/tests/unittests/test_proxy_integration.py` (`40 passed`) - `cd python && uv run ruff check packages/kagent-adk/src/kagent/adk/_remote_a2a_tool.py packages/kagent-adk/src/kagent/adk/types.py packages/kagent-adk/tests/unittests/test_remote_a2a_tool.py packages/kagent-adk/tests/unittests/test_proxy_integration.py` - `git diff --check` ## Risk / Notes - `isolate_sessions=false` remains the default and reuses one context ID for stateful sub-agents. - Isolated calls use a local per-call ID, so concurrent fan-out does not share mutable session state. - Existing upstream/dependency warnings remain in the test output; no new failures were introduced. Follow-up to #2153. Signed-off-by: Whxuan0701 <102815982+Whxuan0701@users.noreply.github.com> Co-authored-by: Whxuan0701 <102815982+Whxuan0701@users.noreply.github.com>
Summary
Fixes #2137
The bug : every call a parent agent makes to a sub-agent (Agent tool) reuses the same A2A context_id since it's minted once when the tool is built. worker just uses that context_id as its session id directly ( executor.go: sessionID := reqCtx.ContextID ) so if a coordinator fires off N parallel calls to the same sub-agent in one turn , they all pile into a single shared session instead of getting their own.
Fix is an opt-in IsolateSessions flag on Agent-type tools :
Default behavior (flag unset/false) doesn't change
one context_id for the tool's whole lifetime so stateful sub-agents keep their session continuity. with the flag on we mint a fresh context_id on every call so each invocation is isolated.
Doesn't touch the x-kagent-root-context-id header stuff. that's still what carries cross-turn continuity and it stays stable either way.
What changed
agent_types.go: addedTool.IsolateSessions *boolplus a CEL rule so it can only be set whentype: Agentadk/types.go:RemoteAgentConfig.IsolateSessions boolcompiler.go: passes the flag through intoRemoteAgentConfigagent.go: forwards the flag toNewKAgentRemoteA2ATool. also skips adding an entry tosubagentSessionIDswhen isolated since there's no single session id to pre-stamp function_call parts with anymoreremote_a2a_tool.go: addedisolateSessionsplus a smallnextContextID()helper that either returns the stable id or mints a new one. This gets reported back assubagent_session_idtypes.py: addedisolate_sessionsfor schema parity only, it doesn't do anything on that side yet (matches what the issue scoped out)make controller-manifestsagent_with_isolated_session_tool) to check it flows through the whole translation pipelineAbout the UI
Isolated tools don't have one fixed session id, so the executor can't pre-populate the stamp map for them at startup. Instead the UI grabs the session id per call from
subagent_session_idin the function_response.AgentCallDisplayalready reads that field, so nothing new needed there.Not doing in this PR
max-concurrency.md)Tests
Ran
go test ./adk/pkg/tools/... ./adk/pkg/agent/... ./api/...and the golden translator tests. Everything passes.Confirmed
isolate_sessions: trueshows up correctly in the generatedconfig.jsonfor the new fixture.One small thing I noticed
In
handleResume,processResultnow setssubagent_session_idfrom the contextID I pass in, but there's older code right after it that sets the same key again with a fallback tolastContextID. Not wrong, just a bit redundant now since it writes the same value twice in the normal case. Left it as is since it's harmless but flagging it in case someone wants it cleaned up.