Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fixes based on testing

Adrian Kahali815ce4256348
diff --git a/docs/documentation/platform/agent-vault/guides/daytona.mdx b/docs/documentation/platform/agent-vault/guides/daytona.mdx
index f5d0aeb11c..9077665e17 100644
--- a/docs/documentation/platform/agent-vault/guides/daytona.mdx
+++ b/docs/documentation/platform/agent-vault/guides/daytona.mdx
@@ -33,7 +33,8 @@ For each run, your code does the following:
2. Creates a sandbox for the proxy, and starts the proxy in it
3. Creates a sandbox for the agent, linked to the proxy's sandbox, that can only connect to the proxy
4. Starts the agent with the session token
-5. Revokes the session and deletes the proxy's sandbox when the agent finishes, which also deletes the agent's sandbox
+5. Stops the proxy when the agent finishes, so the proxy uploads the rest of the [session logs](/documentation/platform/agent-vault/session-logs)
+6. Revokes the session and deletes the proxy's sandbox, which also deletes the agent's sandbox
Every proxy starts from the same proxy token, so you set up the proxy once, no matter how many sandboxes you run.
@@ -139,7 +140,7 @@ func ensureSnapshot(ctx context.Context, client *daytona.Client) error {
return err
}
for line := range logs {
- fmt.Print(line)
+ fmt.Println(line)
}
return nil
}
@@ -158,10 +159,12 @@ IMAGE = Daytona::Image.base("node:24-bookworm-slim").run_commands(
def ensure_snapshot(daytona)
daytona.snapshot.get(SNAPSHOT)
-rescue Daytona::Sdk::Error
+rescue DaytonaApiClient::ApiError => e
+ raise unless e.code == 404
+
daytona.snapshot.create(
Daytona::CreateSnapshotParams.new(name: SNAPSHOT, image: IMAGE),
- on_logs: proc { |chunk| print chunk }
+ on_logs: proc { |chunk| puts chunk }
)
end
```
@@ -220,6 +223,12 @@ GET_LINK_ADDRESS = (
"sleep 0.5; done; exit 1"
)
+# Stops the proxy and waits for it to exit.
+STOP_PROXY = (
+ "pid=$(cat /tmp/proxy.pid); kill -TERM $pid; "
+ "for i in $(seq 30); do kill -0 $pid 2>/dev/null || exit 0; sleep 0.5; done; exit 1"
+)
+
AGENT_ENV = {
# Claude Code won't start without a key; the proxy replaces this one.
"ANTHROPIC_API_KEY": "agent-vault",
@@ -269,7 +278,7 @@ def run_agent(daytona: Daytona, prompt: str) -> str:
},
)
)
- proxy_sandbox.process.exec("nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 &")
+ proxy_sandbox.process.exec("nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 & echo $! > /tmp/proxy.pid")
agent_sandbox = daytona.create(
CreateSandboxFromSnapshotParams(
@@ -312,6 +321,8 @@ def run_agent(daytona: Daytona, prompt: str) -> str:
raise RuntimeError(f"The agent failed:\n{agent.result}")
return agent.result
finally:
+ if proxy_sandbox:
+ proxy_sandbox.process.exec(STOP_PROXY)
# Revoke first, so the session ends even if deleting fails.
try:
requests.post(
@@ -340,6 +351,11 @@ const GET_LINK_ADDRESS =
"ip -4 -o addr show eth1 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep . && exit 0; " +
"sleep 0.5; done; exit 1";
+// Stops the proxy and waits for it to exit.
+const STOP_PROXY =
+ "pid=$(cat /tmp/proxy.pid); kill -TERM $pid; " +
+ "for i in $(seq 30); do kill -0 $pid 2>/dev/null || exit 0; sleep 0.5; done; exit 1";
+
const AGENT_ENV = {
// Claude Code won't start without a key; the proxy replaces this one.
ANTHROPIC_API_KEY: "agent-vault",
@@ -392,7 +408,9 @@ export async function runAgent(daytona: Daytona, prompt: string): Promise<string
INFISICAL_DOMAIN: INFISICAL_URL,
},
});
- await proxySandbox.process.executeCommand("nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 &");
+ await proxySandbox.process.executeCommand(
+ "nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 & echo $! > /tmp/proxy.pid",
+ );
const agentSandbox = await daytona.create({
snapshot: SNAPSHOT,
@@ -432,6 +450,7 @@ export async function runAgent(daytona: Daytona, prompt: string): Promise<string
if (agent.exitCode !== 0) throw new Error(`The agent failed:\n${agent.result}`);
return agent.result;
} finally {
+ await proxySandbox?.process.executeCommand(STOP_PROXY);
// Revoke first, so the session ends even if deleting fails.
try {
await infisical(`/api/v1/agent-vault/sessions/${session.id}/revoke`, { token: accessToken });
@@ -475,6 +494,10 @@ const getLinkAddress = "for i in $(seq 60); do " +
"ip -4 -o addr show eth1 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep . && exit 0; " +
"sleep 0.5; done; exit 1"
+// Stops the proxy and waits for it to exit.
+const stopProxy = "pid=$(cat /tmp/proxy.pid); kill -TERM $pid; " +
+ "for i in $(seq 30); do kill -0 $pid 2>/dev/null || exit 0; sleep 0.5; done; exit 1"
+
var agentEnv = map[string]string{
// Claude Code won't start without a key; the proxy replaces this one.
"ANTHROPIC_API_KEY": "agent-vault",
@@ -552,8 +575,8 @@ func runAgent(ctx context.Context, client *daytona.Client, prompt string) (outpu
session := created.Session
var proxySandbox *daytona.Sandbox
- // Deferred calls run last-in, first-out, so the session is revoked first
- // and ends even if deleting fails.
+ // Deferred calls run last-in, first-out, so the proxy stops first, then the
+ // session is revoked, and the session ends even if deleting fails.
defer func() {
if proxySandbox != nil {
err = errors.Join(err, proxySandbox.Delete(context.Background()))
@@ -563,6 +586,11 @@ func runAgent(ctx context.Context, client *daytona.Client, prompt string) (outpu
revokeErr := infisical(context.Background(), "/api/v1/agent-vault/sessions/"+session.ID+"/revoke", login.AccessToken, nil, nil)
err = errors.Join(err, revokeErr)
}()
+ defer func() {
+ if proxySandbox != nil {
+ _, _ = proxySandbox.Process.ExecuteCommand(context.Background(), stopProxy)
+ }
+ }()
// Deleting this sandbox also deletes the agent's sandbox linked to it.
ttl := 15
@@ -580,7 +608,8 @@ func runAgent(ctx context.Context, client *daytona.Client, prompt string) (outpu
if err != nil {
return "", err
}
- if _, err := proxySandbox.Process.ExecuteCommand(ctx, "nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 &"); err != nil {
+ startProxy := "nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 & echo $! > /tmp/proxy.pid"
+ if _, err := proxySandbox.Process.ExecuteCommand(ctx, startProxy); err != nil {
return "", err
}
@@ -667,6 +696,10 @@ GET_LINK_ADDRESS = "for i in $(seq 60); do " \
"ip -4 -o addr show eth1 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep . && exit 0; " \
"sleep 0.5; done; exit 1"
+# Stops the proxy and waits for it to exit.
+STOP_PROXY = "pid=$(cat /tmp/proxy.pid); kill -TERM $pid; " \
+ "for i in $(seq 30); do kill -0 $pid 2>/dev/null || exit 0; sleep 0.5; done; exit 1"
+
AGENT_ENV = {
# Claude Code won't start without a key; the proxy replaces this one.
"ANTHROPIC_API_KEY" => "agent-vault",
@@ -723,7 +756,7 @@ def run_agent(daytona, prompt)
}
)
)
- proxy_sandbox.process.exec(command: "nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 &")
+ proxy_sandbox.process.exec(command: "nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 & echo $! > /tmp/proxy.pid")
agent_sandbox = daytona.create(
Daytona::CreateSandboxFromSnapshotParams.new(
@@ -752,7 +785,7 @@ def run_agent(daytona, prompt)
raise "The Agent Vault proxy didn't start:\n#{log}"
end
- agent_sandbox.fs.upload_file(StringIO.new(prompt), "/tmp/prompt.txt")
+ agent_sandbox.fs.upload_file_stream(StringIO.new(prompt), "/tmp/prompt.txt")
# Claude Code won't skip its permission prompts as root, so the agent
# runs as the image's node user.
agent = agent_sandbox.process.exec(
@@ -767,6 +800,7 @@ def run_agent(daytona, prompt)
agent.result
ensure
+ proxy_sandbox&.process&.exec(command: STOP_PROXY)
# Revoke first, so the session ends even if deleting fails.
begin
infisical("/api/v1/agent-vault/sessions/#{session['id']}/revoke", token: access_token)
@@ -786,6 +820,7 @@ import io.daytona.sdk.Daytona;
import io.daytona.sdk.Sandbox;
import io.daytona.sdk.model.CreateSandboxFromSnapshotParams;
import io.daytona.sdk.model.ExecuteResponse;
+import io.daytona.sdk.model.SessionExecuteRequest;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
@@ -806,6 +841,10 @@ public class RunAgent {
+ "ip -4 -o addr show eth1 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep . && exit 0; "
+ "sleep 0.5; done; exit 1";
+ // Stops the proxy and waits for it to exit.
+ static final String STOP_PROXY = "pid=$(cat /tmp/proxy.pid); kill -TERM $pid; "
+ + "for i in $(seq 30); do kill -0 $pid 2>/dev/null || exit 0; sleep 0.5; done; exit 1";
+
static final Map<String, String> AGENT_ENV = Map.of(
// Claude Code won't start without a key; the proxy replaces this one.
"ANTHROPIC_API_KEY", "agent-vault",
@@ -859,7 +898,8 @@ public class RunAgent {
"INFISICAL_AGENT_VAULT_PROXY_TOKEN", System.getenv("INFISICAL_AGENT_VAULT_PROXY_TOKEN"),
"INFISICAL_DOMAIN", INFISICAL_URL));
proxySandbox = daytona.create(proxyParams);
- proxySandbox.getProcess().executeCommand("nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 &");
+ proxySandbox.getProcess().executeCommand(
+ "nohup infisical agent-vault proxy > /tmp/proxy.log 2>&1 & echo $! > /tmp/proxy.pid");
CreateSandboxFromSnapshotParams agentParams = new CreateSandboxFromSnapshotParams();
agentParams.setSnapshot(SandboxImage.SNAPSHOT);
@@ -890,18 +930,32 @@ public class RunAgent {
agentSandbox.getFs().uploadFile(prompt.getBytes(StandardCharsets.UTF_8), "/tmp/prompt.txt");
Map<String, String> env = new HashMap<>(AGENT_ENV);
env.put("INFISICAL_AGENT_VAULT_SESSION_TOKEN", session.get("token").asText());
+ StringBuilder envFile = new StringBuilder();
+ env.forEach((key, value) -> envFile.append("export ").append(key).append("='").append(value).append("'\n"));
+ agentSandbox.getFs().uploadFile(envFile.toString().getBytes(StandardCharsets.UTF_8), "/tmp/agent.env");
+
+ // The Java SDK stops waiting for executeCommand after 10 seconds, so the agent
+ // runs in the background and this code checks every 2 seconds whether it exited.
+ agentSandbox.getProcess().createSession("agent");
// Claude Code won't skip its permission prompts as root, so the agent
// runs as the image's node user.
- ExecuteResponse agent = agentSandbox.getProcess().executeCommand(
- "runuser -u node -- sh -c '"
+ String commandId = agentSandbox.getProcess().executeSessionCommand("agent", new SessionExecuteRequest(
+ "cd /home/node && . /tmp/agent.env && runuser -u node -- sh -c '"
+ "infisical agent-vault run --telemetry=false --proxy " + proxyAddress
+ " -- claude -p --permission-mode bypassPermissions < /tmp/prompt.txt'",
- "/home/node", env, 14 * 60);
- if (agent.getExitCode() != 0) {
- throw new RuntimeException("The agent failed:\n" + agent.getResult());
+ true)).getCmdId();
+ Integer exitCode = null;
+ for (long deadline = System.nanoTime() + Duration.ofMinutes(14).toNanos();
+ exitCode == null && System.nanoTime() < deadline; Thread.sleep(2_000)) {
+ exitCode = agentSandbox.getProcess().getSessionCommand("agent", commandId).getExitCode();
+ }
+ String output = agentSandbox.getProcess().getSessionCommandLogs("agent", commandId).getOutput();
+ if (exitCode == null || exitCode != 0) {
+ throw new RuntimeException("The agent failed:\n" + output);
}
- return agent.getResult();
+ return output;
} finally {
+ if (proxySandbox != null) proxySandbox.getProcess().executeCommand(STOP_PROXY);
// Revoke first, so the session ends even if deleting fails.
try {
infisical("/api/v1/agent-vault/sessions/" + session.get("id").asText() + "/revoke", accessToken, null);
@@ -917,7 +971,11 @@ public class RunAgent {
For more about creating sessions from code, see [Create sessions with the API](/documentation/platform/agent-vault/sessions-api). For the flags the agent starts with, see the [`agent-vault run` CLI reference](/cli/reference#agent-vault-run).
-To run a different agent, install it in [the snapshot](#step-3-create-the-snapshot), replace the `claude` command with the agent's non-interactive command, such as `codex exec`, and replace the Claude Code settings in the agent's environment variables. For an agent you built yourself, run it the same way, or set the proxy in its HTTP client as [Connect your own agent](/documentation/platform/agent-vault/guides/custom-agent#step-4-send-requests-through-the-proxy) describes.
+<Note>
+To run a different agent, install it in [the snapshot](#step-3-create-the-snapshot), replace the `claude` command with the agent's non-interactive command, such as `codex exec`, and replace the Claude Code settings in the agent's environment variables.
+
+For an agent you built yourself, run it the same way, or [set the proxy in its HTTP client](/documentation/platform/agent-vault/guides/custom-agent#step-4-send-requests-through-the-proxy).
+</Note>
## Step 5: Verify it works
diff --git a/docs/snippets/agent-vault/SandboxAgentVaultSetup.mdx b/docs/snippets/agent-vault/SandboxAgentVaultSetup.mdx
index 1f68d23a06..35bedf4274 100644
--- a/docs/snippets/agent-vault/SandboxAgentVaultSetup.mdx
+++ b/docs/snippets/agent-vault/SandboxAgentVaultSetup.mdx
@@ -15,7 +15,7 @@ Create an [access bundle](/documentation/platform/agent-vault/access-bundles) th
Select the access bundle you just created, then select **Add Service**.
</Step>
<Step>
- On the **Choose a template** panel, pick the template for the API, such as **Anthropic**, or select **Custom**.
+ On the **Choose a template** panel, pick the template for the API, such as **Anthropic** for Claude Code, or select **Custom**.
</Step>
<Step>
On the **Details** step, check the hosts the service covers, or enter the API's host if you selected **Custom**, then select **Continue**.