Examples and guides for using the OpenAI API
Add AWS Lambda MicroVM sandbox examples for Agents API (#3140)
Abdulrahman Alfozan86ff2cc0c4b2
diff --git a/.gitignore b/.gitignoreindex 9f1087d6..4b203094 100644--- a/.gitignore+++ b/.gitignore@@ -154,3 +154,5 @@ examples/coding-agent-workspace# Generated by examples/agents_sdk/agent_improvement_loop.ipynb/examples/agents_sdk/agent_improvement_loop_artifacts/++/examples/agents_api/sandboxes/aws/*/.local/diff --git a/examples/agents_api/sandboxes/README.md b/examples/agents_api/sandboxes/README.mdindex 6c22881d..8f2349d6 100644--- a/examples/agents_api/sandboxes/README.md+++ b/examples/agents_api/sandboxes/README.md@@ -6,7 +6,7 @@ OpenAI's cloud and connect the sandbox through `codex exec-server`.| Mode | Your application | Sandbox provisioning || --- | --- | --- || Application-managed | Run the provider's `application_managed/main.py`. | Your application starts and stops compute directly; no webhook handler. |-| [Webhook-managed](webhook_managed.md) | Run the provider's `webhook_managed/client.py`. It calls only the Agents API. | A separately deployed handler starts or reconnects compute when OpenAI sends a webhook. |+| [Webhook-managed](webhook_managed.md) | Run the provider's webhook-managed example to send input and follow the turn. | A separately deployed handler starts or reconnects compute when OpenAI sends a webhook. |Choose one provisioning mode per session. Deleting an API session does not stopprovider compute; each example documents cleanup of both.@@ -22,6 +22,7 @@ provider compute; each example documents cleanup of both.| [Docker](docker/README.md) | [Run](docker/application_managed/README.md) | Not included || [E2B](e2b/README.md) | [Run](e2b/application_managed/README.md) | [Deploy](e2b/webhook_managed/README.md) || [Modal](modal/README.md) | [Run](modal/application_managed/README.md) | [Deploy](modal/webhook_managed/README.md) |+| [AWS Lambda MicroVMs](aws/README.md) | [Run](aws/application_managed/README.md) | [Deploy](aws/webhook_managed/README.md) || [OCI](oci/README.md) | [Run](oci/application_managed/README.md) | Not included || [Runloop](runloop/README.md) | [Run](runloop/application_managed/README.md) | [Deploy](runloop/webhook_managed/README.md) || [Vercel](vercel/README.md) | [Run](vercel/application_managed/README.md) | [Deploy](vercel/webhook_managed/README.md) |diff --git a/examples/agents_api/sandboxes/aws/README.md b/examples/agents_api/sandboxes/aws/README.mdnew file mode 100644index 00000000..569b3208--- /dev/null+++ b/examples/agents_api/sandboxes/aws/README.md@@ -0,0 +1,137 @@+# AWS Lambda MicroVMs++Use [AWS Lambda MicroVMs](https://docs.aws.amazon.com/lambda/latest/dg/microvms-getting-started.html) to run your agent's tools in your AWS account. OpenAI runs the agent harness; each MicroVM runs `codex exec-server` and holds the session's workspace files.++Build an image, then run the [application-managed](application_managed/README.md) or [webhook-managed](webhook_managed/README.md) example. Both use the same image and credentials.++Each example asks the agent to write `hello.txt`, then downloads and checks it. Use `--suspend-resume` to verify the file survives between turns.++## How it works++In the webhook path, your application creates a self-hosted session and sends input. When the session needs an executor, OpenAI sends `agent.session.action_required` with an `environment_connection` action. [API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html) delivers the webhook to a launcher [Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html), which verifies the signature, checks the current session, and launches a MicroVM.++The MicroVM's `/run` hook fetches an environment key from [Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) and starts the executor. The executor connects outbound to OpenAI, and the waiting input proceeds. Your application follows the session stream, downloads output files, and terminates the MicroVM after the final turn.++++## Before you begin++- **AWS access:** An account with Lambda MicroVMs access and an AWS CLI that includes `lambda-microvms`. The build script creates the S3 artifact bucket, IAM image build role, and CloudWatch log group. Your AWS credentials need permission to create these resources and build and run MicroVMs. See AWS's [getting started guide](https://docs.aws.amazon.com/lambda/latest/dg/microvms-getting-started.html) for background.+- **Application key:** Use `OPENAI_API_KEY` to create sessions and submit input.+- **Environment key (`OPENAI_EXECUTOR_API_KEY`):** Create a separate [environment key](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication) with matching organization, project, and user or service-account ownership. Store its value in Secrets Manager, for example in a secret named `codex/agents-api/executor`. The `/run` hook passes it to Codex as `CODEX_API_KEY`.+- **MicroVM execution role:** Allow this role to read only the environment-key secret. Add decryption permission if you use a customer-managed KMS key. See AWS [security and permissions](https://docs.aws.amazon.com/lambda/latest/dg/microvms-security.html) for role setup.++Keep the application key and webhook signing secret outside the MicroVM. A webhook launcher needs these credentials in its own Secrets Manager secret; the VM receives only the ARN of its environment-key secret.++## Prepare a reusable image++Build an image with the [Codex CLI](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#prepare-your-environment), tool dependencies, a working directory such as `/workspace`, and an HTTP server for the AWS lifecycle hooks.++| Hook | Behavior |+| --------------------------------------- | ----------------------------------------------------------------------------------------------------- |+| `/aws/lambda-microvms/runtime/v1/ready` | Return HTTP 200 when the server is ready for AWS to snapshot. Leave the executor disconnected. |+| `/aws/lambda-microvms/runtime/v1/run` | Read the session connection values and secret ARN, fetch the environment key, and start the executor. |+| `/aws/lambda-microvms/runtime/v1/validate` | Check that Codex runs and the workspace is writable. |+| `/aws/lambda-microvms/runtime/v1/suspend` | Stop the executor and flush writes before AWS snapshots the VM. |+| `/aws/lambda-microvms/runtime/v1/resume` | Fetch the key again and restart the executor for the same environment. |+| `/aws/lambda-microvms/runtime/v1/terminate` | Stop the executor and flush writes before termination. |++Package the `Dockerfile` and hook server in an S3 artifact, then build `codex-executor` with 8 GB memory (4 vCPU baseline). The build script enables these hooks on port 8080. Keep session IDs, credentials, and live executor connections out of the reusable image snapshot. See AWS [MicroVM images](https://docs.aws.amazon.com/lambda/latest/dg/microvms-images.html) for build and hook configuration.++At launch, your application or launcher serializes these values as JSON in `runHookPayload`:++| Value | Purpose |+| -------------------------------- | ------------------------------------------------------------------ |+| `session.environment.id` | Identifies the environment the executor connects to. |+| `session.environment.remote_url` | Provides the executor's OpenAI connection URL. |+| Environment-key secret ARN | Lets the hook retrieve the key using the MicroVM's execution role. |++The `/run` hook parses the payload, retrieves the key, sets `CODEX_API_KEY`, and [starts the executor](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#start-the-executor). Return once the process starts to avoid a hook timeout.++Allow the executor's required [outbound connections](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#network-access) and access to Secrets Manager. Configure an AWS egress connector for private resources or network restrictions.++Use `PUT /upload/<path>` to write a file under `/workspace` and `GET /download/<path>` to read it. Uploads accept raw bytes up to 64 MiB. The `upload_file` and `download_file` helpers obtain an AWS authentication token for port 8080. Paths outside the workspace are rejected.++## Launch the MicroVM++Keep the session event stream open until the turn finishes.++### Application-managed provisioning++1. [Create a self-hosted session](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#create-or-reuse-a-session) whose working directory matches the image, then [open its event stream](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#consume-a-stream).+2. Call AWS [RunMicrovm](https://docs.aws.amazon.com/lambda/latest/microvm-api/API_RunMicrovm.html) with the image ARN and version, execution role, network connectors, and `runHookPayload`. Save the returned `microvmId` alongside the session ID.+3. [Send input](https://developers.openai.com/api/docs/guides/agents-api/sessions#send-input) and follow the turn's result.+4. Retrieve output files and [stop the MicroVM](#stop-the-microvm).++### Webhook-managed provisioning++Your application creates the session, opens its stream, and submits input. An OpenAI webhook reaches the launcher Lambda through API Gateway.++1. Deploy a `POST /webhook` route that invokes the launcher. Give the launcher permission to read its credentials, inspect, launch, resume, and terminate MicroVMs from the selected image, pass the MicroVM execution role, and use the configured network connectors.+2. [Register the endpoint](https://developers.openai.com/api/docs/guides/agents-api/sessions/webhooks#set-up-a-webhook) for `agent.session.action_required` and `agent.session.failed`. Store the endpoint's signing secret with the launcher's application key.+3. Verify the webhook signature against the raw request body before accessing sessions or launching compute. Retrieve the current session and confirm the handler owns it, for example by matching a dedicated saved agent.+4. If `environment_connection` is still pending, resume the session's recorded VM if suspended. Otherwise, launch a VM if none is recorded and save its ID; if saving fails, terminate it. If the executor connects before the [connection timeout](https://developers.openai.com/api/docs/guides/agents-api/sessions/webhooks#environment-connection-events), the waiting input proceeds without resubmission.+5. If the session is still `failed`, terminate its recorded MicroVM. Ignore deleted sessions, resolved actions, and events owned by another handler.++The example saves the VM ID in session metadata. Concurrent webhook deliveries before that ID is recorded can still launch extra VMs.++## Stop the MicroVM++On the session stream, wait for `agent.session.turn.completed`, `agent.session.turn.failed`, or `agent.session.turn.cancelled` for the main agent (`event.turn.subagent_id` is `null`). Subagents share the MicroVM; their terminal events must not trigger cleanup. Retrieve needed files, call `TerminateMicrovm`, and verify the VM reaches `TERMINATED`. Run cleanup on application errors too.++Turn outcomes are stream events, not webhook subscriptions. The `agent.session.failed` webhook handles session failures, but doesn't cover every failed turn. Don't terminate on `agent.session.idle` alone: it can arrive before waiting input starts.++Set AWS limits in case cleanup fails:++| Setting | Guidance |+| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- |+| `maximumDurationInSeconds` | Set a ceiling for the workload, such as `900` for a 15-minute test. It can interrupt active work. |+| `maxIdleDurationSeconds` | Cover the expected workload. AWS measures inbound traffic; the executor's outbound connection doesn't reset this timer. |+| `suspendedDurationSeconds` / `autoResumeEnabled` | The examples use `0` / `false` by default and `300` / `false` with `--suspend-resume`. |++See AWS [Running and using MicroVMs](https://docs.aws.amazon.com/lambda/latest/dg/microvms-launching.html) for lifetime and idle controls.++[Delete the session](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage#delete-a-session) separately; this doesn't stop the VM or send a deletion webhook. Keep the image and environment-key secret for reuse. See [Sandbox lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle) for handling follow-up turns.++## Suspend and resume between turns++Use AWS [suspend and resume](https://docs.aws.amazon.com/lambda/latest/dg/microvms-launching.html#microvms-launching-suspend-resume) to preserve memory and disk between turns. Set a nonzero `suspendedDurationSeconds`; snapshot storage charges apply while suspended. `maximumDurationInSeconds` limits total running and suspended time to eight hours.++With `--suspend-resume`, the application suspends the VM after the first turn. The application-managed example resumes it directly; the webhook-managed example sends another input so the webhook resumes it. The next turn reads the existing `hello.txt`, and the application checks that its contents survived.++The hooks stop Codex before suspension and reload its key on resume. Suspend only after tools and subagents finish. Automatic resume requires inbound VM traffic; Agents API input alone doesn't wake it.++## Verify and monitor++Run either example and check the downloaded `hello.txt`, VM state (`TERMINATED`), and session deletion (HTTP 404).++Set `MICROVM_IMAGE_ARN` to your image ARN and use your deployment's AWS region:++```bash+aws logs tail /aws/lambda/codex-agents-api-webhook --since 10m++aws lambda-microvms list-microvms \+ --image-identifier "$MICROVM_IMAGE_ARN" \+ --query 'items[].{id:microvmId,state:state}' --output table+```++Log session and MicroVM IDs together to trace a run. Keep credentials and raw webhook bodies out of logs.++## Troubleshooting++| Symptom | What to check |+| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |+| Webhook signature is rejected | Use the endpoint's signing secret and verify the unmodified request body. |+| No MicroVM launches | Check the webhook subscription, session ownership filter, pending `environment_connection` action, and launcher's IAM permissions. |+| Image build fails | Check the S3 artifact, image build role, and `/ready` hook response. |+| `/run` fails or times out | Check secret access and executor startup. Return after starting the process, not after the turn. |+| Executor can't connect | Check the environment ID, remote URL, key ownership, and outbound network access. |+| VM stops during a turn | Check maximum lifetime and idle policy; outbound executor traffic doesn't count as inbound activity. |++For connection failures, inspect `agent.session.environment.failed` and the executor logs. See [Self-hosted sandboxes](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted) for the shared executor contract.++## References++- [AWS Lambda MicroVMs guide for Agents API](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/aws)+- [Running and using MicroVMs](https://docs.aws.amazon.com/lambda/latest/dg/microvms-launching.html)+- [Security and permissions](https://docs.aws.amazon.com/lambda/latest/dg/microvms-security.html)diff --git a/examples/agents_api/sandboxes/aws/application_managed/Dockerfile b/examples/agents_api/sandboxes/aws/application_managed/Dockerfilenew file mode 100644index 00000000..125b5df3--- /dev/null+++ b/examples/agents_api/sandboxes/aws/application_managed/Dockerfile@@ -0,0 +1,16 @@+FROM python:3.14-slim++RUN apt-get update \+ && apt-get install --yes --no-install-recommends ca-certificates git nodejs npm ripgrep \+ && npm install --global @openai/codex@alpha \+ && rm -rf /var/lib/apt/lists/*+RUN pip install --no-cache-dir 'boto3>=1.43.34' 'flask>=3.1'++ENV CODEX_HOME=/codex-home+RUN mkdir -p /workspace /codex-home+WORKDIR /workspace++# Start Codex from the run hook, once the session is known.+COPY sandbox_server.py /opt/sandbox_server.py+EXPOSE 8080+CMD ["python", "/opt/sandbox_server.py"]diff --git a/examples/agents_api/sandboxes/aws/application_managed/README.md b/examples/agents_api/sandboxes/aws/application_managed/README.mdnew file mode 100644index 00000000..040bd501--- /dev/null+++ b/examples/agents_api/sandboxes/aws/application_managed/README.md@@ -0,0 +1,117 @@+# Application-managed AWS Lambda MicroVM++[main.py](main.py) asks the agent to write `hello.txt` in a MicroVM, then downloads+and checks it. It terminates the VM and deletes the session.+See the [AWS guide](../README.md) for the architecture.++## Setup++You need Python 3.11+, `uv`, AWS credentials with Lambda MicroVMs access, and an+`OPENAI_API_KEY` with Agents API access. Run these commands from the repository root:++```bash+export AWS_PROFILE=your-profile+export AWS_REGION=us-west-2+export EXAMPLE_DIR=examples/agents_api/sandboxes/aws/application_managed+aws sts get-caller-identity --region "$AWS_REGION"+```++Set `OPENAI_API_KEY` for the local application. Store a separate environment key+(`OPENAI_EXECUTOR_API_KEY`) in Secrets Manager as `codex/agents-api/executor`.+The two keys must share the same organization, project, and user or service-account+owner. Use a plaintext SecretString or JSON with an `OPENAI_EXECUTOR_API_KEY` field,+and the default Secrets Manager encryption key.++### 1. Create the runtime role++```bash+export EXECUTOR_SECRET_ARN="$(aws secretsmanager describe-secret \+ --secret-id codex/agents-api/executor --region "$AWS_REGION" \+ --query ARN --output text)"+uv run "$EXAMPLE_DIR/configure_execution_role.py" \+ --executor-secret-arn "$EXECUTOR_SECRET_ARN"+```++Run once to create `codex-agents-api-executor` with read access to that secret.+The role and secret ARNs are saved in `.local/execution-role.json`.+A customer-managed KMS key also requires `kms:Decrypt` permission.++### 2. Build the image++```bash+uv run "$EXAMPLE_DIR/build_image.py" --name codex-executor+```++The script creates an S3 source bucket, build role, and CloudWatch log group,+then uploads the [Dockerfile](Dockerfile) and [sandbox_server.py](sandbox_server.py).+AWS builds the image with 8 GB memory (4 vCPU baseline). The script saves its ARN+and version in `.local/image.json`.++### 3. Run++```bash+uv run "$EXAMPLE_DIR/main.py"+cat "$EXAMPLE_DIR/.local/hello.txt"+```++To reuse the VM across two turns:++```bash+uv run "$EXAMPLE_DIR/main.py" --suspend-resume+```++The script suspends and resumes the VM after the first turn. The next turn reads+the existing `hello.txt`, and the script downloads it again to verify its contents.++Use `--image-state`, `--execution-state`, or `--output` to change the local paths.+State and output files are saved in `.local/`, which Git ignores.++## Runtime hooks++[sandbox_server.py](sandbox_server.py) handles AWS's lifecycle hooks. The ready+hook lets AWS snapshot the idle server. At launch, the run hook receives the+session's environment ID, remote URL, and secret ARN. It reads the key through+the VM's IAM role and starts Codex with `CODEX_API_KEY` in its environment.+The validate hook checks Codex and workspace access. Suspend and terminate stop+the executor and flush writes. Resume reloads the key and reconnects.++## Transfer files++Both routes use AWS's authenticated ingress proxy and paths relative to `/workspace`:++- `PUT /upload/<path>` writes raw bytes to a file and creates missing directories.+ The limit is 64 MiB. An incomplete upload leaves the existing file unchanged.+- `GET /download/<path>` downloads a file.++Directories and paths or symlinks outside `/workspace` return 404.+The shared helpers handle AWS authentication and URL encoding:++```python+from pathlib import Path+from common import upload_file, download_file++await upload_file(microvms, vm_id, Path("input.csv"), "data/input.csv")+await download_file(microvms, vm_id, "reports/result.csv", Path("result.csv"))+```++The executor connects outbound to OpenAI through AWS's internet egress connector.+Use a different connector for private networking.++## Reuse and cleanup++The image, roles, source bucket, log group, and secret stay in AWS for reuse.+Rebuild after changing the Dockerfile or server:++```bash+uv run "$EXAMPLE_DIR/build_image.py" --rebuild+```++Cleanup runs on success or error. Each VM has a 15-minute maximum lifetime and a+10-minute inbound idle limit; outbound executor traffic doesn't reset the idle timer.+The suspend/resume example allows up to five minutes suspended. Rebuild an older+image before using this option. Only suspend between turns, after tools finish.++To remove the example, terminate remaining VMs and delete the image, source bucket,+log group, and roles listed in the state files. Delete the secret when no other+workloads use it. The [webhook-managed example](../webhook_managed/README.md)+shares the image and runtime role.diff --git a/examples/agents_api/sandboxes/aws/application_managed/build_image.py b/examples/agents_api/sandboxes/aws/application_managed/build_image.pynew file mode 100644index 00000000..04a885c6--- /dev/null+++ b/examples/agents_api/sandboxes/aws/application_managed/build_image.py@@ -0,0 +1,196 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["boto3>=1.43.34"]+# ///+"""Build a Codex MicroVM image in AWS."""++import argparse+import json+import os+import time+import uuid+import zipfile+from pathlib import Path++import boto3++ROOT = Path(__file__).resolve().parent+++def build(args):+ aws = boto3.Session(profile_name=args.profile, region_name=args.region)+ sts = aws.client("sts")+ s3 = aws.client("s3")+ logs = aws.client("logs")+ iam = aws.client("iam")+ microvms = aws.client("lambda-microvms")+ account = sts.get_caller_identity()["Account"]+ args.state.parent.mkdir(parents=True, exist_ok=True)+ if args.state.exists():+ state = json.loads(args.state.read_text())+ if state.get("deleted"):+ raise RuntimeError("This image was deleted; use a new --name and --state")+ if (state["account"], state["region"], state["name"]) != (+ account,+ args.region,+ args.name,+ ):+ raise RuntimeError("State belongs to another account, region, or image name")+ else:+ state = {+ "account": account,+ "region": args.region,+ "name": args.name,+ "build_name": f"{args.name}-{uuid.uuid4().hex[:8]}",+ }++ def save():+ args.state.write_text(json.dumps(state, indent=2) + "\n")++ save()+ tags = [{"Key": "Purpose", "Value": "codex-agents-api-example"}]+ bucket = f"{state['build_name']}-{account}"+ if "bucket" not in state:+ config = (+ {}+ if args.region == "us-east-1"+ else {"CreateBucketConfiguration": {"LocationConstraint": args.region}}+ )+ s3.create_bucket(Bucket=bucket, **config)+ state["bucket"] = bucket+ save()+ block = s3.get_public_access_block(Bucket=bucket)+ if not all(block["PublicAccessBlockConfiguration"].values()):+ raise RuntimeError("The build bucket must block all public access")+ s3.put_bucket_tagging(Bucket=bucket, Tagging={"TagSet": tags})++ group = state.get("log_group", f"/aws/lambda-microvms/{args.name}")+ if "log_group" not in state:+ logs.create_log_group(logGroupName=group)+ state["log_group"] = group+ save()+ logs.put_retention_policy(logGroupName=group, retentionInDays=7)+ if "role_arn" not in state:+ trust = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"Service": "lambda.amazonaws.com"},+ "Action": ["sts:AssumeRole", "sts:TagSession"],+ }+ ],+ }+ role = iam.create_role(+ RoleName=state["build_name"],+ AssumeRolePolicyDocument=json.dumps(trust),+ Tags=tags,+ Description="Build the reusable Codex Agents API MicroVM image",+ )+ state["role_name"] = state["build_name"]+ state["role_arn"] = role["Role"]["Arn"]+ save()+ policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": ["s3:GetObject"],+ "Resource": f"arn:aws:s3:::{bucket}/image.zip",+ },+ {+ "Effect": "Allow",+ "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],+ "Resource": f"arn:aws:logs:{args.region}:{account}:log-group:{group}:*",+ },+ ],+ }+ iam.put_role_policy(+ RoleName=state["role_name"],+ PolicyName="codex-image-build",+ PolicyDocument=json.dumps(policy),+ )+ state["role_policy"] = "codex-image-build"+ save()++ if "image_arn" not in state or args.rebuild:+ archive = args.state.parent / "image.zip"+ with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as output:+ for filename in ("Dockerfile", "sandbox_server.py"):+ output.write(ROOT / filename, filename)+ s3.upload_file(str(archive), bucket, "image.zip")+ state["object_key"] = "image.zip"+ save()+ time.sleep(10) # Allow the new IAM role and policy to propagate.+ updating = "image_arn" in state+ identity = (+ {"imageIdentifier": state["image_arn"]}+ if updating+ else {"name": args.name, "tags": {"Purpose": "codex-agents-api-example"}}+ )+ create_image = microvms.update_microvm_image if updating else microvms.create_microvm_image+ image = create_image(+ **identity,+ baseImageArn=f"arn:aws:lambda:{args.region}:aws:microvm-image:al2023-1",+ buildRoleArn=state["role_arn"],+ codeArtifact={"uri": f"s3://{bucket}/image.zip"},+ resources=[{"minimumMemoryInMiB": 8192}],+ egressNetworkConnectors=[+ f"arn:aws:lambda:{args.region}:aws:network-connector:aws-network-connector:INTERNET_EGRESS"+ ],+ hooks={+ "port": 8080,+ "microvmHooks": {+ "run": "ENABLED",+ "runTimeoutInSeconds": 60,+ "suspend": "ENABLED",+ "suspendTimeoutInSeconds": 30,+ "resume": "ENABLED",+ "resumeTimeoutInSeconds": 60,+ "terminate": "ENABLED",+ "terminateTimeoutInSeconds": 30,+ },+ "microvmImageHooks": {+ "ready": "ENABLED",+ "readyTimeoutInSeconds": 60,+ "validate": "ENABLED",+ "validateTimeoutInSeconds": 30,+ },+ },+ )+ state["image_arn"] = image["imageArn"]+ state["pending_image_version"] = image["imageVersion"]+ save()+ print(f"Image: {state['image_arn']}", flush=True)+ print(f"Build resources saved to {args.state}", flush=True)+ for _ in range(120):+ image = microvms.get_microvm_image(+ imageIdentifier=state["image_arn"],+ )+ active = image.get("latestActiveImageVersion")+ pending = state.get("pending_image_version")+ if active and (not pending or active == pending):+ state["image_version"] = active+ state.pop("pending_image_version", None)+ save()+ print(f"Ready: {state['image_arn']} version {state['image_version']}")+ return+ if (pending and image.get("latestFailedImageVersion") == pending) or image["state"] in {+ "CREATION_FAILED",+ "UPDATE_FAILED",+ }:+ raise RuntimeError(f"Image build failed; inspect CloudWatch group {group}")+ time.sleep(10)+ raise TimeoutError(f"Build still pending; rerun with the same --state {args.state}")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--profile", default=os.environ.get("AWS_PROFILE"))+ parser.add_argument("--region", default=os.environ.get("AWS_REGION", "us-west-2"))+ parser.add_argument("--name", default="codex-executor")+ parser.add_argument(+ "--rebuild", action="store_true", help="Build a new version from current source"+ )+ parser.add_argument("--state", type=Path, default=ROOT / ".local" / "image.json")+ build(parser.parse_args())diff --git a/examples/agents_api/sandboxes/aws/application_managed/configure_execution_role.py b/examples/agents_api/sandboxes/aws/application_managed/configure_execution_role.pynew file mode 100644index 00000000..48aea871--- /dev/null+++ b/examples/agents_api/sandboxes/aws/application_managed/configure_execution_role.py@@ -0,0 +1,74 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["boto3>=1.43.34"]+# ///+"""Create an execution role that reads one existing Secrets Manager secret."""++import argparse+import json+import os+from pathlib import Path++import boto3+++def configure(args):+ aws = boto3.Session(profile_name=args.profile, region_name=args.region)+ secrets = aws.client("secretsmanager")+ iam = aws.client("iam")+ # Read the secret ARN without retrieving its value.+ secret = secrets.describe_secret(SecretId=args.executor_secret_arn)+ trust = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"Service": "lambda.amazonaws.com"},+ "Action": ["sts:AssumeRole", "sts:TagSession"],+ }+ ],+ }+ role = iam.create_role(+ RoleName=args.name,+ AssumeRolePolicyDocument=json.dumps(trust),+ Description="Read the Codex executor secret at MicroVM runtime",+ )+ state = {+ "role_arn": role["Role"]["Arn"],+ "role_name": args.name,+ "executor_secret_arn": secret["ARN"],+ "region": args.region,+ }+ args.state.parent.mkdir(parents=True, exist_ok=True)+ args.state.write_text(json.dumps(state, indent=2) + "\n")+ policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "secretsmanager:GetSecretValue",+ "Resource": secret["ARN"],+ }+ ],+ }+ iam.put_role_policy(+ RoleName=args.name,+ PolicyName="read-executor-secret",+ PolicyDocument=json.dumps(policy),+ )+ print(f"Execution role: {state['role_arn']}")+ print(f"Resource metadata saved to {args.state}")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--profile", default=os.environ.get("AWS_PROFILE"))+ parser.add_argument("--region", default=os.environ.get("AWS_REGION", "us-west-2"))+ parser.add_argument("--executor-secret-arn", required=True)+ parser.add_argument("--name", default="codex-agents-api-executor")+ parser.add_argument(+ "--state",+ type=Path,+ default=Path(__file__).with_name(".local") / "execution-role.json",+ )+ configure(parser.parse_args())diff --git a/examples/agents_api/sandboxes/aws/application_managed/main.py b/examples/agents_api/sandboxes/aws/application_managed/main.pynew file mode 100644index 00000000..1eb59cc0--- /dev/null+++ b/examples/agents_api/sandboxes/aws/application_managed/main.py@@ -0,0 +1,79 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["openai>=3.19.0", "boto3>=1.43.34", "httpx[socks]>=0.27"]+# ///+"""Run an Agents API task in an AWS Lambda MicroVM."""++import argparse+import asyncio+import json+import os+import sys+from pathlib import Path++import boto3+from openai import AsyncOpenAI++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT.parent))+from common import (+ GREETING,+ OUTPUT_PATH,+ RESUME_PROMPT,+ delete_session,+ download_file,+ launch_microvm,+ resume_microvm,+ run_turn,+ suspend_environment,+ terminate_microvm,+ verify_output,+)+++async def main(args):+ image = json.loads(args.image_state.read_text())+ execution = json.loads(args.execution_state.read_text())+ aws = boto3.Session(profile_name=args.profile, region_name=image["region"])+ microvms = aws.client("lambda-microvms")+ microvms.get_microvm_image(imageIdentifier=image["image_arn"])+ async with AsyncOpenAI(timeout=60) as client:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+ )+ print(f"Session: {session.id}", flush=True)+ vm_id = None+ try:+ vm = launch_microvm(+ microvms, session.environment, image, execution, suspend_resume=args.suspend_resume+ )+ vm_id = vm["microvmId"]+ print(f"MicroVM: {vm_id}", flush=True)+ await run_turn(client, session.id)+ await download_file(microvms, vm_id, OUTPUT_PATH, args.output)+ verify_output(args.output, GREETING)+ if args.suspend_resume:+ await suspend_environment(client, microvms, session.id, vm_id)+ resume_microvm(microvms, vm_id)+ await run_turn(client, session.id, RESUME_PROMPT)+ await download_file(microvms, vm_id, OUTPUT_PATH, args.output)+ verify_output(args.output, GREETING)+ finally:+ try:+ if vm_id:+ terminate_microvm(microvms, vm_id)+ finally:+ await delete_session(client, session.id)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--profile", default=os.environ.get("AWS_PROFILE"))+ parser.add_argument("--image-state", type=Path, default=ROOT / ".local/image.json")+ parser.add_argument("--execution-state", type=Path, default=ROOT / ".local/execution-role.json")+ parser.add_argument("--output", type=Path, default=ROOT / ".local/hello.txt")+ parser.add_argument(+ "--suspend-resume", action="store_true", help="Run a second turn after suspending the VM"+ )+ asyncio.run(main(parser.parse_args()))diff --git a/examples/agents_api/sandboxes/aws/application_managed/sandbox_server.py b/examples/agents_api/sandboxes/aws/application_managed/sandbox_server.pynew file mode 100644index 00000000..30ebc5d8--- /dev/null+++ b/examples/agents_api/sandboxes/aws/application_managed/sandbox_server.py@@ -0,0 +1,125 @@+"""Handle AWS lifecycle hooks and transfer workspace files."""++import json+import os+import shutil+import signal+import subprocess+import tempfile+from contextlib import suppress+from pathlib import Path++import boto3+from flask import Flask, abort, request, send_file++app = Flask(__name__)+app.config["MAX_CONTENT_LENGTH"] = 32768+WORKSPACE = Path("/workspace")+executor = None+connection = None++[email protected]("/aws/lambda-microvms/runtime/v1/ready")+def ready():+ # Fetch credentials in the run hook, after AWS takes the image snapshot.+ return {"ready": True}++[email protected]("/aws/lambda-microvms/runtime/v1/validate")+def validate():+ subprocess.run(["codex", "--version"], check=True, timeout=10, stdout=subprocess.DEVNULL)+ with tempfile.TemporaryFile(dir="/workspace") as probe:+ probe.write(b"ready")+ return {"validated": True}++[email protected]("/aws/lambda-microvms/runtime/v1/run")[email protected]("/aws/lambda-microvms/runtime/v1/resume")+def start():+ global executor, connection+ if executor is not None and executor.poll() is None:+ return {"executor_running": True}+ try:+ if request.path.endswith("/run"):+ connection = json.loads(request.get_json()["runHookPayload"])+ secret_arn = connection["executor_secret_arn"]+ secrets = boto3.client("secretsmanager", region_name=secret_arn.split(":")[3])+ key = secrets.get_secret_value(SecretId=secret_arn)["SecretString"]+ if key.startswith("{"):+ key = json.loads(key)["OPENAI_EXECUTOR_API_KEY"]+ executor = subprocess.Popen(+ [+ "codex",+ "exec-server",+ "--remote",+ connection["remote_url"],+ "--environment-id",+ connection["environment_id"],+ ],+ cwd="/workspace",+ env={**os.environ, "CODEX_API_KEY": key},+ start_new_session=True,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ return {"executor_running": True}+ except Exception as error:+ # Log the error type only; response bodies can contain credentials.+ app.logger.error("Executor startup failed: %s", type(error).__name__)+ return {"error": "executor startup failed"}, 500++[email protected]("/aws/lambda-microvms/runtime/v1/suspend")[email protected]("/aws/lambda-microvms/runtime/v1/terminate")+def stop():+ global executor+ if executor is not None and executor.poll() is None:+ with suppress(ProcessLookupError):+ os.killpg(executor.pid, signal.SIGTERM)+ try:+ executor.wait(timeout=10)+ except subprocess.TimeoutExpired:+ with suppress(ProcessLookupError):+ os.killpg(executor.pid, signal.SIGKILL)+ executor.wait(timeout=5)+ executor = None+ os.sync()+ return {"executor_running": False}+++def workspace_file(filename):+ path = (WORKSPACE / filename).resolve()+ if not path.is_relative_to(WORKSPACE) or path.is_dir():+ abort(404)+ return path++[email protected]("/download/<path:filename>")+def download(filename):+ path = workspace_file(filename)+ if not path.is_file():+ abort(404)+ return send_file(path, as_attachment=True)++[email protected]("/upload/<path:filename>")+def upload(filename):+ request.max_content_length = 64 * 1024 * 1024+ path = workspace_file(filename)+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ except (FileExistsError, NotADirectoryError):+ abort(409)+ with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as output:+ temporary = Path(output.name)+ try:+ shutil.copyfileobj(request.stream, output)+ output.flush()+ temporary.replace(path)+ finally:+ temporary.unlink(missing_ok=True)+ return "", 204+++if __name__ == "__main__":+ app.run(host="0.0.0.0", port=8080, threaded=False)diff --git a/examples/agents_api/sandboxes/aws/common.py b/examples/agents_api/sandboxes/aws/common.pynew file mode 100644index 00000000..989547a1--- /dev/null+++ b/examples/agents_api/sandboxes/aws/common.py@@ -0,0 +1,163 @@+"""Shared MicroVM and session operations."""++import asyncio+import json+import time+from urllib.parse import quote++import httpx+from openai import APIStatusError, NotFoundError++GREETING = "Hello from AWS Lambda MicroVMs!\n"+OUTPUT_PATH = "hello.txt"+PROMPT = f"Write {GREETING!r} to /workspace/{OUTPUT_PATH}."+RESUME_PROMPT = f"Read /workspace/{OUTPUT_PATH} and tell me what it says."+++def launch_microvm(microvms, environment, image, execution, *, suspend_resume=False):+ region = microvms.meta.region_name+ connector = f"arn:aws:lambda:{region}:aws:network-connector:aws-network-connector"+ return microvms.run_microvm(+ imageIdentifier=image["image_arn"],+ imageVersion=image["image_version"],+ executionRoleArn=execution["role_arn"],+ runHookPayload=json.dumps(+ {+ "environment_id": environment.id,+ "remote_url": environment.remote_url,+ "executor_secret_arn": execution["executor_secret_arn"],+ }+ ),+ maximumDurationInSeconds=900,+ idlePolicy={+ "maxIdleDurationSeconds": 600,+ "suspendedDurationSeconds": 300 if suspend_resume else 0,+ "autoResumeEnabled": False,+ },+ ingressNetworkConnectors=[f"{connector}:ALL_INGRESS"],+ egressNetworkConnectors=[f"{connector}:INTERNET_EGRESS"],+ )+++async def run_turn(client, session_id, prompt=PROMPT):+ async with asyncio.timeout(420):+ async with client.beta.agents.sessions.stream(session_id, input=prompt) as events:+ async for event in events:+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ elif event.type in {+ "agent.session.turn.completed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ if event.turn.subagent_id is not None:+ continue+ if event.type != "agent.session.turn.completed":+ raise RuntimeError(f"Turn failed: {event.type}")+ print(f"\nCompleted turn: {event.turn.id}", flush=True)+ return+ elif event.type in {+ "error",+ "agent.session.failed",+ "agent.session.environment.failed",+ }:+ raise RuntimeError(f"Session failed: {event.type}")+ raise RuntimeError("Stream ended without a completed turn")+++def microvm_http(microvms, vm_id):+ vm = microvms.get_microvm(microvmIdentifier=vm_id)+ token = microvms.create_microvm_auth_token(+ microvmIdentifier=vm_id, expirationInMinutes=5, allowedPorts=[{"port": 8080}]+ )+ endpoint = vm["endpoint"]+ if not endpoint.startswith("https://"):+ endpoint = f"https://{endpoint}"+ return endpoint, {+ "X-aws-proxy-auth": token["authToken"]["X-aws-proxy-auth"],+ "X-aws-proxy-port": "8080",+ }+++async def upload_file(microvms, vm_id, source, workspace_path):+ endpoint, headers = microvm_http(microvms, vm_id)+ async with httpx.AsyncClient(timeout=60) as http:+ result = await http.put(+ f"{endpoint}/upload/{quote(workspace_path, safe='/')}",+ headers={**headers, "Content-Type": "application/octet-stream"},+ content=source.read_bytes(),+ )+ result.raise_for_status()+ print(f"Uploaded: {source} → /workspace/{workspace_path}", flush=True)+++async def download_file(microvms, vm_id, workspace_path, output):+ endpoint, headers = microvm_http(microvms, vm_id)+ async with httpx.AsyncClient(timeout=30) as http:+ result = await http.get(+ f"{endpoint}/download/{quote(workspace_path, safe='/')}",+ headers=headers,+ )+ result.raise_for_status()+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_bytes(result.content)+ print(f"Downloaded: {output}", flush=True)+++def verify_output(output, expected):+ if output.read_text(encoding="utf-8") != expected:+ raise RuntimeError("The sandbox output did not match the expected text")+ print(f"Verified: {output}", flush=True)+++def wait_for_microvm(microvms, vm_id, state):+ # Lambda MicroVMs does not yet provide a Boto3 waiter.+ for _ in range(30):+ current = microvms.get_microvm(microvmIdentifier=vm_id)["state"]+ if current == state:+ print(f"MicroVM {state}: {vm_id}", flush=True)+ return+ if current == "TERMINATED":+ raise RuntimeError(f"MicroVM terminated before reaching {state}: {vm_id}")+ time.sleep(2)+ raise TimeoutError(f"MicroVM did not reach {state}: {vm_id}")+++async def suspend_environment(client, microvms, session_id, vm_id):+ async with asyncio.timeout(90):+ async with await client.beta.agents.sessions.events.stream(session_id) as events:+ microvms.suspend_microvm(microvmIdentifier=vm_id)+ async for event in events:+ if event.type == "agent.session.environment.disconnected":+ break+ else:+ raise RuntimeError("Stream ended before the executor disconnected")+ await asyncio.to_thread(wait_for_microvm, microvms, vm_id, "SUSPENDED")+++def resume_microvm(microvms, vm_id):+ microvms.resume_microvm(microvmIdentifier=vm_id)+ wait_for_microvm(microvms, vm_id, "RUNNING")+++def terminate_microvm(microvms, vm_id):+ microvms.terminate_microvm(microvmIdentifier=vm_id)+ wait_for_microvm(microvms, vm_id, "TERMINATED")+++async def delete_session(client, session_id):+ for attempt in range(10):+ try:+ await client.beta.agents.sessions.delete(session_id)+ break+ except APIStatusError as error:+ if error.status_code != 409 or attempt == 9:+ raise+ await client.beta.agents.sessions.cancel(session_id)+ await asyncio.sleep(2)+ try:+ await client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ print(f"Session deleted (404): {session_id}", flush=True)+ return+ raise RuntimeError(f"Session deletion not confirmed: {session_id}")diff --git a/examples/agents_api/sandboxes/aws/images/aws-microvm-sandboxes.webp b/examples/agents_api/sandboxes/aws/images/aws-microvm-sandboxes.webpnew file mode 100644index 00000000..7f278f29Binary files /dev/null and b/examples/agents_api/sandboxes/aws/images/aws-microvm-sandboxes.webp differdiff --git a/examples/agents_api/sandboxes/aws/webhook_managed/README.md b/examples/agents_api/sandboxes/aws/webhook_managed/README.mdnew file mode 100644index 00000000..e0cee1be--- /dev/null+++ b/examples/agents_api/sandboxes/aws/webhook_managed/README.md@@ -0,0 +1,116 @@+# Webhook-managed AWS Lambda MicroVM++An OpenAI webhook starts a MicroVM through API Gateway and Lambda.+[main.py](main.py) asks the agent to write `hello.txt`, then downloads and checks it.+It terminates the VM and deletes the session. See the [AWS guide](../README.md)+for the architecture.++## Setup++Create the runtime role and image with the+[application-managed setup](../application_managed/README.md).+The deploy script reads its `.local/image.json` and `.local/execution-role.json`.+You also need AWS permissions for Lambda, API Gateway, IAM, and Secrets Manager.+Run these commands from the repository root:++```bash+export AWS_PROFILE=your-profile+export AWS_REGION=us-west-2+export EXAMPLE_DIR=examples/agents_api/sandboxes/aws/webhook_managed+```++Set `OPENAI_API_KEY` to the same application key. Create an agent for this webhook+and set its returned ID:++```bash+uv run "$EXAMPLE_DIR/main.py" --create-agent codex-microvm-webhook-demo+export OPENAI_AGENT_ID=agent_...+```++### 1. Create the controller secret++Create `codex/agents-api/webhook-controller` in Secrets Manager with these JSON fields:++- `OPENAI_API_KEY`: the application key.+- `OPENAI_WEBHOOK_SECRET`: leave empty until the webhook is registered.++Use the default Secrets Manager encryption key.++```bash+export CONTROLLER_SECRET_ARN="$(aws secretsmanager describe-secret \+ --secret-id codex/agents-api/webhook-controller --region "$AWS_REGION" \+ --query ARN --output text)"+```++### 2. Deploy and register++```bash+uv run "$EXAMPLE_DIR/deploy.py" \+ --agent-id "$OPENAI_AGENT_ID" \+ --controller-secret-arn "$CONTROLLER_SECRET_ARN"+```++[deploy.py](deploy.py) creates the Lambda and API Gateway's `POST /webhook` route.+It saves resource IDs in `.local/deployment.json`. Rerun it to deploy code changes+or use a new image version.++In your OpenAI project's **Settings → Webhooks**, register the printed URL for+`agent.session.action_required` and `agent.session.failed`. Copy the signing secret+into `OPENAI_WEBHOOK_SECRET` in the controller secret, preserving `OPENAI_API_KEY`.++### 3. Run++```bash+uv run "$EXAMPLE_DIR/main.py"+cat "$EXAMPLE_DIR/.local/hello.txt"+```++[handler.py](handler.py) verifies the webhook signature and checks that the session+belongs to the configured agent and still needs an executor. It launches the VM+and saves its ID in session metadata for the client to read.++The client needs AWS permission to read VM details, create an authentication token, and+terminate the VM.++To test webhook-driven resume, rebuild the image, redeploy the handler, then run:++```bash+uv run "$EXAMPLE_DIR/main.py" --suspend-resume+```++The client suspends the VM after the first turn, then sends another input.+The webhook resumes the same VM. The agent reads the existing `hello.txt`, and+the client downloads it again to verify its contents.++The client also needs `lambda:SuspendMicrovm`. The deployment script grants the+launcher `lambda:GetMicrovm` and `lambda:ResumeMicrovm`.++## Lifetime and retries++The client stops the VM after the final turn. Subagent events do not trigger+cleanup. The handler also stops the VM on+`agent.session.failed` after checking the current session state.++Each VM has a 15-minute lifetime limit. With `--suspend-resume`, it can remain+suspended for five minutes. Only suspend between turns, after tools finish.+If the recorded VM expires, start a new session. Webhook retries before a VM ID+is recorded can still launch extra VMs.++## Monitoring and cleanup++Set `MICROVM_IMAGE_ARN` to the `image_arn` in the shared `.local/image.json`.++```bash+aws logs tail /aws/lambda/codex-agents-api-webhook --since 10m --region "$AWS_REGION"+aws lambda-microvms list-microvms --image-identifier "$MICROVM_IMAGE_ARN" \+ --region "$AWS_REGION" --query 'items[].{id:microvmId,state:state}' --output table+```++HTTP 400 means the signature is invalid; 503 means the signing secret is missing.+For HTTP 500, check the error type in CloudWatch and the handler's IAM permissions.++To remove the deployment, delete the OpenAI webhook and stop new runs first.+Terminate remaining VMs, then remove the API Gateway API, Lambda, role, and log+group listed in `.local/deployment.json`. Delete the agent and controller secret+when no longer used. The image and executor secret are shared with the+application-managed example.diff --git a/examples/agents_api/sandboxes/aws/webhook_managed/deploy.py b/examples/agents_api/sandboxes/aws/webhook_managed/deploy.pynew file mode 100644index 00000000..a8c4364d--- /dev/null+++ b/examples/agents_api/sandboxes/aws/webhook_managed/deploy.py@@ -0,0 +1,245 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["boto3>=1.43.34"]+# ///+"""Deploy the webhook handler to Lambda and API Gateway."""++import argparse+import json+import os+import shutil+import subprocess+import time+import zipfile+from pathlib import Path++import boto3++ROOT = Path(__file__).resolve().parent+SHARED = ROOT.parent / "application_managed"+++def deploy(args):+ aws = boto3.Session(profile_name=args.profile, region_name=args.region)+ sts = aws.client("sts")+ secrets = aws.client("secretsmanager")+ logs = aws.client("logs")+ iam = aws.client("iam")+ lambda_client = aws.client("lambda")+ gateway = aws.client("apigatewayv2")+ image = json.loads(args.image_state.read_text())+ execution = json.loads(args.execution_state.read_text())+ account = sts.get_caller_identity()["Account"]+ if (image["account"], image["region"]) != (account, args.region):+ raise ValueError("Image state belongs to a different account or region")+ secret = secrets.describe_secret(SecretId=args.controller_secret_arn)+ args.state.parent.mkdir(parents=True, exist_ok=True)+ state = json.loads(args.state.read_text()) if args.state.exists() else {}+ if state and (state["account"], state["region"], state["function_name"]) != (+ account,+ args.region,+ args.name,+ ):+ raise ValueError("Deployment state belongs to a different target")+ state.update(+ account=account,+ region=args.region,+ profile=args.profile,+ function_name=args.name,+ agent_id=args.agent_id,+ controller_secret_arn=secret["ARN"],+ )++ def save():+ args.state.write_text(json.dumps(state, indent=2) + "\n")++ save()+ group = f"/aws/lambda/{args.name}"+ if "log_group" not in state:+ logs.create_log_group(logGroupName=group)+ state["log_group"] = group+ save()+ logs.put_retention_policy(logGroupName=group, retentionInDays=7)+ if "role_arn" not in state:+ trust = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": {"Service": "lambda.amazonaws.com"},+ "Action": "sts:AssumeRole",+ }+ ],+ }+ role = iam.create_role(+ RoleName=args.name,+ AssumeRolePolicyDocument=json.dumps(trust),+ )+ state["role_arn"] = role["Role"]["Arn"]+ save()+ policy = {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": "secretsmanager:GetSecretValue",+ "Resource": secret["ARN"],+ },+ {+ "Effect": "Allow",+ "Action": "iam:PassRole",+ "Resource": execution["role_arn"],+ },+ {+ "Effect": "Allow",+ "Action": [+ "lambda:RunMicrovm",+ "lambda:GetMicrovm",+ "lambda:ResumeMicrovm",+ "lambda:TerminateMicrovm",+ ],+ "Resource": image["image_arn"],+ },+ {+ "Effect": "Allow",+ "Action": "lambda:PassNetworkConnector",+ "Resource": [+ f"arn:aws:lambda:{args.region}:aws:network-connector:aws-network-connector:ALL_INGRESS",+ f"arn:aws:lambda:{args.region}:aws:network-connector:aws-network-connector:INTERNET_EGRESS",+ ],+ },+ {+ "Effect": "Allow",+ "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],+ "Resource": f"arn:aws:logs:{args.region}:{account}:log-group:{group}:*",+ },+ ],+ }+ iam.put_role_policy(+ RoleName=args.name,+ PolicyName="webhook-controller",+ PolicyDocument=json.dumps(policy),+ )+ package = args.state.parent / "package"+ if package.exists():+ shutil.rmtree(package)+ subprocess.run(+ [+ "uv",+ "pip",+ "install",+ "--target",+ str(package),+ "--python-version",+ "3.13",+ "--python-platform",+ "x86_64-manylinux2014",+ "--only-binary",+ ":all:",+ "-r",+ str(ROOT / "requirements.txt"),+ ],+ check=True,+ )+ archive = args.state.parent / "function.zip"+ with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as output:+ output.write(ROOT / "handler.py", "handler.py")+ output.write(ROOT.parent / "common.py", "common.py")+ for file in package.rglob("*"):+ if file.is_file() and "__pycache__" not in file.parts:+ output.write(file, file.relative_to(package))+ env = {+ "Variables": {+ "OPENAI_AGENT_ID": args.agent_id,+ "CONTROLLER_SECRET_ARN": secret["ARN"],+ "MICROVM_IMAGE_ARN": image["image_arn"],+ "MICROVM_IMAGE_VERSION": image["image_version"],+ "MICROVM_EXECUTION_ROLE_ARN": execution["role_arn"],+ "EXECUTOR_SECRET_ARN": execution["executor_secret_arn"],+ }+ }+ if state.get("function_arn"):+ function = lambda_client.update_function_code(+ FunctionName=args.name, ZipFile=archive.read_bytes()+ )+ lambda_client.get_waiter("function_updated_v2").wait(FunctionName=args.name)+ lambda_client.update_function_configuration(FunctionName=args.name, Environment=env)+ lambda_client.get_waiter("function_updated_v2").wait(FunctionName=args.name)+ else:+ time.sleep(10) # Allow the new IAM role and policy to propagate.+ function = lambda_client.create_function(+ FunctionName=args.name,+ Runtime="python3.13",+ Handler="handler.lambda_handler",+ Role=state["role_arn"],+ Timeout=60,+ MemorySize=256,+ Code={"ZipFile": archive.read_bytes()},+ Environment=env,+ )+ lambda_client.get_waiter("function_active_v2").wait(FunctionName=args.name)+ state["function_arn"] = function["FunctionArn"]+ save()+ if "api_id" not in state:+ api = gateway.create_api(+ Name=args.name,+ ProtocolType="HTTP",+ )+ state["api_id"] = api["ApiId"]+ state["url"] = f"{api['ApiEndpoint']}/webhook"+ save()+ if "integration_id" not in state:+ integration = gateway.create_integration(+ ApiId=state["api_id"],+ IntegrationType="AWS_PROXY",+ IntegrationUri=state["function_arn"],+ PayloadFormatVersion="2.0",+ TimeoutInMillis=30000,+ )+ state["integration_id"] = integration["IntegrationId"]+ save()+ if "route_id" not in state:+ route = gateway.create_route(+ ApiId=state["api_id"],+ RouteKey="POST /webhook",+ Target=f"integrations/{state['integration_id']}",+ )+ state["route_id"] = route["RouteId"]+ save()+ if "invoke_permission" not in state:+ lambda_client.add_permission(+ FunctionName=args.name,+ StatementId="webhook-api-gateway",+ Action="lambda:InvokeFunction",+ Principal="apigateway.amazonaws.com",+ SourceArn=f"arn:aws:execute-api:{args.region}:{account}:{state['api_id']}/*/POST/webhook",+ SourceAccount=account,+ )+ state["invoke_permission"] = True+ save()+ if "stage" not in state:+ gateway.create_stage(+ ApiId=state["api_id"],+ StageName="$default",+ AutoDeploy=True,+ DefaultRouteSettings={"ThrottlingBurstLimit": 5, "ThrottlingRateLimit": 2},+ )+ state["stage"] = "$default"+ save()+ print(f"Webhook URL: {state['url']}")+ print(f"Deployment metadata: {args.state}")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--profile", default=os.environ.get("AWS_PROFILE"))+ parser.add_argument("--region", default=os.environ.get("AWS_REGION", "us-west-2"))+ parser.add_argument("--name", default="codex-agents-api-webhook")+ parser.add_argument("--agent-id", required=True)+ parser.add_argument("--controller-secret-arn", required=True)+ parser.add_argument("--image-state", type=Path, default=SHARED / ".local/image.json")+ parser.add_argument(+ "--execution-state", type=Path, default=SHARED / ".local/execution-role.json"+ )+ parser.add_argument("--state", type=Path, default=ROOT / ".local/deployment.json")+ deploy(parser.parse_args())diff --git a/examples/agents_api/sandboxes/aws/webhook_managed/handler.py b/examples/agents_api/sandboxes/aws/webhook_managed/handler.pynew file mode 100644index 00000000..9a473dd3--- /dev/null+++ b/examples/agents_api/sandboxes/aws/webhook_managed/handler.py@@ -0,0 +1,107 @@+"""Handle OpenAI webhooks that start, resume, or stop a MicroVM."""++import base64+import json+import os++import boto3+from common import launch_microvm+from openai import InvalidWebhookSignatureError, NotFoundError, OpenAI++VM_METADATA_KEY = "aws_microvm_id"+++def response(status, message):+ return {"statusCode": status, "body": json.dumps({"message": message})}+++def reconcile(client, microvms, session_id):+ try:+ session = client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ return "session deleted"+ if session.agent.id != os.environ["OPENAI_AGENT_ID"]:+ return "different agent"+ if session.environment.type != "self_hosted":+ return "different environment"+ metadata = session.metadata or {}+ if session.status == "failed":+ if metadata.get(VM_METADATA_KEY):+ microvms.terminate_microvm(microvmIdentifier=metadata[VM_METADATA_KEY])+ return "failed session cleanup"+ if not any(a.type == "environment_connection" for a in session.required_actions):+ return "connection no longer required"++ if vm_id := metadata.get(VM_METADATA_KEY):+ vm = microvms.get_microvm(microvmIdentifier=vm_id)+ if vm["state"] == "SUSPENDED":+ microvms.resume_microvm(microvmIdentifier=vm_id)+ print(json.dumps({"action": "resumed", "session_id": session_id, "microvm_id": vm_id}))+ return "resumed"+ if vm["state"] in {"PENDING", "RUNNING"}:+ return "existing VM connecting"+ raise RuntimeError("Recorded VM cannot resume; create a new session")++ vm = launch_microvm(+ microvms,+ session.environment,+ {+ "image_arn": os.environ["MICROVM_IMAGE_ARN"],+ "image_version": os.environ["MICROVM_IMAGE_VERSION"],+ },+ {+ "role_arn": os.environ["MICROVM_EXECUTION_ROLE_ARN"],+ "executor_secret_arn": os.environ["EXECUTOR_SECRET_ARN"],+ },+ suspend_resume=metadata.get("aws_suspend_resume") == "true",+ )+ vm_id = vm["microvmId"]+ # The client reads this ID to download output and terminate the VM.+ try:+ client.beta.agents.sessions.update(+ session_id, metadata={**metadata, VM_METADATA_KEY: vm_id}+ )+ except Exception:+ microvms.terminate_microvm(microvmIdentifier=vm_id)+ raise+ print(json.dumps({"action": "started", "session_id": session_id, "microvm_id": vm_id}))+ return "started"+++def lambda_handler(event, _context):+ if event.get("requestContext", {}).get("http", {}).get("method") != "POST":+ return response(405, "POST required")+ raw = event.get("body") or ""+ if event.get("isBase64Encoded"):+ raw = base64.b64decode(raw).decode("utf-8")+ secrets = boto3.client("secretsmanager").get_secret_value(+ SecretId=os.environ["CONTROLLER_SECRET_ARN"]+ )+ settings = json.loads(secrets["SecretString"])+ if not settings.get("OPENAI_WEBHOOK_SECRET"):+ return response(503, "webhook signing secret not configured")+ with OpenAI(+ api_key=settings["OPENAI_API_KEY"],+ webhook_secret=settings["OPENAI_WEBHOOK_SECRET"],+ timeout=20,+ max_retries=0,+ ) as client:+ try:+ client.webhooks.verify_signature(payload=raw, headers=event.get("headers", {}))+ except (InvalidWebhookSignatureError, ValueError):+ return response(400, "invalid signature")+ try:+ delivery = json.loads(raw)+ relevant = delivery["type"] == "agent.session.failed" or (+ delivery["type"] == "agent.session.action_required"+ and delivery["data"]["required_action"]["type"] == "environment_connection"+ )+ if not relevant:+ return response(200, "ignored")+ message = reconcile(client, boto3.client("lambda-microvms"), delivery["data"]["id"])+ print(json.dumps({"event_id": delivery.get("id"), "outcome": message}))+ return response(200, message)+ except Exception as error:+ # Log the error type only; response bodies can contain credentials.+ print(json.dumps({"error_type": type(error).__name__}))+ return response(500, "provisioning failed")diff --git a/examples/agents_api/sandboxes/aws/webhook_managed/main.py b/examples/agents_api/sandboxes/aws/webhook_managed/main.pynew file mode 100644index 00000000..ab35bbd9--- /dev/null+++ b/examples/agents_api/sandboxes/aws/webhook_managed/main.py@@ -0,0 +1,94 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["openai>=3.19.0", "boto3>=1.43.34", "httpx[socks]>=0.27"]+# ///+"""Run an Agents API task in a MicroVM started by a webhook."""++import argparse+import asyncio+import json+import os+import sys+from pathlib import Path++import boto3+from openai import AsyncOpenAI++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT.parent))+from common import (+ GREETING,+ OUTPUT_PATH,+ RESUME_PROMPT,+ delete_session,+ download_file,+ run_turn,+ suspend_environment,+ terminate_microvm,+ verify_output,+ wait_for_microvm,+)+++async def main(args):+ async with AsyncOpenAI(timeout=60) as client:+ if args.create_agent:+ agent = await client.beta.agents.create(model="gpt-5.6-sol", name=args.create_agent)+ print(f"Agent: {agent.id}")+ return+ state = json.loads(args.state.read_text())+ aws = boto3.Session(+ profile_name=args.profile or state.get("profile"), region_name=state["region"]+ )+ microvms = aws.client("lambda-microvms")+ session = await client.beta.agents.sessions.create(+ agent_id=state["agent_id"],+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+ metadata={"aws_suspend_resume": "true"} if args.suspend_resume else {},+ )+ print(f"Session: {session.id}", flush=True)+ vm_id = None+ try:+ await run_turn(client, session.id)+ session = await client.beta.agents.sessions.retrieve(session.id)+ vm_id = session.metadata["aws_microvm_id"]+ print(f"MicroVM: {vm_id}", flush=True)+ await download_file(microvms, vm_id, OUTPUT_PATH, args.output)+ verify_output(args.output, GREETING)+ if args.suspend_resume:+ await suspend_environment(client, microvms, session.id, vm_id)+ await run_turn(client, session.id, RESUME_PROMPT)+ session = await client.beta.agents.sessions.retrieve(session.id)+ if session.metadata["aws_microvm_id"] != vm_id:+ raise RuntimeError("The webhook replaced the VM instead of resuming it")+ wait_for_microvm(microvms, vm_id, "RUNNING")+ await download_file(microvms, vm_id, OUTPUT_PATH, args.output)+ verify_output(args.output, GREETING)+ finally:+ try:+ # The handler may still be saving the VM ID after a client timeout.+ for _ in range(30):+ session = await client.beta.agents.sessions.retrieve(session.id)+ vm_id = vm_id or (session.metadata or {}).get("aws_microvm_id")+ if vm_id:+ terminate_microvm(microvms, vm_id)+ break+ await asyncio.sleep(1)+ else:+ raise RuntimeError(+ "No VM ID recorded; check launcher logs for pending launches"+ )+ finally:+ await delete_session(client, session.id)+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--create-agent", metavar="NAME")+ parser.add_argument("--state", type=Path, default=ROOT / ".local/deployment.json")+ parser.add_argument("--profile", default=os.environ.get("AWS_PROFILE"))+ parser.add_argument("--output", type=Path, default=ROOT / ".local/hello.txt")+ parser.add_argument(+ "--suspend-resume", action="store_true", help="Run a second turn after suspending the VM"+ )+ asyncio.run(main(parser.parse_args()))diff --git a/examples/agents_api/sandboxes/aws/webhook_managed/requirements.txt b/examples/agents_api/sandboxes/aws/webhook_managed/requirements.txtnew file mode 100644index 00000000..12e6964e--- /dev/null+++ b/examples/agents_api/sandboxes/aws/webhook_managed/requirements.txt@@ -0,0 +1,3 @@+openai>=3.19.0+boto3>=1.43.34+httpx[socks]>=0.27diff --git a/registry.yaml b/registry.yamlindex 6fdce235..ac57cb1b 100644--- a/registry.yaml+++ b/registry.yaml@@ -21,6 +21,18 @@- retrieval- structured-outputs+- title: Run Agents API sandboxes on AWS Lambda MicroVMs+ path: examples/agents_api/sandboxes/aws/README.md+ slug: agents-api-aws-lambda-microvms+ description: Run agent tools in AWS Lambda MicroVMs with application-managed or webhook-managed provisioning, file transfers, and suspend/resume.+ date: 2026-09-29+ authors:+ - alfozan+ tags:+ - agents-api+ - agents+ - sandbox+- title: Build an SRE agent for incident responsepath: examples/agents_api/apps/sev_bot/README.mdslug: agents-api-sev-bot