Skip to content

feat(agent): logical agentId - #2395

Closed
rudy2steiner wants to merge 8 commits into
agentscope-ai:mainfrom
rudy2steiner:agent_id
Closed

rudy2steiner wants to merge 8 commits into
agentscope-ai:mainfrom
rudy2steiner:agent_id

Conversation

@rudy2steiner

Copy link
Copy Markdown
Contributor

Why

agentId currently serves several different purposes in AgentScope Java:

  • a randomly generated identifier for a running Java Agent instance;
  • a stable logical Agent identifier used by platforms for registration, routing, and authorization;
  • an Agent-level namespace for Harness resources such as state, skills, sandboxes, and workspaces;
  • an identifier emitted in events, traces, and sub-agent metadata.

These meanings conflict when the same logical Agent is recreated or scaled to multiple runtime instances. The current random UUID changes for every instance, so platforms must maintain an additional mapping between their stable Agent ID and AgentScope's generated ID which discussed in #2313. However, simply making the existing ID configurable would allow multiple instances to share a value that internal state maps currently assume is unique, potentially causing state, trace, or training data to be overwritten or mixed.

This change separates the two identity concepts:

  • agentId is the stable, caller-defined logical Agent ID.
  • id is the random UUID of a specific runtime Agent instance.

This allows platform integrations to use a stable logical identity while preserving the existing
instance-level isolation.

Main Changes

  • Added Agent#getId() for runtime instance identity. AgentBase always generates an immutable
    UUID for it, while the default interface implementation falls back to getAgentId() for
    compatibility with existing custom Agent implementations.
  • Allowed callers to configure an immutable logical agentId. If it is null or blank, it falls
    back to the generated runtime id, preserving the previous default behavior.
  • Added ReActAgent.Builder.agentId(String).
  • Passed Harness's existing resolved Agent ID into its internal ReActAgent, so
    HarnessAgent#getAgentId() now matches the logical ID already used by Harness resource
    namespaces. The existing Harness resolution order and resource paths remain unchanged.
  • Changed instance-scoped internal state to use id, including graceful-shutdown state savers,
    JSONL trace run state, and TrainingRouter input correlation. This prevents collisions when
    multiple runtime instances share one logical agentId.
  • Kept logical Agent identity in telemetry and external Agent-facing APIs, while
    SubAgentTool.subagent_id continues to identify a unique runtime sub-agent instance by using
    id.
  • Updated tests, documentation, and the multi-Agent Gateway example to cover custom logical IDs,
    default UUID behavior, Harness propagation, and isolation between instances sharing the same
    logical ID.

@codecov

codecov Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

@TianyuGeek001

Copy link
Copy Markdown

看描述和实现
1,id变成内部的唯一运行标识。
2,agentId提供给外部做关联标识。
是这个意思?

@rudy2steiner

Copy link
Copy Markdown
Contributor Author

看描述和实现 1,id变成内部的唯一运行标识。 2,agentId提供给外部做关联标识。 是这个意思?

yes

@TianyuGeek001

Copy link
Copy Markdown

AgentSkillRepository有考虑增加一个agentId回调?

@rudy2steiner

Copy link
Copy Markdown
Contributor Author

@chickenlj could you review this PR when you have time ? Thanks a lot!

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Introduces a logical agentId concept separate from the runtime UUID id. Clean separation of concerns across 22 files.

Analysis

Design is sound:

  • id = runtime UUID (unique per Java object instance)
  • agentId = stable logical identity (user-provided, for routing/telemetry/state)
  • name = display name (human-readable, for messages/logs)

Backward compatibility preserved:

  • getAgentId() defaults to getId() when no explicit agentId is set
  • Existing code that uses getName() for resource paths is migrated to getAgentId() — this is the correct semantic change since name was being overloaded

Key changes reviewed:

  • Agent interface: default getAgentId() with fallback — clean SPI extension
  • AgentBase: stores agentId field, constructor updated
  • ReActAgent.Builder / HarnessAgent.Builder: agentId(String) builder method + fromAgent() propagation
  • Middleware (MemoryFlush, Compaction): correctly switched from getName() to getAgentId() for state paths
  • EventPublisher: uses getAgentId() for event routing — correct
  • HarnessAgent.defaultStateDir(): uses getAgentId() — ensures state isolation by logical identity
  • Tests: comprehensive coverage of explicit agentId, name fallback, and UUID fallback

One consideration:

  • The migration from getName() to getAgentId() for state paths means existing deployments that relied on name for state directory naming will see a different directory on upgrade (unless they set agentId to match the old name). This should be noted in release notes.

Verdict

Well-structured feature. Addresses a real architectural concern (identity conflation). Build and tests pass. Approved.

zouyx

This comment was marked as outdated.

