Skip to content

Commit b27e636

Browse files
committed
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 <files-root>; 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
1 parent 5a90f36 commit b27e636

25 files changed

Lines changed: 1191 additions & 15 deletions

File tree

‎agentscope-extensions/agentscope-extensions-durable-sandbox/src/main/java/io/agentscope/extensions/durable/sandbox/LocalSandboxClient.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,16 @@ public SandboxState getState() {
261261
@Override
262262
public ExecResult exec(RuntimeContext context, String command, Integer timeoutSeconds)
263263
throws Exception {
264+
return exec(context, command, timeoutSeconds, Map.of());
265+
}
266+
267+
@Override
268+
public ExecResult exec(
269+
RuntimeContext context,
270+
String command,
271+
Integer timeoutSeconds,
272+
Map<String, String> environment)
273+
throws Exception {
264274
requireDirectory();
265275
int timeout = timeoutSeconds == null ? 30 : timeoutSeconds;
266276
if (timeout < 1)
@@ -275,6 +285,7 @@ public ExecResult exec(RuntimeContext context, String command, Integer timeoutSe
275285
.redirectOutput(output.toFile())
276286
.redirectError(errors.toFile());
277287
builder.environment().putAll(state.environment);
288+
if (environment != null) builder.environment().putAll(environment);
278289
process = builder.start();
279290
process.getOutputStream().close();
280291
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout);

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@
124124
import io.agentscope.harness.agent.skill.curator.SkillUsageStore;
125125
import io.agentscope.harness.agent.skill.curator.SkillVisibilityFilter;
126126
import io.agentscope.harness.agent.skill.runtime.ShellPathPolicy;
127+
import io.agentscope.harness.agent.skill.runtime.SkillCredentialException;
128+
import io.agentscope.harness.agent.skill.runtime.SkillCredentialProvider;
127129
import io.agentscope.harness.agent.subagent.DefaultAgentManager;
128130
import io.agentscope.harness.agent.subagent.SubagentDeclaration;
129131
import io.agentscope.harness.agent.subagent.SubagentExecution;
@@ -1471,6 +1473,7 @@ public Builder threadJournalStore(ThreadJournalStore store) {
14711473
String agentId;
14721474
final List<AgentSkillRepository> skillRepositories = new ArrayList<>();
14731475
Path projectGlobalSkillsDir;
1476+
SkillCredentialProvider skillCredentialProvider;
14741477

14751478
Path workspace;
14761479
String environmentMemory;
@@ -2156,6 +2159,27 @@ public Builder projectGlobalSkillsDir(Path projectGlobalSkillsDir) {
21562159
return this;
21572160
}
21582161

2162+
/**
2163+
* Installs a per-invocation credential hook for skills.
2164+
*
2165+
* <p>The provider is consulted immediately before each shell command that references a
2166+
* visible skill's {@code <files-root>}, receives the authenticated user and the selected
2167+
* skill, and returns the environment variables to expose to that one command. The framework
2168+
* stores, logs and persists nothing; the host keeps user authorization, encrypted storage,
2169+
* missing-credential flows and redaction. Commands that reference no skill root run
2170+
* unchanged. When the provider throws {@link SkillCredentialException}, the command is not
2171+
* executed and the agent receives the reason as a tool error.
2172+
*
2173+
* <p>Subagents inherit the provider. See {@link SkillCredentialProvider} for the contract
2174+
* and the trust boundary.
2175+
*
2176+
* @param provider the hook, or {@code null} to disable credential resolution
2177+
*/
2178+
public Builder skillCredentialProvider(SkillCredentialProvider provider) {
2179+
this.skillCredentialProvider = provider;
2180+
return this;
2181+
}
2182+
21592183
/**
21602184
* Sets the workspace directory. Pass {@code null} to use the default
21612185
* {@code ${cwd}/.agentscope/workspace}.
@@ -3263,7 +3287,7 @@ && isLocalSession(effectiveSession)) {
32633287
if (!disableShellTool
32643288
&& FilesystemUtils.primaryBackend(filesystem)
32653289
instanceof AbstractSandboxFilesystem sandbox) {
3266-
agentToolkit.registerTool(new ShellExecuteTool(sandbox));
3290+
agentToolkit.registerTool(new ShellExecuteTool(sandbox, skillCredentialProvider));
32673291
}
32683292
if (!disableWebTools) {
32693293
if (webHttpClient != null) {

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgentBuilderSupport.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import io.agentscope.harness.agent.middleware.DynamicSubagentsMiddleware;
4242
import io.agentscope.harness.agent.middleware.SubagentEntry;
4343
import io.agentscope.harness.agent.middleware.SubagentsMiddleware;
44+
import io.agentscope.harness.agent.skill.runtime.SkillCredentialProvider;
4445
import io.agentscope.harness.agent.subagent.AgentSpecLoader;
4546
import io.agentscope.harness.agent.subagent.DefaultAgentManager;
4647
import io.agentscope.harness.agent.subagent.SubagentDeclaration;
@@ -335,6 +336,7 @@ static SubagentFactory buildGeneralPurposeFactory(
335336
final List<MiddlewareBase> capturedMiddlewares = List.copyOf(b.middlewares);
336337
final List<AgentSkillRepository> capturedSkillRepos = List.copyOf(b.skillRepositories);
337338
final Path capturedProjectGlobalSkillsDir = b.projectGlobalSkillsDir;
339+
final SkillCredentialProvider capturedSkillCredentialProvider = b.skillCredentialProvider;
338340
final boolean capturedDisableFilesystemTools = b.disableFilesystemTools;
339341
final int capturedReadFileMaxChars = b.readFileMaxChars;
340342
final boolean capturedDisableShellTool = b.disableShellTool;
@@ -414,6 +416,9 @@ static SubagentFactory buildGeneralPurposeFactory(
414416
if (capturedProjectGlobalSkillsDir != null) {
415417
sub.projectGlobalSkillsDir(capturedProjectGlobalSkillsDir);
416418
}
419+
if (capturedSkillCredentialProvider != null) {
420+
sub.skillCredentialProvider(capturedSkillCredentialProvider);
421+
}
417422
if (capturedBackend != null) sub.abstractFilesystem(capturedBackend);
418423
capturedJournal.accept(sub);
419424
if (capturedStateStore != null) sub.stateStore(capturedStateStore);
@@ -494,6 +499,7 @@ static SubagentFactory buildDeclaredFactory(
494499
capturedLocalFilesystemSpec = b.localFilesystemSpec;
495500
final List<AgentSkillRepository> capturedSkillRepos = List.copyOf(b.skillRepositories);
496501
final Path capturedProjectGlobalSkillsDir = b.projectGlobalSkillsDir;
502+
final SkillCredentialProvider capturedSkillCredentialProvider = b.skillCredentialProvider;
497503
final CompactionConfig capturedCompactionConfig = b.compactionConfig;
498504
final boolean capturedDisableCompaction = b.disableCompaction;
499505
final boolean capturedDisableRepeatedFailureGuard = b.disableRepeatedFailureGuard;
@@ -606,6 +612,9 @@ static SubagentFactory buildDeclaredFactory(
606612
if (capturedProjectGlobalSkillsDir != null) {
607613
sub.projectGlobalSkillsDir(capturedProjectGlobalSkillsDir);
608614
}
615+
if (capturedSkillCredentialProvider != null) {
616+
sub.skillCredentialProvider(capturedSkillCredentialProvider);
617+
}
609618

610619
if (capturedPermissions != null) sub.permissionContext(capturedPermissions);
611620
if (capturedDisableDefaultSkills) sub.disableDefaultWorkspaceSkills();

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/OverlayFilesystem.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,15 @@ public ExecuteResponse execute(
138138
RuntimeContext runtimeContext, String command, Integer timeoutSeconds) {
139139
return shellBackend.execute(runtimeContext, command, timeoutSeconds);
140140
}
141+
142+
@Override
143+
public ExecuteResponse execute(
144+
RuntimeContext runtimeContext,
145+
String command,
146+
Integer timeoutSeconds,
147+
Map<String, String> environment) {
148+
return shellBackend.execute(runtimeContext, command, timeoutSeconds, environment);
149+
}
141150
}
142151

143152
@Override

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/ProjectAwareOverlay.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,15 @@ public ExecuteResponse execute(
128128
return shellBackend.execute(runtimeContext, command, timeoutSeconds);
129129
}
130130

131+
@Override
132+
public ExecuteResponse execute(
133+
RuntimeContext runtimeContext,
134+
String command,
135+
Integer timeoutSeconds,
136+
Map<String, String> environment) {
137+
return shellBackend.execute(runtimeContext, command, timeoutSeconds, environment);
138+
}
139+
131140
// ==================== Write routing ====================
132141

133142
@Override

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/RoutedSandboxFilesystem.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,15 @@ public ExecuteResponse execute(
7474
return primary.execute(runtimeContext, command, timeoutSeconds);
7575
}
7676

77+
@Override
78+
public ExecuteResponse execute(
79+
RuntimeContext runtimeContext,
80+
String command,
81+
Integer timeoutSeconds,
82+
Map<String, String> environment) {
83+
return primary.execute(runtimeContext, command, timeoutSeconds, environment);
84+
}
85+
7786
@Override
7887
public AtomicJournalStorage journalStorage(RuntimeContext runtimeContext) {
7988
return composite.journalStorage(runtimeContext);

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/local/LocalFilesystemWithShell.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,29 @@ public Path getShellCwd() {
334334
@Override
335335
public ExecuteResponse execute(
336336
RuntimeContext runtimeContext, String command, Integer timeoutSeconds) {
337+
return executeWithEnvironment(runtimeContext, command, timeoutSeconds, Map.of());
338+
}
339+
340+
/**
341+
* Executes with extra environment variables layered on top of the configured environment for
342+
* this process only. The host process environment is untouched, so a concurrent invocation
343+
* cannot observe another caller's variables.
344+
*/
345+
@Override
346+
public ExecuteResponse execute(
347+
RuntimeContext runtimeContext,
348+
String command,
349+
Integer timeoutSeconds,
350+
Map<String, String> invocationEnvironment) {
351+
return executeWithEnvironment(
352+
runtimeContext, command, timeoutSeconds, invocationEnvironment);
353+
}
354+
355+
private ExecuteResponse executeWithEnvironment(
356+
RuntimeContext runtimeContext,
357+
String command,
358+
Integer timeoutSeconds,
359+
Map<String, String> invocationEnvironment) {
337360
if (command == null || command.isBlank()) {
338361
return new ExecuteResponse("Error: Command must be a non-empty string.", 1, false);
339362
}
@@ -363,6 +386,9 @@ public ExecuteResponse execute(
363386
pb.environment().clear();
364387
pb.environment().putAll(env);
365388
}
389+
if (invocationEnvironment != null && !invocationEnvironment.isEmpty()) {
390+
pb.environment().putAll(invocationEnvironment);
391+
}
366392

367393
stdout = new StreamCapture(runtimeContext, false);
368394
stderr = new StreamCapture(runtimeContext, true);

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/AbstractSandboxFilesystem.java‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import io.agentscope.core.agent.RuntimeContext;
1919
import io.agentscope.harness.agent.filesystem.AbstractFilesystem;
2020
import io.agentscope.harness.agent.filesystem.model.ExecuteResponse;
21+
import java.util.Map;
2122

2223
/**
2324
* Filesystem abstraction that adds shell command execution (sandbox or remote host).
@@ -46,4 +47,39 @@ public interface AbstractSandboxFilesystem extends AbstractFilesystem {
4647
* command output
4748
*/
4849
ExecuteResponse execute(RuntimeContext runtimeContext, String command, Integer timeoutSeconds);
50+
51+
/**
52+
* Execute a shell command with a per-invocation environment.
53+
*
54+
* <p>The environment participates in this call only: implementations must not persist it into
55+
* the workspace, a snapshot, the sandbox configuration, or a later command. It is used by the
56+
* skill credential hook to scope a resolved secret to one skill invocation.
57+
*
58+
* <p>The default refuses a non-empty environment instead of silently dropping it, so a command
59+
* that needs credentials never runs with them missing. Implementations that support the channel
60+
* override this method; {@code null} or empty {@code environment} always falls back to {@link
61+
* #execute(RuntimeContext, String, Integer)}.
62+
*
63+
* @param runtimeContext per-call agent context; may be {@code null} when unavailable
64+
* @param command full shell command string to execute
65+
* @param timeoutSeconds maximum time in seconds to wait for the command to complete; {@code
66+
* null} uses the filesystem's default timeout
67+
* @param environment extra environment variables for this command only; {@code null} or empty
68+
* for none
69+
* @return the command result, with the same contract as {@link #execute(RuntimeContext,
70+
* String, Integer)}
71+
* @throws UnsupportedOperationException when the environment is non-empty and this filesystem
72+
* cannot scope it to one command
73+
*/
74+
default ExecuteResponse execute(
75+
RuntimeContext runtimeContext,
76+
String command,
77+
Integer timeoutSeconds,
78+
Map<String, String> environment) {
79+
if (environment == null || environment.isEmpty()) {
80+
return execute(runtimeContext, command, timeoutSeconds);
81+
}
82+
throw new UnsupportedOperationException(
83+
"Per-invocation environment is not supported by " + getClass().getName());
84+
}
4985
}

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/SandboxBackedFilesystem.java‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,18 @@ public String id() {
100100
@Override
101101
public ExecuteResponse execute(
102102
RuntimeContext runtimeContext, String command, Integer timeoutSeconds) {
103+
return execute(runtimeContext, command, timeoutSeconds, Map.of());
104+
}
105+
106+
@Override
107+
public ExecuteResponse execute(
108+
RuntimeContext runtimeContext,
109+
String command,
110+
Integer timeoutSeconds,
111+
Map<String, String> environment) {
103112
Sandbox active = requireSandbox(runtimeContext);
104113
try {
105-
ExecResult result = active.exec(runtimeContext, command, timeoutSeconds);
114+
ExecResult result = active.exec(runtimeContext, command, timeoutSeconds, environment);
106115
return new ExecuteResponse(
107116
result.combinedOutput(), result.exitCode(), result.truncated());
108117
} catch (SandboxException.ExecStatusUnknownException e) {
@@ -116,6 +125,10 @@ public ExecuteResponse execute(
116125
? "\n" + e.getStderr()
117126
: "");
118127
return new ExecuteResponse(combined, e.getExitCode(), false, e.isTimedOut());
128+
} catch (UnsupportedOperationException e) {
129+
// A backend without a per-command environment: let the caller report it precisely
130+
// instead of degrading to a generic sandbox error.
131+
throw e;
119132
} catch (Exception e) {
120133
log.error("[sandbox-fs] execute failed: {}", command, e);
121134
return new ExecuteResponse("Internal sandbox error: " + e.getMessage(), -1, false);

‎agentscope-harness/src/main/java/io/agentscope/harness/agent/sandbox/AbstractBaseSandbox.java‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.util.Comparator;
2424
import java.util.HashSet;
2525
import java.util.List;
26+
import java.util.Map;
2627
import java.util.Objects;
2728
import java.util.Optional;
2829
import java.util.Set;
@@ -195,6 +196,23 @@ public ExecResult exec(RuntimeContext runtimeContext, String command, Integer ti
195196
return doExec(runtimeContext, command, timeout);
196197
}
197198

199+
/**
200+
* Delegates to {@link #doExec(RuntimeContext, String, int, Map)} with a fallback timeout. The
201+
* default {@code doExec} wraps the command in a one-shot shell {@code env} prefix; backends with
202+
* a native per-command environment (Docker's {@code docker exec -e}) override that method so
203+
* values never enter the command text.
204+
*/
205+
@Override
206+
public ExecResult exec(
207+
RuntimeContext runtimeContext,
208+
String command,
209+
Integer timeoutSeconds,
210+
Map<String, String> environment)
211+
throws Exception {
212+
int timeout = timeoutSeconds != null ? timeoutSeconds : getDefaultExecTimeoutSeconds();
213+
return doExec(runtimeContext, command, timeout, environment);
214+
}
215+
198216
@Override
199217
public InputStream persistWorkspace() throws Exception {
200218
return doPersistWorkspace();
@@ -261,6 +279,35 @@ protected int getDefaultExecTimeoutSeconds() {
261279
protected abstract ExecResult doExec(
262280
RuntimeContext runtimeContext, String command, int timeoutSeconds) throws Exception;
263281

282+
/**
283+
* Executes a shell command with a one-shot environment. The base implementation wraps the
284+
* command in {@code env 'NAME=VALUE' ... sh -c 'command'}, which works for every POSIX shell
285+
* backend; backends with native support override this so the values are not part of the command
286+
* text.
287+
*
288+
* @param runtimeContext per-call context; may be {@code null} for internal probes
289+
* @param command shell command string
290+
* @param timeoutSeconds maximum execution time
291+
* @param environment extra environment variables for this command only; {@code null} or empty
292+
* for none
293+
* @return execution result
294+
* @throws Exception if execution fails
295+
*/
296+
protected ExecResult doExec(
297+
RuntimeContext runtimeContext,
298+
String command,
299+
int timeoutSeconds,
300+
Map<String, String> environment)
301+
throws Exception {
302+
if (environment == null || environment.isEmpty()) {
303+
return doExec(runtimeContext, command, timeoutSeconds);
304+
}
305+
return doExec(
306+
runtimeContext,
307+
SandboxEnvironment.commandWithEnvironment(command, environment),
308+
timeoutSeconds);
309+
}
310+
264311
/**
265312
* Creates a tar archive of the current workspace contents.
266313
*

0 commit comments

Comments
 (0)