From b27e636aaa8b6ce110a6f86f2f9bb91aedbf5819 Mon Sep 17 00:00:00 2001 From: shanuo0312 <3704135+shanuo0312@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:05:55 +0800 Subject: [PATCH] feat(harness): add per-invocation skill credential hook (#4476) Add SkillCredentialProvider so a host can resolve the authenticated caller's credentials for the selected skill immediately before a skill command runs, and inject them only into that command's environment. execute attributes a command to a visible skill when it references the skill's ; missing credentials reject the command with a tool error instead of running it. Native per-command environments are used where available (Docker, local shell, durable local sandbox); other sandbox backends get a one-shot POSIX env wrapper fallback. Docs (EN/ZH) describe the contract, missing-credential behavior and the trust boundary. Refs #4476 --- .../durable/sandbox/LocalSandboxClient.java | 11 + .../harness/agent/HarnessAgent.java | 26 +- .../agent/HarnessAgentBuilderSupport.java | 9 + .../agent/filesystem/OverlayFilesystem.java | 9 + .../agent/filesystem/ProjectAwareOverlay.java | 9 + .../filesystem/RoutedSandboxFilesystem.java | 9 + .../local/LocalFilesystemWithShell.java | 26 ++ .../sandbox/AbstractSandboxFilesystem.java | 36 ++ .../sandbox/SandboxBackedFilesystem.java | 15 +- .../agent/sandbox/AbstractBaseSandbox.java | 47 +++ .../harness/agent/sandbox/Sandbox.java | 34 ++ .../agent/sandbox/SandboxEnvironment.java | 59 ++++ .../sandbox/impl/docker/DockerSandbox.java | 57 +++- .../agent/skill/runtime/SkillCatalog.java | 70 ++++ .../runtime/SkillCredentialException.java | 36 ++ .../runtime/SkillCredentialProvider.java | 71 ++++ .../agent/skill/runtime/SkillInvocation.java | 57 ++++ .../agent/skill/runtime/SkillRuntime.java | 8 +- .../harness/agent/tool/ShellExecuteTool.java | 114 ++++++- .../local/LocalFilesystemWithShellTest.java | 20 ++ .../agent/sandbox/SandboxEnvironmentTest.java | 73 +++++ .../docker/DockerSandboxRunCommandTest.java | 35 ++ .../ShellExecuteToolSkillCredentialTest.java | 309 ++++++++++++++++++ docs/v2/en/docs/harness/skill.md | 33 +- docs/v2/zh/docs/harness/skill.md | 33 +- 25 files changed, 1191 insertions(+), 15 deletions(-) create mode 100644 agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxEnvironment.java create mode 100644 agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialException.java create mode 100644 agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialProvider.java create mode 100644 agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillInvocation.java create mode 100644 agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/SandboxEnvironmentTest.java create mode 100644 agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/ShellExecuteToolSkillCredentialTest.java diff --git a/agentscope-extensions/agentscope-extensions-durable-sandbox/src/main/java/io/agentscope/extensions/durable/sandbox/LocalSandboxClient.java b/agentscope-extensions/agentscope-extensions-durable-sandbox/src/main/java/io/agentscope/extensions/durable/sandbox/LocalSandboxClient.java index e8219f90d4..5f2cb140d4 100644 --- a/agentscope-extensions/agentscope-extensions-durable-sandbox/src/main/java/io/agentscope/extensions/durable/sandbox/LocalSandboxClient.java +++ b/agentscope-extensions/agentscope-extensions-durable-sandbox/src/main/java/io/agentscope/extensions/durable/sandbox/LocalSandboxClient.java @@ -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 environment) + throws Exception { requireDirectory(); int timeout = timeoutSeconds == null ? 30 : timeoutSeconds; if (timeout < 1) @@ -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); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java index 293f4e2f25..f1a6a2d65c 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java @@ -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; @@ -1471,6 +1473,7 @@ public Builder threadJournalStore(ThreadJournalStore store) { String agentId; final List skillRepositories = new ArrayList<>(); Path projectGlobalSkillsDir; + SkillCredentialProvider skillCredentialProvider; Path workspace; String environmentMemory; @@ -2156,6 +2159,27 @@ public Builder projectGlobalSkillsDir(Path projectGlobalSkillsDir) { return this; } + /** + * Installs a per-invocation credential hook for skills. + * + *

The provider is consulted immediately before each shell command that references a + * visible skill's {@code }, 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. + * + *

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}. @@ -3263,7 +3287,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) { diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java index 9505603889..bac6e81b34 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java @@ -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; @@ -335,6 +336,7 @@ static SubagentFactory buildGeneralPurposeFactory( final List capturedMiddlewares = List.copyOf(b.middlewares); final List 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; @@ -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); @@ -494,6 +499,7 @@ static SubagentFactory buildDeclaredFactory( capturedLocalFilesystemSpec = b.localFilesystemSpec; final List 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; @@ -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(); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java index 3268225a81..f6e827989e 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java @@ -138,6 +138,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 environment) { + return shellBackend.execute(runtimeContext, command, timeoutSeconds, environment); + } } @Override diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java index a79c363192..3c94c5cf7a 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java @@ -128,6 +128,15 @@ public ExecuteResponse execute( return shellBackend.execute(runtimeContext, command, timeoutSeconds); } + @Override + public ExecuteResponse execute( + RuntimeContext runtimeContext, + String command, + Integer timeoutSeconds, + Map environment) { + return shellBackend.execute(runtimeContext, command, timeoutSeconds, environment); + } + // ==================== Write routing ==================== @Override diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java index cde7e6ebd5..fc483e6f3e 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java @@ -74,6 +74,15 @@ public ExecuteResponse execute( return primary.execute(runtimeContext, command, timeoutSeconds); } + @Override + public ExecuteResponse execute( + RuntimeContext runtimeContext, + String command, + Integer timeoutSeconds, + Map environment) { + return primary.execute(runtimeContext, command, timeoutSeconds, environment); + } + @Override public AtomicJournalStorage journalStorage(RuntimeContext runtimeContext) { return composite.journalStorage(runtimeContext); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShell.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShell.java index bde055a7d2..98928bf868 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShell.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShell.java @@ -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 invocationEnvironment) { + return executeWithEnvironment( + runtimeContext, command, timeoutSeconds, invocationEnvironment); + } + + private ExecuteResponse executeWithEnvironment( + RuntimeContext runtimeContext, + String command, + Integer timeoutSeconds, + Map invocationEnvironment) { if (command == null || command.isBlank()) { return new ExecuteResponse("Error: Command must be a non-empty string.", 1, false); } @@ -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); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/AbstractSandboxFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/AbstractSandboxFilesystem.java index 4283e67153..33771825ac 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/AbstractSandboxFilesystem.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/AbstractSandboxFilesystem.java @@ -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). @@ -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. + * + *

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. + * + *

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 environment) { + if (environment == null || environment.isEmpty()) { + return execute(runtimeContext, command, timeoutSeconds); + } + throw new UnsupportedOperationException( + "Per-invocation environment is not supported by " + getClass().getName()); + } } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java index 95d7ba635a..7240a16d23 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java @@ -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 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) { @@ -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); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java index 264779f329..ad33c9fa06 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java @@ -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; @@ -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 environment) + throws Exception { + int timeout = timeoutSeconds != null ? timeoutSeconds : getDefaultExecTimeoutSeconds(); + return doExec(runtimeContext, command, timeout, environment); + } + @Override public InputStream persistWorkspace() throws Exception { return doPersistWorkspace(); @@ -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 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. * diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/Sandbox.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/Sandbox.java index c986978ef8..2a8931e675 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/Sandbox.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/Sandbox.java @@ -17,6 +17,7 @@ import io.agentscope.core.agent.RuntimeContext; import java.io.InputStream; +import java.util.Map; /** * An active sandbox with a fully isolated workspace. @@ -73,6 +74,39 @@ default void shutdown() throws Exception { ExecResult exec(RuntimeContext runtimeContext, String command, Integer timeoutSeconds) throws Exception; + /** + * Runs a shell command with a per-invocation environment. + * + *

The environment applies to this command only. It must not be persisted into the sandbox + * configuration, the workspace, or a snapshot, and the next {@code exec} must start without it. + * Backends that support a native per-command environment (for example {@code docker exec -e}) + * should override this method so values never appear in the command text. Backends that do not + * override it inherit the harness fallback (a shell {@code env} prefix) through {@link + * AbstractBaseSandbox}; direct implementations that support neither should leave the default, + * which refuses a non-empty environment instead of silently running a command without its + * credentials. + * + * @param runtimeContext per-call agent context (session, user, attributes); may be {@code null} + * @param command shell command + * @param timeoutSeconds max wait in seconds; {@code null} for implementation default + * @param environment extra environment variables for this command only; {@code null} or empty + * for none + * @throws UnsupportedOperationException when the environment is non-empty and this backend + * cannot scope it to one command + */ + default ExecResult exec( + RuntimeContext runtimeContext, + String command, + Integer timeoutSeconds, + Map environment) + throws Exception { + if (environment == null || environment.isEmpty()) { + return exec(runtimeContext, command, timeoutSeconds); + } + throw new UnsupportedOperationException( + "Per-invocation environment is not supported by " + getClass().getName()); + } + InputStream persistWorkspace() throws Exception; void hydrateWorkspace(InputStream archive) throws Exception; diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxEnvironment.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxEnvironment.java new file mode 100644 index 0000000000..fb91e101fd --- /dev/null +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/SandboxEnvironment.java @@ -0,0 +1,59 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.sandbox; + +import java.util.Map; + +/** + * Builds a one-shot POSIX shell command carrying extra environment variables. + * + *

Used as the harness fallback for sandbox backends without a native per-command environment. + * Values are single-quoted, so quotes, spaces and shell metacharacters pass through literally. The + * wrapper is not appropriate for secrets that must never appear in process arguments; backends with + * native support (Docker's {@code -e}, local {@code ProcessBuilder.environment()}) use that instead. + */ +final class SandboxEnvironment { + + private SandboxEnvironment() {} + + /** + * Wraps {@code command} so it runs in a new {@code sh} with {@code environment} applied. + * + * @param command shell command to run + * @param environment environment variables to apply to that command only + * @return a single POSIX shell command string + */ + static String commandWithEnvironment(String command, Map environment) { + StringBuilder wrapped = new StringBuilder("env"); + for (Map.Entry variable : environment.entrySet()) { + String name = variable.getKey(); + if (name == null || !name.matches("[A-Za-z_][A-Za-z0-9_]*")) { + throw new IllegalArgumentException("Invalid environment variable name"); + } + String value = variable.getValue(); + if (value == null) { + throw new IllegalArgumentException("Null value for environment variable " + name); + } + wrapped.append(' ').append(shellQuote(name + "=" + value)); + } + wrapped.append(" sh -c ").append(shellQuote(command)); + return wrapped.toString(); + } + + private static String shellQuote(String value) { + return "'" + value.replace("'", "'\\''") + "'"; + } +} diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java index 8c81b837ec..a35dcc4c2f 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandbox.java @@ -144,20 +144,31 @@ public void shutdown() throws Exception { @Override protected ExecResult doExec(RuntimeContext runtimeContext, String command, int timeoutSeconds) throws Exception { + return doExec(runtimeContext, command, timeoutSeconds, Map.of()); + } + + /** + * Runs the command with a native per-command environment. The docker CLI receives only the + * variable names ({@code docker exec -e NAME}); values come from the client process environment + * and therefore never appear in the command text, the container's process arguments, or the + * docker CLI's own command line. + */ + @Override + protected ExecResult doExec( + RuntimeContext runtimeContext, + String command, + int timeoutSeconds, + Map environment) + throws Exception { String containerId = dockerState.getContainerId(); String workspaceRoot = dockerState.getWorkspaceRoot(); - List cmd = new ArrayList<>(); - cmd.add("docker"); - cmd.add("exec"); - cmd.add("-w"); - cmd.add(workspaceRoot); - cmd.add(containerId); - cmd.add("sh"); - cmd.add("-c"); - cmd.add(command); + List cmd = dockerExecCommand(containerId, workspaceRoot, command, environment); ProcessBuilder pb = new ProcessBuilder(cmd); + if (environment != null && !environment.isEmpty()) { + pb.environment().putAll(environment); + } Process process = pb.start(); ExecutorService drainer = @@ -199,6 +210,34 @@ protected ExecResult doExec(RuntimeContext runtimeContext, String command, int t return result; } + /** + * Builds the {@code docker exec} argument list. Only variable names are added through {@code + * -e}; the CLI reads each value from its own process environment, so values never appear in the + * argument list or the shell command text. + */ + static List dockerExecCommand( + String containerId, + String workspaceRoot, + String command, + Map environment) { + List cmd = new ArrayList<>(); + cmd.add("docker"); + cmd.add("exec"); + cmd.add("-w"); + cmd.add(workspaceRoot); + if (environment != null) { + for (String name : environment.keySet()) { + cmd.add("-e"); + cmd.add(name); + } + } + cmd.add(containerId); + cmd.add("sh"); + cmd.add("-c"); + cmd.add(command); + return cmd; + } + @Override protected InputStream doPersistWorkspace() throws Exception { String containerId = dockerState.getContainerId(); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCatalog.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCatalog.java index b39a90a495..20083fe72c 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCatalog.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCatalog.java @@ -20,6 +20,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; /** * Immutable snapshot of the skills visible to a single {@code onSystemPrompt} pass. @@ -69,6 +70,75 @@ public boolean isEmpty() { return entries.isEmpty(); } + /** + * Returns the entry whose {@code filesRoot} is referenced by {@code command}, or empty when the + * command does not invoke a skill. + * + *

The match is a literal path occurrence, so it does not depend on shell quoting: {@code sh + * '/workspace/skills/x/scripts/run.sh'} and {@code sh /workspace/skills/x/scripts/run.sh} both + * match. A workspace-relative spelling of the same root ({@code skills/x/...}, + * {@code .skills-cache/...}) also matches, covering a command run from a + * {@code working_directory} inside the skill or a relative script path. When several roots are + * prefixes of one another (for example skill names {@code x} and {@code x-extra}), the longest + * root wins. + * + * @param command the command about to execute + * @return the attributed entry, or empty when no visible skill root occurs in the command + */ + public Optional matchCommand(String command) { + if (command == null || command.isBlank()) { + return Optional.empty(); + } + HarnessSkillEntry best = null; + int bestLength = -1; + for (HarnessSkillEntry entry : entries.values()) { + String root = stripTrailingSlashes(entry.filesRoot()); + if (root == null || root.isEmpty()) { + continue; + } + if (root.length() > bestLength && command.contains(root)) { + best = entry; + bestLength = root.length(); + continue; + } + String relative = workspaceRelative(root); + if (relative != null && relative.length() > bestLength && command.contains(relative)) { + best = entry; + bestLength = relative.length(); + } + } + return Optional.ofNullable(best); + } + + /** + * Strips the execution environment's workspace prefix from a skill root, returning the + * workspace-relative spelling the agent may use when it changes directory. Returns {@code null} + * when the root carries no recognizable workspace segment. + */ + private static String workspaceRelative(String root) { + int skills = root.lastIndexOf("/skills/"); + if (skills >= 0) { + return root.substring(skills + 1); + } + int cache = root.lastIndexOf("/.skills-cache/"); + if (cache >= 0) { + return root.substring(cache + 1); + } + return null; + } + + private static String stripTrailingSlashes(String path) { + if (path == null) { + return null; + } + String trimmed = path.strip(); + int end = trimmed.length(); + while (end > 0 && trimmed.charAt(end - 1) == '/') { + end--; + } + return trimmed.substring(0, end); + } + public int size() { return entries.size(); } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialException.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialException.java new file mode 100644 index 0000000000..780f12e406 --- /dev/null +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialException.java @@ -0,0 +1,36 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.skill.runtime; + +/** + * Signals that a skill command must not run because its credentials are missing, revoked, or not + * authorized for the authenticated caller. + * + *

The harness converts this exception into a tool error for the agent and does not execute the + * command, so a command never runs with partial or stale credentials. The message is shown to the + * agent and may be paraphrased to the user; it must not contain credential values. Describe the + * missing requirement and the action the user or host must take instead. + */ +public class SkillCredentialException extends RuntimeException { + + public SkillCredentialException(String message) { + super(message); + } + + public SkillCredentialException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialProvider.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialProvider.java new file mode 100644 index 0000000000..eafa7250fd --- /dev/null +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillCredentialProvider.java @@ -0,0 +1,71 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.skill.runtime; + +import java.util.Map; + +/** + * Host-supplied hook that resolves a skill invocation's credentials and returns them as environment + * variables for that one command. + * + *

What the host owns

+ * + *

The framework never stores, caches, logs or persists credential values. The host keeps + * ownership of user authentication, authorization, encrypted storage, decryption, missing-credential + * flows, result redaction and replacement/revocation. The provider receives the {@link + * SkillInvocation} — which identifies the authenticated user and the selected skill — and returns + * the environment variables the host is willing to expose to exactly that command. + * + *

Contract

+ * + *
    + *
  • Called once per command that references a skill's {@code }, immediately before + * execution, on the calling thread. It may block on storage/decryption; it must be + * thread-safe because concurrent sessions can invoke different users' skills. + *
  • The returned map is applied to the environment of that single command. It is never written + * to the skill directory, the workspace, the prompt, tool arguments/results, or agent state, + * and the next command starts without it. + *
  • Returning {@code null} or an empty map means "nothing to inject" and the command runs + * unchanged. + *
  • Throw {@link SkillCredentialException} when the credentials are missing or must not be used + * for this invocation. The harness then returns the exception message to the agent as a tool + * error instead of running the command, so a command is never executed with partial or + * stale credentials. Do not put credential values in that message. + *
+ * + *

Trust boundary

+ * + *

Isolation keeps one user from resolving another user's credentials, but a skill authorized to + * receive a secret can read and potentially exfiltrate it. Sandbox permissions, skill review, + * network egress policy and least-privilege tokens remain necessary. + * + *

Configure a provider with {@code HarnessAgent.Builder#skillCredentialProvider}. Backends that + * support a native per-command environment inject values out of band; other {@code Sandbox} + * backends receive them through a shell {@code env} prefix, which can be visible to the backend in + * the command text, so prefer a backend with native support for high-value secrets. + */ +@FunctionalInterface +public interface SkillCredentialProvider { + + /** + * Resolves the credentials to expose to one skill command. + * + * @param invocation the attributed command and its skill/user context, never {@code null} + * @return environment variables for this command only; {@code null} or empty for none + * @throws SkillCredentialException when credentials are missing or the invocation must not run + */ + Map resolve(SkillInvocation invocation); +} diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillInvocation.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillInvocation.java new file mode 100644 index 0000000000..e1e0201a5e --- /dev/null +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillInvocation.java @@ -0,0 +1,57 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.skill.runtime; + +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.skill.AgentSkill; + +/** + * One shell command that the harness attributed to a skill, handed to a {@link + * SkillCredentialProvider} immediately before the command runs. + * + *

The attribution is path-based: a command is attributed to a skill when it references that + * skill's {@code } (the absolute root the agent is instructed to use for the skill's + * scripts). A command that references no skill root is not an invocation and never reaches the + * provider. + * + * @param skill the resolved skill; carries the frontmatter metadata (including any declared + * credential requirements and an optional declared version) plus the skill's source and id + * @param filesRoot the absolute skill root referenced by {@code command}; may be a sandbox path + * or a host path, matching the execution environment's shell + * @param command the command about to execute, after any {@code working_directory} prefixing and + * before any credential is injected; the host can inspect it to authorize the invocation + * @param runtimeContext per-call context carrying the authenticated user and session identity; may + * be {@code null} when the framework has no merged context + */ +public record SkillInvocation( + AgentSkill skill, String filesRoot, String command, RuntimeContext runtimeContext) { + + public SkillInvocation { + if (skill == null) { + throw new IllegalArgumentException("skill must not be null"); + } + } + + /** Returns the skill id, {@code name + "_" + source}, unique within the visible catalog. */ + public String skillId() { + return skill.getSkillId(); + } + + /** Returns the authenticated user id for this invocation, or {@code null} when unavailable. */ + public String userId() { + return runtimeContext != null ? runtimeContext.getUserId() : null; + } +} diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillRuntime.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillRuntime.java index aab1afb25e..a64c42216c 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillRuntime.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/runtime/SkillRuntime.java @@ -67,7 +67,13 @@ public SkillCatalog currentCatalog(RuntimeContext context) { return catalogFor(context); } - static SkillCatalog catalogFor(RuntimeContext context) { + /** + * Returns the catalog bound to {@code context}, or an empty catalog when none is bound. + * + *

Request-scoped lookup for code that has no {@link SkillRuntime} instance (for example the + * shell tool attributing a command to a skill). + */ + public static SkillCatalog catalogFor(RuntimeContext context) { if (context == null) { return SkillCatalog.empty(); } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/ShellExecuteTool.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/ShellExecuteTool.java index 248d3073c0..68fe55f0c7 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/ShellExecuteTool.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/tool/ShellExecuteTool.java @@ -29,9 +29,18 @@ import io.agentscope.harness.agent.filesystem.local.LocalFilesystemWithShell; import io.agentscope.harness.agent.filesystem.model.ExecuteResponse; import io.agentscope.harness.agent.filesystem.sandbox.AbstractSandboxFilesystem; +import io.agentscope.harness.agent.skill.runtime.HarnessSkillEntry; +import io.agentscope.harness.agent.skill.runtime.SkillCatalog; +import io.agentscope.harness.agent.skill.runtime.SkillCredentialException; +import io.agentscope.harness.agent.skill.runtime.SkillCredentialProvider; +import io.agentscope.harness.agent.skill.runtime.SkillInvocation; +import io.agentscope.harness.agent.skill.runtime.SkillRuntime; import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; /** * Shell execution tool backed by a {@link AbstractSandboxFilesystem}. @@ -44,9 +53,21 @@ public class ShellExecuteTool { public static final String NAME = "execute"; private final AbstractSandboxFilesystem sandbox; + private final SkillCredentialProvider credentialProvider; public ShellExecuteTool(AbstractSandboxFilesystem sandbox) { + this(sandbox, null); + } + + /** + * @param sandbox shell-capable filesystem + * @param credentialProvider optional per-invocation credential hook; {@code null} disables + * credential resolution and every command runs unchanged + */ + public ShellExecuteTool( + AbstractSandboxFilesystem sandbox, SkillCredentialProvider credentialProvider) { this.sandbox = sandbox; + this.credentialProvider = credentialProvider; } /** @@ -101,7 +122,44 @@ public ToolResultBlock execute( .withMetadata(ToolErrorMetadata.of(ToolErrorKind.INVALID_ARGUMENT)); } int timeoutSeconds = timeout != null ? timeout : 30; - ExecuteResponse result = sandbox.execute(runtimeContext, effectiveCommand, timeoutSeconds); + + Map skillEnvironment = Map.of(); + Optional attributedSkill = + attributedSkill(runtimeContext, effectiveCommand); + if (credentialProvider != null && attributedSkill.isPresent()) { + HarnessSkillEntry entry = attributedSkill.get(); + try { + skillEnvironment = + validateEnvironment( + credentialProvider.resolve( + new SkillInvocation( + entry.skill(), + entry.filesRoot(), + effectiveCommand, + runtimeContext))); + } catch (RuntimeException e) { + // Includes SkillCredentialException: the command must not run and the agent gets + // the reason instead of a partially configured environment. + return credentialError(entry.skill().getName(), e.getMessage()); + } + } + + ExecuteResponse result; + try { + result = + skillEnvironment.isEmpty() + ? sandbox.execute(runtimeContext, effectiveCommand, timeoutSeconds) + : sandbox.execute( + runtimeContext, + effectiveCommand, + timeoutSeconds, + skillEnvironment); + } catch (UnsupportedOperationException e) { + return ToolResultBlock.error( + "Cannot run this command: the configured execution environment does" + + " not support per-invocation skill credentials.") + .withMetadata(ToolErrorMetadata.of(ToolErrorKind.UNSUPPORTED)); + } StringBuilder sb = new StringBuilder(); sb.append("Exit code: ").append(result.exitCode()).append("\n"); @@ -153,6 +211,60 @@ public ToolResultBlock execute( kind, executableScope(command), kind == ToolErrorKind.TIMEOUT)); } + /** + * Attributes a command to the skill whose {@code } it references. Only the current + * call's filtered catalog is consulted, so skills invisible to this caller can never trigger a + * credential lookup. + */ + private static Optional attributedSkill( + RuntimeContext runtimeContext, String command) { + if (runtimeContext == null) { + return Optional.empty(); + } + SkillCatalog catalog = SkillRuntime.catalogFor(runtimeContext); + return catalog.matchCommand(command); + } + + /** + * Rejects malformed provider output before any value reaches a process environment. Messages + * deliberately name neither variables nor values. + */ + private static Map validateEnvironment(Map resolved) { + if (resolved == null || resolved.isEmpty()) { + return Map.of(); + } + Map environment = new LinkedHashMap<>(); + for (Map.Entry variable : resolved.entrySet()) { + String name = variable.getKey(); + if (name == null || !name.matches("[A-Za-z_][A-Za-z0-9_]*")) { + throw new SkillCredentialException( + "the credential provider returned an invalid environment variable name"); + } + if (variable.getValue() == null) { + throw new SkillCredentialException( + "the credential provider returned a null value for an environment" + + " variable"); + } + environment.put(name, variable.getValue()); + } + return Collections.unmodifiableMap(environment); + } + + private static ToolResultBlock credentialError(String skillName, String reason) { + String detail = + reason == null || reason.isBlank() + ? "no credentials are configured for the current caller." + : reason; + return ToolResultBlock.error( + "Cannot run this command: credentials for skill '" + + skillName + + "' are unavailable. " + + detail + + " Do not retry the command; ask the user to provide or refresh" + + " the credentials for this skill.") + .withMetadata(ToolErrorMetadata.of(ToolErrorKind.CONFIGURATION_ERROR)); + } + /** * Best-effort failure classification, not a shell parser or a security boundary. Recognizes * simple cd/assignment/launcher prefixes; ambiguous shell syntax has no scope. diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShellTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShellTest.java index 8b07a2a395..8b27933240 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShellTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShellTest.java @@ -47,6 +47,7 @@ import java.util.Arrays; import java.util.HexFormat; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -80,6 +81,25 @@ void outputCharset_fallsBackToDefaultWhenWindowsNativeEncodingIsUnavailable() { LocalFilesystemWithShell.outputCharset("Windows 10", null)); } + @Test + void execute_invocationEnvironmentIsScopedToThatCommand(@TempDir Path tempDir) { + LocalFilesystemWithShell fs = new LocalFilesystemWithShell(tempDir); + String readValue = isWindows() ? "echo %AS_TEST_TOKEN%" : "printf '%s' \"$AS_TEST_TOKEN\""; + String readPresence = + isWindows() + ? "if defined AS_TEST_TOKEN (echo set) else (echo unset)" + : "printf '%s' \"${AS_TEST_TOKEN:-unset}\""; + + ExecuteResponse withEnvironment = + fs.execute(null, readValue, 30, Map.of("AS_TEST_TOKEN", "one-shot")); + ExecuteResponse withoutEnvironment = fs.execute(null, readPresence, 30); + + assertEquals("one-shot", withEnvironment.output().strip()); + assertTrue( + withoutEnvironment.output().contains("unset"), + "the value must not leak into a later command: " + withoutEnvironment.output()); + } + @Test void execute_outputLargerThanOsPipeBufferCompletesWithoutDeadlock(@TempDir Path tempDir) { // ~68-72 KB of stdout: beyond the OS pipe buffer (~4 KB on Windows, 64 KB on Linux), diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/SandboxEnvironmentTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/SandboxEnvironmentTest.java new file mode 100644 index 0000000000..11b0802ba0 --- /dev/null +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/SandboxEnvironmentTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.sandbox; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** POSIX shell fallback used by sandbox backends without a native per-command environment. */ +class SandboxEnvironmentTest { + + @Test + void wrapperAppliesValueToWholeCompoundCommandAndPreservesQuotes() throws Exception { + // The wrapper is only used by POSIX sandbox backends; Windows local shell uses the native + // process environment instead. + assumeFalse(System.getProperty("os.name").toLowerCase().contains("win")); + String command = "printf '%s\\n' \"$AS_TEST_TOKEN\" && printf '%s\\n' \"$AS_TEST_TOKEN\""; + String wrapped = + SandboxEnvironment.commandWithEnvironment( + command, Map.of("AS_TEST_TOKEN", "a'b c $d `e`")); + + Process process = new ProcessBuilder("sh", "-c", wrapped).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + + assertEquals(0, process.waitFor(), output); + assertEquals("a'b c $d `e`\na'b c $d `e`\n", output); + } + + @Test + void rejectsInvalidVariableNames() { + assertThrows( + IllegalArgumentException.class, + () -> + SandboxEnvironment.commandWithEnvironment( + "echo hi", Map.of("BAD-NAME", "value"))); + assertThrows( + IllegalArgumentException.class, + () -> + SandboxEnvironment.commandWithEnvironment( + "echo hi", Map.of("1BAD", "value"))); + } + + @Test + void rejectsNullValues() { + Map environment = new HashMap<>(); + environment.put("AS_TEST_TOKEN", null); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> SandboxEnvironment.commandWithEnvironment("echo hi", environment)); + assertTrue(error.getMessage().contains("AS_TEST_TOKEN")); + } +} diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxRunCommandTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxRunCommandTest.java index 818fe8ff6b..9db2939486 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxRunCommandTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/sandbox/impl/docker/DockerSandboxRunCommandTest.java @@ -22,6 +22,7 @@ import io.agentscope.harness.agent.sandbox.WorkspaceSpec; import java.lang.reflect.Method; import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; /** @@ -111,6 +112,40 @@ void runCommandStartsWithDetachedNamedRun() throws Exception { assertEquals("ubuntu:22.04", cmd.get(cmd.size() - 4)); } + @Test + void execCommandPassesPerInvocationEnvironmentNatively() { + List cmd = + DockerSandbox.dockerExecCommand( + "container-1", "/workspace", "echo hi", Map.of("AS_TEST_TOKEN", "secret")); + + // Only the variable name is on the command line; docker reads the value from its own + // process environment, so the secret never appears in argv or the command text. + assertEquals( + List.of( + "docker", + "exec", + "-w", + "/workspace", + "-e", + "AS_TEST_TOKEN", + "container-1", + "sh", + "-c", + "echo hi"), + cmd); + assertFalse(cmd.toString().contains("secret"), "the value must not appear in argv"); + } + + @Test + void execCommandOmitsEnvironmentOptionsWhenNoEnvironmentIsGiven() { + List cmd = + DockerSandbox.dockerExecCommand("container-1", "/workspace", "echo hi", Map.of()); + + assertEquals( + List.of("docker", "exec", "-w", "/workspace", "container-1", "sh", "-c", "echo hi"), + cmd); + } + @Test void hydrateCommandPreservesArchivePermissions() { DockerSandbox sandbox = new DockerSandbox(minimalState()); diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/ShellExecuteToolSkillCredentialTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/ShellExecuteToolSkillCredentialTest.java new file mode 100644 index 0000000000..0ea37a72b9 --- /dev/null +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/tool/ShellExecuteToolSkillCredentialTest.java @@ -0,0 +1,309 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.tool; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.message.TextBlock; +import io.agentscope.core.message.ToolResultBlock; +import io.agentscope.core.message.ToolResultState; +import io.agentscope.core.skill.AgentSkill; +import io.agentscope.harness.agent.filesystem.local.LocalFilesystemWithShell; +import io.agentscope.harness.agent.filesystem.model.ExecuteResponse; +import io.agentscope.harness.agent.skill.runtime.HarnessSkillEntry; +import io.agentscope.harness.agent.skill.runtime.SkillCatalog; +import io.agentscope.harness.agent.skill.runtime.SkillCredentialException; +import io.agentscope.harness.agent.skill.runtime.SkillCredentialProvider; +import io.agentscope.harness.agent.skill.runtime.SkillInvocation; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Per-invocation skill credential hook at the {@link ShellExecuteTool} boundary. */ +class ShellExecuteToolSkillCredentialTest { + + private static final String SKILL_ROOT = "/workspace/skills/code-reviewer"; + + @TempDir Path tempDir; + + private RecordingShellFilesystem sandbox; + private final AtomicReference lastInvocation = new AtomicReference<>(); + + @BeforeEach + void setUp() { + sandbox = new RecordingShellFilesystem(tempDir); + } + + private static String textOf(ToolResultBlock result) { + return result.getOutput().stream() + .filter(block -> block instanceof TextBlock) + .map(block -> ((TextBlock) block).getText()) + .collect(Collectors.joining()); + } + + private static HarnessSkillEntry entry(String name, String filesRoot) { + AgentSkill skill = new AgentSkill(name, "description of " + name, "instructions", Map.of()); + return new HarnessSkillEntry(skill, null, filesRoot); + } + + private static RuntimeContext contextWith(HarnessSkillEntry... entries) { + RuntimeContext context = RuntimeContext.builder().userId("alice").sessionId("s1").build(); + context.put(SkillCatalog.class, SkillCatalog.of(List.of(entries))); + return context; + } + + @Test + void commandReferencingSkillRootResolvesAndInjectsEnvironment() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + SkillCredentialProvider provider = + invocation -> { + lastInvocation.set(invocation); + return Map.of("GITHUB_TOKEN", "user-token"); + }; + + ToolResultBlock result = + new ShellExecuteTool(sandbox, provider) + .execute( + context, + "sh '" + SKILL_ROOT + "/scripts/run.sh' target", + null, + null); + + assertEquals(ToolResultState.SUCCESS, result.getState()); + assertEquals(1, sandbox.extendedCalls); + assertEquals(0, sandbox.plainCalls); + assertEquals("sh '" + SKILL_ROOT + "/scripts/run.sh' target", sandbox.command); + assertEquals(Map.of("GITHUB_TOKEN", "user-token"), sandbox.environment); + + SkillInvocation invocation = lastInvocation.get(); + assertNotNull(invocation); + assertEquals("code-reviewer", invocation.skill().getName()); + assertEquals("code-reviewer_custom", invocation.skillId()); + assertEquals(SKILL_ROOT, invocation.filesRoot()); + assertEquals("alice", invocation.userId()); + assertSame(context, invocation.runtimeContext()); + } + + @Test + void commandNotReferencingSkillRootDoesNotResolveCredentials() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + AtomicInteger resolutions = new AtomicInteger(); + SkillCredentialProvider provider = + invocation -> { + resolutions.incrementAndGet(); + return Map.of("GITHUB_TOKEN", "user-token"); + }; + + ToolResultBlock result = + new ShellExecuteTool(sandbox, provider).execute(context, "ls -la", null, null); + + assertEquals(ToolResultState.SUCCESS, result.getState()); + assertEquals(0, resolutions.get()); + assertEquals(0, sandbox.extendedCalls); + assertEquals(1, sandbox.plainCalls); + assertNull(sandbox.environment); + } + + @Test + void missingCredentialsReturnToolErrorAndNeverRunTheCommand() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + SkillCredentialProvider provider = + invocation -> { + throw new SkillCredentialException( + "Connect your GitHub account before using this skill."); + }; + + ToolResultBlock result = + new ShellExecuteTool(sandbox, provider) + .execute(context, "sh '" + SKILL_ROOT + "/scripts/run.sh'", null, null); + + assertEquals(ToolResultState.ERROR, result.getState()); + String text = textOf(result); + assertTrue(text.contains("code-reviewer"), text); + assertTrue(text.contains("Connect your GitHub account"), text); + assertTrue(text.contains("Do not retry"), text); + assertEquals(0, sandbox.plainCalls); + assertEquals(0, sandbox.extendedCalls); + } + + @Test + void unexpectedProviderFailureReturnsToolErrorAndNeverRunTheCommand() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + SkillCredentialProvider provider = + invocation -> { + throw new IllegalStateException("credential store unavailable"); + }; + + ToolResultBlock result = + new ShellExecuteTool(sandbox, provider) + .execute(context, "sh '" + SKILL_ROOT + "/scripts/run.sh'", null, null); + + assertEquals(ToolResultState.ERROR, result.getState()); + assertTrue(textOf(result).contains("credential store unavailable")); + assertEquals(0, sandbox.plainCalls); + assertEquals(0, sandbox.extendedCalls); + } + + @Test + void malformedEnvironmentIsRejectedBeforeExecution() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + SkillCredentialProvider invalidName = invocation -> Map.of("BAD-NAME", "value"); + SkillCredentialProvider nullValue = + invocation -> { + Map environment = new java.util.HashMap<>(); + environment.put("GITHUB_TOKEN", null); + return environment; + }; + + ToolResultBlock invalidNameResult = + new ShellExecuteTool(sandbox, invalidName) + .execute(context, "sh '" + SKILL_ROOT + "/scripts/run.sh'", null, null); + ToolResultBlock nullValueResult = + new ShellExecuteTool(sandbox, nullValue) + .execute(context, "sh '" + SKILL_ROOT + "/scripts/run.sh'", null, null); + + assertEquals(ToolResultState.ERROR, invalidNameResult.getState()); + assertTrue(textOf(invalidNameResult).contains("invalid environment variable name")); + assertEquals(ToolResultState.ERROR, nullValueResult.getState()); + assertTrue(textOf(nullValueResult).contains("null value")); + assertEquals(0, sandbox.plainCalls); + assertEquals(0, sandbox.extendedCalls); + } + + @Test + void longestMatchingSkillRootWins() { + RuntimeContext context = + contextWith( + entry("x", "/workspace/skills/x"), + entry("x-extra", "/workspace/skills/x-extra")); + SkillCredentialProvider provider = + invocation -> { + lastInvocation.set(invocation); + return Map.of("TOKEN", "value"); + }; + + ToolResultBlock result = + new ShellExecuteTool(sandbox, provider) + .execute( + context, "sh /workspace/skills/x-extra/scripts/run.sh", null, null); + + assertEquals(ToolResultState.SUCCESS, result.getState()); + assertEquals("x-extra", lastInvocation.get().skill().getName()); + assertEquals("/workspace/skills/x-extra", lastInvocation.get().filesRoot()); + } + + @Test + void workingDirectoryPrefixStillAttributesTheSkill() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + SkillCredentialProvider provider = invocation -> Map.of("TOKEN", "value"); + + ToolResultBlock result = + new ShellExecuteTool(sandbox, provider) + .execute(context, "sh '" + SKILL_ROOT + "/scripts/run.sh'", "sub", null); + + assertEquals(ToolResultState.SUCCESS, result.getState()); + assertTrue(sandbox.command.startsWith("cd "), sandbox.command); + assertTrue( + sandbox.command.endsWith("sh '" + SKILL_ROOT + "/scripts/run.sh'"), + sandbox.command); + assertEquals(1, sandbox.extendedCalls); + } + + @Test + void workspaceRelativeSpellingOfTheSkillRootStillAttributesTheSkill() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + SkillCredentialProvider provider = invocation -> Map.of("TOKEN", "value"); + + ToolResultBlock relativePath = + new ShellExecuteTool(sandbox, provider) + .execute(context, "sh skills/code-reviewer/scripts/run.sh", null, null); + ToolResultBlock workingDirectory = + new ShellExecuteTool(sandbox, provider) + .execute(context, "./scripts/run.sh", "skills/code-reviewer", null); + + assertEquals(ToolResultState.SUCCESS, relativePath.getState()); + assertEquals(ToolResultState.SUCCESS, workingDirectory.getState()); + assertEquals( + ShellExecuteTool.commandWithWorkingDirectory( + "skills/code-reviewer", "./scripts/run.sh", isWindowsHost()), + sandbox.command); + assertEquals(2, sandbox.extendedCalls); + } + + private static boolean isWindowsHost() { + return System.getProperty("os.name").toLowerCase().contains("win"); + } + + @Test + void noProviderKeepsPlainExecutionEvenForSkillCommands() { + RuntimeContext context = contextWith(entry("code-reviewer", SKILL_ROOT)); + + ToolResultBlock result = + new ShellExecuteTool(sandbox) + .execute(context, "sh '" + SKILL_ROOT + "/scripts/run.sh'", null, null); + + assertEquals(ToolResultState.SUCCESS, result.getState()); + assertEquals(1, sandbox.plainCalls); + assertEquals(0, sandbox.extendedCalls); + } + + private static final class RecordingShellFilesystem extends LocalFilesystemWithShell { + + private String command; + private Integer timeoutSeconds; + private Map environment; + private int plainCalls; + private int extendedCalls; + private ExecuteResponse response = new ExecuteResponse("ok", 0, false); + + private RecordingShellFilesystem(Path root) { + super(root); + } + + @Override + public ExecuteResponse execute( + RuntimeContext runtimeContext, String command, Integer timeoutSeconds) { + plainCalls++; + this.command = command; + this.timeoutSeconds = timeoutSeconds; + return response; + } + + @Override + public ExecuteResponse execute( + RuntimeContext runtimeContext, + String command, + Integer timeoutSeconds, + Map environment) { + extendedCalls++; + this.command = command; + this.timeoutSeconds = timeoutSeconds; + this.environment = environment; + return response; + } + } +} diff --git a/docs/v2/en/docs/harness/skill.md b/docs/v2/en/docs/harness/skill.md index 4e6b9ed8c1..198d796f22 100644 --- a/docs/v2/en/docs/harness/skill.md +++ b/docs/v2/en/docs/harness/skill.md @@ -202,8 +202,9 @@ Example: the team Git has a generic `code-reviewer`; the project's `workspace/sk | `skillRepositories(list)` | Replace all marketplaces at once | | `projectGlobalSkillsDir(path)` | Enable the project-global dir; skipped if missing | | `disableDynamicSkills()` | Turn off "re-merge before each reasoning"; merge once at build | +| `skillCredentialProvider(provider)` | Per-invocation credential hook for shared skills; see [Per-user credentials](#per-user-credentials-for-shared-skills) | -Subagents inherit the parent's marketplaces and project-global dir automatically. +Subagents inherit the parent's marketplaces, project-global dir and credential provider automatically. When to use `disableDynamicSkills()`: one-shot tasks; or slow marketplace stores you don't want to refetch per turn. Usually don't touch it. @@ -397,6 +398,36 @@ If a script installs dependencies or generates artifacts (`npm install`, `pip in A common point of confusion: **reading** a skill (`load_skill_through_path` fetching `SKILL.md` / `references/`) goes through memory or the host filesystem and has nothing to do with the sandbox; only **running scripts via shell** requires the files to actually be inside the container. So even with projection disabled, or for a skill that ships no scripts at all, the agent can still read its instructions and reference material normally. +## Per-user credentials for shared skills + +One shared skill package can serve many users, but a skill that calls an external service usually needs the caller's own API key. Keep values out of the package and out of the workspace: store them in the host (encrypted, keyed by the trusted user plus skill identity, and optionally the skill version), authorize the call, and hand them to the framework only for the one command that needs them. + +`skillCredentialProvider(...)` installs a `SkillCredentialProvider`. On each `execute` call harness checks whether the command references a visible skill's `` (absolute or workspace-relative); if it does, the provider is called once immediately before execution: + +```java +HarnessAgent agent = HarnessAgent.builder() + .skillRepository(new GitSkillRepository("https://github.com/your-org/team-skills.git")) + .skillCredentialProvider(invocation -> { + // invocation.userId() authenticated caller (from RuntimeContext, not client input) + // invocation.skill() resolved skill: name, source, id, frontmatter metadata + // invocation.filesRoot() skill root the command references + // invocation.command() the command about to run + return skillSecrets.resolve(invocation.userId(), invocation.skill().getSkillId()); + }) + .build(); +``` + +- Return a map of environment variable names to values. It applies to that command only: it is never written to the skill directory, workspace, marketplace cache, snapshot, prompt, tool arguments/results or agent state, and the next command starts without it. +- `null` or empty returns nothing. Commands that reference no skill root never call the provider, and the provider is optional. +- Throw `SkillCredentialException` when the caller has not supplied the credential or may not use it. The command then does not run and the agent receives the message as a tool error, so a command is never executed with partial or stale credentials. Never put a credential value in that message. +- Subagents inherit the provider. + +Injection is native where the backend supports it — Docker (`docker exec -e`), `LocalFilesystemWithShell`, and the durable local sandbox (process environment). Other sandbox backends inherit a one-shot shell `env` prefix, so values can appear in that backend's command text and logs; prefer a native backend for high-value secrets, or override `Sandbox.exec(..., environment)` in a custom backend. + +A shared skill may declare credential *requirements* in its frontmatter (names, descriptions, required flags, version) and the provider reads them from `invocation.skill().getMetadata()`. The package must never contain values or shared defaults. + +> **Trust boundary.** Per-user isolation keeps one caller from resolving another caller's row, but a skill authorized to receive a key can read and potentially exfiltrate it. Skill review, sandbox permissions, network egress policy and least-privilege tokens remain necessary. Do not automatically replay a command whose external side effects are uncertain. + ## Tips **`description` decides whether the agent uses your skill.** The agent only sees name + description initially and decides whether to load details. "Data-analysis tool" is much less useful than "Use when the user asks for stats, reports, or trend charts". diff --git a/docs/v2/zh/docs/harness/skill.md b/docs/v2/zh/docs/harness/skill.md index d58f82144e..69c8d71ece 100644 --- a/docs/v2/zh/docs/harness/skill.md +++ b/docs/v2/zh/docs/harness/skill.md @@ -202,8 +202,9 @@ workspace/ | `skillRepositories(list)` | 一次性替换所有市场 | | `projectGlobalSkillsDir(path)` | 启用项目全局目录;目录不存在则跳过 | | `disableDynamicSkills()` | 关掉"每次推理前重新合并",改成 build 时合并一次 | +| `skillCredentialProvider(provider)` | 共享 skill 的单次调用凭证钩子,见[按用户下发凭证](#共享-skill-的按用户凭证) | -子 agent 自动继承父的市场列表和项目全局目录,不用重复配。 +子 agent 自动继承父的市场列表、项目全局目录和凭证钩子,不用重复配。 什么时候用 `disableDynamicSkills()`:单次任务,跑完就退出;或市场后端慢、不想每轮拉。平时不用动这个开关。 @@ -397,6 +398,36 @@ execute_shell_command("python3 /workspace/skills/code-reviewer/scripts/run-check 容易混淆的一点:**读** skill(`load_skill_through_path` 取 `SKILL.md` / `references/`)走的是内存或宿主文件系统,跟沙箱无关;只有**用 shell 跑脚本**才需要文件真的进到容器里。所以即便关了投影、或某个 skill 根本没带脚本,agent 依然能正常读它的说明和参考资料。 +## 共享 skill 的按用户凭证 + +一个共享 skill 包可以服务很多用户,但调用外部服务的 skill 通常需要每个用户自己的 API Key。凭证值不要放进 skill 包,也不要写进工作区:由宿主持有(加密存储,按可信用户 + skill 标识、可选再加 skill 版本作为键),先做授权,再只把值交给真正需要它的那一条命令。 + +`skillCredentialProvider(...)` 用来安装一个 `SkillCredentialProvider`。每次 `execute` 调用时,harness 会判断命令是否引用了某个可见 skill 的 ``(绝对路径或工作区相对路径);如果引用了,就在执行前调用一次 provider: + +```java +HarnessAgent agent = HarnessAgent.builder() + .skillRepository(new GitSkillRepository("https://github.com/your-org/team-skills.git")) + .skillCredentialProvider(invocation -> { + // invocation.userId() 已认证的调用者(来自 RuntimeContext,不是客户端传入) + // invocation.skill() 解析后的 skill:name、source、id、frontmatter 元数据 + // invocation.filesRoot() 命令引用的 skill 根目录 + // invocation.command() 即将执行的命令 + return skillSecrets.resolve(invocation.userId(), invocation.skill().getSkillId()); + }) + .build(); +``` + +- 返回"环境变量名 → 值"的 Map,只作用于这一条命令:不会写入 skill 目录、工作区、市场缓存、快照、prompt、工具参数/结果或 agent state,下一条命令也看不到它。 +- 返回 `null` 或空 Map 表示不注入。没有引用任何 skill 根目录的命令不会调用 provider;不配置 provider 也完全可用。 +- 调用者没提供凭证、或无权使用该凭证时,抛 `SkillCredentialException`。这时命令不会执行,agent 会把异常信息当作工具错误收到,从而避免带着残缺或过期凭证跑命令。异常信息里绝不能出现凭证值。 +- 子 agent 自动继承该 provider。 + +支持的执行后端会原生注入:Docker(`docker exec -e`)、`LocalFilesystemWithShell` 以及 durable local sandbox(进程环境变量)。其他沙箱后端会退化为一次性的 shell `env` 前缀,值可能出现在该后端的命令文本和日志里;处理高价值凭证时优先用原生支持的后端,或在自定义后端里覆写 `Sandbox.exec(..., environment)`。 + +共享 skill 可以在 frontmatter 里声明凭证**需求**(变量名、说明、是否必填、版本),provider 通过 `invocation.skill().getMetadata()` 读取。skill 包里绝不能出现凭证值或共享默认值。 + +> **信任边界。** 按用户隔离只能防止一个调用者读到另一个调用者的记录;一旦某个 skill 被授权拿到 key,它的代码就能读取甚至外泄这个 key。skill 审核、沙箱权限、网络出口策略和最小权限 token 依然必要。外部副作用不确定的命令不要自动重放。 + ## 一些建议 **`description` 决定 agent 用不用这个 skill。** agent 一开始只看得到 name 和 description,觉得相关才会 load 详情。写"数据分析工具"远不如写"当用户要算统计、出报表、做趋势图时使用"有效。