@zouyx zouyx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Concurrency issue: this change still keys per-invocation state by Agent.getId(), which identifies the agent instance rather than one call. ReActAgent explicitly permits concurrent calls for different userId/sessionId slots. In TrainingRouter, concurrent PreCall events from the same agent overwrite callInputs[id]; the first PostCall can train against the second request's input and the second receives no input. JsonlTraceExporter has the same run/turn correlation issue: concurrent PRE_CALL events overwrite one RunState for the shared instance. Please introduce a per-invocation correlation key propagated through hook events or call scope, and add a parallel, different-session regression test before merging.

callInputs.put(agentId, event.getInputMessages());
logger.debug("Saved input messages for agent: {}", agentId);
String id = event.getAgent().getId();
callInputs.put(id, event.getInputMessages());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

is it right logical for multi session in the same agent?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. Agent.getId() only isolates agent instances; it is still shared by concurrent calls on the same ReActAgent. I’ll add a per-invocation correlation id propagated through the hook event lifecycle

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I fixed the input/output message mismatch by using the request ID stored in the Reactor context. If no request ID is available, it falls back to the agent ID

@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/agent Agent runtime, pipeline, hooks, plan area/core/tool Tool, skill, RAG abstractions area/docs Documentation area/examples agentscope-examples area/ext/integration External protocols & middleware integrations area/harness agentscope-harness (test/runtime support) labels Aug 11, 2026

@AgentScopeJavaBot AgentScopeJavaBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 AI Review

This PR separates agent identity into two concepts: a stable logical agentId (user-settable, survives restarts/clones) and a per-instance runtime id (immutable UUID). All internal callers are migrated to use the correct getter based on their needs (isolation vs display). Tests are comprehensive. Note: PR title ("fix event ordering in async event bus") does not match actual changes.

(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)

@AgentScopeJavaBot AgentScopeJavaBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 AI Review

This PR separates agent identity into two concepts: a stable logical agentId (user-settable, survives restarts/clones) and a per-instance runtime id (immutable UUID). All internal callers are migrated to use the correct getter based on their needs (isolation vs display). Tests are comprehensive. Note: PR title ("fix event ordering in async event bus") does not match actual changes.

(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)

@AgentScopeJavaBot AgentScopeJavaBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 AI Review

This PR separates agent identity into two concepts: a stable logical agentId (user-settable, survives restarts/clones) and a per-instance runtime id (immutable UUID). All internal callers are migrated to use the correct getter based on their needs (isolation vs display). Tests are comprehensive. Note: PR title ("fix event ordering in async event bus") does not match actual changes.

