Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(agent): Add sandbox (#14712)

Ben Bachem1cab02814caf
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md
index 80c8a4b7e8..cf6db16c08 100644
--- a/.agents/AGENTS.md
+++ b/.agents/AGENTS.md
@@ -42,6 +42,7 @@ evaluating, and debugging AI applications.
without explicit user approval for the exact rule and scope.
- Always quote file paths in shell commands, or use `noglob` for path-heavy
commands, to avoid zsh glob expansion issues with dynamic Next.js routes.
+- Never invoke Node-installed binaries through `./node_modules/.bin/*`. Always run them through `pnpm`.
- Never commit secrets or credentials. Keep `.env*.example` files in
sync with required env vars.
diff --git a/.env.dev.example b/.env.dev.example
index 510e474fd0..60a0886f5b 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -192,6 +192,17 @@ LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-opus-4-8"
LANGFUSE_AWS_BEDROCK_SMALL_MODEL="eu.anthropic.claude-haiku-4-5-20251001-v1:0"
LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"
+# In-app agent sandbox. Local development defaults to the dangerous docker provider.
+# Set to enable sandboxing locally. Leave unset to disable sandbox tools entirely.
+# LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER="dangerous-docker"
+# To test the Lambda MicroVM provider instead:
+# Set to enable the Lambda microvm sandbox. Leave unset to disable sandboxing entirely.
+# LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER="lambda-microvm"
+# Required:
+# LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER="arn:aws:lambda:us-east-1:123456789012:microvm-image:langfuse-in-app-agent-sandbox"
+# LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN="arn:aws:iam::123456789012:role/langfuse-in-app-agent-sandbox"
+# LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION="us-east-1"
+
# V4 migration flags.
# Write target: `legacy` | `dual` | `events_only`.
LANGFUSE_MIGRATION_V4_WRITE_MODE=dual
diff --git a/knip.jsonc b/knip.jsonc
index 13d14d9e81..75ecb85ae4 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -64,6 +64,10 @@
"ee": {
"project": ["src/**/*.ts"],
},
+ "packages/in-app-agent-sandbox-runtime": {
+ "entry": ["src/server.ts"],
+ "project": ["src/**/*.ts"],
+ },
"packages/config-eslint": {
"project": ["*.js"],
},
diff --git a/packages/in-app-agent-sandbox-runtime/.gitignore b/packages/in-app-agent-sandbox-runtime/.gitignore
new file mode 100644
index 0000000000..1639d62c45
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/.gitignore
@@ -0,0 +1,3 @@
+.local-image-built
+.env
+*.zip
diff --git a/packages/in-app-agent-sandbox-runtime/Dockerfile b/packages/in-app-agent-sandbox-runtime/Dockerfile
new file mode 100644
index 0000000000..35eb4c3733
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/Dockerfile
@@ -0,0 +1,30 @@
+FROM node:24-alpine
+
+RUN apk add --no-cache jq python3
+# The entire runtime runs as a single unprivileged user. Lambda MicroVMs set
+# `no new privileges`, which prevents `sudo`-based user switching at runtime.
+RUN addgroup -S sandbox-server && adduser -S sandbox-server -G sandbox-server
+
+WORKDIR /app
+
+COPY package.json ./package.json
+RUN node -e 'const fs = require("node:fs"); const pkg = JSON.parse(fs.readFileSync("package.json", "utf8")); fs.writeFileSync("package.json", JSON.stringify({ name: pkg.name, private: true, type: pkg.type, dependencies: pkg.dependencies }, null, 2));' \
+ && npm install --omit=dev
+
+COPY dist ./dist
+
+# Keep `/app` immutable to the runtime user. `/workspace` stays sticky-writable,
+# and `/workspace/tool_calls` is recreated from prior tool outputs before each
+# tool invocation.
+RUN chown -R root:root /app \
+ && mkdir -p /workspace \
+ && chown sandbox-server:sandbox-server /workspace \
+ && chmod 1777 /workspace \
+ && mkdir -p /workspace/tool_calls \
+ && chown -R sandbox-server:sandbox-server /workspace/tool_calls
+
+EXPOSE 5000
+
+USER sandbox-server
+
+CMD ["node", "/app/dist/server.js"]
diff --git a/packages/in-app-agent-sandbox-runtime/README.md b/packages/in-app-agent-sandbox-runtime/README.md
new file mode 100644
index 0000000000..fa54a39f76
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/README.md
@@ -0,0 +1,75 @@
+# In-App Agent Sandbox Runtime
+
+Minimal HTTP control server for the in-app agent sandbox runtime.
+
+See `web/src/ee/features/in-app-agent/README.md` for how this package fits into the in-app agent sandbox architecture.
+
+## Privileges
+
+The runtime runs as a single unprivileged `sandbox-server` user inside the container.
+This keeps the setup compatible with Lambda MicroVMs, which set `no new privileges`
+and prevent `sudo`-based user switching at runtime.
+
+- The HTTP sandbox server runs as `sandbox-server`.
+- Tool operations (`read`, `write`, `edit`, `bash`) also run as `sandbox-server`.
+- `/workspace/tool_calls` is recreated from prior tool outputs before each tool invocation, so any modifications made during one tool call are discarded before the next one.
+
+## Endpoints:
+
+- `GET /health`
+- `POST /sandbox`
+- `POST /aws/lambda-microvms/runtime/v1/ready`
+- `POST /aws/lambda-microvms/runtime/v1/run`
+- `POST /aws/lambda-microvms/runtime/v1/resume`
+- `POST /aws/lambda-microvms/runtime/v1/suspend`
+- `POST /aws/lambda-microvms/runtime/v1/terminate`
+
+## Development
+
+To rebuild the local Docker image manually:
+
+```bash
+pnpm turbo run build:docker-image --filter @repo/in-app-agent-sandbox-runtime --force
+```
+
+This produces `langfuse-in-app-agent-sandbox:latest`.
+
+## Build And Publish An AWS Lambda MicroVM Image
+
+Use `packages/in-app-agent-sandbox-runtime/build-microvm-image.sh` as the canonical build and publish flow.
+
+From the repo root:
+
+```bash
+bash packages/in-app-agent-sandbox-runtime/build-microvm-image.sh
+```
+
+The script:
+
+- optionally loads `packages/in-app-agent-sandbox-runtime/.env`
+- validates required commands and environment variables
+- builds the local Docker image and package `dist`
+- creates and uploads the zip artifact to S3
+- creates or updates the Lambda MicroVM image
+- waits for the build to finish
+- prints `IMAGE_ARN=...` and `IMAGE_VERSION=...`
+
+Required environment variables:
+
+- `AWS_PROFILE`
+- `AWS_REGION`
+- `S3_BUCKET`
+- `MICROVM_IMAGE_NAME`
+- `LAMBDA_MICROVM_BUILD_ROLE_ARN`
+- `BASE_IMAGE_ARN`
+- `BASE_IMAGE_VERSION`
+
+Prerequisites:
+
+- Docker
+- AWS CLI with `lambda-microvms` support
+- An authenticated AWS profile
+- An S3 bucket for the artifact upload
+- A Lambda MicroVM build role ARN with access to read the S3 artifact and write build logs
+
+The script configures the required MicroVM hooks for this runtime, including `ready`, `run`, `resume`, `suspend`, and `terminate` on port `5000`.
diff --git a/packages/in-app-agent-sandbox-runtime/build-microvm-image.sh b/packages/in-app-agent-sandbox-runtime/build-microvm-image.sh
new file mode 100755
index 0000000000..9c3b5096da
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/build-microvm-image.sh
@@ -0,0 +1,179 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ENV_FILE="$SCRIPT_DIR/.env"
+
+if [[ -f "$ENV_FILE" ]]; then
+ set -a
+ # shellcheck disable=SC1090
+ source "$ENV_FILE"
+ set +a
+fi
+
+required_vars=(
+ AWS_PROFILE
+ AWS_REGION
+ S3_BUCKET
+ MICROVM_IMAGE_NAME
+ LAMBDA_MICROVM_BUILD_ROLE_ARN
+ BASE_IMAGE_ARN
+ BASE_IMAGE_VERSION
+)
+
+for command in aws git pnpm zip; do
+ if ! command -v "$command" >/dev/null 2>&1; then
+ printf 'Missing required command: %s\n' "$command" >&2
+ exit 1
+ fi
+done
+
+for var_name in "${required_vars[@]}"; do
+ if [[ -z "${!var_name:-}" ]]; then
+ printf 'Missing required env var: %s\n' "$var_name" >&2
+ exit 1
+ fi
+done
+
+REPO_ROOT="$(git rev-parse --show-toplevel)"
+PACKAGE_DIR="$SCRIPT_DIR"
+ARTIFACT_NAME="microvm-artifact.zip"
+ARTIFACT_PATH="$PACKAGE_DIR/$ARTIFACT_NAME"
+S3_URI="s3://$S3_BUCKET/$MICROVM_IMAGE_NAME.zip"
+
+cleanup() {
+ rm -f "$ARTIFACT_PATH"
+}
+
+trap cleanup EXIT
+
+read -r -d '' HOOKS_JSON <<'JSON' || true
+{
+ "port": 5000,
+ "microvmImageHooks": {
+ "ready": "ENABLED",
+ "readyTimeoutInSeconds": 60
+ },
+ "microvmHooks": {
+ "run": "ENABLED",
+ "runTimeoutInSeconds": 30,
+ "resume": "ENABLED",
+ "resumeTimeoutInSeconds": 30,
+ "suspend": "ENABLED",
+ "suspendTimeoutInSeconds": 60,
+ "terminate": "ENABLED",
+ "terminateTimeoutInSeconds": 30
+ }
+}
+JSON
+
+printf 'Building docker image...\n' >&2
+pnpm turbo run build:docker-image --filter @repo/in-app-agent-sandbox-runtime --force
+
+printf 'Building package dist...\n' >&2
+pnpm --filter @repo/in-app-agent-sandbox-runtime run build
+
+printf 'Creating zip artifact...\n' >&2
+(
+ cd "$PACKAGE_DIR"
+ rm -f "$ARTIFACT_NAME"
+ zip -r "$ARTIFACT_NAME" Dockerfile package.json dist >/dev/null
+)
+
+printf 'Uploading artifact to %s...\n' "$S3_URI" >&2
+aws s3 cp "$ARTIFACT_PATH" "$S3_URI" \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION"
+
+EXISTING_IMAGE_ARN="$({
+ aws lambda-microvms list-microvm-images \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION" \
+ --name-filter "$MICROVM_IMAGE_NAME" \
+ --query "items[?name=='$MICROVM_IMAGE_NAME'] | [0].imageArn" \
+ --output text 2>/dev/null || true; \
+} | tr -d '\r')"
+
+if [[ -n "$EXISTING_IMAGE_ARN" && "$EXISTING_IMAGE_ARN" != "None" && "$EXISTING_IMAGE_ARN" != "null" ]]; then
+ printf 'Updating existing MicroVM image...\n' >&2
+ IMAGE_ARN="$({
+ aws lambda-microvms update-microvm-image \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION" \
+ --image-identifier "$EXISTING_IMAGE_ARN" \
+ --base-image-arn "$BASE_IMAGE_ARN" \
+ --base-image-version "$BASE_IMAGE_VERSION" \
+ --build-role-arn "$LAMBDA_MICROVM_BUILD_ROLE_ARN" \
+ --code-artifact "uri=$S3_URI" \
+ --hooks "$HOOKS_JSON" \
+ --cpu-configurations architecture=ARM_64 \
+ --resources minimumMemoryInMiB=512 \
+ --query 'imageArn' \
+ --output text; \
+ } | tr -d '\r')"
+else
+ printf 'Creating MicroVM image...\n' >&2
+ IMAGE_ARN="$({
+ aws lambda-microvms create-microvm-image \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION" \
+ --name "$MICROVM_IMAGE_NAME" \
+ --base-image-arn "$BASE_IMAGE_ARN" \
+ --base-image-version "$BASE_IMAGE_VERSION" \
+ --build-role-arn "$LAMBDA_MICROVM_BUILD_ROLE_ARN" \
+ --code-artifact "uri=$S3_URI" \
+ --hooks "$HOOKS_JSON" \
+ --cpu-configurations architecture=ARM_64 \
+ --resources minimumMemoryInMiB=512 \
+ --query 'imageArn' \
+ --output text; \
+ } | tr -d '\r')"
+fi
+
+if [[ -z "$IMAGE_ARN" || "$IMAGE_ARN" == "None" || "$IMAGE_ARN" == "null" ]]; then
+ printf 'Failed to create MicroVM image or parse image ARN\n' >&2
+ exit 1
+fi
+
+printf 'Waiting for MicroVM image to finish building...\n' >&2
+while true; do
+ IMAGE_STATE="$({
+ aws lambda-microvms get-microvm-image \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION" \
+ --image-identifier "$IMAGE_ARN" \
+ --query 'state' \
+ --output text; \
+ } | tr -d '\r')"
+ IMAGE_VERSION="$({
+ aws lambda-microvms get-microvm-image \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION" \
+ --image-identifier "$IMAGE_ARN" \
+ --query 'latestActiveImageVersion' \
+ --output text; \
+ } | tr -d '\r')"
+
+ printf 'Current MicroVM image state: %s\n' "$IMAGE_STATE" >&2
+
+ case "$IMAGE_STATE" in
+ CREATED|UPDATED)
+ printf 'IMAGE_ARN=%s\n' "$IMAGE_ARN"
+ printf 'IMAGE_VERSION=%s\n' "$IMAGE_VERSION"
+ exit 0
+ ;;
+ CREATE_FAILED|UPDATE_FAILED|DELETE_FAILED)
+ printf 'MicroVM image entered failure state: %s\n' "$IMAGE_STATE" >&2
+ aws lambda-microvms get-microvm-image \
+ --profile "$AWS_PROFILE" \
+ --region "$AWS_REGION" \
+ --image-identifier "$IMAGE_ARN" \
+ --output json >&2
+ exit 1
+ ;;
+ *)
+ sleep 5
+ ;;
+ esac
+done
diff --git a/packages/in-app-agent-sandbox-runtime/package.json b/packages/in-app-agent-sandbox-runtime/package.json
new file mode 100644
index 0000000000..9e6dc61dc4
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@repo/in-app-agent-sandbox-runtime",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "engines": {
+ "node": "24"
+ },
+ "scripts": {
+ "build": "tsc",
+ "build:docker-image": "docker build . -t langfuse-in-app-agent-sandbox:latest && touch .local-image-built",
+ "start": "node ./dist/server.js",
+ "format": "prettier --write .",
+ "format:check": "prettier --check ."
+ },
+ "dependencies": {
+ "zod": "^4.3.6"
+ },
+ "devDependencies": {
+ "@repo/typescript-config": "workspace:*",
+ "@types/node": "^24.3.0",
+ "prettier": "^3.8.3",
+ "typescript": "^5.7.2"
+ }
+}
diff --git a/packages/in-app-agent-sandbox-runtime/src/contracts.ts b/packages/in-app-agent-sandbox-runtime/src/contracts.ts
new file mode 100644
index 0000000000..f3bd4e7bd1
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/src/contracts.ts
@@ -0,0 +1,49 @@
+import { z } from "zod";
+
+export const SandboxFileSchema = z.object({
+ path: z.string(),
+ content: z.string(),
+});
+
+const ReadSandboxOperationSchema = z.object({
+ operation: z.literal("read"),
+ path: z.string(),
+ toolCallFiles: z.array(SandboxFileSchema).optional(),
+});
+
+const WriteSandboxOperationSchema = z.object({
+ operation: z.literal("write"),
+ path: z.string(),
+ content: z.string(),
+ toolCallFiles: z.array(SandboxFileSchema).optional(),
+});
+
+const EditSandboxOperationSchema = z.object({
+ operation: z.literal("edit"),
+ path: z.string(),
+ oldText: z.string(),
+ newText: z.string(),
+ toolCallFiles: z.array(SandboxFileSchema).optional(),
+});
+
+const BashSandboxOperationSchema = z.object({
+ operation: z.literal("bash"),
+ command: z.string(),
+ timeoutMs: z.number().finite().optional(),
+ toolCallFiles: z.array(SandboxFileSchema).optional(),
+});
+
+export const SandboxOperationSchema = z.discriminatedUnion("operation", [
+ ReadSandboxOperationSchema,
+ WriteSandboxOperationSchema,
+ EditSandboxOperationSchema,
+ BashSandboxOperationSchema,
+]);
+
+export type SandboxFile = z.infer<typeof SandboxFileSchema>;
+
+export type ReadSandboxOperation = z.infer<typeof ReadSandboxOperationSchema>;
+export type WriteSandboxOperation = z.infer<typeof WriteSandboxOperationSchema>;
+export type EditSandboxOperation = z.infer<typeof EditSandboxOperationSchema>;
+export type BashSandboxOperation = z.infer<typeof BashSandboxOperationSchema>;
+export type SandboxOperation = z.infer<typeof SandboxOperationSchema>;
diff --git a/packages/in-app-agent-sandbox-runtime/src/server.ts b/packages/in-app-agent-sandbox-runtime/src/server.ts
new file mode 100644
index 0000000000..9264faf31c
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/src/server.ts
@@ -0,0 +1,496 @@
+import { spawn } from "node:child_process";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import {
+ createServer,
+ type IncomingMessage,
+ type ServerResponse,
+} from "node:http";
+import path from "node:path";
+
+import {
+ SandboxFileSchema,
+ SandboxOperationSchema,
+ type BashSandboxOperation,
+ type EditSandboxOperation,
+ type ReadSandboxOperation,
+ type SandboxFile,
+ type SandboxOperation,
+ type WriteSandboxOperation,
+} from "./contracts.js";
+
+const SERVER_PORT = 5000;
+const WORKSPACE_ROOT = "/workspace";
+const TOOL_CALLS_ROOT = path.join(WORKSPACE_ROOT, "tool_calls");
+const MICROVM_RUNTIME_HOOKS_ROOT = "/aws/lambda-microvms/runtime/v1";
+const MAX_REQUEST_BODY_BYTES = 10 * 1024 * 1024;
+let requestCounter = 0;
+
+const server = createServer(async (request, response) => {
+ const requestId = `req-${++requestCounter}`;
+ const startedAt = Date.now();
+
+ try {
+ logSandboxServer("request.start", {
+ requestId,
+ method: request.method ?? "UNKNOWN",
+ url: request.url ?? "",
+ });
+
+ const result = await routeRequest(request, requestId);
+ sendJson(response, result.statusCode, result.body);
+ logSandboxServer("request.end", {
+ requestId,
+ statusCode: result.statusCode,
+ durationMs: Date.now() - startedAt,
+ });
+ } catch (error) {
+ logSandboxServer("request.error", {
+ requestId,
+ durationMs: Date.now() - startedAt,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ sendJson(response, 500, {
+ error:
+ error instanceof Error ? error.message : "Unknown sandbox server error",
+ });
+ logSandboxServer("request.end", {
+ requestId,
+ statusCode: 500,
+ durationMs: Date.now() - startedAt,
+ });
+ }
+});
+
+server.listen(SERVER_PORT, () => {
+ logSandboxServer("server.listening", {
+ port: SERVER_PORT,
+ workspaceRoot: WORKSPACE_ROOT,
+ });
+});
+
+async function syncToolCallFiles(toolCallFiles: unknown, requestId: string) {
+ await rm(TOOL_CALLS_ROOT, { recursive: true, force: true });
+ await mkdir(TOOL_CALLS_ROOT, { recursive: true });
+
+ if (!toolCallFiles) {
+ logSandboxServer("toolCalls.sync", { requestId, fileCount: 0 });
+ return;
+ }
+
+ const files: SandboxFile[] = SandboxFileSchema.array().parse(toolCallFiles);
+ logSandboxServer("toolCalls.sync", {
+ requestId,
+ fileCount: files.length,
+ paths: files.map((file) => file.path),
+ });
+
+ for (const file of files) {
+ const filePath = resolveSandboxPath(file.path);
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, file.content, "utf8");
+ }
+}
+
+async function routeRequest(request: IncomingMessage, requestId: string) {
+ if (request.method === "GET" && request.url === "/health") {
+ logSandboxServer("health.ok", { requestId });
+ return { statusCode: 200, body: { status: "ok" } };
+ }
+
+ if (
+ request.method === "POST" &&
+ request.url === `${MICROVM_RUNTIME_HOOKS_ROOT}/ready`
+ ) {
+ return { statusCode: 200, body: await readyHook(requestId) };
+ }
+
+ if (
+ request.method === "POST" &&
+ request.url === `${MICROVM_RUNTIME_HOOKS_ROOT}/run`
+ ) {
+ return { statusCode: 200, body: await runHook(requestId, request) };
+ }
+
+ if (
+ request.method === "POST" &&
+ request.url === `${MICROVM_RUNTIME_HOOKS_ROOT}/suspend`
+ ) {
+ return { statusCode: 200, body: await suspendHook(requestId) };
+ }
+
+ if (
+ request.method === "POST" &&
+ request.url === `${MICROVM_RUNTIME_HOOKS_ROOT}/resume`
+ ) {
+ return { statusCode: 200, body: await resumeHook(requestId) };
+ }
+
+ if (
+ request.method === "POST" &&
+ request.url === `${MICROVM_RUNTIME_HOOKS_ROOT}/terminate`
+ ) {
+ return { statusCode: 200, body: await terminateHook(requestId) };
+ }
+
+ if (request.method === "POST" && request.url === "/sandbox") {
+ const body = SandboxOperationSchema.parse(await readJsonBody(request));
+ logSandboxServer("sandbox.request", {
+ requestId,
+ operation: summarizeOperation(body),
+ });
+ await syncToolCallFiles(body.toolCallFiles, requestId);
+
+ if (body.operation === "read") {
+ return { statusCode: 200, body: await readOperation(body, requestId) };
+ }
+
+ if (body.operation === "write") {
+ return { statusCode: 200, body: await writeOperation(body, requestId) };
+ }
+
+ if (body.operation === "edit") {
+ return { statusCode: 200, body: await editOperation(body, requestId) };
+ }
+
+ return { statusCode: 200, body: await bashOperation(body, requestId) };
+ }
+
+ return { statusCode: 404, body: { error: "Not found" } };
+}
+
+async function readOperation(body: ReadSandboxOperation, requestId: string) {
+ const filePath = resolveSandboxPath(body.path);
+ let content: string | null;
+
+ try {
+ content = await readFile(filePath, "utf8");
+ } catch (error) {
+ if (!isMissingFileError(error)) {
+ throw error;
+ }
+
+ content = null;
+ }
+
+ const result = { path: filePath, content };
+ logSandboxServer("read.complete", {
+ requestId,
+ path: body.path,
+ result,
+ });
+ return { result };
+}
+
+async function writeOperation(body: WriteSandboxOperation, requestId: string) {
+ const filePath = resolveSandboxPath(body.path);
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, body.content, "utf8");
+
+ const result = {
+ path: filePath,
+ bytesWritten: Buffer.byteLength(body.content, "utf8"),
+ };
+ logSandboxServer("write.complete", {
+ requestId,
+ path: body.path,
+ result,
+ });
+ return { result };
+}
+
+async function editOperation(body: EditSandboxOperation, requestId: string) {
+ const filePath = resolveSandboxPath(body.path);
+ let current = "";
+
+ try {
+ current = await readFile(filePath, "utf8");
+ } catch (error) {
+ if (!isMissingFileError(error)) {
+ throw error;
+ }
+ }
+
+ const firstMatch = current.indexOf(body.oldText);
+ const replaced = firstMatch !== -1;
+ if (
+ replaced &&
+ current.indexOf(body.oldText, firstMatch + body.oldText.length) !== -1
+ ) {
+ throw new Error(`Sandbox edit target is ambiguous: ${body.path}`);
+ }
+
+ if (replaced) {
+ await writeFile(
+ filePath,
+ current.replace(body.oldText, body.newText),
+ "utf8",
+ );
+ }
+
+ const result = { path: filePath, replaced };
+ logSandboxServer("edit.complete", {
+ requestId,
+ path: body.path,
+ result,
+ });
+ return { result };
+}
+
+async function bashOperation(body: BashSandboxOperation, requestId: string) {
+ const result = await runCommand(body.command, body.timeoutMs, requestId);
+ logSandboxServer("bash.complete", {
+ requestId,
+ result,
+ });
+ return { result };
+}
+
+async function runHook(requestId: string, request: IncomingMessage) {
+ await readJsonBody(request);
+
+ logSandboxServer("hook.run.start", {
+ requestId,
+ });
+
+ await ensureWorkspaceRoots();
+
+ return { ready: true };
+}
+
+async function readyHook(requestId: string) {
+ await ensureWorkspaceRoots();
+ logSandboxServer("hook.ready", { requestId });
+ return { ready: true };
+}
+
+async function suspendHook(requestId: string) {
+ await ensureWorkspaceRoots();
+ logSandboxServer("hook.suspend.start", {
+ requestId,
+ });
+
+ return { suspended: true };
+}
+
+async function resumeHook(requestId: string) {
+ await ensureWorkspaceRoots();
+ logSandboxServer("hook.resume", {
+ requestId,
+ });
+ return { resumed: true };
+}
+
+async function terminateHook(requestId: string) {
+ await ensureWorkspaceRoots();
+ logSandboxServer("hook.terminate.start", {
+ requestId,
+ });
+
+ return { terminated: true };
+}
+
+async function ensureWorkspaceRoots() {
+ await mkdir(WORKSPACE_ROOT, { recursive: true });
+ await mkdir(TOOL_CALLS_ROOT, { recursive: true });
+}
+
+function runCommand(
+ command: string,
+ timeoutMs: number | undefined,
+ requestId: string,
+) {
+ return new Promise<{
+ stdout: string;
+ stderr: string;
+ exitCode: number;
+ startedAt: string;
+ completedAt: string;
+ }>((resolve, reject) => {
+ const child = spawn("sh", ["-lc", command], { cwd: WORKSPACE_ROOT });
+ let stdout = "";
+ let stderr = "";
+ let settled = false;
+ const startedAt = new Date().toISOString();
+ const startedAtMs = Date.now();
+
+ logSandboxServer("bash.start", {
+ requestId,
+ pid: child.pid ?? null,
+ command,
+ timeoutMs: timeoutMs ?? null,
+ });
+
+ child.stdout.on("data", (chunk: Buffer | string) => {
+ stdout += chunk.toString("utf8");
+ });
+ child.stderr.on("data", (chunk: Buffer | string) => {
+ stderr += chunk.toString("utf8");
+ });
+ child.on("error", (error) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ logSandboxServer("bash.error", {
+ requestId,
+ pid: child.pid ?? null,
+ durationMs: Date.now() - startedAtMs,
+ error: error.message,
+ });
+ reject(error);
+ });
+
+ const timeoutId =
+ timeoutMs === undefined
+ ? undefined
+ : setTimeout(() => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ child.kill("SIGKILL");
+ resolve({
+ stdout,
+ stderr: `${stderr}Sandbox command timed out after ${timeoutMs}ms`,
+ exitCode: 124,
+ startedAt,
+ completedAt: new Date().toISOString(),
+ });
+ }, timeoutMs);
+
+ child.on("close", (code) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+
+ logSandboxServer("bash.processComplete", {
+ requestId,
+ pid: child.pid ?? null,
+ exitCode: code ?? 1,
+ durationMs: Date.now() - startedAtMs,
+ stdoutBytes: Buffer.byteLength(stdout, "utf8"),
+ stderrBytes: Buffer.byteLength(stderr, "utf8"),
+ });
+
+ resolve({
+ stdout,
+ stderr,
+ exitCode: code ?? 1,
+ startedAt,
+ completedAt: new Date().toISOString(),
+ });
+ });
+ });
+}
+
+function logSandboxServer(event: string, details?: Record<string, unknown>) {
+ const payload = details ? ` ${JSON.stringify(details)}` : "";
+ console.log(`[sandbox] ${new Date().toISOString()} ${event}${payload}`);
+}
+
+function summarizeOperation(body: SandboxOperation) {
+ switch (body.operation) {
+ case "read":
+ return { operation: body.operation, path: body.path };
+ case "write":
+ return {
+ operation: body.operation,
+ path: body.path,
+ contentBytes: Buffer.byteLength(body.content, "utf8"),
+ };
+ case "edit":
+ return {
+ operation: body.operation,
+ path: body.path,
+ oldTextLength: body.oldText.length,
+ newTextLength: body.newText.length,
+ };
+ case "bash":
+ return {
+ operation: body.operation,
+ timeoutMs: body.timeoutMs ?? null,
+ command: body.command,
+ };
+ }
+}
+
+function resolveSandboxPath(requestPath: string) {
+ const candidate = path.isAbsolute(requestPath)
+ ? requestPath
+ : path.join(WORKSPACE_ROOT, requestPath);
+ const normalized = path.resolve(candidate);
+
+ if (
+ normalized === WORKSPACE_ROOT ||
+ normalized.startsWith(`${WORKSPACE_ROOT}${path.sep}`)
+ ) {
+ return normalized;
+ }
+
+ throw new Error(`Sandbox path escapes workspace: ${requestPath}`);
+}
+
+function readJsonBody(request: IncomingMessage) {
+ return new Promise<unknown>((resolve, reject) => {
+ let body = "";
+ let bytesRead = 0;
+ let rejected = false;
+
+ request.on("data", (chunk: Buffer | string) => {
+ if (rejected) {
+ return;
+ }
+
+ bytesRead += Buffer.byteLength(chunk);
+ if (bytesRead > MAX_REQUEST_BODY_BYTES) {
+ rejected = true;
+ reject(
+ new Error(
+ `Sandbox request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes`,
+ ),
+ );
+ request.destroy();
+ return;
+ }
+
+ body += chunk.toString("utf8");
+ });
+ request.on("end", () => {
+ if (rejected) {
+ return;
+ }
+
+ try {
+ resolve(body ? (JSON.parse(body) as unknown) : {});
+ } catch (error) {
+ reject(error);
+ }
+ });
+ request.on("error", reject);
+ });
+}
+
+function sendJson(
+ response: ServerResponse<IncomingMessage>,
+ statusCode: number,
+ body: unknown,
+) {
+ response.writeHead(statusCode, { "Content-Type": "application/json" });
+ response.end(JSON.stringify(body));
+}
+
+function isMissingFileError(error: unknown) {
+ return (
+ error !== null &&
+ typeof error === "object" &&
+ "code" in error &&
+ error.code === "ENOENT"
+ );
+}
diff --git a/packages/in-app-agent-sandbox-runtime/tsconfig.json b/packages/in-app-agent-sandbox-runtime/tsconfig.json
new file mode 100644
index 0000000000..49dac55de6
--- /dev/null
+++ b/packages/in-app-agent-sandbox-runtime/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "extends": "@repo/typescript-config/base.json",
+ "compilerOptions": {
+ "moduleResolution": "NodeNext",
+ "module": "NodeNext",
+ "lib": ["es2023"],
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "target": "es2024",
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 89586a9858..6770245ff8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -7,26 +7,29 @@ settings:
catalogs:
default:
'@aws-sdk/client-cloudwatch':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
'@aws-sdk/client-lambda':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
+ '@aws-sdk/client-lambda-microvms':
+ specifier: 3.1074.0
+ version: 3.1074.0
'@aws-sdk/client-s3':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
'@aws-sdk/client-sesv2':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
'@aws-sdk/credential-providers':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
'@aws-sdk/lib-storage':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
'@aws-sdk/s3-request-presigner':
- specifier: 3.1056.0
- version: 3.1056.0
+ specifier: 3.1074.0
+ version: 3.1074.0
typescript:
specifier: ^6.0.3
version: 6.0.3
@@ -177,6 +180,25 @@ importers:
specifier: ^4.1.8
+ packages/in-app-agent-sandbox-runtime:
+ dependencies:
+ zod:
+ specifier: 4.3.6
+ version: 4.3.6
+ devDependencies:
+ '@repo/typescript-config':
+ specifier: workspace:*
+ version: link:../config-typescript
+ '@types/node':
+ specifier: ^24.3.0
+ version: 24.3.0
+ prettier:
+ specifier: ^3.8.3
+ version: 3.8.3
+ typescript:
+ specifier: ^5.7.2
+ version: 5.9.3
+
packages/shared:
dependencies:
'@ai-sdk/amazon-bedrock':
@@ -202,25 +224,25 @@ importers:
version: 3.0.3([email protected])
'@aws-sdk/client-cloudwatch':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@aws-sdk/client-lambda':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@aws-sdk/client-s3':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@aws-sdk/client-sesv2':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@aws-sdk/credential-providers':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@aws-sdk/lib-storage':
specifier: 'catalog:'
- version: 3.1056.0(@aws-sdk/[email protected])
+ version: 3.1074.0(@aws-sdk/[email protected])
'@aws-sdk/s3-request-presigner':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@azure/storage-blob':
specifier: ^12.26.0
version: 12.26.0
@@ -411,9 +433,12 @@ importers:
'@aws-crypto/sha256-browser':
specifier: ^5.2.0
version: 5.2.0
+ '@aws-sdk/client-lambda-microvms':
+ specifier: 'catalog:'
+ version: 3.1074.0
'@aws-sdk/credential-providers':
specifier: 'catalog:'
- version: 3.1056.0
+ version: 3.1074.0
'@baselime/trpc-opentelemetry-middleware':
specifier: ^0.1.2
version: 0.1.2(@opentelemetry/[email protected])(@trpc/[email protected]([email protected]))
@@ -859,6 +884,9 @@ importers:
'@types/d3-zoom':
specifier: ^3.0.8
version: 3.0.8
+ '@types/dockerode':
+ specifier: ^4.0.1
+ version: 4.0.1
'@types/lodash':
specifier: ^4.17.24
version: 4.17.24
@@ -883,6 +911,9 @@ importers:
'@vitest/browser-playwright':
specifier: 4.1.8
+ dockerode:
+ specifier: ^4.0.9
+ version: 4.0.12
dotenv:
specifier: ^16.6.1
version: 16.6.1
@@ -1359,96 +1390,128 @@ packages:
resolution: {integrity: sha512-LU80q1avpBwQ0eVAGbQpPApdVY4vcdBEIycY5iaznI10mdabeG83nrFySJrZ8knX7G6hl5d5KIOSjcpnolMKSA==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-CAGI9907XAGHAGeOz0I3eZpgsPxIoQupMev7A/rolxByxFlKpZ23Dz3NS8gD6PevqKnIQZmxFrTObjyYj8SY3A==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-rgpdSPmF5Lr+v7chdsbuc4u6tQI0eALSwX7NXES/E59nTd2AV6aRIOVlRxJda1PocHwW4kIe/fOyRigj7hxxSw==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-Fywg6+B39uGiYZRYFEsOXbIeHQ8wvtMqlt6FUwWev8N2H+V0pVdgCKn32pSOzud1i17wnm5gpB2VXZEoyVHc2A==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-+Ty97ACrY0BEH/aWczd5Vs7VK/MAVpUGatxbv4Rkwkk5llLAHLvqJPwp8QUTQpa7DRuMuyUWbyMwIghLVf81MA==}
engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-KYd1SYF+WaZinfzg4rsfprZQ3X1qboaJnHtjppd82JG3YSO/LVkenOkFIIsREPnXMoy6Dy6Xx+BXh4Y9A+a1zQ==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-ReG6Pj7yZKyh+wD2uG+6PP5LcAet2hArf7rLNokoUZCRxEBf0kbRtvfCSAMAoXbTXLKhIwbH6/6E1FbJDxDmLQ==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-h4NyvOj6jzgcnsZPD+ycJxCMUTFqmY5IpDuBu+MWpNBKZdYxu0L7lUVF7tdI2HeibjVuN+xdtArgxRcovUcobQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-tgDW9kK5na7InYISCCC29x2yjhriyS1/4tNrpos3zVqccjhzRmcd/q3WZADZ9CgZPu+C9tziseVojkAiJ5ajHw==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-WfMZEM2eC96anIT0RzR/QmhaefWKsNjOHNv09ORBkcA++ULBnm1fRau+KKGEIbr5nDnf9BTG7E7U3oOVklQS8g==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-NxC62ifhtaDDdJjZ8f8Y49DCOpviGGSwzdE4KO/DA1vui4dJP4CAq+64HQkdAjFw64i5cVZb5mF6off+pZX/pg==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-LXvqjyJ1heyT0hlHQqZGXuZyaBjH52adIwVUjYPg8I5k7MLBWQVPTFg6MFnlqxJAMhbJSfoI08e5gAY4T9lceg==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-6InRiPba0YgOw71/UPADykqyLAF8qJDOBBReUz91LTYERDoWTVG/4Adu8Zaa74Z1W9ictgC5e7l7D0vBj4GSwg==}
engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-WRWEgIq6vx+NU6ot3VrRu4Jovj9MIObitSi6of/GV5THDDPccBhivCRNkWJutMM+m3GvdeI3l/UbGNcoOobxOA==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-OHkK6xOx/IHkSbQdDWxnVCLU+j28EFl8wyWgBILQDFAPY8n240C/O4gjmFx+zFU12lL8njgJQ5GWAIWq88CnSQ==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-8qh/6EYb7hl/ZwVfQufhbMEZs1gQIc7GbdrIf4eprQJ7cv042+74nE6l3YDfyWNzb9iPXb8fRyYSHkNIk5eE6Q==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-nedaZz6Wz2FGUBMsWhlvBPGIkTMfRuMJ99YDHJI4CaC31JS8WPyTavEAio74cfd5nGhi0A8XASB4fZA5VqTdOQ==}
engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-n1EbJ98yvPWWdHZZv8bRBMqqDQJrtgtxyJ4xLy2Uqrh25BCOZQ7nnS1CsFXvuH8r0b0KVHDZEGEH5FxmEMP8jg==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-1RfJaF7SW1TOnvNGU7kaYjwUf5H3sfm+synGH1bHhRlqcnxCt3szebH3dmKEyY4tuGcbQ6ffzUT89cRitBV8OQ==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-TT76RN1NkI9WoyZqCNxOw6/WBMF7pYOTJcXbMokNFU+euSG40Kaf/t/FhDACVZWP+43wEM6ZynIPIkzS1wR1iA==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-sRCkpTiFnCdQvuaRVjQ6SVoHu6i7RUpurVo1c4F81HWhPvUJ7Wdp5MNtSdX1O29CNXc8em3O5m52hCjVtAD9SA==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-hvcgcwOiS0nb2XFb5Op1Pz/vYaWz5K8kKullziGpdNRuG0NwzRXseuPt2CoBqknHGaSPVesu1aOn2OcctEYdCA==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-6d8H6ZAh3ZPKZ6fe1nG2OWeZEZPtt9ravoD1dezPdPtsSkJRoxGAnFSHwKT3E/Te6fHE30zRzjV6TD12rvF6yQ==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-MZQv4SNjByk1iOKmrqmzcUF/uCB05wjvEHyXKxmGQTUANTIVayX6HPUF0bzkWLvtnkH7sAn9kUCfkXbSpj9sDA==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-GREWRrMj0XnNKMaVa/Mauoaui26qBEHu71WWqXbwZOu/jFQOnPZjTf7u0KtGKC8VGa6VUs9kDWGgocrKNLS9vw==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-HrId+C0DWA5qDIyLG64/kjUB2RNtPypxmABnIctK+TA1P1kHlOYoE/Wf5T5tKOMKgb08P7k/zNyhvfJ3lh5Oag==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-f+qjRXZpz7sgzbc4QB+6nLKfyKFgRRXzWdXbsKPv/VhVRyHsDyq4yBWC/B75BAJpFIcUeI2XR/3gdWJ677zB4A==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-7I/n1zkysouLOWvkEhjNEP4vMnD2v4kzzr3/3QBdrripEpn7ap1/I5DF3Hou1SUqkKWo1f3oPGMyFAA1FAMvsQ==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-TiVQhuU0pbhIZAUZacbPHMyzrIdiH+lnx+PMY/Pu/b93dJrq3wdZwzUJ0TPpvNxaqbHsxJvQZW3/h/beLiKq7Q==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-oHgbz/eFD8IKiksqDsz9ZMU4A59BpQq4QwJedBnGD80ZqYcHPPHZBwjBnxLVkB7iRVVHWpDclR8yWdD2PkQIUA==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-3foTZUJ4821Ij60X7K3NJroygiZLnbBmarN+T//O2cjkISan90zElN3NBmgSlDrTQ7Gs6z/yO8V7h60QNcDZHQ==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-CDhzKdb2onv5bpnjn/acgdNmJOQthPDLsPizU7rZflsEcgMMp8Mlri+U5hdxf8ldvZJpvM3vLU6D56vfJm5AMQ==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-Qp7ndCG+dZldiaURze6BM/dLkHQJxwi6WNRR1sR9lhX9jS9QG5ZIOiY3jm6T668vgGqHuNQS7r/P9pimxnHyyg==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-8qZLFhM69eKcS37m459ctPR05Qimycm/74OPVioe6wNZabMT54GYhwBju0+J656RkMasNSawWQu+c8CmBe3TUQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-tsKoElm0YKNDpxevbhiQ9xwNrrj8eUJ8IUfHusVvgZ/abrWEu9WWmDbsA2my9jon20Rof81iagyJ94fllvlwYQ==}
engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-2IrLrOruRr1NhTK0vguBL1gCWv1pu4bf4KaqpsA+/vCJpFEbvXFawn71GvCzk1wyjnDUsemtKypqoKGv4cSGbA==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-+Gg4n2/1RVyREDiI53VlUYSjXg1g70uhhujojnUqwH1FyQ8bTFPZ23zJNdNAU5QCIAusgNkqhZS03fVk2bXCRA==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-wOtCdKdspz/Riew4j0KBHjtHexR61IvkKfI3FeB9vY05B8qRXS6VXUEu8POZ1oIfBAeogwOiMuC7bEQKvPFzMg==}
engines: {node: '>=20.0.0'}
peerDependencies:
- '@aws-sdk/client-s3': ^3.1056.0
-
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-qAq2i5wj8wnZ+V/WlwwE0cfvJamyvV2k6v9Iq7UfDYzQC60xCHG/4/f4hJG4DELoCQeR6DstbD93pR7wLtfOtg==}
- engines: {node: '>=20.0.0'}
+ '@aws-sdk/client-s3': ^3.1074.0
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-r+oP+tbCxgqXVC3pu3MUVePgSY0ILMjA+aEwOosS77m3/DRbtvHrHwqvMcw+cjANMeGzJ+i0ar+n77KXpRA8RQ==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-yqwl26dLHxWYVcF8drGETF5vU0rmoYd6tY89qeoe9lsS+NWerD/0YkgUnRe1p4ZALiO3vHcxWYoi3dtahAvDZQ==}
- engines: {node: '>=20.0.0'}
-
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-EI6E7KlYzEGXCqfznmkmqebY3XLcqHQNnl/o3rOFRX//LJ4Vc81igwtohmfM/kHnqxE8J/hyItwL5+LdDynXQg==}
engines: {node: '>=20.0.0'}
@@ -1457,10 +1520,6 @@ packages:
resolution: {integrity: sha512-CBC6+tVYaOJo7QXgN1zJ4Ba2f3/Cpy4eRViYFimXW/O5Mn8hBmgXXzHu4vy4ubT80YWnp8aCFygr7dTOa14yQg==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-a/1rbT9Vhz8Z6KXppZFFh+2zuFclkeTkzVJcRHfd4ejqkO/Gdsy7OINCAQHfX3VV0yDhRb7HjoAXy03D9N56rA==}
- engines: {node: '>=20.0.0'}
-
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-OOuGvvz1Dm20SjZo5oEBePFqxt5nf8AwkNDSyUHvD9/bfNASmstcYxFAHUowy4n6Io7mWUZ04JURZwSBvyQanQ==}
engines: {node: '>=20.0.0'}
@@ -1473,10 +1532,6 @@ packages:
resolution: {integrity: sha512-6uaWRRYJGhOqc9EoTSbLDf9nI/doSAb5vAwGshs5/Hlv5Ce25b246lBkbRd/77fLAi+uMI1a70mJzVyLyCEufQ==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-m/+ToPJQkdRF0o9CWaQWFwdsCM1IEsppDHff43/o4fAADAZPx7YRxo18XsKStjghr7QBTdEinE4PdLcmxNqf0w==}
- engines: {node: '>=20.0.0'}
-
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-MlNSvNsSVlMKKWaCzA0GP1nS4Cuq3WCXUN1vmMvd+Ctztib5kmRcpmTtKx9kikN8szAc+gcdp7uqJJervV2nQg==}
engines: {node: '>=20.0.0'}
@@ -1489,18 +1544,26 @@ packages:
resolution: {integrity: sha512-2pA6eyb5nSo/ZD2cayhOTEMoGQYgspq0RI05GDLkzQ3ajZ6isS6waV6E92Am/hz4LIlLUTrbwPLurJ/fuiHvkg==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-BDHTpwcsZHEBNEJzOg/B1BkFYJxAXY50dau/NyVWs3d51F0WgIUGSWZot/Os+N3KpDhXeaXnz37mWffAvduREw==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-VuLXVmm7+lKVxqFcOItPkXhjbJ02iUfxkxheRu41SfWf6/xrZup2A2SwHZos/LeQGu3SBHeqTQht80Uo3ienPA==}
engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-bRqvWgjfJOLakgsmcXgUnTCrTep1B9ppCUjsUyu0M7ueRnVjcNc2uZox/bneCKOgjbzQG7Hs8bo+lTotRdOVOA==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-cCHgOUZmuJ8h7WhAb5cRfDTENjENkee/XQLr01VQ0ZGPoUnBuUTDfdmXqQGe2sETtSCtALDnwrp7q7i1RhNMaw==}
engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-C379Sk+MiFZCfWZphKlMyLHKxV22OjoGM5KJjj5IJNJcOCWL4IGIpnEGzv1FQiRwhYXfq55SJMfxlqPE08JJ9g==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-8+srXqYIF8KYMLC4FxMLEM5Ek7kUNibJu1R4m8/fUhhNYIZZz26oGtKkCr8I/HiG2fFQxBvaGgQZT4/mqRCSnA==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-IL1c54UvbuERrs9oLm5rvkzMciwhhpn1FL0SlC3XUMoLlFhdBsWJgQKK8O5fsQLxbFVqjbjFx9OBkrn44X9PHw==}
engines: {node: '>=20.0.0'}
@@ -1509,10 +1572,18 @@ packages:
resolution: {integrity: sha512-81duvlltQlsfn5K+o8zILcystBRdbT1G2JJYVCML5NZHBz4CL/zf+sAemCtBh/uh6RQUMyInGeZLQ7/8igZhbA==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-s0woKnxuHrExLc5L2ArIH5BMkbonHPtt+5hSBM8oknp9M6QTuUmmAmJ2E0EdzCGONrO+8+ADPqvv6UX0nNcc7A==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-IULn8uBV/SMtmOIANsm4WHXIOtVPBWfOWs3WGL0j/sI+KhaYehvOw0ET+9urnn8MBpiijuU/0JOpuwKOE451PQ==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-QIBrw90CDm4O0UaIIzkU6DrFdeJzEb2Va5EPEVpyldj6sHJxB6cshhStJuhZxk3wR3PmjJlYsjPmY1kNb+KGBg==}
+ engines: {node: '>=20.0.0'}
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-ibx8Vd73rCTHekNGeXX8cpGWoBKbNAlwKHL3yjSxxttu5QnNDaSAM7/0MFYDjU31/F4lyrPoQcGirT0ew61xcg==}
engines: {node: '>=20.0.0'}
@@ -1541,6 +1612,10 @@ packages:
resolution: {integrity: sha512-ezbwz9WpuLctm6o7P2t2naDhVVPI5jFGrVefVybhcKGjU57VIyT46pQVO0RI2RYkUdhdj2Z9uSIlAzGZE9NW9A==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-wHhWL1y7sN3enBA8POrPpQM5jCcmu2ozyhbRei4c8OjVcEaEs6yLucLa/pla457ggS/ysuy7bosagz3HaJkZXA==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==}
engines: {node: '>=18.0.0'}
@@ -1687,6 +1762,9 @@ packages:
resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
engines: {node: '>=6.9.0'}
+ '@balena/[email protected]':
+ resolution: {integrity: sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q==}
+
'@baselime/[email protected]':
resolution: {integrity: sha512-CSI0ELi3PKnTa7ujdz59sfoRSNAxDGIYNgGfOfnQK2/JpKUKyfGwY87oAetMsfFQWH39dBQM89Lbf7knpTdgOA==}
peerDependencies:
@@ -2252,6 +2330,11 @@ packages:
resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
engines: {node: '>=12.10.0'}
+ resolution: {integrity: sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==}
+ engines: {node: '>=6'}
+ hasBin: true
+
resolution: {integrity: sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==}
engines: {node: '>=6'}
@@ -4875,10 +4958,18 @@ packages:
resolution: {integrity: sha512-qoiY4nrk5OCu1+eIR1VB8l5DmON/oKiqrd5zZFAhXJXjJlLWQusKEW/SkBDAtGDcPaz86m9kfcE1lngU0GlM6A==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-L+Ys6ecjk5vwPMAKHBpPKlJ3DkqwNcnfEISXBZIsVvWG/XKXfsAP8mwIYlTeLcd2ElHdesPI8OuOmJSFAPhm6A==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-tHhdiWZfG1ZIh2YcRfPJmY2gHcBmqbAzqm3ER4TIDFYsSEqTD5tICT7cgQ/kI8LRakxp12myOYyK68XPn7MnHw==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-q9J7JTiXrAhB8sDp4px97uEPT7CwKH61Co78grdNQvU8QZAdiuaSRhP0tUVf2ogy36RZTrlMU1rBmDEH+cnkiA==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-rasV+96Obv6tEhWPKWaehEhR+MEd2/lE/rdOYcmSMh6tJiQdoZg4v21p37Y1A7DMZOFgFDUX/3eNl/J3+MJDdA==}
engines: {node: '>=18.0.0'}
@@ -4903,6 +4994,10 @@ packages:
resolution: {integrity: sha512-SK3VMeH0fibgdTg2QeB+O4p7Yy/2E5HBOHJeC58FshkDdeuX8lOgO7PfjYfLyPLP1ch55j91cQqKBzDS0mRjSQ==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-SuqeisTyPoiIPtIYru/sGxGyXzmZ+8nnFOhC+qRPglt06Ebd1yH//CDltZB2J/3WBNVhwfUaZ0EtHB3cm2X32g==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-4a+KoVqr1SZtw7cZvY24XU1S5OL+c23MdDQ3jFmMCQ5s9diBFdMG/UIgp5dNqlwvDrWA0U5KO+z3Gzq1ize+LA==}
engines: {node: '>=18.0.0'}
@@ -4955,6 +5050,10 @@ packages:
resolution: {integrity: sha512-3dA9TQ+ybRSZ/m0wnbZhiBy4Dezjgq1Ib/ZZrYTpJDBgpoLLU/SDzZc/g0x0MNAdOJe1wPcM+x2PBRmoOur+Sw==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-bNqdxTQTxmLbomSmlkZFz8L6B/feQ2HHzw4L2zY7Ecp2XffYAZq2uzdWDdxJHJFbEvqd+SRuluJso0P8+xPdbw==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-/YBWtO2SdvPSAUk/Ke1Xpdg1E1lfaNGblla7mnIVGtaGkSQ5bK7KBZqpuj5IokHlU9UcLDvt2QwTLV7oRzBUTA==}
engines: {node: '>=18.0.0'}
@@ -4975,6 +5074,10 @@ packages:
resolution: {integrity: sha512-QgHflghMoPxCJ9axiCVh8KZfbC9fuP6vkXXyK//E3cq7nLaSSyyLj0GAoqVWezYeDQmXIZhmlRvLE16jsqDK6g==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-B89bpf2t/y/wia6LZ+4JfHXYQT9PnVftsH05rgJKKIStS7r/4XSs9HOjtPoLtgcA6HCW9jVqX5DBbq7E0PAkiQ==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-lysfoRCr7PdD9CsPp9VQuJYRGI5mWYb8FRkbdBSQttxpQmW7tZsFgmpBNKVcgvBsAgBCkYX/UQs0NmznuBcZQQ==}
engines: {node: '>=18.0.0'}
@@ -4983,6 +5086,10 @@ packages:
resolution: {integrity: sha512-x3L0XSACF6UYzKpa9biqiRMgvH5+wnFFew9Tm/grFYqgaupPwx/+ojDPpPJM8dZON3S9tjz5U+PQYsCBd1Mw5Q==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-I5tCWs/ndLrJrbvlnsN1cOt8PVAbQEqg0nNeQqebD5ynQcbhgch9uA7KmpX9vfq/vEudq0iVYAOxt+4aBkUlWA==}
engines: {node: '>=18.0.0'}
@@ -5606,6 +5713,12 @@ packages:
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-yKpAGEuKRSS8wwx0joknWxsmLha78wNMe9R2S3UNsVOkZded8UqOrV8KoeDXoXsjndxwyF3eIhyClGbO1SEhEg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-cmUpB+dPN955PxBEuXE3f6lKO1hHiIGYJA46IVF3BJpNsZGvtBDcRnlrHYHtOH/B6vtDOyl2kZ2ShAu3mgc27Q==}
+
resolution: {integrity: sha512-eOIHzCUSH7SMfonMG1LsC2f8vxBFtho6NGBznK41R84YzPuvSBzrhEps33IsQiOW9+VL6NQ9DbjQJznk/S4uRA==}
@@ -5726,6 +5839,9 @@ packages:
resolution: {integrity: sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ==}
+
resolution: {integrity: sha512-cru1waDhHZnZuB18E6Dgf2UXf8U93mdOEDcKYe5jTri+fpucidSs7DLmGICpLxN+95aYkwtgeyny9fBFzQVdmA==}
@@ -6472,6 +6588,9 @@ packages:
resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==}
+ resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
+
resolution: {integrity: sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
@@ -6517,6 +6636,10 @@ packages:
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
+ resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==}
+ engines: {node: '>=10.0.0'}
+
resolution: {integrity: sha512-UBICMeWLYa+Dz7IGBNebXApQ1OIxNd4t6nX+AFPQ5gFA3sosW34PENe8Q1cvbjcbMTaU3xrKPorb6tM1czRSsw==}
engines: {node: '>=12.22.0'}
@@ -6636,6 +6759,9 @@ packages:
resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}
engines: {node: '>= 20.19.0'}
+ resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
+
resolution: {integrity: sha512-IJnETTalXbsLx1eKEgx19d5L6SRM7cH4vINw/99p/M11HCuXGRWL+6YmCm7FWFGIo6dtWuQoQi1dc5yQ7ESIHg==}
@@ -6813,6 +6939,10 @@ packages:
resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==}
+ resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==}
+ engines: {node: '>=10.0.0'}
+
resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}
@@ -7196,6 +7326,14 @@ packages:
resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
engines: {node: '>=0.3.1'}
+ resolution: {integrity: sha512-XJgGhoR/CLpqshm4d3L7rzH6t8NgDFUIIpztYlLHIApeJjMZKYJMz2zxPsYxnejq5h3ELYSw/RBsi3t5h7gNTA==}
+ engines: {node: '>= 8.0'}
+
+ resolution: {integrity: sha512-/bCZd6KlGcjZO8Buqmi/vXuqEGVEZ0PNjx/biBNqJD3MhK9DmdiAuKxqfNhflgDESDIiBz3qF+0e55+CpnrUcw==}
+ engines: {node: '>= 8.0'}
+
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
@@ -7845,6 +7983,9 @@ packages:
resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
+
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -9198,6 +9339,9 @@ packages:
resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
engines: {node: '>=16 || 14 >=14.17'}
+ resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
+
resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}
@@ -9246,6 +9390,9 @@ packages:
resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==}
engines: {node: ^20.17.0 || >=22.9.0}
+ resolution: {integrity: sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ==}
+
resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -10523,6 +10670,9 @@ packages:
resolution: {integrity: sha512-wcFzz9cDfbuqe0FZzfi2or1sgyIrsDwmPwfZC4hiNidPdPINjeUwNfv5kldczoEAcjl9Y1L3SM7Uz2PUEQzxQw==}
+ resolution: {integrity: sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ==}
+
resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}
engines: {node: '>= 10.x'}
@@ -10530,6 +10680,10 @@ packages:
resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==}
+ resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==}
+ engines: {node: '>=10.16.0'}
+
resolution: {integrity: sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==}
engines: {node: '>=0.10.0'}
@@ -10763,6 +10917,13 @@ packages:
resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==}
+
+ resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==}
engines: {node: '>=14'}
@@ -11002,6 +11163,11 @@ packages:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
typescript: '>=4.8.4 <6.1.0'
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==}
engines: {node: '>=14.17'}
@@ -12024,30 +12190,30 @@ snapshots:
- aws-crt
optional: true
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.27
- '@aws-sdk/credential-provider-node': 3.972.47
+ '@aws-sdk/credential-provider-node': 3.972.66
'@aws-sdk/types': 3.973.15
'@smithy/core': 3.29.1
- '@smithy/fetch-http-handler': 5.4.5
+ '@smithy/fetch-http-handler': 5.6.5
'@smithy/middleware-compression': 4.5.6
- '@smithy/node-http-handler': 4.7.5
+ '@smithy/node-http-handler': 4.9.5
'@smithy/types': 4.15.1
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.27
- '@aws-sdk/credential-provider-node': 3.972.47
+ '@aws-sdk/credential-provider-node': 3.972.66
'@aws-sdk/types': 3.973.15
'@smithy/core': 3.29.1
- '@smithy/fetch-http-handler': 5.4.5
- '@smithy/node-http-handler': 4.7.5
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
'@smithy/types': 4.15.1
tslib: 2.8.1
@@ -12096,51 +12262,60 @@ snapshots:
- aws-crt
optional: true
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.27
- '@aws-sdk/credential-provider-node': 3.972.47
+ '@aws-sdk/credential-provider-node': 3.972.66
'@aws-sdk/types': 3.973.15
'@smithy/core': 3.29.1
- '@smithy/fetch-http-handler': 5.4.5
- '@smithy/node-http-handler': 4.7.5
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
+ '@smithy/types': 4.15.1
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-crypto/sha256-browser': 5.2.0
+ '@aws-crypto/sha256-js': 5.2.0
+ '@aws-sdk/core': 3.974.27
+ '@aws-sdk/credential-provider-node': 3.972.66
+ '@aws-sdk/types': 3.973.15
+ '@smithy/core': 3.29.1
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
'@smithy/types': 4.15.1
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha1-browser': 5.2.0
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.27
- '@aws-sdk/credential-provider-node': 3.972.47
- '@aws-sdk/middleware-bucket-endpoint': 3.972.31
- '@aws-sdk/middleware-expect-continue': 3.972.27
+ '@aws-sdk/credential-provider-node': 3.972.66
'@aws-sdk/middleware-flexible-checksums': 3.974.37
- '@aws-sdk/middleware-location-constraint': 3.972.24
'@aws-sdk/middleware-sdk-s3': 3.972.58
- '@aws-sdk/middleware-ssec': 3.972.24
'@aws-sdk/signature-v4-multi-region': 3.996.38
'@aws-sdk/types': 3.973.15
'@smithy/core': 3.29.1
- '@smithy/fetch-http-handler': 5.4.5
- '@smithy/node-http-handler': 4.7.5
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
'@smithy/types': 4.15.1
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.27
- '@aws-sdk/credential-provider-node': 3.972.47
+ '@aws-sdk/credential-provider-node': 3.972.66
'@aws-sdk/signature-v4-multi-region': 3.996.38
'@aws-sdk/types': 3.973.15
'@smithy/core': 3.29.1
- '@smithy/fetch-http-handler': 5.4.5
- '@smithy/node-http-handler': 4.7.5
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
'@smithy/types': 4.15.1
tslib: 2.8.1
@@ -12155,12 +12330,23 @@ snapshots:
bowser: 2.14.1
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/nested-clients': 3.997.13
- '@aws-sdk/types': 3.973.15
- '@smithy/core': 3.29.1
- '@smithy/types': 4.15.1
+ '@aws-sdk/types': 3.974.0
+ '@aws-sdk/xml-builder': 3.972.34
+ '@aws/lambda-invoke-store': 0.3.0
+ '@smithy/core': 3.29.3
+ '@smithy/signature-v4': 5.6.4
+ '@smithy/types': 4.16.1
+ bowser: 2.14.1
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/nested-clients': 3.997.31
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
tslib: 2.8.1
'@aws-sdk/[email protected]':
@@ -12170,6 +12356,15 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12180,6 +12375,17 @@ snapshots:
'@smithy/node-http-handler': 4.7.5
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12196,6 +12402,23 @@ snapshots:
'@smithy/credential-provider-imds': 4.3.6
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/credential-provider-env': 3.972.57
+ '@aws-sdk/credential-provider-http': 3.972.59
+ '@aws-sdk/credential-provider-login': 3.972.63
+ '@aws-sdk/credential-provider-process': 3.972.57
+ '@aws-sdk/credential-provider-sso': 3.973.1
+ '@aws-sdk/credential-provider-web-identity': 3.972.63
+ '@aws-sdk/nested-clients': 3.997.31
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/credential-provider-imds': 4.4.8
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12205,6 +12428,16 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/nested-clients': 3.997.31
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12219,6 +12452,21 @@ snapshots:
'@smithy/credential-provider-imds': 4.3.6
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/credential-provider-env': 3.972.57
+ '@aws-sdk/credential-provider-http': 3.972.59
+ '@aws-sdk/credential-provider-ini': 3.973.1
+ '@aws-sdk/credential-provider-process': 3.972.57
+ '@aws-sdk/credential-provider-sso': 3.973.1
+ '@aws-sdk/credential-provider-web-identity': 3.972.63
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/credential-provider-imds': 4.4.8
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12227,6 +12475,15 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12237,6 +12494,17 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/nested-clients': 3.997.31
+ '@aws-sdk/token-providers': 3.1083.0
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12246,24 +12514,34 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/nested-clients': 3.997.31
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/client-cognito-identity': 3.1056.0
+ '@aws-sdk/client-cognito-identity': 3.1074.0
'@aws-sdk/core': 3.974.27
- '@aws-sdk/credential-provider-cognito-identity': 3.972.38
- '@aws-sdk/credential-provider-env': 3.972.41
- '@aws-sdk/credential-provider-http': 3.972.43
- '@aws-sdk/credential-provider-ini': 3.972.46
- '@aws-sdk/credential-provider-login': 3.972.45
- '@aws-sdk/credential-provider-node': 3.972.47
- '@aws-sdk/credential-provider-process': 3.972.41
- '@aws-sdk/credential-provider-sso': 3.972.45
- '@aws-sdk/credential-provider-web-identity': 3.972.45
- '@aws-sdk/nested-clients': 3.997.13
+ '@aws-sdk/credential-provider-cognito-identity': 3.972.56
+ '@aws-sdk/credential-provider-env': 3.972.57
+ '@aws-sdk/credential-provider-http': 3.972.59
+ '@aws-sdk/credential-provider-ini': 3.973.1
+ '@aws-sdk/credential-provider-login': 3.972.63
+ '@aws-sdk/credential-provider-node': 3.972.66
+ '@aws-sdk/credential-provider-process': 3.972.57
+ '@aws-sdk/credential-provider-sso': 3.973.1
+ '@aws-sdk/credential-provider-web-identity': 3.972.63
+ '@aws-sdk/nested-clients': 3.997.31
'@aws-sdk/types': 3.973.15
'@smithy/core': 3.29.1
- '@smithy/credential-provider-imds': 4.3.6
+ '@smithy/credential-provider-imds': 4.4.8
'@smithy/types': 4.15.1
tslib: 2.8.1
@@ -12275,9 +12553,9 @@ snapshots:
tslib: 2.8.1
optional: true
- '@aws-sdk/[email protected](@aws-sdk/[email protected])':
+ '@aws-sdk/[email protected](@aws-sdk/[email protected])':
dependencies:
- '@aws-sdk/client-s3': 3.1056.0
+ '@aws-sdk/client-s3': 3.1074.0
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
buffer: 5.6.0
@@ -12285,11 +12563,6 @@ snapshots:
stream-browserify: 3.0.0
tslib: 2.8.1
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/middleware-sdk-s3': 3.972.58
- tslib: 2.8.1
-
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/types': 3.973.15
@@ -12298,11 +12571,6 @@ snapshots:
tslib: 2.8.1
optional: true
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/middleware-sdk-s3': 3.972.58
- tslib: 2.8.1
-
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/checksums': 3.1000.12
@@ -12316,11 +12584,6 @@ snapshots:
tslib: 2.8.1
optional: true
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/middleware-sdk-s3': 3.972.58
- tslib: 2.8.1
-
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/types': 3.973.15
@@ -12346,11 +12609,6 @@ snapshots:
'@smithy/types': 4.15.1
tslib: 2.8.1
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/middleware-sdk-s3': 3.972.58
- tslib: 2.8.1
-
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/core': 3.974.27
@@ -12389,6 +12647,18 @@ snapshots:
'@smithy/node-http-handler': 4.7.5
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/signature-v4-multi-region': 3.996.39
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/fetch-http-handler': 5.6.5
+ '@smithy/node-http-handler': 4.9.5
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
@@ -12398,7 +12668,7 @@ snapshots:
tslib: 2.8.1
optional: true
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/core': 3.974.27
'@aws-sdk/signature-v4-multi-region': 3.996.38
@@ -12414,6 +12684,13 @@ snapshots:
'@smithy/types': 4.15.1
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.974.0
+ '@smithy/signature-v4': 5.6.4
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/core': 3.974.27
@@ -12433,12 +12710,27 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.975.1
+ '@aws-sdk/nested-clients': 3.997.31
+ '@aws-sdk/types': 3.974.0
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
'@smithy/types': 4.15.1
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
+
'@aws-sdk/[email protected]':
dependencies:
'@aws-sdk/types': 3.973.15
@@ -12481,6 +12773,11 @@ snapshots:
'@smithy/types': 4.15.1
tslib: 2.8.1
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
+
optional: true
@@ -12697,6 +12994,8 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
+ '@balena/[email protected]': {}
+
dependencies:
'@opentelemetry/api': 1.9.1
@@ -13331,6 +13630,13 @@ snapshots:
'@grpc/proto-loader': 0.8.0
'@js-sdsl/ordered-map': 4.4.2
+ dependencies:
+ lodash.camelcase: 4.3.0
+ long: 5.3.2
+ protobufjs: 7.6.5
+ yargs: 17.7.2
+
dependencies:
lodash.camelcase: 4.3.0
@@ -15902,11 +16208,23 @@ snapshots:
'@smithy/types': 4.15.1
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@smithy/[email protected]':
dependencies:
@@ -15945,6 +16263,13 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@smithy/[email protected]':
dependencies:
@@ -16022,6 +16347,13 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
'@smithy/[email protected]':
dependencies:
@@ -16052,6 +16384,12 @@ snapshots:
'@smithy/types': 4.15.1
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.29.3
+ '@smithy/types': 4.16.1
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
@@ -16063,6 +16401,10 @@ snapshots:
dependencies:
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
@@ -16685,6 +17027,17 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 24.3.0
+ '@types/ssh2': 1.15.5
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/docker-modem': 3.0.6
+ '@types/node': 24.3.0
+ '@types/ssh2': 1.15.5
+
'@types/[email protected]': {}
@@ -16815,6 +17168,10 @@ snapshots:
'@types/http-errors': 2.0.5
'@types/node': 24.3.0
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 18.19.123
+
dependencies:
'@types/node': 24.3.0
@@ -17652,6 +18009,12 @@ snapshots:
+ dependencies:
+ buffer: 5.6.0
+ inherits: 2.0.4
+ readable-stream: 3.6.2
+
dependencies:
bytes: 3.1.2
@@ -17726,6 +18089,9 @@ snapshots:
base64-js: 1.5.1
ieee754: 1.2.1
+ optional: true
+
dependencies:
cron-parser: 4.9.0
@@ -17878,6 +18244,8 @@ snapshots:
dependencies:
readdirp: 5.0.0
+
@@ -18040,6 +18408,12 @@ snapshots:
dependencies:
layout-base: 2.0.1
+ dependencies:
+ buildcheck: 0.0.7
+ nan: 2.28.0
+ optional: true
+
@@ -18419,6 +18793,27 @@ snapshots:
+ dependencies:
+ debug: 4.4.3
+ readable-stream: 3.6.2
+ split-ca: 1.0.1
+ ssh2: 1.17.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@balena/dockerignore': 1.0.2
+ '@grpc/grpc-js': 1.14.4
+ '@grpc/proto-loader': 0.7.15
+ docker-modem: 5.0.7
+ protobufjs: 7.6.5
+ tar-fs: 2.1.5
+ uuid: 10.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
esutils: 2.0.3
@@ -19285,6 +19680,8 @@ snapshots:
+
optional: true
@@ -20897,6 +21294,8 @@ snapshots:
+
dependencies:
acorn: 8.16.0
@@ -20961,6 +21360,9 @@ snapshots:
+ optional: true
+
@@ -22515,10 +22917,20 @@ snapshots:
optional: true
+
+ dependencies:
+ asn1: 0.2.6
+ bcrypt-pbkdf: 1.0.2
+ optionalDependencies:
+ cpu-features: 0.0.10
+ nan: 2.28.0
+
dependencies:
asn1: 0.2.6
@@ -22787,6 +23199,21 @@ snapshots:
+ dependencies:
+ chownr: 1.1.4
+ mkdirp-classic: 0.5.3
+ pump: 3.0.4
+ tar-stream: 2.2.0
+
+ dependencies:
+ bl: 4.1.0
+ end-of-stream: 1.4.5
+ fs-constants: 1.0.0
+ inherits: 2.0.4
+ readable-stream: 3.6.2
+
dependencies:
http-proxy-agent: 5.0.0
@@ -23007,6 +23434,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index a5c806a2aa..2c77055c70 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -5,13 +5,14 @@ packages:
- "packages/**"
- "ee"
catalog:
- "@aws-sdk/client-cloudwatch": 3.1056.0
- "@aws-sdk/client-lambda": 3.1056.0
- "@aws-sdk/client-s3": 3.1056.0
- "@aws-sdk/client-sesv2": 3.1056.0
- "@aws-sdk/credential-providers": 3.1056.0
- "@aws-sdk/lib-storage": 3.1056.0
- "@aws-sdk/s3-request-presigner": 3.1056.0
+ "@aws-sdk/client-cloudwatch": 3.1074.0
+ "@aws-sdk/client-lambda": 3.1074.0
+ "@aws-sdk/client-lambda-microvms": 3.1074.0
+ "@aws-sdk/client-s3": 3.1074.0
+ "@aws-sdk/client-sesv2": 3.1074.0
+ "@aws-sdk/credential-providers": 3.1074.0
+ "@aws-sdk/lib-storage": 3.1074.0
+ "@aws-sdk/s3-request-presigner": 3.1074.0
typescript: ^6.0.3
# 5 day delay for new dep upgrades to reduce supply chain attack risk
minimumReleaseAge: 7200
@@ -37,6 +38,8 @@ allowBuilds:
protobufjs: false
"@datadog/pprof": false
"@scarf/scarf": false
+ cpu-features: true
+ ssh2: true
overrides:
esbuild: "0.28.1"
"undici@7": 7.28.0
diff --git a/scripts/codex/setup.sh b/scripts/codex/setup.sh
index 1c6245840c..b3b620c3e2 100755
--- a/scripts/codex/setup.sh
+++ b/scripts/codex/setup.sh
@@ -26,6 +26,16 @@ ensure_env_file .env.test .env.test.example
pnpm install --frozen-lockfile
+if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
+ if ! docker image inspect "langfuse-in-app-agent-sandbox:latest" >/dev/null 2>&1; then
+ rm -f "packages/in-app-agent-sandbox-runtime/.local-image-built"
+ fi
+
+ pnpm turbo run build:docker-image --filter @repo/in-app-agent-sandbox-runtime --output-logs errors-only
+else
+ echo "Skipping local in-app agent sandbox image build because Docker is not available."
+fi
+
# Install Chromium into the default user-level Playwright cache so frontend
# browser review works on first bootstrap.
pnpm run playwright:install
diff --git a/turbo.json b/turbo.json
index d792804a6b..67af06e22f 100644
--- a/turbo.json
+++ b/turbo.json
@@ -104,6 +104,13 @@
"cache": true,
"outputLogs": "errors-only"
},
+ "@repo/in-app-agent-sandbox-runtime#build:docker-image": {
+ "dependsOn": ["build"],
+ "inputs": ["Dockerfile", "package.json", "tsconfig.json"],
+ "outputs": [".local-image-built"],
+ "cache": true,
+ "outputLogs": "errors-only"
+ },
"worker#dev": {
"cache": false,
"persistent": true
diff --git a/web/next.config.mjs b/web/next.config.mjs
index cd60902aa9..0ace902652 100644
--- a/web/next.config.mjs
+++ b/web/next.config.mjs
@@ -82,6 +82,10 @@ const nextConfig = {
"bullmq",
"@opentelemetry/sdk-node",
"@opentelemetry/instrumentation-winston",
+ // The local-only dangerous-docker sandbox provider depends on dockerode,
+ // which pulls ssh2 assets that Turbopack cannot place into ESM chunks.
+ // Keep it external to the server bundle and load it only at runtime.
+ "dockerode",
],
poweredByHeader: false,
basePath: env.NEXT_PUBLIC_BASE_PATH,
diff --git a/web/package.json b/web/package.json
index c477f53c91..d9a595a21d 100644
--- a/web/package.json
+++ b/web/package.json
@@ -36,6 +36,7 @@
"@appsignal/opentelemetry-instrumentation-bullmq": "^0.8.0",
"@astral-sh/ruff-wasm-web": "0.15.13",
"@aws-crypto/sha256-browser": "^5.2.0",
+ "@aws-sdk/client-lambda-microvms": "catalog:",
"@aws-sdk/credential-providers": "catalog:",
"@baselime/trpc-opentelemetry-middleware": "^0.1.2",
"@codemirror/autocomplete": "^6.17.0",
@@ -187,6 +188,7 @@
"@types/cors": "^2.8.19",
"@types/d3-selection": "^3.0.11",
"@types/d3-zoom": "^3.0.8",
+ "@types/dockerode": "^4.0.1",
"@types/lodash": "^4.17.24",
"@types/node": "24.3.0",
"@types/react": "19.2.14",
@@ -195,6 +197,7 @@
"@typescript/native-preview": "7.0.0-dev.20260122.3",
"@vitejs/plugin-react": "^4.7.0",
"@vitest/browser-playwright": "4.1.8",
+ "dockerode": "^4.0.9",
"dotenv": "^16.6.1",
"dotenv-cli": "^7.4.2",
"dotenv-expand": "^10.0.0",
diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
index b98bce59d7..80be0ccdb4 100644
--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts
@@ -1,7 +1,12 @@
+import { EventType } from "@ag-ui/core";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { filterInAppAgentAvailableLangfuseMcpTools } from "@/src/ee/features/in-app-agent/server/tools";
import { storePendingToolApproval } from "@/src/ee/features/in-app-agent/server/human-in-the-loop";
-import type { InAppAgentToolApprovalRequest } from "@/src/ee/features/in-app-agent/schema";
+import type {
+ AgUiEvent,
+ InAppAgentToolApprovalRequest,
+} from "@/src/ee/features/in-app-agent/schema";
+import { replaceRunEvents } from "@/src/ee/features/in-app-agent/server/persistence";
import { env } from "@/src/env.mjs";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -33,6 +38,9 @@ const agentMocks = vi.hoisted(() => ({
createAgUiStream: vi.fn(),
}));
+const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
+ "Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";
+
const langfuseClientMocks = vi.hoisted(() => ({
getLangfuseClient: vi.fn(() => ({})),
}));
@@ -614,6 +622,152 @@ describe("in-app agent public API route auth", () => {
});
});
+ it("blocks writes to old conversations with sandbox tool history", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { project, userId } = await setupInAppAgentProjectSession();
+ const conversationId = `conversation-${randomUUID()}`;
+ const createdAt = new Date(Date.now() - 9 * 60 * 60 * 1000);
+
+ await prisma.inAppAgentConversation.create({
+ data: {
+ id: conversationId,
+ projectId: project.id,
+ createdByUserId: userId,
+ title: "Old sandbox conversation",
+ createdAt,
+ },
+ });
+ await prisma.inAppAgentRun.create({
+ data: {
+ id: "run-old-sandbox",
+ projectId: project.id,
+ conversationId,
+ triggeredByUserId: userId,
+ model: "haiku",
+ mcpApiKeyId: "api-key-old-sandbox",
+ },
+ });
+ await replaceRunEvents({
+ prisma,
+ projectId: project.id,
+ conversationId,
+ runId: "run-old-sandbox",
+ events: [
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-call-1",
+ toolCallName: "bash",
+ } as AgUiEvent,
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-call-1",
+ content: "done",
+ } as AgUiEvent,
+ ],
+ });
+
+ const { default: handler } =
+ await import("@/src/ee/features/in-app-agent/server/handler");
+ const response = await handler(
+ new Request("http://localhost/api/in-app-agent", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ threadId: conversationId,
+ runId: "client-run-locked",
+ messages: [{ id: "message-1", role: "user", content: "hello" }],
+ tools: [],
+ context: [],
+ state: {
+ type: "existingConversation",
+ projectId: project.id,
+ conversationId,
+ },
+ forwardedProps: {},
+ }),
+ }),
+ );
+
+ expect(response.status).toBe(412);
+ await expect(response.json()).resolves.toEqual({
+ error: SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ });
+ expect(agentMocks.createAgUiStream).not.toHaveBeenCalled();
+ });
+ });
+
+ it("blocks resume writes to old conversations with sandbox tool history", async () => {
+ await withInAppAgentCloudEnv(async () => {
+ const { project, userId } = await setupInAppAgentProjectSession();
+ const conversationId = `conversation-${randomUUID()}`;
+ const createdAt = new Date(Date.now() - 9 * 60 * 60 * 1000);
+ const forwardedProps = createResumeForwardedProps();
+
+ await prisma.inAppAgentConversation.create({
+ data: {
+ id: conversationId,
+ projectId: project.id,
+ createdByUserId: userId,
+ title: "Old sandbox resume conversation",
+ createdAt,
+ },
+ });
+ await prisma.inAppAgentRun.create({
+ data: {
+ id: "run-old-sandbox-resume",
+ projectId: project.id,
+ conversationId,
+ triggeredByUserId: userId,
+ model: "haiku",
+ mcpApiKeyId: "api-key-old-sandbox-resume",
+ },
+ });
+ await replaceRunEvents({
+ prisma,
+ projectId: project.id,
+ conversationId,
+ runId: "run-old-sandbox-resume",
+ events: [
+ {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-call-1",
+ toolCallName: "write",
+ } as AgUiEvent,
+ {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-call-1",
+ content: "done",
+ } as AgUiEvent,
+ ],
+ });
+ await seedPendingToolApproval({
+ projectId: project.id,
+ conversationId,
+ userId,
+ approvalRequest: forwardedProps.command.resume.approvalRequest,
+ });
+
+ const { response } = await callInAppAgentRoute({
+ projectId: project.id,
+ conversationId,
+ forwardedProps,
+ });
+
+ expect(response.status).toBe(412);
+ await expect(response.json()).resolves.toEqual({
+ error: SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ });
+ await expect(
+ pendingToolApprovalExists({
+ projectId: project.id,
+ conversationId,
+ toolCallId: forwardedProps.command.resume.approvalRequest.toolCallId,
+ }),
+ ).resolves.toBe(true);
+ expect(agentMocks.createAgUiStream).not.toHaveBeenCalled();
+ });
+ });
+
it("returns 429 when an in-app agent run exceeds the rate limit", async () => {
const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;
diff --git a/web/src/__tests__/server/in-app-agent-router.servertest.ts b/web/src/__tests__/server/in-app-agent-router.servertest.ts
index 861af6d490..1c81551cc2 100644
--- a/web/src/__tests__/server/in-app-agent-router.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-router.servertest.ts
@@ -1,5 +1,6 @@
import { randomUUID } from "crypto";
import type { Session } from "next-auth";
+import { describe, expect, it } from "vitest";
import { prisma } from "@langfuse/shared/src/db";
import { appRouter } from "@/src/server/api/root";
@@ -8,7 +9,11 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";
describe("in-app agent router", () => {
it("soft-deletes an owned conversation", async () => {
const { caller, projectId, userId } = await createCaller();
- const conversation = await createConversation({ projectId, userId });
+ const conversation = await createConversation({
+ projectId,
+ userId,
+ providerSessionId: "session-1",
+ });
await caller.inAppAgent.deleteConversation({
projectId,
@@ -26,6 +31,7 @@ describe("in-app agent router", () => {
});
expect(deletedConversation.deletedAt).toBeInstanceOf(Date);
+ expect(deletedConversation.providerSessionId).toBeNull();
});
it("excludes deleted conversations from list and get", async () => {
@@ -203,10 +209,12 @@ async function createConversation({
projectId,
userId,
title = "Test conversation",
+ providerSessionId,
}: {
projectId: string;
userId: string;
title?: string;
+ providerSessionId?: string;
}) {
return prisma.inAppAgentConversation.create({
data: {
@@ -214,6 +222,7 @@ async function createConversation({
projectId,
createdByUserId: userId,
title,
+ providerSessionId,
},
});
}
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index 6ba61ab1e5..78bb1614e5 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -10,6 +10,11 @@ import {
IN_APP_AGENT_REDIRECT_TOOL_NAME,
} from "@/src/ee/features/in-app-agent/constants";
import { patchMastraToolCallInputStreaming } from "@/src/ee/features/in-app-agent/server/agent";
+import {
+ createInAppAgentSandbox,
+ type SandboxProvider,
+ type SandboxSession,
+} from "@/src/ee/features/in-app-agent/server/sandbox";
import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_POLICIES } from "@/src/ee/features/in-app-agent/server/tools";
import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@/src/features/filters/constants/internal-environments";
import { decodeFiltersGeneric } from "@/src/features/filters/lib/filter-query-encoding";
@@ -81,6 +86,71 @@ const defaultInAppAgentUserAccess = {
isAdmin: false,
};
+async function createTestSandbox() {
+ let sandboxState: {
+ providerSessionId: string | null;
+ } = {
+ providerSessionId: null,
+ };
+ let sessionCounter = 0;
+ const files = new Map<string, string>();
+ let activeSessionId: string | null = null;
+ const sandboxSession: SandboxSession = {
+ async syncReadonlyFiles({ files: readonlyFiles }) {
+ for (const key of Array.from(files.keys())) {
+ if (key.startsWith("tool_calls/")) files.delete(key);
+ }
+ for (const file of readonlyFiles) {
+ files.set(file.path, file.content);
+ }
+ },
+ async read({ path }) {
+ return { path, content: files.get(path) ?? null };
+ },
+ async write({ path, content }) {
+ files.set(path, content);
+ return { path, bytesWritten: content.length };
+ },
+ async edit({ path, oldText, newText }) {
+ const current = files.get(path) ?? "";
+ const replaced = current.includes(oldText);
+ if (replaced) files.set(path, current.replace(oldText, newText));
+ return { path, replaced };
+ },
+ async bash() {
+ return { stdout: "", stderr: "", exitCode: 0 };
+ },
+ };
+
+ const provider: SandboxProvider = {
+ async ensureSession({ sessionId }) {
+ if (sessionId && activeSessionId === sessionId) {
+ return { sessionId, sandbox: sandboxSession };
+ }
+
+ activeSessionId = `sandbox-session-${sessionCounter++}`;
+ files.clear();
+ return { sessionId: activeSessionId, sandbox: sandboxSession };
+ },
+ };
+
+ return createInAppAgentSandbox({
+ conversationId: "conversation-1",
+ projectId: "project-1",
+ providerSessionId: sandboxState.providerSessionId,
+ provider,
+ getToolCallFiles: async () => [],
+ saveState: async (nextState) => {
+ sandboxState = {
+ ...sandboxState,
+ ...nextState,
+ providerSessionId:
+ nextState.providerSessionId ?? sandboxState.providerSessionId,
+ };
+ },
+ });
+}
+
vi.mock("@ag-ui/mastra", () => ({
MastraAgent: vi.fn().mockImplementation(function () {
return {
@@ -349,6 +419,70 @@ describe("patchMastraToolCallInputStreaming", () => {
]);
});
+ it("passes non-tool streaming chunks through unchanged", () => {
+ const { forwardedChunks, onError, processor } =
+ createPatchedChunkProcessor();
+
+ processor.handleChunk({
+ type: "step-start",
+ payload: {},
+ });
+ processor.handleChunk({
+ type: "text-start",
+ payload: { textMessageId: "assistant-1" },
+ });
+ processor.handleChunk({
+ type: "text-delta",
+ payload: {
+ textMessageId: "assistant-1",
+ textDelta: "Investigating...",
+ },
+ });
+ processor.handleChunk({
+ type: "tool-result",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "langfuseDocs_search",
+ result: { ok: true },
+ },
+ });
+ processor.handleChunk({
+ type: "step-finish",
+ payload: {},
+ });
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(forwardedChunks).toEqual([
+ {
+ type: "step-start",
+ payload: {},
+ },
+ {
+ type: "text-start",
+ payload: { textMessageId: "assistant-1" },
+ },
+ {
+ type: "text-delta",
+ payload: {
+ textMessageId: "assistant-1",
+ textDelta: "Investigating...",
+ },
+ },
+ {
+ type: "tool-result",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "langfuseDocs_search",
+ result: { ok: true },
+ },
+ },
+ {
+ type: "step-finish",
+ payload: {},
+ },
+ ]);
+ });
+
it("passes through native tool-calls that were not synthesized", () => {
const { forwardedChunks, processor } = createPatchedChunkProcessor();
@@ -373,6 +507,66 @@ describe("patchMastraToolCallInputStreaming", () => {
]);
});
+ it("keeps suppressing the duplicate native tool-call after a tool-result arrives", () => {
+ const { forwardedChunks, onError, processor } =
+ createPatchedChunkProcessor();
+
+ processor.handleChunk({
+ type: "tool-call-input-streaming-start",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ },
+ });
+ processor.handleChunk({
+ type: "tool-call-delta",
+ payload: {
+ toolCallId: "tool-call-1",
+ argsTextDelta: '{"command":"date"}',
+ },
+ });
+ processor.handleChunk({
+ type: "tool-call-input-streaming-end",
+ payload: { toolCallId: "tool-call-1" },
+ });
+ processor.handleChunk({
+ type: "tool-result",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ result: "Wed Jul 08 2026",
+ },
+ });
+ processor.handleChunk({
+ type: "tool-call",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ args: { command: "date" },
+ },
+ });
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(forwardedChunks).toEqual([
+ {
+ type: "tool-call",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ args: { command: "date" },
+ },
+ },
+ {
+ type: "tool-result",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ result: "Wed Jul 08 2026",
+ },
+ },
+ ]);
+ });
+
it("converts tool-call approval chunks to suspended tool calls", () => {
const { forwardedChunks, onError, processor } =
createPatchedChunkProcessor();
@@ -518,6 +712,161 @@ describe("patchMastraToolCallInputStreaming", () => {
);
expect(forwardedChunks).toEqual([]);
});
+
+ it("passes through text streaming chunks", () => {
+ const { forwardedChunks, onError, processor } =
+ createPatchedChunkProcessor();
+
+ processor.handleChunk({
+ type: "text-start",
+ payload: { textMessageId: "message-1" },
+ });
+ processor.handleChunk({
+ type: "text-delta",
+ payload: { textMessageId: "message-1", textDelta: "hello" },
+ });
+ processor.handleChunk({
+ type: "text-end",
+ payload: { textMessageId: "message-1" },
+ });
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(forwardedChunks).toEqual([
+ {
+ type: "text-start",
+ payload: { textMessageId: "message-1" },
+ },
+ {
+ type: "text-delta",
+ payload: { textMessageId: "message-1", textDelta: "hello" },
+ },
+ {
+ type: "text-end",
+ payload: { textMessageId: "message-1" },
+ },
+ ]);
+ });
+
+ it("passes lifecycle chunks through unchanged", () => {
+ const { forwardedChunks, onError, processor } =
+ createPatchedChunkProcessor();
+
+ processor.handleChunk({
+ type: "start",
+ runId: "run-1",
+ from: "AGENT",
+ payload: { id: "langfuse-in-app-assistant", messageId: "message-1" },
+ });
+ processor.handleChunk({
+ type: "step-start",
+ runId: "run-1",
+ from: "AGENT",
+ payload: { request: {}, warnings: [], messageId: "message-1" },
+ });
+ processor.handleChunk({
+ type: "step-finish",
+ runId: "run-1",
+ from: "AGENT",
+ payload: {
+ messageId: "message-1",
+ stepResult: { reason: "tool-calls", isContinued: true },
+ },
+ });
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(forwardedChunks).toEqual([
+ {
+ type: "start",
+ from: "AGENT",
+ runId: "run-1",
+ payload: {
+ id: "langfuse-in-app-assistant",
+ messageId: "message-1",
+ },
+ },
+ {
+ type: "step-start",
+ from: "AGENT",
+ runId: "run-1",
+ payload: {
+ messageId: "message-1",
+ request: {},
+ warnings: [],
+ },
+ },
+ {
+ type: "step-finish",
+ from: "AGENT",
+ runId: "run-1",
+ payload: {
+ messageId: "message-1",
+ stepResult: {
+ isContinued: true,
+ reason: "tool-calls",
+ },
+ },
+ },
+ ]);
+ });
+
+ it("converts tool-error chunks to tool-result error chunks", () => {
+ const { forwardedChunks, onError, processor } =
+ createPatchedChunkProcessor();
+
+ processor.handleChunk({
+ type: "tool-error",
+ runId: "run-1",
+ from: "AGENT",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ args: { command: "date" },
+ error: {
+ details: { errorMessage: "Error: Region is missing" },
+ },
+ },
+ });
+
+ expect(onError).not.toHaveBeenCalled();
+ expect(forwardedChunks).toEqual([
+ {
+ type: "tool-result",
+ payload: {
+ toolCallId: "tool-call-1",
+ toolName: "bash",
+ args: { command: "date" },
+ isError: true,
+ result: JSON.stringify(
+ {
+ error: "Error: Region is missing",
+ },
+ null,
+ 2,
+ ),
+ },
+ },
+ ]);
+ });
+
+ it("reports malformed tool-error chunks", () => {
+ const { forwardedChunks, onError, processor } =
+ createPatchedChunkProcessor();
+
+ const shouldStop = processor.handleChunk({
+ type: "tool-error",
+ payload: {
+ error: { message: "boom" },
+ },
+ });
+
+ expect(shouldStop).toBe(true);
+ expect(onError).toHaveBeenCalledWith(
+ new Error(
+ "Malformed tool-error: missing toolCallId or toolName in payload",
+ ),
+ );
+ expect(forwardedChunks).toEqual([]);
+ });
});
describe("IN_APP_AGENT_LANGFUSE_MCP_TOOL_APPROVALS", () => {
@@ -591,6 +940,9 @@ describe("createAgUiStream", () => {
const langfuseClient = {
getPrompt: promptMocks.getPrompt,
} as unknown as Langfuse;
+
+ const sandboxState = await createTestSandbox();
+
adapterEvents.inputs = [];
adapterEvents.items = [
@@ -668,6 +1020,8 @@ describe("createAgUiStream", () => {
isV4Enabled: false,
},
langfuseClient,
+ sandbox: sandboxState.sandbox,
+ onFinish: sandboxState.onTurnEnded,
useLocalPrompt: false,
langfuseTracing: createTestTracingConfig(),
},
@@ -698,6 +1052,18 @@ describe("createAgUiStream", () => {
server: "langfuseDocs",
execute: expect.any(Function),
}),
+ read: expect.objectContaining({
+ id: "read",
+ }),
+ write: expect.objectContaining({
+ id: "write",
+ }),
+ edit: expect.objectContaining({
+ id: "edit",
+ }),
+ bash: expect.objectContaining({
+ id: "bash",
+ }),
langfuse_proposeRedirect: expect.objectContaining({
id: "langfuse_proposeRedirect",
}),
@@ -730,6 +1096,10 @@ describe("createAgUiStream", () => {
expect(agentTools?.langfuseDocs_fetch).not.toHaveProperty(
"requireApproval",
);
+ expect(agentTools?.read?.requireApproval).not.toBe(true);
+ expect(agentTools?.write?.requireApproval).not.toBe(true);
+ expect(agentTools?.edit?.requireApproval).not.toBe(true);
+ expect(agentTools?.bash?.requireApproval).not.toBe(true);
expect(
agentTools?.[IN_APP_AGENT_REDIRECT_TOOL_NAME]?.requireApproval,
).not.toBe(true);
@@ -777,6 +1147,7 @@ describe("createAgUiStream", () => {
expect.objectContaining({
currentDate: expect.any(String),
redirectToolName: IN_APP_AGENT_REDIRECT_TOOL_NAME,
+ sandboxFilesystem: expect.stringContaining("<sandbox_filesystem>"),
screenContext: expect.stringContaining("<screen_context>"),
userContext: expect.stringContaining("<user_context>"),
sidebarHiddenEnvironments: DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS.map(
@@ -1666,6 +2037,75 @@ describe("createAgUiStream", () => {
fetchMock.mockRestore();
}
});
+
+ it("does not expose sandbox tools when sandboxing is disabled", async () => {
+ const { createAgUiStream } =
+ await import("@/src/ee/features/in-app-agent/server/agent");
+ const input = {
+ threadId: "conversation-1",
+ runId: "run-1",
+ messages: [
+ {
+ id: "user-message-1",
+ role: "user" as const,
+ content: "hello",
+ },
+ ],
+ tools: [],
+ context: [],
+ state: null,
+ forwardedProps: {},
+ };
+
+ adapterEvents.items = [
+ {
+ type: EventType.RUN_STARTED,
+ threadId: input.threadId,
+ runId: input.runId,
+ },
+ {
+ type: EventType.RUN_FINISHED,
+ threadId: input.threadId,
+ runId: input.runId,
+ },
+ ];
+
+ const stream = await createAgUiStream({
+ input,
+ signal: new AbortController().signal,
+ options: {
+ awsBedrock: { modelId: "test-model" },
+ langfuseMcp: {
+ url: "https://example.com/api/public/mcp",
+ publicKey: "pk",
+ secretKey: "sk",
+ userAccess: defaultInAppAgentUserAccess,
+ },
+ redirectAction: {
+ projectId: "project-1",
+ isV4Enabled: false,
+ },
+ langfuseClient: {
+ getPrompt: promptMocks.getPrompt,
+ } as unknown as Langfuse,
+ useLocalPrompt: false,
+ },
+ });
+
+ await readStream(stream);
+
+ const agentConfig = vi.mocked(Agent).mock.calls.at(-1)?.[0];
+
+ expect(agentConfig?.tools).not.toHaveProperty("read");
+ expect(agentConfig?.tools).not.toHaveProperty("write");
+ expect(agentConfig?.tools).not.toHaveProperty("edit");
+ expect(agentConfig?.tools).not.toHaveProperty("bash");
+ expect(promptMocks.compile).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sandboxFilesystem: "",
+ }),
+ );
+ });
});
async function readStream(
diff --git a/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.ts
new file mode 100644
index 0000000000..49c77bca5a
--- /dev/null
+++ b/web/src/__tests__/server/unit/in-app-agent-docker-provider.servertest.ts
@@ -0,0 +1,192 @@
+import { PassThrough } from "node:stream";
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type FakeContainerState = {
+ containersById: Map<string, FakeContainer>;
+ containersByName: Map<string, FakeContainer>;
+ createCount: number;
+};
+
+const fakeDockerState: FakeContainerState = {
+ containersById: new Map(),
+ containersByName: new Map(),
+ createCount: 0,
+};
+
+class MissingContainer {
+ constructor(private readonly identifier: string) {}
+
+ get id() {
+ return this.identifier;
+ }
+
+ modem = {
+ demuxStream: () => undefined,
+ };
+
+ async exec() {
+ throw createMissingContainerError(this.identifier);
+ }
+
+ async getArchive() {
+ throw createMissingContainerError(this.identifier);
+ }
+
+ async inspect() {
+ throw createMissingContainerError(this.identifier);
+ }
+
+ async logs() {
+ throw createMissingContainerError(this.identifier);
+ }
+
+ async putArchive() {
+ throw createMissingContainerError(this.identifier);
+ }
+
+ async remove() {
+ throw createMissingContainerError(this.identifier);
+ }
+
+ async start() {
+ throw createMissingContainerError(this.identifier);
+ }
+}
+
+class FakeContainer {
+ readonly modem = {
+ demuxStream: (
+ stream: NodeJS.ReadableStream,
+ stdout: NodeJS.WritableStream,
+ ) => {
+ stream.pipe(stdout);
+ },
+ };
+
+ running = false;
+
+ constructor(
+ public readonly id: string,
+ private readonly name: string,
+ ) {}
+
+ async exec(options: { Cmd: string[] }) {
+ const payload =
+ options.Cmd[3] === undefined
+ ? JSON.stringify({ status: "ok" })
+ : JSON.stringify({ result: { command: "ok" } });
+
+ return {
+ inspect: async () => ({ ExitCode: 0 }),
+ start: async () => {
+ const stream = new PassThrough();
+ queueMicrotask(() => {
+ stream.end(payload);
+ });
+ return stream;
+ },
+ };
+ }
+
+ async getArchive() {
+ const stream = new PassThrough();
+ stream.end("");
+ return stream;
+ }
+
+ async inspect() {
+ if (!fakeDockerState.containersById.has(this.id)) {
+ throw createMissingContainerError(this.id);
+ }
+
+ return {
+ State: {
+ ExitCode: this.running ? 0 : 1,
+ Running: this.running,
+ Status: this.running ? "running" : "exited",
+ },
+ };
+ }
+
+ async logs() {
+ return Buffer.from("");
+ }
+
+ async putArchive() {}
+
+ async remove() {
+ fakeDockerState.containersById.delete(this.id);
+ fakeDockerState.containersByName.delete(this.name);
+ }
+
+ async start() {
+ this.running = true;
+ }
+}
+
+class DockerMock {
+ async createContainer(options: { name: string }) {
+ fakeDockerState.createCount += 1;
+ const container = new FakeContainer(
+ `container-${fakeDockerState.createCount}`,
+ options.name,
+ );
+ fakeDockerState.containersById.set(container.id, container);
+ fakeDockerState.containersByName.set(options.name, container);
+ return container;
+ }
+
+ getContainer(identifier: string) {
+ return (
+ fakeDockerState.containersById.get(identifier) ??
+ fakeDockerState.containersByName.get(identifier) ??
+ new MissingContainer(identifier)
+ );
+ }
+}
+
+function createMissingContainerError(identifier: string) {
+ const error = new Error(`No such container: ${identifier}`) as Error & {
+ statusCode: number;
+ };
+ error.statusCode = 404;
+ return error;
+}
+
+vi.mock("dockerode", () => ({
+ default: DockerMock,
+}));
+
+describe("in-app agent docker sandbox provider", () => {
+ beforeEach(() => {
+ fakeDockerState.containersById.clear();
+ fakeDockerState.containersByName.clear();
+ fakeDockerState.createCount = 0;
+ });
+
+ it("recreates the named container when it was manually removed", async () => {
+ const { createDockerSandboxProvider } =
+ await import("@/src/ee/features/in-app-agent/server/sandbox/providers/docker");
+ const provider = await createDockerSandboxProvider({
+ image: "langfuse-in-app-agent-sandbox:latest",
+ });
+
+ const session = await provider.ensureSession({
+ conversationId: "conversation-1",
+ sessionId: "old-container-id",
+ });
+
+ expect(session.sessionId).toBe("conversation-1");
+ expect(fakeDockerState.createCount).toBe(1);
+
+ const container = Array.from(fakeDockerState.containersById.values())[0];
+ expect(container).toBeDefined();
+ await container?.remove();
+
+ await expect(session.sandbox.bash({ command: "ls" })).resolves.toEqual({
+ command: "ok",
+ });
+ expect(fakeDockerState.createCount).toBe(2);
+ });
+});
diff --git a/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts
new file mode 100644
index 0000000000..e245459f92
--- /dev/null
+++ b/web/src/__tests__/server/unit/in-app-agent-lambda-microvm-provider.servertest.ts
@@ -0,0 +1,161 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const microvmSendMock = vi.fn();
+
+vi.mock("@aws-sdk/client-lambda-microvms", () => {
+ class LambdaMicrovmsClient {
+ send = microvmSendMock;
+ }
+
+ class CreateMicrovmAuthTokenCommand {
+ constructor(public readonly input: unknown) {}
+ }
+
+ class GetMicrovmCommand {
+ constructor(public readonly input: unknown) {}
+ }
+
+ class ResumeMicrovmCommand {
+ constructor(public readonly input: unknown) {}
+ }
+
+ class RunMicrovmCommand {
+ constructor(public readonly input: unknown) {}
+ }
+
+ class SuspendMicrovmCommand {
+ constructor(public readonly input: unknown) {}
+ }
+
+ class TerminateMicrovmCommand {
+ constructor(public readonly input: unknown) {}
+ }
+
+ return {
+ CreateMicrovmAuthTokenCommand,
+ GetMicrovmCommand,
+ LambdaMicrovmsClient,
+ ResumeMicrovmCommand,
+ RunMicrovmCommand,
+ SuspendMicrovmCommand,
+ TerminateMicrovmCommand,
+ };
+});
+
+describe("in-app agent lambda microvm sandbox provider", () => {
+ beforeEach(() => {
+ microvmSendMock.mockReset();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it("uses suspend for suspendSession and terminate for terminateSession", async () => {
+ const { createLambdaMicrovmSandboxProvider } =
+ await import("@/src/ee/features/in-app-agent/server/sandbox/providers/lambdaMicrovm");
+
+ const provider = createLambdaMicrovmSandboxProvider({
+ imageIdentifier: "image-1",
+ executionRoleArn: "arn:aws:iam::123456789012:role/sandbox",
+ region: "us-east-1",
+ });
+
+ await provider.suspendSession?.({ sessionId: "microvm-1" });
+ await provider.terminateSession?.({ sessionId: "microvm-1" });
+
+ expect(microvmSendMock).toHaveBeenCalledTimes(2);
+ expect(microvmSendMock.mock.calls[0]?.[0]?.constructor.name).toBe(
+ "SuspendMicrovmCommand",
+ );
+ expect(microvmSendMock.mock.calls[0]?.[0]?.input).toEqual({
+ microvmIdentifier: "microvm-1",
+ });
+ expect(microvmSendMock.mock.calls[1]?.[0]?.constructor.name).toBe(
+ "TerminateMicrovmCommand",
+ );
+ expect(microvmSendMock.mock.calls[1]?.[0]?.input).toEqual({
+ microvmIdentifier: "microvm-1",
+ });
+ });
+
+ it("reuses the microvm endpoint and refreshes expired auth tokens", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
+
+ const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (url) => {
+ const urlString = String(url);
+ if (urlString.endsWith("/health")) {
+ return new Response(null, { status: 200 });
+ }
+
+ return Response.json({ result: { content: "hello" } });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ microvmSendMock.mockImplementation(async (command: { input: unknown }) => {
+ if (command.constructor.name === "RunMicrovmCommand") {
+ return {
+ microvmId: "microvm-1",
+ endpoint: "https://microvm.example.com:8443",
+ state: "RUNNING",
+ };
+ }
+
+ if (command.constructor.name === "GetMicrovmCommand") {
+ return {
+ microvmId: "microvm-1",
+ endpoint: "https://microvm.example.com:8443",
+ state: "RUNNING",
+ };
+ }
+
+ if (command.constructor.name === "CreateMicrovmAuthTokenCommand") {
+ const tokenNumber = microvmSendMock.mock.calls.filter(
+ ([calledCommand]) =>
+ calledCommand.constructor.name === "CreateMicrovmAuthTokenCommand",
+ ).length;
+ return { authToken: { "X-aws-proxy-auth": `token-${tokenNumber}` } };
+ }
+
+ throw new Error(`Unexpected command ${command.constructor.name}`);
+ });
+
+ const { createLambdaMicrovmSandboxProvider } =
+ await import("@/src/ee/features/in-app-agent/server/sandbox/providers/lambdaMicrovm");
+ const provider = createLambdaMicrovmSandboxProvider({
+ imageIdentifier: "image-1",
+ executionRoleArn: "arn:aws:iam::123456789012:role/sandbox",
+ region: "us-east-1",
+ });
+
+ const session = await provider.ensureSession({
+ conversationId: "conversation-1",
+ });
+ await session.sandbox.read({ path: "notes.txt" });
+ vi.setSystemTime(new Date("2026-01-01T00:28:00Z"));
+ await session.sandbox.read({ path: "notes.txt" });
+ vi.setSystemTime(new Date("2026-01-01T00:29:01Z"));
+ await session.sandbox.read({ path: "notes.txt" });
+
+ expect(
+ microvmSendMock.mock.calls.filter(
+ ([command]) => command.constructor.name === "GetMicrovmCommand",
+ ),
+ ).toHaveLength(1);
+ expect(
+ microvmSendMock.mock.calls.filter(
+ ([command]) =>
+ command.constructor.name === "CreateMicrovmAuthTokenCommand",
+ ),
+ ).toHaveLength(3);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
+ headers: { "X-aws-proxy-auth": "token-2" },
+ });
+ expect(fetchMock.mock.calls[2]?.[1]).toMatchObject({
+ headers: { "X-aws-proxy-auth": "token-2" },
+ });
+ expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({
+ headers: { "X-aws-proxy-auth": "token-3" },
+ });
+ });
+});
diff --git a/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.ts
new file mode 100644
index 0000000000..f80fb8bb0c
--- /dev/null
+++ b/web/src/__tests__/server/unit/in-app-agent-sandbox.servertest.ts
@@ -0,0 +1,171 @@
+import { EventType } from "@ag-ui/core";
+import { describe, expect, it } from "vitest";
+
+import { getSandboxToolCallFiles } from "@/src/ee/features/in-app-agent/server/persistence";
+import { createInAppAgentSandbox } from "@/src/ee/features/in-app-agent/server/sandbox";
+
+describe("in-app agent sandbox", () => {
+ it("persists sandbox session state when a turn ends", async () => {
+ const sandboxSession = {
+ async syncReadonlyFiles() {},
+ async read() {
+ return { path: "notes.txt", content: null };
+ },
+ async write() {
+ return { path: "notes.txt", bytesWritten: 0 };
+ },
+ async edit() {
+ return { path: "notes.txt", replaced: false };
+ },
+ async bash() {
+ return { stdout: "", stderr: "", exitCode: 0 };
+ },
+ };
+ const provider = {
+ async ensureSession() {
+ return { sessionId: "session-1", sandbox: sandboxSession };
+ },
+ };
+ const savedStates: Array<Record<string, unknown>> = [];
+ const sandbox = await createInAppAgentSandbox({
+ conversationId: "conversation-1",
+ projectId: "project-1",
+ provider,
+ getToolCallFiles: async () => [],
+ saveState: async (state) => {
+ savedStates.push(state);
+ },
+ });
+
+ await sandbox.sandbox.write({ path: "notes.txt", content: "hello" });
+ await sandbox.onTurnEnded();
+
+ expect(savedStates[0]).toEqual({
+ providerSessionId: "session-1",
+ });
+ expect(savedStates[1]).toEqual({
+ providerSessionId: "session-1",
+ });
+ });
+
+ it("exports prior non-sandbox tool calls into tool_calls files", () => {
+ const files = getSandboxToolCallFiles([
+ {
+ createdAt: new Date("2026-07-02T12:00:00.000Z"),
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-call-1",
+ toolCallName: "langfuse_getHealth",
+ },
+ },
+ {
+ createdAt: new Date("2026-07-02T12:00:00.100Z"),
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "tool-call-1",
+ delta: '{"projectId":"project-1"}',
+ },
+ },
+ {
+ createdAt: new Date("2026-07-02T12:00:00.200Z"),
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-call-1",
+ content: '{"status":"ok"}',
+ },
+ },
+ {
+ createdAt: new Date("2026-07-02T12:00:01.000Z"),
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-call-2",
+ toolCallName: "read",
+ },
+ },
+ {
+ createdAt: new Date("2026-07-02T12:00:01.100Z"),
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_ARGS,
+ toolCallId: "tool-call-2",
+ delta: '{"path":"tool_calls/file.json"}',
+ },
+ },
+ {
+ createdAt: new Date("2026-07-02T12:00:01.200Z"),
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-call-2",
+ content: '{"content":"ignored"}',
+ },
+ },
+ ]);
+
+ expect(files).toEqual([
+ {
+ path: "tool_calls/2026-07-02T12-00-00.000Z_langfuse_getHealth_tool-call-1.json",
+ content: JSON.stringify(
+ {
+ request: { projectId: "project-1" },
+ response: { status: "ok" },
+ error: null,
+ },
+ null,
+ 2,
+ ),
+ },
+ ]);
+ });
+
+ it("keeps repeated same-name tool calls with identical timestamps", () => {
+ const createdAt = new Date("2026-07-02T12:00:00.000Z");
+ const files = getSandboxToolCallFiles([
+ {
+ createdAt,
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-call-1",
+ toolCallName: "langfuse_getHealth",
+ },
+ },
+ {
+ createdAt,
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-call-1",
+ content: '{"status":"ok"}',
+ },
+ },
+ {
+ createdAt,
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_START,
+ toolCallId: "tool-call-2",
+ toolCallName: "langfuse_getHealth",
+ },
+ },
+ {
+ createdAt,
+ runId: "run-1",
+ event: {
+ type: EventType.TOOL_CALL_RESULT,
+ toolCallId: "tool-call-2",
+ content: '{"status":"ok"}',
+ },
+ },
+ ]);
+
+ expect(files.map((file) => file.path)).toEqual([
+ "tool_calls/2026-07-02T12-00-00.000Z_langfuse_getHealth_tool-call-1.json",
+ "tool_calls/2026-07-02T12-00-00.000Z_langfuse_getHealth_tool-call-2.json",
+ ]);
+ });
+});
diff --git a/web/src/ee/features/in-app-agent/README.md b/web/src/ee/features/in-app-agent/README.md
index 719589d8a5..e18d1d4444 100644
--- a/web/src/ee/features/in-app-agent/README.md
+++ b/web/src/ee/features/in-app-agent/README.md
@@ -20,9 +20,15 @@ Runs are foreground-only. A conversation can have one active run; stale unfinish
- `server/persistence.ts`: conversations, runs, events, replay, active-run locking, and stale-run recovery.
- `server/router.ts`: non-streaming tRPC routes for conversation lists, replay, and feedback.
- `server/instrumentation.ts`: optional Langfuse tracing for agent runs, prompts, events, and errors.
+- `server/sandbox/config.ts`: sandbox provider selection and runtime configuration.
+- `server/sandbox/service.ts`: conversation-scoped sandbox session reuse, readonly file sync, and turn-end suspension.
+- `server/sandbox/providers/*`: provider adapters for local Docker and Lambda MicroVM sandboxes.
+- `server/sandbox/types.ts`: runtime-neutral sandbox interface used by tools/agent.
- `constants.ts`: stable names shared across prompts, tools, persistence, and rendering.
- `components/*`: client controller and prop-driven render components.
+Outside this feature folder, `packages/in-app-agent-sandbox-runtime/src/*` provides the shared sandbox runtime and contract types used by both the local Docker provider and the Lambda MicroVM image.
+
## File Relationships
```mermaid
@@ -42,10 +48,14 @@ flowchart TB
Schema -.-> Persistence["server/persistence.ts"]
Handler --> Persistence
+ Handler --> Sandbox["server/sandbox/service.ts\nsandbox lifecycle"]
Handler --> Agent["server/agent.ts\nagent runtime"]
Handler --> HumanLoop
+ Sandbox --> Persistence
+ Sandbox --> Providers["server/sandbox/providers/*\nDocker or Lambda MicroVM"]
Agent --> HumanLoop
Agent --> Tools["server/tools.ts\ncustom tools"]
+ Agent --> Tools
Agent --> Instrumentation["server/instrumentation.ts\nLangfuse telemetry"]
Router --> Persistence
```
@@ -54,13 +64,49 @@ flowchart TB
1. Browser sends the latest message, conversation state, and screen context through `HttpAgent`.
2. `server/handler.ts` validates the request and creates a server-owned run.
-3. `server/handler.ts` creates a temporary in-app-agent MCP API key and passes the signed-in user's project role/admin state into the agent runtime.
-4. `server/agent.ts` filters Langfuse MCP tools through RBAC before exposing them to the model, and for approved Langfuse MCP resumes adds a tool-scoped override payload.
-5. `server/agent.ts` connects Mastra to Langfuse MCP with the temporary API key and sends the override in `x-langfuse-in-app-agent-tool-override` when a single approved mutating MCP tool may run.
-6. `server/agent.ts` streams normalized AG-UI events and calls telemetry hooks.
-7. `server/instrumentation.ts` records prompt metadata, stream events, completion, aborts, and errors.
-8. `server/persistence.ts` stores compacted events and reconstructs replay messages.
-9. `InAppAiAgentProvider.tsx` renders live AG-UI state and hydrates selected conversations through `server/router.ts`.
+3. `server/handler.ts` loads conversation history and creates or resumes a conversation-scoped sandbox when a provider is enabled.
+4. `server/persistence.ts` rebuilds readonly `tool_calls/*.json` files from prior non-sandbox tool calls, and `server/sandbox/service.ts` syncs them into the sandbox before each tool use.
+5. `server/handler.ts` creates a temporary in-app-agent MCP API key and passes the signed-in user's project role/admin state plus optional sandbox access into the agent runtime.
+6. `server/agent.ts` filters Langfuse MCP tools through RBAC, exposes sandbox tools (`read`, `write`, `edit`, `bash`) when available, and for approved Langfuse MCP resumes adds a tool-scoped override payload.
+7. `server/agent.ts` connects Mastra to Langfuse MCP with the temporary API key and sends the override in `x-langfuse-in-app-agent-tool-override` when a single approved mutating MCP tool may run.
+8. `server/agent.ts` streams normalized AG-UI events, calls telemetry hooks, and lets the request `onFinish` cleanup persist/suspend the sandbox at turn end.
+9. `server/instrumentation.ts` records prompt metadata, stream events, completion, aborts, and errors.
+10. `server/persistence.ts` stores compacted events and reconstructs replay messages.
+11. `InAppAiAgentProvider.tsx` renders live AG-UI state and hydrates selected conversations through `server/router.ts`.
+
+## Sandbox Runtime
+
+`server/sandbox/service.ts` gives the agent a conversation-scoped sandbox interface with `read`, `write`, and `edit` plus a separate turn-end callback. It reuses an existing provider session when the stored provider/session/TTL still match, otherwise it boots a fresh session and persists the new state on the conversation.
+
+Both sandbox providers target the same runtime contract from `packages/in-app-agent-sandbox-runtime`.
+
+- The local `dangerous-docker` provider starts a container from that package's Docker image and calls the runtime over `http://127.0.0.1:5000` using `docker exec`.
+- The Lambda MicroVM provider starts a MicroVM image built from the same package and calls the runtime through the AWS-assigned HTTPS endpoint plus `X-aws-proxy-auth`.
+- Providers own runtime session lifecycle only: create/resume/suspend/terminate plus proxying sandbox operations.
+
+Provider contract:
+
+- `ensureSession({ conversationId, sessionId? })`
+- `syncReadonlyFiles({ sessionId, files })`
+- `read`, `write`, `edit`, `bash`
+- optional `suspendSession({ sessionId })`
+
+Runtime HTTP surface:
+
+- `GET /health`
+- `POST /sandbox`
+
+`POST /sandbox` is the narrow control surface for the current tool set: `read`, `write`, `edit`, and `bash`. Before each request, the provider rebuilds `tool_calls/` from persisted non-sandbox tool calls so the runtime always sees the same readonly context regardless of provider.
+
+## Sandbox Persistence And Cleanup
+
+Sandbox state is stored on the conversation row as `providerSessionId`. The configured sandbox provider is assumed to remain stable for the lifetime of the database.
+
+Session reuse only relies on an existing live or suspended runtime instance identified by `providerSessionId`.
+
+`server/router.ts` clears sandbox state before soft-deleting a conversation.
+
+`dangerous-docker` is development-only. Worker data-retention cleanup only tears down `lambda-microvm` sandboxes; local Docker sandbox cleanup stays in the web process where that provider is used.
## MCP Tool Authorization
@@ -83,8 +129,11 @@ Human approval is separate from the MCP tool override. `server/agent.ts` classif
`IN_APP_AGENT_AUTO_APPROVED_TOOL_NAMES` is generated from that map by prefixing Langfuse MCP tools with `langfuse_` and adding local tools such as `IN_APP_AGENT_REDIRECT_TOOL_NAME`; docs MCP tools are auto-approved by the `langfuseDocs_` prefix. `server/agent.ts` marks every other tool with Mastra `requireApproval: true`. Mastra emits an interrupt, the browser asks the user, and resumed approvals are validated by `server/handler.ts` against the pending approval row persisted in Postgres. `server/human-in-the-loop.ts` adapts Mastra's runtime interrupt payload into the Langfuse-owned `tool_approval_request` contract from `schema.ts`; the browser stores and forwards only that runtime-neutral shape. `server/human-in-the-loop.ts` consumes the pending approval, executes approved tool calls at the adapter boundary, and injects synthetic AG-UI tool-call events/messages before the agent continues. The pending approval row stays server-local, stores the tool call identity and a stable argument fingerprint, and expires after a short TTL.
+Sandbox tools are separate from MCP authorization. When a sandbox provider is enabled, `server/tools.ts` adds local `read`, `write`, `edit`, and `bash` tools backed by the sandbox provider contract rather than the MCP registry.
+
## Change Rules
- Check AG-UI docs at `https://docs.ag-ui.com/llms.txt` before changing event semantics, ordering, stream handling, compaction, tools, state, or `HttpAgent` integration.
- Keep persisted schemas backward-compatible unless there is an explicit migration.
+- Keep sandbox conversation state backward-compatible unless there is an explicit migration or cleanup plan.
- Keep presentational components prop-driven; connect tRPC, streaming, and persistence at provider/router/handler boundaries.
diff --git a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
index 137e01c081..85eeb76ea3 100644
--- a/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/ControlledInAppAgentWindow.tsx
@@ -8,6 +8,9 @@ import { useInAppAiAgent } from "./InAppAiAgentProvider";
import { getDrawerMessages } from "./utils/utils";
import { getInAppAgentScreenContextDescription } from "@/src/ee/features/in-app-agent/context";
+const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
+ "Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";
+
type ControlledInAppAgentWindowBaseProps = {
isHeaderDragHandleEnabled?: boolean;
isExpanded: boolean;
@@ -47,14 +50,22 @@ export function ControlledInAppAgentWindow(
rejectToolCall,
selectConversation,
selectedConversationId,
+ selectedConversationIsWriteLocked,
submit,
submitFeedback,
} = useInAppAiAgent();
const isInputDisabled =
isRunning ||
isSubmitting ||
+ selectedConversationIsWriteLocked ||
isSelectedConversationHydrating ||
pendingToolApprovals.length > 0;
+ const displayError = selectedConversationIsWriteLocked
+ ? ({
+ type: "generic",
+ message: SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ } as const)
+ : error;
const screenContextDescription = useMemo(
() => getInAppAgentScreenContextDescription(router.asPath),
[router.asPath],
@@ -78,11 +89,12 @@ export function ControlledInAppAgentWindow(
return (
<InAppAgentWindow
- error={error}
+ error={displayError}
isAssistantTurnInProgress={isRunning || pendingToolApprovals.length > 0}
isHeaderDragHandleEnabled={props.isHeaderDragHandleEnabled}
isExpanded={props.isExpanded}
isInputDisabled={isInputDisabled}
+ disablePendingToolApprovalActions={selectedConversationIsWriteLocked}
messages={drawerMessages}
screenContextDescription={screenContextDescription}
conversations={conversations}
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
index 452f5ae681..507c14206c 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx
@@ -161,6 +161,7 @@ type InAppAgentWindowCloseButtonProps =
export type InAppAgentWindowProps = {
conversations: InAppAgentWindowConversation[];
+ disablePendingToolApprovalActions?: boolean;
error: InAppAgentError | null;
hasMoreConversations: boolean;
isAssistantTurnInProgress: boolean;
@@ -255,6 +256,7 @@ function InAppAgentGenericError({
export function InAppAgentWindow(props: InAppAgentWindowProps) {
const {
conversations,
+ disablePendingToolApprovalActions = false,
error,
hasMoreConversations,
isAssistantTurnInProgress,
@@ -717,7 +719,9 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {
key={`${tool.approval?.id ?? tool.name}-${index}`}
tool={tool}
isCompact={!isExpanded}
- isDisabled={isRateLimited}
+ isDisabled={
+ isRateLimited || disablePendingToolApprovalActions
+ }
onApproveToolCall={onApproveToolCall}
onRejectToolCall={onRejectToolCall}
/>
diff --git a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
index 33734b38c9..9164738a07 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAiAgentProvider.tsx
@@ -51,6 +51,8 @@ const SELECTED_CONVERSATION_STORAGE_KEY_PREFIX =
"langfuse:in-app-ai-agent-selected-conversation";
const OPEN_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-open";
const FEEDBACK_STORAGE_KEY_PREFIX = "langfuse:in-app-ai-agent-feedback";
+const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
+ "Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";
const EMPTY_MESSAGES: AgUiMessage[] = [];
const MastraSuspendEventSchema = z.object({
@@ -86,6 +88,7 @@ const NOOP_CONTEXT: InAppAiAgentContextType = {
hasMoreConversations: false,
isLoadingMoreConversations: false,
selectedConversationId: undefined,
+ selectedConversationIsWriteLocked: false,
loadMoreConversations: () => undefined,
invalidateConversations: () => undefined,
selectConversation: () => undefined,
@@ -111,6 +114,7 @@ export type InAppAiAgentConversation = {
id: string;
title: string | null;
updatedAt: Date;
+ isWriteLocked: boolean;
};
type InAppAiAgentContextType = {
@@ -129,6 +133,7 @@ type InAppAiAgentContextType = {
hasMoreConversations: boolean;
isLoadingMoreConversations: boolean;
selectedConversationId: string | undefined;
+ selectedConversationIsWriteLocked: boolean;
loadMoreConversations: () => void;
invalidateConversations: () => void;
selectConversation: (conversationId: string | null) => void;
@@ -277,6 +282,8 @@ function InAppAiAgentProviderInner({
);
const hasMoreConversations = conversationListQuery.hasNextPage === true;
const isLoadingMoreConversations = conversationListQuery.isFetchingNextPage;
+ const selectedConversationIsWriteLocked =
+ conversationQuery.data?.conversation.isWriteLocked ?? false;
const currentMessages = useMemo(() => {
if (isSelectedConversationNotFound) {
return EMPTY_MESSAGES;
@@ -770,6 +777,14 @@ function InAppAiAgentProviderInner({
let startedRun = false;
try {
+ if (selectedConversationIsWriteLocked) {
+ setError({
+ type: "generic",
+ message: SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ });
+ return false;
+ }
+
const isNewConversation = !selectedConversationId;
const conversationId =
selectedConversationId ?? createInAppAgentConversationId();
@@ -836,6 +851,7 @@ function InAppAiAgentProviderInner({
releaseSubmitLock,
runAgent,
selectedConversationId,
+ selectedConversationIsWriteLocked,
setSelectedConversationId,
],
);
@@ -912,6 +928,14 @@ function InAppAiAgentProviderInner({
const resumeToolApproval = useCallback(
async (approvalId: string, approved: boolean) => {
+ if (selectedConversationIsWriteLocked) {
+ setError({
+ type: "generic",
+ message: SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ });
+ return;
+ }
+
const approval = pendingToolApprovals.find(
(approval) => approval.id === approvalId,
);
@@ -1007,6 +1031,7 @@ function InAppAiAgentProviderInner({
pendingToolApprovals,
runAgent,
selectedConversationId,
+ selectedConversationIsWriteLocked,
updatePendingToolApprovals,
],
);
@@ -1040,6 +1065,7 @@ function InAppAiAgentProviderInner({
hasMoreConversations,
isLoadingMoreConversations,
selectedConversationId: selectedConversationId ?? undefined,
+ selectedConversationIsWriteLocked,
loadMoreConversations,
invalidateConversations,
selectConversation,
@@ -1058,6 +1084,7 @@ function InAppAiAgentProviderInner({
isLoadingMoreConversations,
isRunning,
isSelectedConversationHydrating,
+ selectedConversationIsWriteLocked,
isSubmitting,
isSelectedConversationNotFound,
deleteConversation,
diff --git a/web/src/ee/features/in-app-agent/constants.ts b/web/src/ee/features/in-app-agent/constants.ts
index 32d474859e..3ddfcba8af 100644
--- a/web/src/ee/features/in-app-agent/constants.ts
+++ b/web/src/ee/features/in-app-agent/constants.ts
@@ -6,6 +6,9 @@ export const IN_APP_AGENT_REDIRECT_TOOL_NAME = "langfuse_proposeRedirect";
export const IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER =
"x-langfuse-in-app-agent-tool-override";
+export const IN_APP_AGENT_LOCAL_SANDBOX_IMAGE =
+ "langfuse-in-app-agent-sandbox:latest";
+
// Observation ids stay equal to the per-turn run id so persisted messages,
// feedback, and traced generations all point at the same Langfuse observation.
export const getInAppAgentInstrumentationObservationId = (runId: string) =>
diff --git a/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt b/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt
index e7f3459617..8d15574aa5 100644
--- a/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt
+++ b/web/src/ee/features/in-app-agent/prompts/in-app-agent-system-prompt.txt
@@ -66,3 +66,5 @@ The current date is {{currentDate}}.
{{screenContext}}
{{userContext}}
+
+{{sandboxFilesystem}}
diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.ts
index e228480544..7189c14ccc 100644
--- a/web/src/ee/features/in-app-agent/server/agent.ts
+++ b/web/src/ee/features/in-app-agent/server/agent.ts
@@ -22,12 +22,14 @@ import type {
} from "@/src/ee/features/in-app-agent/server/instrumentation";
import { createInAppAgentInstrumentation } from "@/src/ee/features/in-app-agent/server/instrumentation";
import {
+ createSandboxTools,
createRedirectActionTool,
filterInAppAgentAvailableLangfuseMcpTools,
type InAppAgentUserAccess,
withInAppAgentToolApproval,
} from "@/src/ee/features/in-app-agent/server/tools";
import { LANGFUSE_IN_APP_AGENT_SKILLS } from "@/src/ee/features/in-app-agent/server/skills";
+import type { InAppAgentSandbox } from "@/src/ee/features/in-app-agent/server/sandbox";
import { DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS } from "@/src/features/filters/constants/internal-environments";
import { logger } from "@langfuse/shared/src/server";
import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";
@@ -115,6 +117,20 @@ ${serializedContext}
`;
}
+function formatSandboxContext(sandbox?: InAppAgentSandbox): string {
+ if (!sandbox) {
+ return "";
+ }
+
+ return `
+<sandbox_filesystem>
+When working in the sandbox filesystem, assume this layout:
+- "/workspace" is the current working directory for normal file operations and shell commands.
+- "/workspace/tool_calls" contains all past tool calls and their outputs. Treat this directory as read-only. Any changes to it will be discarded before the next tool call.
+</sandbox_filesystem>
+`;
+}
+
// Adaptive thinking is the default for every Claude model so new generations
// work without maintaining a model list. Older models that only support
// thinking.type.enabled (e.g. haiku 4.5) reject adaptive with a 400 — the
@@ -164,6 +180,7 @@ type CreateAgUiStreamOptions = {
langfuseClient: Langfuse;
useLocalPrompt: boolean;
langfuseTracing?: InAppAgentTracingConfig;
+ sandbox?: InAppAgentSandbox;
};
export async function createAgUiStream(params: {
@@ -184,6 +201,7 @@ export async function createAgUiStream(params: {
variables: {
currentDate: new Date().toISOString(),
redirectToolName: IN_APP_AGENT_REDIRECT_TOOL_NAME,
+ sandboxFilesystem: formatSandboxContext(params.options.sandbox),
screenContext: formatScreenContext(params.input.context),
userContext: formatUserContext(params.input.context),
sidebarHiddenEnvironments: DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS.map(
@@ -214,6 +232,7 @@ export async function createAgUiStream(params: {
let eventQueue = Promise.resolve();
let cleanupAdapter: (() => Promise<void>) | undefined;
let interruptAdapter: (() => void) | undefined;
+ let onFinishPromise: Promise<void> | undefined;
const removeAbortHandler = () => {
if (!abortHandler) {
@@ -232,10 +251,7 @@ export async function createAgUiStream(params: {
finished = true;
eventQueue
.then(async () => {
- const results = await Promise.allSettled([
- cleanupAdapter?.(),
- params.options.onFinish?.(),
- ]);
+ const results = await Promise.allSettled([cleanupAdapter?.()]);
for (const result of results) {
if (result.status === "rejected") {
@@ -257,6 +273,11 @@ export async function createAgUiStream(params: {
});
};
+ const runOnFinish = () => {
+ onFinishPromise ??= Promise.resolve(params.options.onFinish?.());
+ return onFinishPromise;
+ };
+
const runTerminalCallback = async (
callback: (() => void | Promise<void>) | undefined,
errorContext: string,
@@ -301,7 +322,14 @@ export async function createAgUiStream(params: {
runTerminalCallback(
() => params.options.onError?.(error),
"Error while marking agent stream as failed",
- ).finally(finish);
+ )
+ .then(() =>
+ runTerminalCallback(
+ runOnFinish,
+ "Error while running agent stream finish callback after failure",
+ ),
+ )
+ .finally(finish);
controller.error(error);
};
@@ -358,6 +386,7 @@ export async function createAgUiStream(params: {
}
await terminalCallback?.();
+ await runOnFinish();
if (closed) {
return;
@@ -391,6 +420,12 @@ export async function createAgUiStream(params: {
"Error while marking agent stream as aborted",
),
)
+ .then(() =>
+ runTerminalCallback(
+ runOnFinish,
+ "Error while running agent stream finish callback after abort",
+ ),
+ )
.then(() => {
if (closed) {
return;
@@ -649,6 +684,12 @@ export async function createAgUiStream(params: {
"Error while marking agent stream as aborted",
),
)
+ .then(() =>
+ runTerminalCallback(
+ runOnFinish,
+ "Error while running agent stream finish callback after cancel",
+ ),
+ )
.then(() => {
closed = true;
})
@@ -744,6 +785,9 @@ async function createMastraAdapter(params: {
projectId: params.options.redirectAction.projectId,
isV4Enabled: params.options.redirectAction.isV4Enabled,
}),
+ ...(params.options.sandbox
+ ? createSandboxTools(params.options.sandbox)
+ : {}),
});
params.onToolsAvailable?.(tools);
@@ -857,17 +901,39 @@ type PatchableMastraAgent = {
type MastraStreamChunk = {
type?:
+ | "start"
+ | "step-start"
+ | "step-finish"
+ | "text-start"
+ | "text-delta"
+ | "text-end"
| "tool-call-input-streaming-start"
| "tool-call-delta"
| "tool-call-input-streaming-end"
| "tool-call"
+ | "tool-result"
+ | "tool-error"
| "tool-call-approval"
| "tool-call-suspended";
payload?: {
+ text?: string;
+ textDelta?: string;
+ textMessageId?: string;
+ error?: {
+ message?: string;
+ cause?: {
+ message?: string;
+ };
+ details?: {
+ errorMessage?: string;
+ };
+ };
toolCallId?: string;
toolName?: string;
argsTextDelta?: string;
args?: unknown;
+ result?: unknown;
+ isError?: boolean;
resumeSchema?: unknown;
suspendPayload?: unknown;
};
@@ -876,10 +942,18 @@ type MastraStreamChunk = {
type MastraStreamChunkType = NonNullable<MastraStreamChunk["type"]>;
const MASTRA_STREAM_CHUNK_TYPES = [
+ "start",
+ "step-start",
+ "step-finish",
+ "text-start",
+ "text-delta",
+ "text-end",
"tool-call-input-streaming-start",
"tool-call-delta",
"tool-call-input-streaming-end",
"tool-call",
+ "tool-result",
+ "tool-error",
"tool-call-approval",
"tool-call-suspended",
] as const satisfies readonly MastraStreamChunkType[];
@@ -948,11 +1022,16 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
"Received unknown Mastra chunk while patching tool-call input streaming",
chunk,
);
+
return processor.handleChunk(chunk);
}
const mastraChunk = chunk;
+ if (mastraChunk.type === undefined) {
+ return processor.handleChunk(chunk);
+ }
+
if (mastraChunk.type === "tool-call-input-streaming-start") {
const { toolCallId, toolName } = mastraChunk.payload ?? {};
if (!toolCallId || !toolName) {
@@ -1034,6 +1113,60 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
return processor.handleChunk(chunk);
}
+ if (mastraChunk.type === "tool-error") {
+ const { toolCallId, toolName, args } = mastraChunk.payload ?? {};
+ if (!toolCallId || !toolName) {
+ callbacks.onError(
+ new Error(
+ "Malformed tool-error: missing toolCallId or toolName in payload",
+ ),
+ );
+ return true;
+ }
+
+ streamingToolCalls.delete(toolCallId);
+ synthesizedToolCallIds.delete(toolCallId);
+
+ return processor.handleChunk({
+ type: "tool-result",
+ payload: {
+ toolCallId,
+ toolName,
+ args,
+ isError: true,
+ result: JSON.stringify(
+ {
+ error: ((): string => {
+ if (
+ typeof mastraChunk.payload?.error?.details
+ ?.errorMessage === "string"
+ ) {
+ return mastraChunk.payload.error.details.errorMessage;
+ }
+
+ if (
+ typeof mastraChunk.payload?.error?.cause?.message ===
+ "string"
+ ) {
+ return mastraChunk.payload.error.cause.message;
+ }
+
+ if (
+ typeof mastraChunk.payload?.error?.message === "string"
+ ) {
+ return mastraChunk.payload.error.message;
+ }
+
+ return "Unknown tool error";
+ })(),
+ },
+ null,
+ 2,
+ ),
+ },
+ });
+ }
+
if (mastraChunk.type === "tool-call-approval") {
const { toolCallId, toolName, args, resumeSchema } =
mastraChunk.payload ?? {};
@@ -1075,7 +1208,15 @@ export function patchMastraToolCallInputStreaming(adapter: MastraAgent) {
return processor.handleChunk(chunk);
}
- if (mastraChunk.type === undefined) {
+ if (
+ mastraChunk.type === "start" ||
+ mastraChunk.type === "step-start" ||
+ mastraChunk.type === "step-finish" ||
+ mastraChunk.type === "text-start" ||
+ mastraChunk.type === "text-delta" ||
+ mastraChunk.type === "text-end" ||
+ mastraChunk.type === "tool-result"
+ ) {
return processor.handleChunk(chunk);
}
@@ -1094,6 +1235,7 @@ async function getSystemPromptInstructions(params: {
variables: {
currentDate: string;
redirectToolName: string;
+ sandboxFilesystem: string;
screenContext: string;
userContext: string;
sidebarHiddenEnvironments: string;
diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.ts
index f631f317bf..4985895e37 100644
--- a/web/src/ee/features/in-app-agent/server/handler.ts
+++ b/web/src/ee/features/in-app-agent/server/handler.ts
@@ -35,12 +35,20 @@ import {
createRun,
ensureOwnedConversation,
finishRun,
+ getConversationEvents,
getConversationMessagesForReplay,
+ isInAppAgentConversationWriteLocked,
maybeInferAndPersistConversationTitle,
+ getSandboxToolCallFiles,
replaceRunEvents,
shouldFlushPersistedEvent,
toPersistableAgentEvent,
} from "@/src/ee/features/in-app-agent/server/persistence";
+import { createInAppAgentSandbox } from "@/src/ee/features/in-app-agent/server/sandbox";
+import {
+ createInAppAgentSandboxProvider,
+ getDefaultInAppAgentSandboxProviderType,
+} from "@/src/ee/features/in-app-agent/server/sandbox/config";
import { getLangfuseClient } from "@/src/features/natural-language-filters/server/utils";
import { getAuthOptions } from "@/src/server/auth";
import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
@@ -74,6 +82,8 @@ import {
const IN_APP_AGENT_API_KEY_NOTE = "In-app agent MCP session";
const MAX_IN_APP_AGENT_INPUT_BYTES = 1024 * 1024;
+const SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE =
+ "Sandbox-enabled conversations become read-only after 8 hours. Start a new conversation to continue.";
export default async function handler(request: Request) {
try {
@@ -242,6 +252,25 @@ export default async function handler(request: Request) {
conversationId,
userId: userId,
});
+ const conversationEvents = await getConversationEvents({
+ prisma,
+ projectId,
+ conversationId: conversation.id,
+ });
+
+ if (
+ isInAppAgentConversationWriteLocked({
+ conversation,
+ events: conversationEvents,
+ })
+ ) {
+ throw new BaseError(
+ "PreconditionFailedError",
+ 412,
+ SANDBOX_CONVERSATION_WRITE_LOCK_MESSAGE,
+ true,
+ );
+ }
if (isResumeAgentInput(sanitizedInput)) {
await validatePendingToolApproval({
@@ -263,6 +292,30 @@ export default async function handler(request: Request) {
const resumeApprovalRequest = isResumeAgentInput(sanitizedInput)
? sanitizedInput.forwardedProps.command.resume.approvalRequest
: undefined;
+ const sandboxProviderType = getDefaultInAppAgentSandboxProviderType();
+ const sandboxProvider =
+ await getInAppAgentSandboxProvider(sandboxProviderType);
+ const sandboxState = sandboxProvider
+ ? await createInAppAgentSandbox({
+ conversationId: conversation.id,
+ projectId,
+ providerSessionId: conversation.providerSessionId,
+ provider: sandboxProvider,
+ getToolCallFiles: async () =>
+ getSandboxToolCallFiles(conversationEvents),
+ saveState: async (state) => {
+ await prisma.inAppAgentConversation.update({
+ where: {
+ id_projectId: {
+ id: conversation.id,
+ projectId,
+ },
+ },
+ data: state,
+ });
+ },
+ })
+ : undefined;
const approvedResumeApprovalRequest =
isResumeAgentInput(sanitizedInput) &&
@@ -441,7 +494,11 @@ export default async function handler(request: Request) {
: "Unknown agent error",
}),
),
- onFinish: cleanupMcpApiKey,
+ sandbox: sandboxState?.sandbox,
+ onFinish: async () => {
+ await cleanupMcpApiKey();
+ await sandboxState?.onTurnEnded();
+ },
awsBedrock: {
region: env.LANGFUSE_AWS_BEDROCK_REGION,
modelId: bedrockModelId,
@@ -552,6 +609,25 @@ export default async function handler(request: Request) {
}
}
+async function getInAppAgentSandboxProvider(
+ providerType: ReturnType<typeof getDefaultInAppAgentSandboxProviderType>,
+) {
+ if (providerType === null || env.NODE_ENV === "test") {
+ return undefined;
+ }
+
+ if (providerType === "dangerous-docker") {
+ logger.warn(
+ "Using dangerous-docker in-app agent sandbox provider. This is for local development only.",
+ );
+ logger.warn(
+ "The dangerous-docker sandbox provider executes commands in a local Docker container and should not be enabled in production.",
+ );
+ }
+
+ return createInAppAgentSandboxProvider(providerType);
+}
+
type SessionUser = NonNullable<Session["user"]>;
function getInAppAgentUserAccess(
diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.ts
index ce815fea89..91d7f518b5 100644
--- a/web/src/ee/features/in-app-agent/server/persistence.ts
+++ b/web/src/ee/features/in-app-agent/server/persistence.ts
@@ -30,6 +30,8 @@ import {
} from "@/src/ee/features/in-app-agent/schema";
import { compactTextMessageChunks } from "@/src/ee/features/in-app-agent/server/eventCompaction";
import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";
+import { safeJsonParse } from "@/src/utils/json";
+import { IN_APP_AGENT_SANDBOX_TOOL_NAMES } from "@/src/ee/features/in-app-agent/server/tools";
// Keep this close to the route maxDuration (120s) so a killed foreground stream
// does not block the conversation long after the route can no longer respond.
@@ -39,17 +41,20 @@ const ACTIVE_RUN_CONFLICT_MESSAGE =
const STALE_RUN_ERROR_CODE = "stale";
const STALE_RUN_ERROR_MESSAGE =
"Run was marked stale before starting a new run";
+const SANDBOX_CONVERSATION_WRITE_WINDOW_MS = 8 * 60 * 60 * 1000;
export type SerializedInAppAgentConversation = {
id: string;
title: string | null;
createdAt: Date;
updatedAt: Date;
+ isWriteLocked: boolean;
};
-type PersistedConversationEvent = {
+export type PersistedConversationEvent = {
event: AgUiEvent;
runId: string;
+ createdAt: Date;
};
export function serializeConversation(
@@ -57,15 +62,43 @@ export function serializeConversation(
InAppAgentConversation,
"id" | "title" | "createdAt" | "updatedAt"
>,
+ options?: { isWriteLocked?: boolean },
): SerializedInAppAgentConversation {
return {
id: conversation.id,
title: conversation.title,
createdAt: conversation.createdAt,
updatedAt: conversation.updatedAt,
+ isWriteLocked: options?.isWriteLocked ?? false,
};
}
+export function isInAppAgentConversationWriteLocked(params: {
+ conversation: Pick<InAppAgentConversation, "createdAt">;
+ events: readonly PersistedConversationEvent[];
+ now?: Date;
+}) {
+ const now = params.now ?? new Date();
+ const ageMs = now.getTime() - params.conversation.createdAt.getTime();
+
+ if (ageMs <= SANDBOX_CONVERSATION_WRITE_WINDOW_MS) {
+ return false;
+ }
+
+ return params.events.some(({ event }) => {
+ if (event.type !== EventType.TOOL_CALL_START) {
+ return false;
+ }
+
+ const toolName = getString(event, "toolCallName");
+ if (!toolName) {
+ return false;
+ }
+
+ return IN_APP_AGENT_SANDBOX_TOOL_NAMES.has(toolName);
+ });
+}
+
export async function getOwnedConversationOrThrow(params: {
prisma: PrismaClient;
projectId: string;
@@ -288,15 +321,91 @@ export async function getConversationEvents(params: {
conversationId: params.conversationId,
},
orderBy: { sequenceNumber: "asc" },
- select: { event: true, runId: true },
+ select: { event: true, runId: true, createdAt: true },
});
- return events.map(({ event, runId }) => ({
+ return events.map(({ event, runId, createdAt }) => ({
event: event as unknown as AgUiEvent,
runId,
+ createdAt,
}));
}
+/**
+ * Returns `tool_calls` file payloads reconstructed from prior non-sandbox tool
+ * calls so each sandbox session can mount the same context.
+ */
+export function getSandboxToolCallFiles(
+ events: readonly PersistedConversationEvent[],
+) {
+ const drafts = new Map<
+ string,
+ {
+ createdAt: Date;
+ toolName: string;
+ request: string;
+ }
+ >();
+ const files: Array<{ path: string; content: string }> = [];
+
+ for (const { event, createdAt } of events) {
+ if (event.type === EventType.TOOL_CALL_START) {
+ const toolCallId = getString(event, "toolCallId");
+ const toolName = getString(event, "toolCallName");
+
+ if (
+ toolCallId &&
+ toolName &&
+ !IN_APP_AGENT_SANDBOX_TOOL_NAMES.has(toolName)
+ ) {
+ drafts.set(toolCallId, {
+ createdAt,
+ toolName,
+ request: "",
+ });
+ }
+ continue;
+ }
+
+ if (event.type === EventType.TOOL_CALL_ARGS) {
+ const toolCallId = getString(event, "toolCallId");
+ const draft = toolCallId ? drafts.get(toolCallId) : undefined;
+
+ if (draft) {
+ draft.request += getString(event, "delta") ?? "";
+ }
+ continue;
+ }
+
+ if (event.type !== EventType.TOOL_CALL_RESULT) {
+ continue;
+ }
+
+ const toolCallId = getString(event, "toolCallId");
+ const draft = toolCallId ? drafts.get(toolCallId) : undefined;
+
+ if (!toolCallId || !draft) {
+ continue;
+ }
+
+ drafts.delete(toolCallId);
+ files.push({
+ path: `tool_calls/${formatSandboxToolCallTimestamp(draft.createdAt)}_${draft.toolName}_${toolCallId}.json`,
+ content: JSON.stringify(
+ {
+ request: parseSandboxToolCallValue(draft.request),
+ response: parseSandboxToolCallValue(getString(event, "content")),
+ error: getString(event, "error") ?? null,
+ },
+ null,
+ 2,
+ ),
+ });
+ }
+
+ return files;
+}
+
export async function getConversationMessages(params: {
prisma: PrismaClient;
projectId: string;
@@ -1184,7 +1293,20 @@ function compactObject<T extends Record<string, unknown>>(value: T): T {
) as T;
}
-export function getDefaultConversationTitle(date: Date) {
+function parseSandboxToolCallValue(value: string | undefined) {
+ if (!value) {
+ return null;
+ }
+
+ const parsed = safeJsonParse(value);
+ return parsed === undefined ? value : parsed;
+}
+
+function formatSandboxToolCallTimestamp(date: Date) {
+ return date.toISOString().replaceAll(":", "-");
+}
+
+function getDefaultConversationTitle(date: Date) {
const weekday = date.toLocaleDateString("en-US", { weekday: "long" });
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
diff --git a/web/src/ee/features/in-app-agent/server/router.ts b/web/src/ee/features/in-app-agent/server/router.ts
index 4ded36eb6b..e35ea6af11 100644
--- a/web/src/ee/features/in-app-agent/server/router.ts
+++ b/web/src/ee/features/in-app-agent/server/router.ts
@@ -27,9 +27,11 @@ import {
protectedProjectProcedureWithoutTracing,
} from "@/src/server/api/trpc";
import {
+ getConversationEvents,
getConversationMessagesForDisplay,
getConversationMessages,
getOwnedConversationOrThrow,
+ isInAppAgentConversationWriteLocked,
serializeConversation,
} from "@/src/ee/features/in-app-agent/server/persistence";
@@ -96,7 +98,9 @@ export const inAppAgentRouter = createTRPCRouter({
const lastConversation = page.at(-1);
return {
- conversations: page.map(serializeConversation),
+ conversations: page.map((conversation) =>
+ serializeConversation(conversation),
+ ),
nextCursor:
conversations.length > input.limit && lastConversation
? {
@@ -119,14 +123,26 @@ export const inAppAgentRouter = createTRPCRouter({
userId: ctx.session.user.id,
});
- const messages = await getConversationMessagesForDisplay({
- prisma: ctx.prisma,
- projectId: input.projectId,
- conversationId: input.conversationId,
- });
+ const [messages, events] = await Promise.all([
+ getConversationMessagesForDisplay({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ }),
+ getConversationEvents({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ conversationId: input.conversationId,
+ }),
+ ]);
return {
- conversation: serializeConversation(conversation),
+ conversation: serializeConversation(conversation, {
+ isWriteLocked: isInAppAgentConversationWriteLocked({
+ conversation,
+ events,
+ }),
+ }),
messages,
state: {
type: "existingConversation" as const,
@@ -156,6 +172,7 @@ export const inAppAgentRouter = createTRPCRouter({
},
},
data: {
+ providerSessionId: null,
deletedAt: new Date(),
},
});
diff --git a/web/src/ee/features/in-app-agent/server/sandbox/config.ts b/web/src/ee/features/in-app-agent/server/sandbox/config.ts
new file mode 100644
index 0000000000..ef4d39e828
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/server/sandbox/config.ts
@@ -0,0 +1,62 @@
+import { createLambdaMicrovmSandboxProvider } from "./providers/lambdaMicrovm";
+import type { InAppAgentSandboxProviderType, SandboxProvider } from "./types";
+import { env } from "@/src/env.mjs";
+import { IN_APP_AGENT_LOCAL_SANDBOX_IMAGE } from "@/src/ee/features/in-app-agent/constants";
+import { assertUnreachable } from "@/src/utils/types";
+
+export function getDefaultInAppAgentSandboxProviderType(): InAppAgentSandboxProviderType | null {
+ const providerType = env.LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER ?? null;
+
+ if (providerType === null) {
+ return null;
+ }
+
+ if (providerType === "dangerous-docker" && env.NODE_ENV !== "development") {
+ throw new Error(
+ "The dangerous-docker in-app agent sandbox provider is only supported in development.",
+ );
+ }
+
+ return providerType;
+}
+
+export async function createInAppAgentSandboxProvider(
+ providerType: InAppAgentSandboxProviderType,
+): Promise<SandboxProvider> {
+ if (providerType === "dangerous-docker") {
+ if (env.NODE_ENV !== "development") {
+ throw new Error(
+ "The dangerous-docker in-app agent sandbox provider is only supported in development.",
+ );
+ }
+
+ // Keep the Docker provider behind a runtime import since it's only used in development
+ const { createDockerSandboxProvider } = await import("./providers/docker");
+ return createDockerSandboxProvider({
+ image: IN_APP_AGENT_LOCAL_SANDBOX_IMAGE,
+ });
+ }
+
+ if (providerType === "lambda-microvm") {
+ const microvmImageIdentifier =
+ env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER;
+ const microvmExecutionRoleArn =
+ env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN;
+ const microvmRegion =
+ env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION;
+
+ if (!microvmImageIdentifier || !microvmExecutionRoleArn || !microvmRegion) {
+ throw new Error(
+ "Invalid lambda-microvm sandbox config: image identifier, execution role ARN, and region are required.",
+ );
+ }
+
+ return createLambdaMicrovmSandboxProvider({
+ imageIdentifier: microvmImageIdentifier,
+ executionRoleArn: microvmExecutionRoleArn,
+ region: microvmRegion,
+ });
+ }
+
+ assertUnreachable(providerType);
+}
diff --git a/web/src/ee/features/in-app-agent/server/sandbox/index.ts b/web/src/ee/features/in-app-agent/server/sandbox/index.ts
new file mode 100644
index 0000000000..57fe34ab17
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/server/sandbox/index.ts
@@ -0,0 +1,10 @@
+export { createLambdaMicrovmSandboxProvider } from "./providers/lambdaMicrovm";
+export { getDefaultInAppAgentSandboxProviderType } from "./config";
+export { createInAppAgentSandbox } from "./service";
+export type {
+ InAppAgentSandbox,
+ InAppAgentSandboxProviderType,
+ SandboxFile,
+ SandboxProvider,
+ SandboxSession,
+} from "./types";
diff --git a/web/src/ee/features/in-app-agent/server/sandbox/providers/docker.ts b/web/src/ee/features/in-app-agent/server/sandbox/providers/docker.ts
new file mode 100644
index 0000000000..0d7b6c0232
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/server/sandbox/providers/docker.ts
@@ -0,0 +1,685 @@
+import { PassThrough } from "node:stream";
+
+import type Docker from "dockerode";
+import { logger } from "@langfuse/shared/src/server";
+
+import type { SandboxFile, SandboxProvider, SandboxSession } from "../types";
+
+type DockerExecResult = {
+ exitCode: number;
+ stderr: string;
+ stdout: string;
+};
+
+type DockerContainer = Docker.Container;
+
+type DockerSandboxSession = {
+ toolCallFiles: ReadonlyArray<SandboxFile>;
+};
+
+type DockerExecContext = {
+ operation: string;
+ containerId: string;
+ attempt?: number;
+};
+
+const DOCKER_SANDBOX_SERVER_PORT = 5000;
+
+export async function createDockerSandboxProvider(params: {
+ image: string;
+}): Promise<SandboxProvider> {
+ const { default: Docker } = await import("dockerode");
+ const docker = new Docker();
+ const sessions = new Map<string, DockerSandboxSession>();
+
+ const ensureSessionState = (conversationId: string) => {
+ const session = sessions.get(conversationId) ?? {
+ toolCallFiles: [],
+ };
+ sessions.set(conversationId, session);
+ return session;
+ };
+
+ const getContainerByIdentifier = async (identifier: string) => {
+ const container = docker.getContainer(identifier);
+
+ try {
+ return {
+ container,
+ inspect: await container.inspect(),
+ };
+ } catch (error) {
+ if (isMissingDockerContainerError(error)) {
+ return null;
+ }
+
+ throw error;
+ }
+ };
+
+ const getContainerByConversationId = async (conversationId: string) => {
+ return getContainerByIdentifier(
+ getDockerSandboxContainerName(conversationId),
+ );
+ };
+
+ const createContainer = async (createParams: { conversationId: string }) => {
+ let container: DockerContainer;
+ const containerName = getDockerSandboxContainerName(
+ createParams.conversationId,
+ );
+
+ try {
+ logger.debug("In-app agent docker sandbox creating container", {
+ image: params.image,
+ containerName,
+ });
+ container = await docker.createContainer({
+ Image: params.image,
+ name: containerName,
+ WorkingDir: "/workspace",
+ AttachStdout: true,
+ AttachStderr: true,
+ NetworkDisabled: true,
+ Tty: false,
+ });
+ } catch (error) {
+ if (isMissingDockerImageError(error)) {
+ throw new Error(
+ `Missing local sandbox image ${params.image}. Re-run \`bash scripts/codex/setup.sh\` or run \`pnpm turbo run build:docker-image --filter @repo/in-app-agent-sandbox-runtime --force\`.`,
+ );
+ }
+
+ throw error;
+ }
+
+ logger.debug("In-app agent docker sandbox starting container", {
+ containerId: container.id,
+ conversationId: createParams.conversationId,
+ });
+ await container.start();
+ logger.debug("In-app agent docker sandbox started container", {
+ containerId: container.id,
+ conversationId: createParams.conversationId,
+ });
+
+ ensureSessionState(createParams.conversationId);
+ await waitForSandboxServer(container);
+ return container;
+ };
+
+ const ensureContainer = async (params: { conversationId: string }) => {
+ logger.debug("In-app agent docker sandbox inspecting existing container", {
+ conversationId: params.conversationId,
+ containerName: getDockerSandboxContainerName(params.conversationId),
+ });
+
+ const existing = await getContainerByConversationId(params.conversationId);
+ if (!existing) {
+ logger.debug("In-app agent docker sandbox missing container", {
+ conversationId: params.conversationId,
+ });
+ return createContainer(params);
+ }
+
+ if (!existing.inspect.State?.Running) {
+ logger.debug("In-app agent docker sandbox removing stale container", {
+ conversationId: params.conversationId,
+ containerId: existing.container.id,
+ state: formatContainerState(existing.inspect),
+ });
+ await existing.container
+ .remove({ force: true, v: true })
+ .catch(() => undefined);
+ return createContainer(params);
+ }
+
+ ensureSessionState(params.conversationId);
+ logger.debug("In-app agent docker sandbox reusing running container", {
+ conversationId: params.conversationId,
+ containerId: existing.container.id,
+ state: formatContainerState(existing.inspect),
+ });
+ return existing.container;
+ };
+
+ const createSessionSandbox = (conversationId: string): SandboxSession => ({
+ async syncReadonlyFiles({ files }) {
+ ensureSessionState(conversationId).toolCallFiles = files;
+ logger.debug("In-app agent docker sandbox synced readonly files", {
+ conversationId,
+ fileCount: files.length,
+ paths: files.map((file) => file.path),
+ });
+ },
+ async read({ path }) {
+ const container = await ensureContainer({ conversationId });
+ return callSandboxServer(container, {
+ operation: "read",
+ path,
+ toolCallFiles: getSession(sessions, conversationId).toolCallFiles,
+ });
+ },
+ async write({ path, content }) {
+ const container = await ensureContainer({ conversationId });
+ return callSandboxServer(container, {
+ operation: "write",
+ path,
+ content,
+ toolCallFiles: getSession(sessions, conversationId).toolCallFiles,
+ });
+ },
+ async edit({ path, oldText, newText }) {
+ const container = await ensureContainer({ conversationId });
+ return callSandboxServer(container, {
+ operation: "edit",
+ path,
+ oldText,
+ newText,
+ toolCallFiles: getSession(sessions, conversationId).toolCallFiles,
+ });
+ },
+ async bash({ command, timeoutMs }) {
+ const container = await ensureContainer({ conversationId });
+ return callSandboxServer(container, {
+ operation: "bash",
+ command,
+ ...(timeoutMs ? { timeoutMs } : {}),
+ toolCallFiles: getSession(sessions, conversationId).toolCallFiles,
+ });
+ },
+ });
+
+ return {
+ async ensureSession({ conversationId, sessionId }) {
+ logger.debug("In-app agent docker sandbox ensureSession", {
+ conversationId,
+ requestedSessionId: sessionId,
+ });
+ const container = await ensureContainer({
+ conversationId,
+ });
+ logger.debug("In-app agent docker sandbox ready session", {
+ conversationId,
+ sessionId: container.id,
+ });
+ return {
+ sessionId: conversationId,
+ sandbox: createSessionSandbox(conversationId),
+ };
+ },
+ async suspendSession({ sessionId }) {
+ sessions.delete(sessionId);
+ logger.debug(
+ "In-app agent docker sandbox leaving container running across local session suspend",
+ {
+ sessionId,
+ },
+ );
+ },
+ async terminateSession({ sessionId }: { sessionId: string }) {
+ sessions.delete(sessionId);
+ const existing =
+ (await getContainerByIdentifier(sessionId)) ??
+ (await getContainerByConversationId(sessionId));
+
+ await existing?.container
+ .remove({ force: true, v: true })
+ .catch(() => undefined);
+ },
+ };
+}
+
+async function waitForSandboxServer(container: DockerContainer) {
+ const startedAt = Date.now();
+ let lastError: unknown;
+ let attempt = 0;
+
+ while (Date.now() - startedAt < 30_000) {
+ attempt += 1;
+ try {
+ logger.debug("In-app agent docker sandbox health probe start", {
+ containerId: container.id,
+ attempt,
+ elapsedMs: Date.now() - startedAt,
+ });
+ const result = await execJsonInContainer(container, [
+ "node",
+ "-e",
+ `
+ (async () => {
+ const response = await fetch("http://127.0.0.1:${DOCKER_SANDBOX_SERVER_PORT}/health");
+ if (!response.ok) {
+ process.stderr.write(await response.text());
+ process.exit(1);
+ }
+ process.stdout.write(await response.text());
+ })().catch((error) => {
+ process.stderr.write(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ });
+ `,
+ ]);
+
+ logger.debug("In-app agent docker sandbox health probe result", {
+ containerId: container.id,
+ attempt,
+ result,
+ });
+
+ if (
+ result &&
+ typeof result === "object" &&
+ "status" in result &&
+ result.status === "ok"
+ ) {
+ logger.debug("In-app agent docker sandbox health probe ready", {
+ containerId: container.id,
+ attempt,
+ elapsedMs: Date.now() - startedAt,
+ });
+ return;
+ }
+ } catch (error) {
+ lastError = error;
+ logger.debug("In-app agent docker sandbox health probe failed", {
+ containerId: container.id,
+ attempt,
+ elapsedMs: Date.now() - startedAt,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+
+ throw await createSandboxServerNotReadyError({ container, lastError });
+}
+
+async function createSandboxServerNotReadyError(params: {
+ container: DockerContainer;
+ lastError: unknown;
+}) {
+ const details = ["Sandbox server did not become ready within 30000ms."];
+
+ if (params.lastError instanceof Error) {
+ details.push(`Last health probe error: ${params.lastError.message}`);
+ }
+
+ const inspect = await params.container.inspect().catch(() => null);
+ if (inspect) {
+ details.push(`Container state: ${formatContainerState(inspect)}`);
+ }
+
+ const logs = await readContainerLogs(params.container).catch(() => null);
+ if (logs) {
+ details.push(`Container logs: ${logs}`);
+ }
+
+ return new Error(details.join(" "));
+}
+
+async function callSandboxServer(
+ container: DockerContainer,
+ payload: Record<string, unknown>,
+) {
+ logger.debug("In-app agent docker sandbox tool call start", {
+ containerId: container.id,
+ payload: summarizePayload(payload),
+ });
+ const result = await execJsonInContainer(
+ container,
+ [
+ "node",
+ "-e",
+ `
+ (async () => {
+ const payload = JSON.parse(process.argv[1]);
+ const response = await fetch("http://127.0.0.1:${DOCKER_SANDBOX_SERVER_PORT}/sandbox", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ const text = await response.text();
+ if (!response.ok) {
+ process.stderr.write(text);
+ process.exit(1);
+ }
+ process.stdout.write(text);
+ })().catch((error) => {
+ process.stderr.write(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ });
+ `,
+ JSON.stringify(payload),
+ ],
+ undefined,
+ {
+ operation: `sandbox:${String(payload.operation ?? "unknown")}`,
+ containerId: container.id,
+ },
+ );
+
+ logger.debug("In-app agent docker sandbox tool call result", {
+ containerId: container.id,
+ payload: summarizePayload(payload),
+ result,
+ });
+
+ if (result && typeof result === "object" && "result" in result) {
+ return result.result;
+ }
+
+ return result;
+}
+
+function getSession(
+ sessions: Map<string, DockerSandboxSession>,
+ sessionId: string,
+) {
+ const session = sessions.get(sessionId);
+ if (!session) {
+ throw new Error(`Missing sandbox session: ${sessionId}`);
+ }
+
+ return session;
+}
+
+async function execJsonInContainer(
+ container: DockerContainer,
+ cmd: string[],
+ timeoutMs?: number,
+ context?: DockerExecContext,
+) {
+ const result = await execInContainer(container, cmd, timeoutMs, context);
+ if (result.exitCode !== 0) {
+ throw new Error(
+ result.stderr || result.stdout || "Container command failed",
+ );
+ }
+ return JSON.parse(result.stdout || "null") as unknown;
+}
+
+async function execInContainer(
+ container: DockerContainer,
+ cmd: string[],
+ timeoutMs?: number,
+ context?: DockerExecContext,
+): Promise<DockerExecResult> {
+ logger.debug("In-app agent docker sandbox exec create", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ timeoutMs: timeoutMs ?? null,
+ commandPreview: summarizeCommand(cmd),
+ });
+ const exec = await container.exec({
+ Cmd: cmd,
+ AttachStdout: true,
+ AttachStderr: true,
+ WorkingDir: "/workspace",
+ });
+ logger.debug("In-app agent docker sandbox exec created", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ });
+ const stream = await exec.start({ Tty: false });
+ logger.debug("In-app agent docker sandbox exec stream started", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ });
+
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ container.modem.demuxStream(stream, stdout, stderr);
+ const finalizeDemuxStreams = () => {
+ stdout.end();
+ stderr.end();
+ };
+ stream.once("end", () => {
+ logger.debug("In-app agent docker sandbox exec stream end", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ });
+ finalizeDemuxStreams();
+ });
+ stream.once("close", () => {
+ logger.debug("In-app agent docker sandbox exec stream close", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ });
+ finalizeDemuxStreams();
+ });
+ stream.once("error", (error) => {
+ logger.debug("In-app agent docker sandbox exec stream error", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ finalizeDemuxStreams();
+ });
+
+ const timeoutId = timeoutMs
+ ? setTimeout(
+ () =>
+ stream.destroy(
+ new Error(`Sandbox command timed out after ${timeoutMs}ms`),
+ ),
+ timeoutMs,
+ )
+ : undefined;
+
+ try {
+ const [stdoutBytes, stderrBytes, inspect] = await Promise.all([
+ readStreamToUint8Array(stdout).then((bytes) => {
+ logger.debug("In-app agent docker sandbox exec stdout complete", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ bytes: bytes.length,
+ });
+ return bytes;
+ }),
+ readStreamToUint8Array(stderr).then((bytes) => {
+ logger.debug("In-app agent docker sandbox exec stderr complete", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ bytes: bytes.length,
+ });
+ return bytes;
+ }),
+ waitForStreamEnd(stream).then(async () => {
+ logger.debug("In-app agent docker sandbox exec inspect start", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ });
+ const inspect = await exec.inspect();
+ logger.debug("In-app agent docker sandbox exec inspect complete", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ exitCode: inspect.ExitCode ?? 1,
+ });
+ return inspect;
+ }),
+ ]);
+
+ const stdoutText = Buffer.from(stdoutBytes).toString("utf8");
+ const stderrText = Buffer.from(stderrBytes).toString("utf8");
+ logger.debug("In-app agent docker sandbox exec complete", {
+ containerId: container.id,
+ operation: context?.operation ?? "unknown",
+ attempt: context?.attempt,
+ exitCode: inspect.ExitCode ?? 1,
+ stdoutPreview: summarizeText(stdoutText),
+ stderrPreview: summarizeText(stderrText),
+ });
+
+ return {
+ exitCode: inspect.ExitCode ?? 1,
+ stdout: stdoutText,
+ stderr: stderrText,
+ };
+ } finally {
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ }
+}
+
+function summarizePayload(payload: Record<string, unknown>) {
+ if (payload.operation === "read") {
+ return {
+ operation: payload.operation,
+ path: payload.path,
+ toolCallFileCount: Array.isArray(payload.toolCallFiles)
+ ? payload.toolCallFiles.length
+ : 0,
+ };
+ }
+
+ if (payload.operation === "write") {
+ return {
+ operation: payload.operation,
+ path: payload.path,
+ contentBytes:
+ typeof payload.content === "string"
+ ? Buffer.byteLength(payload.content, "utf8")
+ : null,
+ toolCallFileCount: Array.isArray(payload.toolCallFiles)
+ ? payload.toolCallFiles.length
+ : 0,
+ };
+ }
+
+ if (payload.operation === "edit") {
+ return {
+ operation: payload.operation,
+ path: payload.path,
+ oldTextLength:
+ typeof payload.oldText === "string" ? payload.oldText.length : null,
+ newTextLength:
+ typeof payload.newText === "string" ? payload.newText.length : null,
+ toolCallFileCount: Array.isArray(payload.toolCallFiles)
+ ? payload.toolCallFiles.length
+ : 0,
+ };
+ }
+
+ if (payload.operation === "bash") {
+ return {
+ operation: payload.operation,
+ timeoutMs: payload.timeoutMs,
+ command:
+ typeof payload.command === "string"
+ ? summarizeText(payload.command)
+ : null,
+ toolCallFileCount: Array.isArray(payload.toolCallFiles)
+ ? payload.toolCallFiles.length
+ : 0,
+ };
+ }
+
+ return payload;
+}
+
+function summarizeCommand(cmd: string[]) {
+ return summarizeText(cmd.join(" "));
+}
+
+function summarizeText(text: string, maxLength = 500) {
+ return text.length <= maxLength ? text : `${text.slice(0, maxLength)}...`;
+}
+
+async function readStreamToUint8Array(stream: NodeJS.ReadableStream) {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return new Uint8Array(Buffer.concat(chunks));
+}
+
+async function waitForStreamEnd(stream: NodeJS.ReadableStream) {
+ await new Promise<void>((resolve, reject) => {
+ stream.once("end", resolve);
+ stream.once("error", reject);
+ stream.once("close", resolve);
+ });
+}
+
+async function readContainerLogs(container: DockerContainer) {
+ const logs = await container.logs({
+ stdout: true,
+ stderr: true,
+ tail: 50,
+ });
+
+ const content = Buffer.isBuffer(logs)
+ ? logs.toString("utf8")
+ : Buffer.from(await readStreamToUint8Array(logs)).toString("utf8");
+ const trimmed = content.trim();
+
+ if (!trimmed) {
+ return null;
+ }
+
+ return trimmed.split(/\r?\n/).slice(-10).join(" | ");
+}
+
+function formatContainerState(
+ inspect: Awaited<ReturnType<DockerContainer["inspect"]>>,
+) {
+ const state = inspect.State;
+ if (!state) {
+ return "state unavailable";
+ }
+
+ return [
+ `status=${state.Status ?? "unknown"}`,
+ `running=${String(state.Running ?? false)}`,
+ `exitCode=${String(state.ExitCode ?? "unknown")}`,
+ ...(state.Error ? [`error=${state.Error}`] : []),
+ ].join(", ");
+}
+
+function isMissingDockerImageError(error: unknown) {
+ return (
+ error !== null &&
+ typeof error === "object" &&
+ "statusCode" in error &&
+ error.statusCode === 404 &&
+ "message" in error &&
+ typeof error.message === "string" &&
+ error.message.includes("No such image")
+ );
+}
+
+function isMissingDockerContainerError(error: unknown) {
+ return (
+ error !== null &&
+ typeof error === "object" &&
+ "statusCode" in error &&
+ error.statusCode === 404 &&
+ "message" in error &&
+ typeof error.message === "string" &&
+ error.message.toLowerCase().includes("no such container")
+ );
+}
+
+function getDockerSandboxContainerName(conversationId: string) {
+ const sanitizedConversationId = conversationId
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9_.-]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 48);
+
+ return `langfuse-in-app-agent-sandbox-${sanitizedConversationId || "unknown"}`;
+}
diff --git a/web/src/ee/features/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts b/web/src/ee/features/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts
new file mode 100644
index 0000000000..cb619791f1
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/server/sandbox/providers/lambdaMicrovm.ts
@@ -0,0 +1,509 @@
+import { randomUUID } from "crypto";
+
+import {
+ CreateMicrovmAuthTokenCommand,
+ GetMicrovmCommand,
+ LambdaMicrovmsClient,
+ ResumeMicrovmCommand,
+ RunMicrovmCommand,
+ SuspendMicrovmCommand,
+ TerminateMicrovmCommand,
+ type RunMicrovmCommandInput,
+} from "@aws-sdk/client-lambda-microvms";
+import { logger } from "@langfuse/shared/src/server";
+import { z } from "zod";
+
+import type { SandboxFile, SandboxProvider, SandboxSession } from "../types";
+
+const DEFAULT_AUTH_TOKEN_EXPIRATION_MINUTES = 30;
+const AUTH_TOKEN_REFRESH_BUFFER_MS = 60_000;
+const DEFAULT_SANDBOX_SERVER_PORT = 5000;
+const DEFAULT_SUSPEND_AFTER_IDLE_SECONDS = 60;
+const DEFAULT_TERMINATE_AFTER_SUSPEND_SECONDS = 8 * 60 * 60;
+const DEFAULT_MAXIMUM_DURATION_SECONDS = 3_600;
+const BRIDGE_READY_TIMEOUT_MS = 30_000;
+
+const LambdaMicrovmErrorSchema = z.object({
+ name: z.string().optional(),
+ $metadata: z
+ .object({
+ httpStatusCode: z.number().optional(),
+ })
+ .optional(),
+});
+
+const LambdaMicrovmOperationResultSchema = z.object({
+ result: z.unknown(),
+});
+
+type LambdaMicrovmOperation =
+ | { operation: "read"; path: string }
+ | { operation: "write"; path: string; content: string }
+ | { operation: "edit"; path: string; oldText: string; newText: string }
+ | { operation: "bash"; command: string; timeoutMs?: number };
+
+type LambdaMicrovmSession = {
+ endpoint: string;
+ authToken?: {
+ value: string;
+ expiresAtMs: number;
+ };
+ toolCallFiles: ReadonlyArray<SandboxFile>;
+};
+
+type LambdaMicrovmInfo = {
+ microvmId: string;
+ endpoint: string;
+ state: string;
+ stateReason?: string;
+};
+
+export function createLambdaMicrovmSandboxProvider(params: {
+ imageIdentifier: string;
+ executionRoleArn: string;
+ region: string;
+}): SandboxProvider {
+ const client = new LambdaMicrovmsClient({
+ region: params.region,
+ });
+ const sessions = new Map<string, LambdaMicrovmSession>();
+
+ const ensureSession = async (request: {
+ conversationId: string;
+ sessionId?: string | null;
+ }) => {
+ logger.debug("[Lambda MicroVM Sandbox] ensureSession", {
+ conversationId: request.conversationId,
+ requestedSessionId: request.sessionId,
+ });
+
+ if (request.sessionId) {
+ logger.debug(
+ "[Lambda MicroVM Sandbox] checking existing session before restore",
+ {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ },
+ );
+ }
+
+ if (request.sessionId) {
+ const existing = await getMicrovm(client, request.sessionId);
+ if (existing) {
+ if (existing.state === "SUSPENDED") {
+ logger.debug("[Lambda MicroVM Sandbox] resuming suspended session", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ });
+ await client.send(
+ new ResumeMicrovmCommand({ microvmIdentifier: request.sessionId }),
+ );
+ }
+
+ await waitForBridge({
+ client,
+ microvmId: request.sessionId,
+ endpoint: existing.endpoint,
+ });
+
+ const session = sessions.get(request.sessionId);
+ sessions.set(request.sessionId, {
+ ...session,
+ endpoint: existing.endpoint,
+ toolCallFiles: session?.toolCallFiles ?? [],
+ });
+ logger.debug("[Lambda MicroVM Sandbox] reusing existing session", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ state: existing.state,
+ });
+ return { sessionId: request.sessionId, endpoint: existing.endpoint };
+ }
+
+ logger.debug("[Lambda MicroVM Sandbox] existing session not found", {
+ conversationId: request.conversationId,
+ sessionId: request.sessionId,
+ });
+ sessions.delete(request.sessionId);
+ }
+
+ logger.debug("[Lambda MicroVM Sandbox] creating new session", {
+ conversationId: request.conversationId,
+ imageIdentifier: params.imageIdentifier,
+ hasExecutionRoleArn: Boolean(params.executionRoleArn),
+ });
+ const microvm = readMicrovmInfo(
+ await client.send(
+ new RunMicrovmCommand({
+ imageIdentifier: params.imageIdentifier,
+ executionRoleArn: params.executionRoleArn,
+ idlePolicy: {
+ autoResumeEnabled: true,
+ maxIdleDurationSeconds: DEFAULT_SUSPEND_AFTER_IDLE_SECONDS,
+ suspendedDurationSeconds: DEFAULT_TERMINATE_AFTER_SUSPEND_SECONDS,
+ },
+ maximumDurationInSeconds: DEFAULT_MAXIMUM_DURATION_SECONDS,
+ clientToken: randomUUID(),
+ } satisfies RunMicrovmCommandInput),
+ ),
+ );
+
+ sessions.set(microvm.microvmId, {
+ endpoint: microvm.endpoint,
+ toolCallFiles: [],
+ });
+ await waitForBridge({
+ client,
+ microvmId: microvm.microvmId,
+ endpoint: microvm.endpoint,
+ });
+
+ logger.debug("[Lambda MicroVM Sandbox] created new session", {
+ conversationId: request.conversationId,
+ sessionId: microvm.microvmId,
+ state: microvm.state,
+ });
+
+ return { sessionId: microvm.microvmId, endpoint: microvm.endpoint };
+ };
+
+ const executeOperation = async (
+ sessionId: string,
+ operation: LambdaMicrovmOperation,
+ ) => {
+ const session = getSession(sessions, sessionId);
+ if (
+ !session.authToken ||
+ session.authToken.expiresAtMs - AUTH_TOKEN_REFRESH_BUFFER_MS <= Date.now()
+ ) {
+ session.authToken = await createMicrovmAuthToken({
+ client,
+ microvmId: sessionId,
+ endpoint: session.endpoint,
+ });
+ }
+
+ logger.debug("[Lambda MicroVM Sandbox] executing operation", {
+ sessionId,
+ operation: operation.operation,
+ endpoint: session.endpoint,
+ normalizedEndpoint: normalizeEndpoint(session.endpoint),
+ endpointPort: getEndpointPort(session.endpoint),
+ sandboxServerPort: DEFAULT_SANDBOX_SERVER_PORT,
+ });
+
+ const response = await fetch(
+ `${normalizeEndpoint(session.endpoint)}/sandbox`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-aws-proxy-port": String(DEFAULT_SANDBOX_SERVER_PORT),
+ "X-aws-proxy-auth": session.authToken.value,
+ },
+ body: JSON.stringify({
+ ...operation,
+ toolCallFiles: session.toolCallFiles,
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ logger.debug("[Lambda MicroVM Sandbox] operation request failed", {
+ sessionId,
+ operation: operation.operation,
+ endpoint: session.endpoint,
+ normalizedEndpoint: normalizeEndpoint(session.endpoint),
+ endpointPort: getEndpointPort(session.endpoint),
+ sandboxServerPort: DEFAULT_SANDBOX_SERVER_PORT,
+ status: response.status,
+ statusText: response.statusText,
+ body: errorText,
+ });
+ throw new Error(
+ errorText || `Lambda MicroVM bridge request failed: ${response.status}`,
+ );
+ }
+
+ const result = (await response.json()) as unknown;
+ const parsedResult = LambdaMicrovmOperationResultSchema.safeParse(result);
+ if (parsedResult.success) {
+ return parsedResult.data.result;
+ }
+
+ return result;
+ };
+
+ const createSessionSandbox = (sessionId: string): SandboxSession => ({
+ async syncReadonlyFiles({ files }) {
+ getSession(sessions, sessionId).toolCallFiles = files;
+ },
+ async read({ path }) {
+ return executeOperation(sessionId, { operation: "read", path });
+ },
+ async write({ path, content }) {
+ return executeOperation(sessionId, {
+ operation: "write",
+ path,
+ content,
+ });
+ },
+ async edit({ path, oldText, newText }) {
+ return executeOperation(sessionId, {
+ operation: "edit",
+ path,
+ oldText,
+ newText,
+ });
+ },
+ async bash({ command, timeoutMs }) {
+ return executeOperation(sessionId, {
+ operation: "bash",
+ command,
+ ...(timeoutMs ? { timeoutMs } : {}),
+ });
+ },
+ });
+
+ return {
+ async ensureSession({ conversationId, sessionId }) {
+ const session = await ensureSession({
+ conversationId,
+ sessionId,
+ });
+ return {
+ sessionId: session.sessionId,
+ sandbox: createSessionSandbox(session.sessionId),
+ };
+ },
+ async suspendSession({ sessionId }) {
+ try {
+ await client.send(
+ new SuspendMicrovmCommand({ microvmIdentifier: sessionId }),
+ );
+ logger.debug("[Lambda MicroVM Sandbox] suspended session", {
+ sessionId,
+ });
+ } catch (error) {
+ if (!isMissingMicrovmError(error)) {
+ throw error;
+ }
+
+ logger.debug(
+ "[Lambda MicroVM Sandbox] suspend skipped missing session",
+ {
+ sessionId,
+ },
+ );
+ } finally {
+ sessions.delete(sessionId);
+ }
+ },
+ async terminateSession({ sessionId }) {
+ logger.debug("[Lambda MicroVM Sandbox] terminating session", {
+ sessionId,
+ });
+ sessions.delete(sessionId);
+
+ try {
+ await client.send(
+ new TerminateMicrovmCommand({ microvmIdentifier: sessionId }),
+ );
+ logger.debug("[Lambda MicroVM Sandbox] terminated session", {
+ sessionId,
+ });
+ } catch (error) {
+ if (!isMissingMicrovmError(error)) {
+ throw error;
+ }
+
+ logger.debug(
+ "[Lambda MicroVM Sandbox] terminate skipped missing session",
+ {
+ sessionId,
+ },
+ );
+ }
+ },
+ };
+}
+
+async function waitForBridge(params: {
+ client: LambdaMicrovmsClient;
+ microvmId: string;
+ endpoint: string;
+}) {
+ const startedAt = Date.now();
+ let lastError: unknown;
+
+ while (Date.now() - startedAt < BRIDGE_READY_TIMEOUT_MS) {
+ const microvm = await getMicrovm(params.client, params.microvmId);
+ if (!microvm) {
+ throw new Error(
+ `[Lambda MicroVM Sandbox] startup failed before bridge became ready: session ${params.microvmId} no longer exists`,
+ );
+ }
+
+ if (microvm.state === "TERMINATING" || microvm.state === "TERMINATED") {
+ throw new Error(
+ `[Lambda MicroVM Sandbox] startup failed before bridge became ready: state=${microvm.state}${microvm.stateReason ? ` stateReason=${microvm.stateReason}` : ""}`,
+ );
+ }
+
+ try {
+ logger.debug("[Lambda MicroVM Sandbox] bridge health probe", {
+ microvmId: params.microvmId,
+ endpoint: params.endpoint,
+ normalizedEndpoint: normalizeEndpoint(params.endpoint),
+ endpointPort: getEndpointPort(params.endpoint),
+ sandboxServerPort: DEFAULT_SANDBOX_SERVER_PORT,
+ });
+ const response = await fetch(
+ `${normalizeEndpoint(params.endpoint)}/health`,
+ {
+ headers: {
+ "X-aws-proxy-port": String(DEFAULT_SANDBOX_SERVER_PORT),
+ "X-aws-proxy-auth": (await createMicrovmAuthToken(params)).value,
+ },
+ },
+ );
+
+ if (response.ok) {
+ return;
+ }
+
+ lastError = new Error(
+ (await response.text()) ||
+ `[Lambda MicroVM Sandbox] health probe failed with ${response.status}`,
+ );
+ } catch (error) {
+ lastError = error;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+
+ throw lastError instanceof Error
+ ? lastError
+ : new Error("[Lambda MicroVM Sandbox] bridge did not become ready");
+}
+
+async function createMicrovmAuthToken(params: {
+ client: LambdaMicrovmsClient;
+ microvmId: string;
+ endpoint: string;
+}) {
+ const endpointPort = getEndpointPort(params.endpoint);
+ logger.debug("[Lambda MicroVM Sandbox] creating auth token", {
+ microvmId: params.microvmId,
+ endpoint: params.endpoint,
+ normalizedEndpoint: normalizeEndpoint(params.endpoint),
+ endpointPort,
+ sandboxServerPort: DEFAULT_SANDBOX_SERVER_PORT,
+ });
+
+ const response = await params.client.send(
+ new CreateMicrovmAuthTokenCommand({
+ microvmIdentifier: params.microvmId,
+ expirationInMinutes: DEFAULT_AUTH_TOKEN_EXPIRATION_MINUTES,
+ allowedPorts: [{ allPorts: {} }],
+ }),
+ );
+
+ const token =
+ response.authToken?.["X-aws-proxy-auth"] ??
+ response.authToken?.["x-aws-proxy-auth"] ??
+ Object.values(response.authToken ?? {})[0];
+
+ if (!token) {
+ throw new Error(
+ "Lambda MicroVM auth token response did not include X-aws-proxy-auth",
+ );
+ }
+
+ logger.debug("[Lambda MicroVM Sandbox] created auth token", {
+ microvmId: params.microvmId,
+ endpointPort,
+ sandboxServerPort: DEFAULT_SANDBOX_SERVER_PORT,
+ authTokenKeys: Object.keys(response.authToken ?? {}),
+ });
+
+ return {
+ value: token,
+ expiresAtMs: Date.now() + DEFAULT_AUTH_TOKEN_EXPIRATION_MINUTES * 60 * 1000,
+ };
+}
+
+async function getMicrovm(client: LambdaMicrovmsClient, microvmId: string) {
+ try {
+ return readMicrovmInfo(
+ await client.send(
+ new GetMicrovmCommand({ microvmIdentifier: microvmId }),
+ ),
+ );
+ } catch (error) {
+ if (isMissingMicrovmError(error)) {
+ return null;
+ }
+
+ throw error;
+ }
+}
+
+function getSession(
+ sessions: Map<string, LambdaMicrovmSession>,
+ sessionId: string,
+) {
+ const session = sessions.get(sessionId);
+ if (!session) {
+ throw new Error(`Missing sandbox session: ${sessionId}`);
+ }
+ return session;
+}
+
+function readMicrovmInfo(value: {
+ microvmId?: string;
+ endpoint?: string;
+ state?: string;
+ stateReason?: string;
+}) {
+ if (!value.microvmId || !value.endpoint || !value.state) {
+ throw new Error("Lambda MicroVM response did not include required fields");
+ }
+
+ return {
+ microvmId: value.microvmId,
+ endpoint: value.endpoint,
+ state: value.state,
+ ...(value.stateReason ? { stateReason: value.stateReason } : {}),
+ } satisfies LambdaMicrovmInfo;
+}
+
+function normalizeEndpoint(endpoint: string) {
+ const trimmed = endpoint.replace(/\/$/, "");
+ return /^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
+}
+
+function getEndpointPort(endpoint: string) {
+ const normalizedEndpoint = normalizeEndpoint(endpoint);
+ const parsedEndpoint = new URL(normalizedEndpoint);
+
+ if (parsedEndpoint.port) {
+ return Number(parsedEndpoint.port);
+ }
+
+ return parsedEndpoint.protocol === "http:" ? 80 : 443;
+}
+
+function isMissingMicrovmError(error: unknown) {
+ const parsedError = LambdaMicrovmErrorSchema.safeParse(error);
+ if (!parsedError.success) {
+ return false;
+ }
+
+ const { name, $metadata } = parsedError.data;
+ const statusCode = $metadata?.httpStatusCode;
+
+ return name === "ResourceNotFoundException" || statusCode === 404;
+}
diff --git a/web/src/ee/features/in-app-agent/server/sandbox/service.ts b/web/src/ee/features/in-app-agent/server/sandbox/service.ts
new file mode 100644
index 0000000000..dbf9eea50d
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/server/sandbox/service.ts
@@ -0,0 +1,79 @@
+import type { InAppAgentSandbox, SandboxFile, SandboxProvider } from "./types";
+
+export async function createInAppAgentSandbox(params: {
+ conversationId: string;
+ projectId: string;
+ providerSessionId?: string | null;
+ provider: SandboxProvider;
+ getToolCallFiles: () => Promise<ReadonlyArray<SandboxFile>>;
+ saveState: (state: { providerSessionId?: string | null }) => Promise<void>;
+}): Promise<{
+ sandbox: InAppAgentSandbox;
+ onTurnEnded: () => Promise<void>;
+}> {
+ let sessionId = params.providerSessionId ?? null;
+ let sessionIsKnownActive = sessionId !== null;
+
+ const persistState = async () => {
+ await params.saveState({
+ providerSessionId: sessionId,
+ });
+ };
+
+ const updateSessionState = async (nextSessionId: string) => {
+ if (nextSessionId === sessionId) {
+ sessionIsKnownActive = true;
+ return;
+ }
+
+ sessionId = nextSessionId;
+ await persistState();
+ sessionIsKnownActive = true;
+ };
+
+ const ensureSession = async () => {
+ const session = await params.provider.ensureSession({
+ conversationId: params.conversationId,
+ sessionId: sessionIsKnownActive ? sessionId : null,
+ });
+
+ await updateSessionState(session.sessionId);
+
+ await session.sandbox.syncReadonlyFiles({
+ files: await params.getToolCallFiles(),
+ });
+
+ return session.sandbox;
+ };
+
+ const createExecutionSandbox = (): InAppAgentSandbox => ({
+ read: async ({ path }) => (await ensureSession()).read({ path }),
+ write: async ({ path, content }) =>
+ (await ensureSession()).write({
+ path,
+ content,
+ }),
+ edit: async ({ path, oldText, newText }) =>
+ (await ensureSession()).edit({
+ path,
+ oldText,
+ newText,
+ }),
+ bash: async ({ command, timeoutMs }) =>
+ (await ensureSession()).bash({
+ command,
+ timeoutMs,
+ }),
+ });
+
+ return {
+ sandbox: createExecutionSandbox(),
+ onTurnEnded: async () => {
+ if (!sessionId) {
+ return;
+ }
+
+ await persistState();
+ },
+ };
+}
diff --git a/web/src/ee/features/in-app-agent/server/sandbox/types.ts b/web/src/ee/features/in-app-agent/server/sandbox/types.ts
new file mode 100644
index 0000000000..11efe52755
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/server/sandbox/types.ts
@@ -0,0 +1,83 @@
+export type SandboxFile = {
+ path: string;
+ content: string;
+};
+
+export type InAppAgentSandboxProviderType =
+ | "dangerous-docker"
+ | "lambda-microvm";
+
+/**
+ * Session-bound sandbox execution handle returned by a provider.
+ * Implementations close over the backing runtime session so callers only pass
+ * per-operation inputs.
+ */
+export type SandboxSession = {
+ /**
+ * Refreshes the readonly tool-call files exposed to the current session.
+ */
+ syncReadonlyFiles(params: {
+ files: ReadonlyArray<SandboxFile>;
+ }): Promise<void>;
+ /**
+ * Executes a sandbox `read` operation within the session workspace.
+ */
+ read(params: { path: string }): Promise<unknown>;
+ /**
+ * Executes a sandbox `write` operation within the session workspace.
+ */
+ write(params: { path: string; content: string }): Promise<unknown>;
+ /**
+ * Executes a sandbox `edit` operation within the session workspace.
+ */
+ edit(params: {
+ path: string;
+ oldText: string;
+ newText: string;
+ }): Promise<unknown>;
+ /**
+ * Executes a sandbox shell command within the session workspace.
+ */
+ bash(params: { command: string; timeoutMs?: number }): Promise<unknown>;
+};
+
+/**
+ * Low-level sandbox runtime contract backed by a concrete provider.
+ * Implementations own sandbox creation and return session-bound execution
+ * handles for isolated workspaces.
+ */
+export type SandboxProvider = {
+ /**
+ * Reuses an existing sandbox session when possible or creates a new one,
+ * then returns a session-bound sandbox handle for tool execution.
+ */
+ ensureSession(params: {
+ conversationId: string;
+ sessionId?: string | null;
+ }): Promise<{ sessionId: string; sandbox: SandboxSession }>;
+ /**
+ * Persists session state for later reuse and releases any live runtime
+ * resources associated with the session.
+ */
+ suspendSession?(params: { sessionId: string }): Promise<void> | void;
+ /**
+ * Permanently tears down the backing runtime session without saving state.
+ */
+ terminateSession?(params: { sessionId: string }): Promise<void> | void;
+};
+
+/**
+ * Conversation-scoped sandbox handle exposed to the in-app agent turn logic.
+ * This wraps a provider-backed session so callers only pass per-operation
+ * inputs instead of raw session identifiers.
+ */
+export type InAppAgentSandbox = {
+ read: (params: { path: string }) => Promise<unknown>;
+ write: (params: { path: string; content: string }) => Promise<unknown>;
+ edit: (params: {
+ path: string;
+ oldText: string;
+ newText: string;
+ }) => Promise<unknown>;
+ bash: (params: { command: string; timeoutMs?: number }) => Promise<unknown>;
+};
diff --git a/web/src/ee/features/in-app-agent/server/tools.ts b/web/src/ee/features/in-app-agent/server/tools.ts
index 6085c9afe9..83599ae2c9 100644
--- a/web/src/ee/features/in-app-agent/server/tools.ts
+++ b/web/src/ee/features/in-app-agent/server/tools.ts
@@ -1,4 +1,5 @@
import { createTool } from "@mastra/core/tools";
+import type { InAppAgentSandbox } from "@/src/ee/features/in-app-agent/server/sandbox";
import type { ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";
import { hasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { assertUnreachable } from "@/src/utils/types";
@@ -323,6 +324,13 @@ export const IN_APP_AGENT_AUTO_APPROVED_EXTERNAL_TOOL_NAMES = new Set([
IN_APP_AGENT_REDIRECT_TOOL_NAME,
]);
+export const IN_APP_AGENT_SANDBOX_TOOL_NAMES = new Set([
+ "read",
+ "write",
+ "edit",
+ "bash",
+]);
+
// Tools in this set can run without a human-in-the-loop approval prompt. Every
// other MCP tool is still exposed to the model, but Mastra suspends execution
// until the user explicitly approves the exact call.
@@ -331,6 +339,7 @@ export const IN_APP_AGENT_AUTO_APPROVED_TOOL_NAMES = new Set([
.filter(([, policy]) => policy.approval === "auto")
.map(([toolName]) => `langfuse_${toolName}`),
...IN_APP_AGENT_AUTO_APPROVED_EXTERNAL_TOOL_NAMES,
+ ...IN_APP_AGENT_SANDBOX_TOOL_NAMES,
]);
export function isMcpToolName(input: string): input is McpToolName {
@@ -404,6 +413,47 @@ function isInAppAgentAutoApprovedToolName(toolName: string): boolean {
);
}
+export function createSandboxTools(sandbox: InAppAgentSandbox) {
+ return {
+ read: createTool({
+ id: "read",
+ description: "Read a file.",
+ inputSchema: z.object({ path: z.string().min(1) }),
+ execute: async ({ path }) => sandbox.read({ path }),
+ }),
+ write: createTool({
+ id: "write",
+ description: "Create or overwrite a file.",
+ inputSchema: z.object({
+ path: z.string().min(1),
+ content: z.string(),
+ }),
+ execute: async ({ path, content }) => sandbox.write({ path, content }),
+ }),
+ edit: createTool({
+ id: "edit",
+ description: "Replace an exact text span inside a file with new text.",
+ inputSchema: z.object({
+ path: z.string().min(1),
+ oldText: z.string(),
+ newText: z.string(),
+ }),
+ execute: async ({ path, oldText, newText }) =>
+ sandbox.edit({ path, oldText, newText }),
+ }),
+ bash: createTool({
+ id: "bash",
+ description: "Run a shell command.",
+ inputSchema: z.object({
+ command: z.string().min(1),
+ timeoutMs: z.number().int().positive().max(120_000).default(120_000),
+ }),
+ execute: async ({ command, timeoutMs }) =>
+ sandbox.bash({ command, timeoutMs }),
+ }),
+ };
+}
+
const InAppAgentRedirectDestinationSchema = z.enum([
"dashboardWidget",
"dashboards",
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 6ddb882cc1..17a0b278ce 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -499,6 +499,18 @@ export const env = createEnv({
AWS_SECRET_ACCESS_KEY: z.string().optional(),
LANGFUSE_AWS_BEDROCK_REGION: z.string().optional(),
LANGFUSE_IN_APP_AGENT_AWS_PROFILE: z.string().optional(),
+ LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER: z
+ .enum(["dangerous-docker", "lambda-microvm"])
+ .optional(),
+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER: z
+ .string()
+ .optional(),
+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN: z
+ .string()
+ .optional(),
+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION: z
+ .string()
+ .optional(),
},
/**
@@ -562,6 +574,14 @@ export const env = createEnv({
LANGFUSE_AWS_BEDROCK_REGION: process.env.LANGFUSE_AWS_BEDROCK_REGION,
LANGFUSE_IN_APP_AGENT_AWS_PROFILE:
process.env.LANGFUSE_IN_APP_AGENT_AWS_PROFILE,
+ LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER:
+ process.env.LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER,
+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER:
+ process.env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER,
+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN:
+ process.env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN,
+ LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION:
+ process.env.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION,
LANGFUSE_TEAM_SLACK_WEBHOOK: process.env.LANGFUSE_TEAM_SLACK_WEBHOOK,
LANGFUSE_NEW_USER_SIGNUP_WEBHOOK:
process.env.LANGFUSE_NEW_USER_SIGNUP_WEBHOOK,
@@ -915,3 +935,26 @@ export const env = createEnv({
skipValidation: process.env.DOCKER_BUILD === "1",
emptyStringAsUndefined: true, // https://env.t3.gg/docs/customization#treat-empty-strings-as-undefined
});
+
+/**
+ * @param {typeof env} parsed
+ */
+const validateInAppAgentSandboxConfig = (parsed) => {
+ if (parsed.LANGFUSE_IN_APP_AGENT_SANDBOX_PROVIDER !== "lambda-microvm") {
+ return;
+ }
+
+ if (
+ !parsed.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_IMAGE_IDENTIFIER ||
+ !parsed.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_EXECUTION_ROLE_ARN ||
+ !parsed.LANGFUSE_IN_APP_AGENT_SANDBOX_AWS_LAMBDA_MICROVM_REGION
+ ) {
+ throw new Error(
+ "Invalid lambda-microvm sandbox config: image identifier, execution role ARN, and region are required.",
+ );
+ }
+};
+
+if (typeof window === "undefined") {
+ validateInAppAgentSandboxConfig(env);
+}