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
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@ public SandboxState getState() {
@Override
public ExecResult exec(RuntimeContext context, String command, Integer timeoutSeconds)
throws Exception {
return exec(context, command, timeoutSeconds, Map.of());
}

@Override
public ExecResult exec(
RuntimeContext context,
String command,
Integer timeoutSeconds,
Map<String, String> environment)
throws Exception {
requireDirectory();
int timeout = timeoutSeconds == null ? 30 : timeoutSeconds;
if (timeout < 1)
Expand All @@ -275,6 +285,7 @@ public ExecResult exec(RuntimeContext context, String command, Integer timeoutSe
.redirectOutput(output.toFile())
.redirectError(errors.toFile());
builder.environment().putAll(state.environment);
if (environment != null) builder.environment().putAll(environment);
process = builder.start();
process.getOutputStream().close();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@
import io.agentscope.harness.agent.skill.curator.SkillUsageStore;
import io.agentscope.harness.agent.skill.curator.SkillVisibilityFilter;
import io.agentscope.harness.agent.skill.runtime.ShellPathPolicy;
import io.agentscope.harness.agent.skill.runtime.SkillCredentialException;
import io.agentscope.harness.agent.skill.runtime.SkillCredentialProvider;
import io.agentscope.harness.agent.subagent.DefaultAgentManager;
import io.agentscope.harness.agent.subagent.SubagentDeclaration;
import io.agentscope.harness.agent.subagent.SubagentExecution;
Expand Down Expand Up @@ -1471,6 +1473,7 @@ public Builder threadJournalStore(ThreadJournalStore store) {
String agentId;
final List<AgentSkillRepository> skillRepositories = new ArrayList<>();
Path projectGlobalSkillsDir;
SkillCredentialProvider skillCredentialProvider;

Path workspace;
String environmentMemory;
Expand Down Expand Up @@ -2157,6 +2160,27 @@ public Builder projectGlobalSkillsDir(Path projectGlobalSkillsDir) {
return this;
}

/**
* Installs a per-invocation credential hook for skills.
*
* <p>The provider is consulted immediately before each shell command that references a
* visible skill's {@code <files-root>}, receives the authenticated user and the selected
* skill, and returns the environment variables to expose to that one command. The framework
* stores, logs and persists nothing; the host keeps user authorization, encrypted storage,
* missing-credential flows and redaction. Commands that reference no skill root run
* unchanged. When the provider throws {@link SkillCredentialException}, the command is not
* executed and the agent receives the reason as a tool error.
*
* <p>Subagents inherit the provider. See {@link SkillCredentialProvider} for the contract
* and the trust boundary.
*
* @param provider the hook, or {@code null} to disable credential resolution
*/
public Builder skillCredentialProvider(SkillCredentialProvider provider) {
this.skillCredentialProvider = provider;
return this;
}

/**
* Sets the workspace directory. Pass {@code null} to use the default
* {@code ${cwd}/.agentscope/workspace}.
Expand Down Expand Up @@ -3299,7 +3323,7 @@ && isLocalSession(effectiveSession)) {
if (!disableShellTool
&& FilesystemUtils.primaryBackend(filesystem)
instanceof AbstractSandboxFilesystem sandbox) {
agentToolkit.registerTool(new ShellExecuteTool(sandbox));
agentToolkit.registerTool(new ShellExecuteTool(sandbox, skillCredentialProvider));
}
if (!disableWebTools) {
if (webHttpClient != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import io.agentscope.harness.agent.middleware.DynamicSubagentsMiddleware;
import io.agentscope.harness.agent.middleware.SubagentEntry;
import io.agentscope.harness.agent.middleware.SubagentsMiddleware;
import io.agentscope.harness.agent.skill.runtime.SkillCredentialProvider;
import io.agentscope.harness.agent.subagent.AgentSpecLoader;
import io.agentscope.harness.agent.subagent.DefaultAgentManager;
import io.agentscope.harness.agent.subagent.SubagentDeclaration;
Expand Down Expand Up @@ -335,6 +336,7 @@ static SubagentFactory buildGeneralPurposeFactory(
final List<MiddlewareBase> capturedMiddlewares = List.copyOf(b.middlewares);
final List<AgentSkillRepository> capturedSkillRepos = List.copyOf(b.skillRepositories);
final Path capturedProjectGlobalSkillsDir = b.projectGlobalSkillsDir;
final SkillCredentialProvider capturedSkillCredentialProvider = b.skillCredentialProvider;
final boolean capturedDisableFilesystemTools = b.disableFilesystemTools;
final int capturedReadFileMaxChars = b.readFileMaxChars;
final boolean capturedDisableShellTool = b.disableShellTool;
Expand Down Expand Up @@ -414,6 +416,9 @@ static SubagentFactory buildGeneralPurposeFactory(
if (capturedProjectGlobalSkillsDir != null) {
sub.projectGlobalSkillsDir(capturedProjectGlobalSkillsDir);
}
if (capturedSkillCredentialProvider != null) {
sub.skillCredentialProvider(capturedSkillCredentialProvider);
}
if (capturedBackend != null) sub.abstractFilesystem(capturedBackend);
capturedJournal.accept(sub);
if (capturedStateStore != null) sub.stateStore(capturedStateStore);
Expand Down Expand Up @@ -494,6 +499,7 @@ static SubagentFactory buildDeclaredFactory(
capturedLocalFilesystemSpec = b.localFilesystemSpec;
final List<AgentSkillRepository> capturedSkillRepos = List.copyOf(b.skillRepositories);
final Path capturedProjectGlobalSkillsDir = b.projectGlobalSkillsDir;
final SkillCredentialProvider capturedSkillCredentialProvider = b.skillCredentialProvider;
final CompactionConfig capturedCompactionConfig = b.compactionConfig;
final boolean capturedDisableCompaction = b.disableCompaction;
final boolean capturedDisableRepeatedFailureGuard = b.disableRepeatedFailureGuard;
Expand Down Expand Up @@ -606,6 +612,9 @@ static SubagentFactory buildDeclaredFactory(
if (capturedProjectGlobalSkillsDir != null) {
sub.projectGlobalSkillsDir(capturedProjectGlobalSkillsDir);
}
if (capturedSkillCredentialProvider != null) {
sub.skillCredentialProvider(capturedSkillCredentialProvider);
}

if (capturedPermissions != null) sub.permissionContext(capturedPermissions);
if (capturedDisableDefaultSkills) sub.disableDefaultWorkspaceSkills();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,15 @@ public ExecuteResponse execute(
RuntimeContext runtimeContext, String command, Integer timeoutSeconds) {
return shellBackend.execute(runtimeContext, command, timeoutSeconds);
}

@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> environment) {
return shellBackend.execute(runtimeContext, command, timeoutSeconds, environment);
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,15 @@ public ExecuteResponse execute(
return shellBackend.execute(runtimeContext, command, timeoutSeconds);
}

@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> environment) {
return shellBackend.execute(runtimeContext, command, timeoutSeconds, environment);
}

// ==================== Write routing ====================

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ public ExecuteResponse execute(
return primary.execute(runtimeContext, command, timeoutSeconds);
}

@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> environment) {
return primary.execute(runtimeContext, command, timeoutSeconds, environment);
}

@Override
public AtomicJournalStorage journalStorage(RuntimeContext runtimeContext) {
return composite.journalStorage(runtimeContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,29 @@ public Path getShellCwd() {
@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext, String command, Integer timeoutSeconds) {
return executeWithEnvironment(runtimeContext, command, timeoutSeconds, Map.of());
}

/**
* Executes with extra environment variables layered on top of the configured environment for
* this process only. The host process environment is untouched, so a concurrent invocation
* cannot observe another caller's variables.
*/
@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> invocationEnvironment) {
return executeWithEnvironment(
runtimeContext, command, timeoutSeconds, invocationEnvironment);
}

private ExecuteResponse executeWithEnvironment(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> invocationEnvironment) {
if (command == null || command.isBlank()) {
return new ExecuteResponse("Error: Command must be a non-empty string.", 1, false);
}
Expand Down Expand Up @@ -363,6 +386,9 @@ public ExecuteResponse execute(
pb.environment().clear();
pb.environment().putAll(env);
}
if (invocationEnvironment != null && !invocationEnvironment.isEmpty()) {
pb.environment().putAll(invocationEnvironment);
}

stdout = new StreamCapture(runtimeContext, false);
stderr = new StreamCapture(runtimeContext, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.agentscope.core.agent.RuntimeContext;
import io.agentscope.harness.agent.filesystem.AbstractFilesystem;
import io.agentscope.harness.agent.filesystem.model.ExecuteResponse;
import java.util.Map;

/**
* Filesystem abstraction that adds shell command execution (sandbox or remote host).
Expand Down Expand Up @@ -46,4 +47,39 @@ public interface AbstractSandboxFilesystem extends AbstractFilesystem {
* command output
*/
ExecuteResponse execute(RuntimeContext runtimeContext, String command, Integer timeoutSeconds);

/**
* Execute a shell command with a per-invocation environment.
*
* <p>The environment participates in this call only: implementations must not persist it into
* the workspace, a snapshot, the sandbox configuration, or a later command. It is used by the
* skill credential hook to scope a resolved secret to one skill invocation.
*
* <p>The default refuses a non-empty environment instead of silently dropping it, so a command
* that needs credentials never runs with them missing. Implementations that support the channel
* override this method; {@code null} or empty {@code environment} always falls back to {@link
* #execute(RuntimeContext, String, Integer)}.
*
* @param runtimeContext per-call agent context; may be {@code null} when unavailable
* @param command full shell command string to execute
* @param timeoutSeconds maximum time in seconds to wait for the command to complete; {@code
* null} uses the filesystem's default timeout
* @param environment extra environment variables for this command only; {@code null} or empty
* for none
* @return the command result, with the same contract as {@link #execute(RuntimeContext,
* String, Integer)}
* @throws UnsupportedOperationException when the environment is non-empty and this filesystem
* cannot scope it to one command
*/
default ExecuteResponse execute(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> environment) {
if (environment == null || environment.isEmpty()) {
return execute(runtimeContext, command, timeoutSeconds);
}
throw new UnsupportedOperationException(
"Per-invocation environment is not supported by " + getClass().getName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,18 @@ public String id() {
@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext, String command, Integer timeoutSeconds) {
return execute(runtimeContext, command, timeoutSeconds, Map.of());
}

@Override
public ExecuteResponse execute(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> environment) {
Sandbox active = requireSandbox(runtimeContext);
try {
ExecResult result = active.exec(runtimeContext, command, timeoutSeconds);
ExecResult result = active.exec(runtimeContext, command, timeoutSeconds, environment);
return new ExecuteResponse(
result.combinedOutput(), result.exitCode(), result.truncated());
} catch (SandboxException.ExecStatusUnknownException e) {
Expand All @@ -116,6 +125,10 @@ public ExecuteResponse execute(
? "\n" + e.getStderr()
: "");
return new ExecuteResponse(combined, e.getExitCode(), false, e.isTimedOut());
} catch (UnsupportedOperationException e) {
// A backend without a per-command environment: let the caller report it precisely
// instead of degrading to a generic sandbox error.
throw e;
} catch (Exception e) {
log.error("[sandbox-fs] execute failed: {}", command, e);
return new ExecuteResponse("Internal sandbox error: " + e.getMessage(), -1, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
Expand Down Expand Up @@ -195,6 +196,23 @@ public ExecResult exec(RuntimeContext runtimeContext, String command, Integer ti
return doExec(runtimeContext, command, timeout);
}

/**
* Delegates to {@link #doExec(RuntimeContext, String, int, Map)} with a fallback timeout. The
* default {@code doExec} wraps the command in a one-shot shell {@code env} prefix; backends with
* a native per-command environment (Docker's {@code docker exec -e}) override that method so
* values never enter the command text.
*/
@Override
public ExecResult exec(
RuntimeContext runtimeContext,
String command,
Integer timeoutSeconds,
Map<String, String> environment)
throws Exception {
int timeout = timeoutSeconds != null ? timeoutSeconds : getDefaultExecTimeoutSeconds();
return doExec(runtimeContext, command, timeout, environment);
}

@Override
public InputStream persistWorkspace() throws Exception {
return doPersistWorkspace();
Expand Down Expand Up @@ -261,6 +279,35 @@ protected int getDefaultExecTimeoutSeconds() {
protected abstract ExecResult doExec(
RuntimeContext runtimeContext, String command, int timeoutSeconds) throws Exception;

/**
* Executes a shell command with a one-shot environment. The base implementation wraps the
* command in {@code env 'NAME=VALUE' ... sh -c 'command'}, which works for every POSIX shell
* backend; backends with native support override this so the values are not part of the command
* text.
*
* @param runtimeContext per-call context; may be {@code null} for internal probes
* @param command shell command string
* @param timeoutSeconds maximum execution time
* @param environment extra environment variables for this command only; {@code null} or empty
* for none
* @return execution result
* @throws Exception if execution fails
*/
protected ExecResult doExec(
RuntimeContext runtimeContext,
String command,
int timeoutSeconds,
Map<String, String> environment)
throws Exception {
if (environment == null || environment.isEmpty()) {
return doExec(runtimeContext, command, timeoutSeconds);
}
return doExec(
runtimeContext,
SandboxEnvironment.commandWithEnvironment(command, environment),
timeoutSeconds);
}

/**
* Creates a tar archive of the current workspace contents.
*
Expand Down
Loading
Loading