(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

#3360 和 当前 PR 做了一样的事情,当前 PR 多引入了一个 id 属性,相关代码修改面略大。

维护者按需选择合并哪个关闭哪个,本质都是提供 agentId 的设置。

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Separates agent identity into a stable logical agentId (builder-settable, falls back to the random instance id) and a new immutable per-instance getId() (UUID), and migrates internal lifecycle/telemetry keying (GracefulShutdownManager state savers, JsonlTraceExporter run state, SubAgentTool forwarded metadata, TrainingRouter call inputs) to the instance/request id so multiple live instances sharing one logical id no longer collide. Re-review after the new push; the previous COMMENT/inline points on identity separation look addressed.

Well executed: backward-compatible constructor overloads, Agent#getId() default delegation for external implementors, blank/null fallback, solid new tests in core + harness + training, and bilingual (EN/ZH) docs.

Findings

  • [Warning] TrainingRouter.java:267 (new callId(...)) — pre/post-call key resolution can diverge across the context-keyed vs getId() fallback paths, leaving entries in callInputs (unbounded growth). Suggest a defensive cleanup or a test pinning the mixed-context case.
  • [Warning] SubAgentTool.java:406 — subagent_id metadata changes semantics from logical id to instance id; externally observable (Studio/AG-UI/custom hooks). Fine as a design choice, but should be called out in the changelog for 2.0.

Not blocking: the change is internal-consistent and well covered by tests. Comment-only review since the two items above are worth an explicit author answer / changelog note before merge.


Automated review by github-manager-bot

Additional notes (not anchored to a changed line)

  • [WARNING] agentscope-extensions/agentscope-extensions-training/src/main/java/io/agentscope/core/training/runner/TrainingRouter.java:667 — [Warning] callId() now keys callInputs by the lifecycle request id when the Reactor context carries AgentBase.SHUTDOWN_REQUEST_ID_KEY, but falls back to agent.getId() otherwise. If a PRE_CALL is emitted outside the registered lifecycle (no request id in context) while the matching POST_CALL runs inside one (or vice versa), the remove(callId) in handlePostCall misses the entry and the map grows unboundedly — the previous code always used one stable key so pre/post could not diverge.

Could you either (a) assert/document that both hooks always resolve the same key, or (b) add a defensive cleanup, e.g. on PRE_CALL overwrite-by-instance and on ERROR/shadow-skip also remove the agent.getId() fallback key? A small test that fires PreCallEvent without the context key and PostCallEvent with it would pin the behaviour down. (line outside diff)

@@ -402,7 +403,7 @@ private void forwardEvent(Event event, ToolEmitter emitter, Agent agent, String
Map<String, Object> metadata = new HashMap<>();
metadata.put("subagent_event", event == null ? "" : event);
metadata.put("subagent_name", agent.getName() == null ? "" : agent.getName());
metadata.put("subagent_id", agent.getAgentId() == null ? "" : agent.getAgentId());
metadata.put("subagent_id", agent.getId() == null ? "" : agent.getId());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] subagent_id in forwarded ToolResultBlock metadata switches from the logical getAgentId() to the per-instance getId() (same class of change in GracefulShutdownManager.stateSavers and JsonlTraceExporter run-state keys). Internally consistent here, but it is an observable wire/telemetry semantics change for downstream consumers (Studio, AG-UI, custom hooks) that may have been aggregating events by subagent_id. Since Agent.getId() previously did not exist and getAgentId() was the only id, worth calling this out explicitly in the changelog / release notes for 2.0 so integrators can switch to agentId-keyed aggregation deliberately.

@rudy2steiner

rudy2steiner commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor Author

#3360 和 当前 PR 做了一样的事情,当前 PR 多引入了一个 id 属性,相关代码修改面略大。

维护者按需选择合并哪个关闭哪个,本质都是提供 agentId 的设置。
原有代码中至少 GracefulShutdownManager、JsonlTraceExporter、TrainingRouter 和 SubAgentTool 依赖 agentId 的实例唯一性。若不增加 id,直接使用新的 agentId 会让这些组件发生 key 冲突

@rudy2steiner

Copy link
Copy Markdown
Contributor Author

#3360 和 当前 PR 做了一样的事情,当前 PR 多引入了一个 id 属性,相关代码修改面略大。
维护者按需选择合并哪个关闭哪个,本质都是提供 agentId 的设置。

原有代码中至少 GracefulShutdownManager、JsonlTraceExporter、TrainingRouter 和 SubAgentTool 依赖 agentId 的实例唯一性。若不增加 id,直接使用新的 agentId 会让这些组件发生 key 冲突

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

#3360 和 当前 PR 做了一样的事情,当前 PR 多引入了一个 id 属性,相关代码修改面略大。
维护者按需选择合并哪个关闭哪个,本质都是提供 agentId 的设置。

原有代码中至少 GracefulShutdownManager、JsonlTraceExporter、TrainingRouter 和 SubAgentTool 依赖 agentId 的实例唯一性。若不增加 id,直接使用新的 agentId 会让这些组件发生 key 冲突

agentId 本就表示唯一标识,使用UUID生成。自持传入,自然应由传入者决定唯一(谁管理谁保证的原则),相关doc和文档写清楚即可。况且这个只是支持传入并不是必须传入,不传入则框架默认UUID。
框架不需要冗余过渡设计再引入一个id属性,agentId本来定义为唯一概念。

@rudy2steiner

Copy link
Copy Markdown
Contributor Author

#3360 和 当前 PR 做了一样的事情,当前 PR 多引入了一个 id 属性,相关代码修改面略大。
维护者按需选择合并哪个关闭哪个,本质都是提供 agentId 的设置。

原有代码中至少 GracefulShutdownManager、JsonlTraceExporter、TrainingRouter 和 SubAgentTool 依赖 agentId 的实例唯一性。若不增加 id,直接使用新的 agentId 会让这些组件发生 key 冲突

agentId 本就表示唯一标识,使用UUID生成。自持传入,自然应由传入者决定唯一(谁管理谁保证的原则),相关doc和文档写清楚即可。况且这个只是支持传入并不是必须传入,不传入则框架默认UUID。 框架不需要冗余过渡设计再引入一个id属性,agentId本来定义为唯一概念。

我理解主要是我们对agentId 的含义及定位理解不一致导致的。当前的agent接口定义的agentId含义上是实例id 不支持同一个jvm里有多个相同的agentId(否则导致GracefulShutdownManage等类维护的agent状态被覆盖)。但是HarnessAgent的agentid 是会影响namespace 同一个逻辑agent的agentId是一样的且HarnessAgent设计上支持多实例 一旦打通这两个agent的id在原始定义上有冲突,所以我设计上用id 实现原实例id的功能, agentId作为agent的逻辑唯一标识 将两个含义拆开了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/agent Agent runtime, pipeline, hooks, plan area/core/tool Tool, skill, RAG abstractions area/docs Documentation area/examples agentscope-examples area/ext/integration External protocols & middleware integrations area/harness agentscope-harness (test/runtime support) enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants