Class HarnessAgent.Builder
- Enclosing class:
- HarnessAgent
HarnessAgent. Owns the harness orchestration: workspace + filesystem +
sandbox + hooks/middlewares + tools + skills + subagents + tools.json + plan-mode.-
Method Summary
Modifier and TypeMethodDescriptionEscape hatch: sets a customAbstractFilesystemimplementation directly.additionalContextFile(String relativePath) Adds a custom context file (relative to workspace) loaded into the system prompt alongside AGENTS.md, MEMORY.md, and KNOWLEDGE.md.Sets the stable identifier used as the agent's namespace key in the composite filesystem (e.g.Allows the shell tool (execute) to run while plan mode is active.allowShellInPlanMode(boolean allowed) Configures theArtifactDeliveryTargetused by thedeliver_artifacttool.asyncToolRegistry(AsyncToolRegistry registry) Sets theAsyncToolRegistryfor tracking async tool executions.asyncToolTimeout(Duration timeout) EnablesAsyncToolMiddlewarewith the given timeout.build()buildSubagentEntries(Path resolvedWorkspace) Builds the subagent entries (general-purpose + declared + custom factories) without constructing the full agent.buildSubagentEntries(Path resolvedWorkspace, SandboxBackedFilesystem sandboxFs) checkRunning(boolean checkRunning) compaction(CompactionConfig config) Overrides the defaultCompactionMiddlewareconfiguration.defaultSessionId(String defaultSessionId) description(String description) Disables theCompactionMiddlewareentirely.Skips registration of the default Layer-4WorkspaceSkillRepository.Disables dynamic per-call skill loading from the workspace filesystem.Skips registration ofFilesystemTool.Disables memory flush + background consolidation, and removes the "automatically extracted" Persistence line from the workspace system prompt.Skips registration ofmemory_search/memory_get/memory_save/session_search, and omits matching Memory Recall / tool-based Persistence guidance from the workspace system prompt.No-op since 2.0; session persistence is owned by ReActAgent itself.Skips registration ofShellExecuteTool.disableSkills(String... skillNames) Disables theToolResultEvictionMiddlewareentirely.Disables the independent session-transcript middleware.Skips registration of the optional Tavily-backedweb_searchandweb_fetchtools.distributedStore(DistributedStore store) Configures a distributed store that provides all storage components at once:AgentStateStore,BaseStore,SandboxSnapshotSpec, andSandboxExecutionGuard.enableAgentTracingLog(boolean enabled) Enables or disables agent execution trace logging viaAgentTraceMiddleware.enableMetaTool(boolean enableMetaTool) enablePendingToolRecovery(boolean enable) Enables recovery of orphaned tool calls when a new message arrives.Enables plan mode (read-only design phase) withplan_enter/plan_write/plan_exittools and aPlanModeMiddlewarethat enforces read-only tools while plan mode is active.enablePlanMode(boolean enabled) enableSkillCurator(SkillCuratorConfig config) Enables the background skill curator.enableSkillManageTool(boolean autoPromote) Shorthand forenableSkillManageTool(SkillManageConfig)with default config.Enables the agent-callableskill_managetool so the agent can create / edit / patch / archive its own skills in the workspace, and upgrades the workspace skill repository to a writable variant.enableSkillPromotionGate(SkillPromotionGate gate, SkillVisibilityFilter visibilityFilter) Configures the runtime promotion gate + visibility filter chain.enableSkills(String... skillNames) enableTaskList(boolean enabled) environment(String env) Sets the deployment environment label used byEnvironmentFilter.environmentMemory(String environmentMemory) externalSubagentTool(Object tool) Injects an external subagent tool (typicallySessionsTool).failoverListener(io.agentscope.core.agent.config.FailoverListener failoverListener) Sets the listener notified when the fallback model takes over from a failed primary model.fallbackModel(io.agentscope.core.model.Model fallbackModel) fallbackModel(String modelId) Configures Mode 3 — local filesystem with shell.Configures Mode 1 — composite (non-sandbox) filesystem.Configures Mode 2 — sandbox filesystem.filesystemRoute(String prefix, AbstractFilesystem filesystem) Mounts an additionalAbstractFilesystemunder a path prefix, alongside the primary filesystem configured viafilesystem(SandboxFilesystemSpec),filesystem(RemoteFilesystemSpec), orfilesystem(LocalFilesystemSpec).static HarnessAgent.BuilderfromAgent(io.agentscope.core.ReActAgent agent) Returns a newHarnessAgent.Builderpre-populated with as much of the givenReActAgent's observable configuration as can be read back from public getters.generateOptions(io.agentscope.core.model.GenerateOptions options) hook(io.agentscope.core.hook.Hook hook) maxContextTokens(int maxTokens) Sets the maximum token budget for workspace context.maxIters(int maxIters) maxRetries(int maxRetries) mcpServerRegistrationListener(McpServerRegistrationListener mcpServerRegistrationListener) Sets the listener for terminal MCP server registration results produced while building this agent.memory(MemoryConfig config) Overrides the long-term memory pipeline configuration (flush + consolidation + maintenance).messageBus(MessageBus messageBus) Sets theMessageBusfor inbox-based message delivery.middleware(io.agentscope.core.middleware.MiddlewareBase middleware) middlewares(List<? extends io.agentscope.core.middleware.MiddlewareBase> middlewareList) model(io.agentscope.core.model.Model model) modelExecutionConfig(io.agentscope.core.model.ExecutionConfig config) modelResolver(Function<String, io.agentscope.core.model.Model> resolver) Sets a resolver for model name strings toModelinstances for subagents.permissionContext(io.agentscope.core.permission.PermissionContextState permissionContext) planFileDirectory(String dir) projectGlobalSkillsDir(Path projectGlobalSkillsDir) Configures a project-global skills directory layered below marketplace and workspace skills (lowest precedence).registerExternalSchemas(List<io.agentscope.core.model.ToolSchema> schemas) Registers schema-only external tools on the builder toolkit (merged into the final agent toolkit atbuild()).skillFilter(io.agentscope.core.skill.SkillFilter filter) skillRepositories(List<io.agentscope.core.skill.repository.AgentSkillRepository> repositories) Replaces the current marketplace repository list with the given collection.skillRepository(io.agentscope.core.skill.repository.AgentSkillRepository skillRepository) Adds a marketplace / external skill repository (e.g.skillsEnabled(boolean enabled) stateStore(io.agentscope.core.state.AgentStateStore stateStore) stopOnReject(boolean stopOnReject) subagent(SubagentDeclaration declaration) Adds a subagent declaration.subagentFactory(String name, String description, Function<String, io.agentscope.core.agent.Agent> factory) Adds a fully custom subagent factory for a given agent id, with a description shown to the orchestrator.subagentFactory(String name, Function<String, io.agentscope.core.agent.Agent> factory) Adds a fully custom subagent factory for a given agent id.subagents(List<SubagentDeclaration> declarations) taskRepository(TaskRepository taskRepository) Sets a customTaskRepositoryfor background subagent execution.teamsMode(TeamClient teamClient, TeamContext teamContext) Enables AgentTeams mode: attachesTeamsMiddlewareand registers the role-clippedteamtool.teamsMode(TeamClient teamClient, TeamContext teamContext, String sessionId) Same asteamsMode(io.agentscope.harness.agent.team.TeamClient, io.agentscope.harness.agent.team.TeamContext)but also binds the middleware tosessionIdso control-plane TeamEvents addressed at that session reach this agent.toolExecutionConfig(io.agentscope.core.model.ExecutionConfig config) toolExecutionContext(io.agentscope.core.tool.ToolExecutionContext ctx) toolkit(io.agentscope.core.tool.Toolkit toolkit) Overrides the defaultToolResultEvictionMiddlewareconfiguration.toolsConfig(ToolsConfig toolsConfig) Programmatic override forworkspace/tools.json.transcriptStore(TranscriptStore transcriptStore) Optional override for the sessionTranscriptStore(segmented append store).transcriptTenant(String transcriptTenant) Tenant segment used in transcript object keys (default"default").useLegacyXmlWorkspaceContext(boolean enabled) Switches workspace context rendering between markdown (default) and legacy XML style.webHttpClient(HttpClient client) Supplies a customHttpClientused by the built-inweb_fetchandweb_searchtools (e.g. custom proxy, TLS or HTTP version settings).Sets the workspace directory from a filesystem path string.Sets the workspace directory.
-
Method Details
-
teamsMode
Enables AgentTeams mode: attachesTeamsMiddlewareand registers the role-clippedteamtool. Used for both Managed resolve(teamContext) and Entry-B lead sessions that declare a roster template. -
teamsMode
public HarnessAgent.Builder teamsMode(TeamClient teamClient, TeamContext teamContext, String sessionId) Same asteamsMode(io.agentscope.harness.agent.team.TeamClient, io.agentscope.harness.agent.team.TeamContext)but also binds the middleware tosessionIdso control-plane TeamEvents addressed at that session reach this agent. -
fromAgent
Returns a newHarnessAgent.Builderpre-populated with as much of the givenReActAgent's observable configuration as can be read back from public getters.This is a partial migration helper. The caller still needs to set every harness-specific concern explicitly (workspace, filesystem, sandbox, subagents, skills, plan mode, etc.) — those have no analog on a vanilla
ReActAgent, so they cannot be derived fromagent.What this method copies
Fields copied from the source ReActAgent Group Field Source Observable configuration nameagent.getName()descriptionagent.getDescription()sysPromptagent.getSysPrompt()modelagent.getModel()maxItersagent.getMaxIters()generateOptionsagent.getGenerateOptions()toolkitdefensive copy via agent.getToolkit().copy()Persistence sessionagent.getStateStore()if non-nulldefaultSessionIdagent.getDefaultSessionId()if non-nullModel resilience (from agent.getModelConfig())maxRetriesModelConfig.maxRetries()fallbackModelModelConfig.fallbackModel()if non-nullfailoverListenerModelConfig.failoverListener()if non-nullReasoning loop (from agent.getReactConfig())stopOnRejectReactConfig.stopOnReject()Execution modelExecutionConfigagent.getModelExecutionConfig()if non-nulltoolExecutionConfigagent.getToolExecutionConfig()if non-nullBehavior toolExecutionContextagent.getToolExecutionContext()if non-nullenablePendingToolRecoveryagent.isPendingToolRecoveryEnabled()checkRunningagent.isCheckRunning()Permissions permissionContextagent.getPermissionContext()if non-null (the samePermissionContextStateis reused; it carries the rules registered on the source engine)Extension surface middlewaresagent.getMiddlewares()copied, excluding harness runtime middlewaresLegacy extension hooksagent.getHooks()appended as-is (Hookitself is@Deprecated(forRemoval=true); prefer middlewares for new code)Note:
enableMetaToolandenableTaskListare builder-time flags that mutate the toolkit at build. They do not round-trip as flags, but the toolkit copy already carries the tools they registered, so the resulting agent has the same tool surface.What this method does not copy
Skipped — harness-only, has no source on a
ReActAgent. These must be configured on the returned builder if you want HarnessAgent semantics:- Workspace & filesystem:
workspace(Path),filesystem(SandboxFilesystemSpec),filesystem(LocalFilesystemSpec),filesystem(RemoteFilesystemSpec),abstractFilesystem(AbstractFilesystem),environmentMemory(String) - Subagents:
subagent(SubagentDeclaration),subagents(List),subagentFactory(String, Function),externalSubagentTool(Object),taskRepository(TaskRepository),modelResolver(Function) - Skill governance:
skillRepository(AgentSkillRepository),projectGlobalSkillsDir(Path),enableSkillManageTool(SkillManageConfig),enableSkillCurator(SkillCuratorConfig),enableSkillPromotionGate(SkillPromotionGate, SkillVisibilityFilter),skillFilter(io.agentscope.core.skill.SkillFilter),environment(String) - Plan mode:
enablePlanMode(),planFileDirectory(String) - Context engineering:
additionalContextFile(String),maxContextTokens(int),compaction(CompactionConfig),toolResultEviction(ToolResultEvictionConfig),toolsConfig(ToolsConfig),mcpServerRegistrationListener(McpServerRegistrationListener) - All
disableXxx()toggles andenableAgentTracingLog(boolean)
Behavior caveats
Even after this method, the built
HarnessAgentis not behaviorally equivalent to the sourceReActAgent: HarnessAgent installs additional orchestration (workspace projection, agent-tracing middleware, default skill / subagent middlewares) that the source did not have. If left unset,sessionalso defaults to aJsonFileAgentStateStorerooted at~/.agentscope/state/<agentId>/rather than the in-memory default, changing the on-disk persistence layout.- Parameters:
agent- sourceReActAgentto inherit observable configuration from- Returns:
- a new
HarnessAgent.Builderpre-populated with the inheritable subset
- Workspace & filesystem:
-
name
-
description
-
sysPrompt
-
checkRunning
-
model
-
model
-
toolkit
-
maxIters
-
modelExecutionConfig
-
toolExecutionConfig
-
generateOptions
-
hook
-
hooks
-
middleware
-
middlewares
public HarnessAgent.Builder middlewares(List<? extends io.agentscope.core.middleware.MiddlewareBase> middlewareList) -
stateStore
-
distributedStore
Configures a distributed store that provides all storage components at once:AgentStateStore,BaseStore,SandboxSnapshotSpec, andSandboxExecutionGuard.Explicit builder methods (
stateStore(),filesystem()) take precedence over the distributed store for the components they configure.- Parameters:
store- the distributed store to use- Returns:
- this builder
-
defaultSessionId
-
toolExecutionContext
-
enableMetaTool
-
enablePendingToolRecovery
Enables recovery of orphaned tool calls when a new message arrives. Automatically constructed local subagents inherit this setting unless their declaration overrides it. Pending permission confirmations still require an explicit confirmation result.- Parameters:
enable- whether to synthesize error results for orphaned tool calls- Returns:
- this builder
-
enableTaskList
-
enableTaskList
-
maxRetries
-
fallbackModel
-
fallbackModel
-
failoverListener
public HarnessAgent.Builder failoverListener(io.agentscope.core.agent.config.FailoverListener failoverListener) Sets the listener notified when the fallback model takes over from a failed primary model. Delegates to the innerReActAgent.Builder.- See Also:
-
for the threading and failure contract
-
stopOnReject
-
permissionContext
public HarnessAgent.Builder permissionContext(io.agentscope.core.permission.PermissionContextState permissionContext) -
agentId
Sets the stable identifier used as the agent's namespace key in the composite filesystem (e.g.[agents, <agentId>, users, <userId>, ...]). When unset,build()falls back toname(String)for the namespace key. -
skillRepository
public HarnessAgent.Builder skillRepository(io.agentscope.core.skill.repository.AgentSkillRepository skillRepository) Adds a marketplace / external skill repository (e.g.GitSkillRepository). Repositories compose additively with workspace skills. -
skillRepositories
public HarnessAgent.Builder skillRepositories(List<io.agentscope.core.skill.repository.AgentSkillRepository> repositories) Replaces the current marketplace repository list with the given collection. -
projectGlobalSkillsDir
Configures a project-global skills directory layered below marketplace and workspace skills (lowest precedence). -
workspace
Sets the workspace directory.When left unset, the workspace is resolved at
build()time viaHarnessAgent.resolveDefaultWorkspace(): theagentscope.workspacesystem property, then theAGENTSCOPE_WORKSPACEenvironment variable, then${user.dir}/.agentscope/workspace. Setting a value here takes precedence over both the system property and the environment variable.- Parameters:
workspace- the workspace directory, ornullto fall back to the resolved default- Returns:
- this builder
-
workspace
Sets the workspace directory from a filesystem path string.See
workspace(Path)for the fallback behaviour when unset.- Parameters:
path- the workspace directory path, ornullto fall back to the resolved default- Returns:
- this builder
-
environmentMemory
-
abstractFilesystem
Escape hatch: sets a customAbstractFilesystemimplementation directly. -
filesystem
Configures Mode 2 — sandbox filesystem. -
filesystem
Configures Mode 1 — composite (non-sandbox) filesystem. -
filesystem
Configures Mode 3 — local filesystem with shell. -
filesystemRoute
Mounts an additionalAbstractFilesystemunder a path prefix, alongside the primary filesystem configured viafilesystem(SandboxFilesystemSpec),filesystem(RemoteFilesystemSpec), orfilesystem(LocalFilesystemSpec).When the primary filesystem is sandbox-backed, the route is applied via
RoutedSandboxFilesystemsoshell_executestill targets the sandbox. Otherwise the route is applied viaCompositeFilesystem.- Parameters:
prefix- path prefix for the route (e.g."memory-stores/notes/")filesystem- backend serving paths underprefix
-
compaction
Overrides the defaultCompactionMiddlewareconfiguration. Compaction is enabled by default withCompactionConfig.builder().build() defaults (dynamic trigger based on model context window, dynamic tail preservation). UsedisableCompaction()to turn it off entirely. -
disableCompaction
Disables theCompactionMiddlewareentirely. -
memory
Overrides the long-term memory pipeline configuration (flush + consolidation + maintenance). When not called,MemoryConfig.defaults()is used and behaviour matches the harness's historical defaults.For the compaction (in-context summarization) pipeline, see
compaction(CompactionConfig). -
toolResultEviction
Overrides the defaultToolResultEvictionMiddlewareconfiguration. Tool result eviction is enabled by default withToolResultEvictionConfig.defaults()(trigger at 80k chars). UsedisableToolResultEviction()to turn it off entirely. -
disableToolResultEviction
Disables theToolResultEvictionMiddlewareentirely. -
toolsConfig
Programmatic override forworkspace/tools.json. -
mcpServerRegistrationListener
public HarnessAgent.Builder mcpServerRegistrationListener(McpServerRegistrationListener mcpServerRegistrationListener) Sets the listener for terminal MCP server registration results produced while building this agent. The listener is not propagated to dynamically created subagents. Passingnulldisables result delivery. -
subagent
Adds a subagent declaration. -
subagents
-
subagentFactory
public HarnessAgent.Builder subagentFactory(String name, Function<String, io.agentscope.core.agent.Agent> factory) Adds a fully custom subagent factory for a given agent id. -
subagentFactory
public HarnessAgent.Builder subagentFactory(String name, String description, Function<String, io.agentscope.core.agent.Agent> factory) Adds a fully custom subagent factory for a given agent id, with a description shown to the orchestrator. Whendescriptionis null or blank, the name is used. -
taskRepository
Sets a customTaskRepositoryfor background subagent execution. -
messageBus
Sets theMessageBusfor inbox-based message delivery. When set, anInboxMiddlewareis automatically registered to drain the session's inbox before each reasoning step. -
asyncToolTimeout
EnablesAsyncToolMiddlewarewith the given timeout. RequiresmessageBus(io.agentscope.harness.agent.bus.MessageBus)to be set. Tool executions that exceed the timeout are offloaded to the background; results are delivered via the inbox. -
asyncToolRegistry
Sets theAsyncToolRegistryfor tracking async tool executions. Enables stale async tool detection and cleanup inInboxMiddleware. When not set, async tool lifecycle tracking is skipped. -
externalSubagentTool
Injects an external subagent tool (typicallySessionsTool). -
modelResolver
Sets a resolver for model name strings toModelinstances for subagents. -
additionalContextFile
Adds a custom context file (relative to workspace) loaded into the system prompt alongside AGENTS.md, MEMORY.md, and KNOWLEDGE.md. -
maxContextTokens
Sets the maximum token budget for workspace context. -
useLegacyXmlWorkspaceContext
Switches workspace context rendering between markdown (default) and legacy XML style. -
enableAgentTracingLog
Enables or disables agent execution trace logging viaAgentTraceMiddleware. Default istrue. -
artifactDeliveryTarget
Configures theArtifactDeliveryTargetused by thedeliver_artifacttool.When set, the generic
ArtifactDeliveryToolis registered on the main agent and the sandbox workspace prompt tells the model to use it to hand artifacts it produced to a destination outside the sandbox. When unset (default), no delivery tool is exposed.The tool is exposed only to the main agent — it is not propagated to automatically constructed subagents, which return plain text results for the main agent to deliver.
Note: the tool reads files from the agent filesystem, so it is also suppressed when
disableFilesystemTools()is used. Combining both leaves the tool unregistered. -
disableFilesystemTools
Skips registration ofFilesystemTool. -
disableShellTool
Skips registration ofShellExecuteTool. -
disableWebTools
Skips registration of the optional Tavily-backedweb_searchandweb_fetchtools. -
webHttpClient
Supplies a customHttpClientused by the built-inweb_fetchandweb_searchtools (e.g. custom proxy, TLS or HTTP version settings). When unset, the tools use a default client with JDK version negotiation (HTTP/2 preferred, automatic HTTP/1.1 fallback); inject an HTTP/1.1-only client here if a target server fails under HTTP/2 negotiation (see issue #3101). -
registerExternalSchemas
public HarnessAgent.Builder registerExternalSchemas(List<io.agentscope.core.model.ToolSchema> schemas) Registers schema-only external tools on the builder toolkit (merged into the final agent toolkit atbuild()). Used byself_hostedenvironments to expose hands tools that suspend for worker execution. -
disableDynamicSkills
Disables dynamic per-call skill loading from the workspace filesystem. -
disableDefaultWorkspaceSkills
Skips registration of the default Layer-4WorkspaceSkillRepository. User-supplied repositories and the workspace skills directory (Layer 3) are still composed; only the namespaced AbstractFilesystem-backed source is omitted. -
enableSkillManageTool
Enables the agent-callableskill_managetool so the agent can create / edit / patch / archive its own skills in the workspace, and upgrades the workspace skill repository to a writable variant. -
enableSkillManageTool
Shorthand forenableSkillManageTool(SkillManageConfig)with default config. -
enableSkillPromotionGate
public HarnessAgent.Builder enableSkillPromotionGate(SkillPromotionGate gate, SkillVisibilityFilter visibilityFilter) Configures the runtime promotion gate + visibility filter chain. -
environment
Sets the deployment environment label used byEnvironmentFilter. -
enableSkillCurator
Enables the background skill curator. RequiresenableSkillManageTool(io.agentscope.harness.agent.tool.SkillManageConfig). -
enablePlanMode
Enables plan mode (read-only design phase) withplan_enter/plan_write/plan_exittools and aPlanModeMiddlewarethat enforces read-only tools while plan mode is active. -
enablePlanMode
-
planFileDirectory
-
allowShellInPlanMode
Allows the shell tool (execute) to run while plan mode is active. By default plan mode is strictly read-only and the shell is denied (it is dual-use and cannot be classified as read-only by name). Opt in when shell-based investigation (e.g.cat/grep/git log) is needed to produce a realistic plan; the plan banner instructs the model to keep shell usage read-only. Writes still flow through the (denied) file-editing tools. Prefer pairing this with a sandboxed filesystem. -
allowShellInPlanMode
-
skillFilter
-
skillsEnabled
-
enableSkills
-
disableSkills
-
disableDynamicSubagents
-
disableMemoryTools
Skips registration ofmemory_search/memory_get/memory_save/session_search, and omits matching Memory Recall / tool-based Persistence guidance from the workspace system prompt. -
disableMemoryHooks
Disables memory flush + background consolidation, and removes the "automatically extracted" Persistence line from the workspace system prompt. Combined withdisableMemoryTools(), also skipsMEMORY.mdinjection into<memory_context>. -
disableTranscript
Disables the independent session-transcript middleware. Prefer leaving transcript on; memory hooks can be disabled separately viadisableMemoryHooks(). -
transcriptStore
Optional override for the sessionTranscriptStore(segmented append store). -
transcriptTenant
Tenant segment used in transcript object keys (default"default"). -
disableSessionPersistence
No-op since 2.0; session persistence is owned by ReActAgent itself. -
disableWorkspaceContext
-
disableAtPathExpansion
-
disableSubagents
-
disableToolsConfig
-
buildSubagentEntries
Builds the subagent entries (general-purpose + declared + custom factories) without constructing the full agent. Useful for callers that need to extract subagent factories up front (for example to mount them on a session router). -
buildSubagentEntries
public List<SubagentEntry> buildSubagentEntries(Path resolvedWorkspace, SandboxBackedFilesystem sandboxFs) -
build
-