Examples and guides for using the OpenAI API
Add Agents API apps and sandbox examples (#3077)
Abdulrahman Alfozan6e43b29a962e
diff --git a/examples/agents_api/.gitignore b/examples/agents_api/.gitignorenew file mode 100644index 00000000..58ba05bf--- /dev/null+++ b/examples/agents_api/.gitignore@@ -0,0 +1,6 @@+node_modules/+.ruff_cache/+*.py.lock+/apps/data_analyst/memories.json+/apps/sev_bot/incident_memory.json+/apps/sev_bot/incident_memory.json.tmpdiff --git a/examples/agents_api/README.md b/examples/agents_api/README.mdnew file mode 100644index 00000000..c11e163e--- /dev/null+++ b/examples/agents_api/README.md@@ -0,0 +1,63 @@+# Agents API examples++Complete applications and sandbox integrations for the Agents API.++## Applications++| Example | What it does |+| --- | --- |+| [Incident response](apps/sev_bot/README.md) | Investigate alerts and request approval for recovery actions. |+| [Slack bot](apps/slack_bot/README.md) | Answer requests using conversation history and connected workplace tools. |+| [Data analyst](apps/data_analyst/README.md) | Answer questions with read-only warehouse queries. |+| [GitHub issue investigator](apps/github_issues/README.md) | Reproduce reported bugs and prepare findings for GitHub. |+| [Document reviewer](apps/document_review/README.md) | Review invoices and contracts with policy skills and specialist agents. |++## Sandbox integrations++- [Application-managed](sandboxes/application_managed/README.md): your application+ starts and stops the sandbox directly.+- [Webhook-managed](sandboxes/webhook_managed/README.md): a deployed handler+ provisions the sandbox while a shared client calls the Agents API.++See the [sandbox overview](sandboxes/README.md) to choose a provisioning mode.++## Run an example++Run commands from the Cookbook repository root. Each example's README covers+dependencies, credentials, sample inputs, and cleanup. Python entry points declare+their dependencies inline for [uv](https://docs.astral.sh/uv/).++The application examples require Python 3.14. Provider examples declare their+supported Python version in each script.++These examples target the upcoming OpenAI Python SDK with `client.beta.agents`+and `sessions.stream()`. The inline dependencies target `openai>=3.12.0`; wait+for the Agents API SDK release before running them from PyPI.++Create sessions with the standard client:++```python+from openai import OpenAI++client = OpenAI()++session = client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+)+```++The sandbox examples then start `codex exec-server` with the returned+`session.environment.id` and `session.environment.remote_url`, stream a turn,+and clean up. Async applications use `AsyncOpenAI` with the same+`client.beta.agents` resources and `await` for requests.++Keep credentials in environment variables or the example's local `.env` file.+Use a separate restricted `OPENAI_EXECUTOR_API_KEY` for sandbox execution. Follow+the [executor authentication requirements](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).++## Documentation++- [Agents API overview](https://developers.openai.com/api/docs/guides/agents-api/overview)+- [Self-hosted sandboxes](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted)+- [Sandbox lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle)diff --git a/examples/agents_api/__init__.py b/examples/agents_api/__init__.pynew file mode 100644index 00000000..d851f6e4--- /dev/null+++ b/examples/agents_api/__init__.py@@ -0,0 +1 @@+"""Agents API applications and sandbox integrations."""diff --git a/examples/agents_api/apps/__init__.py b/examples/agents_api/apps/__init__.pynew file mode 100644index 00000000..ecd179b4--- /dev/null+++ b/examples/agents_api/apps/__init__.py@@ -0,0 +1 @@+"""Complete Agents API application examples."""diff --git a/examples/agents_api/apps/data_analyst/.env.example b/examples/agents_api/apps/data_analyst/.env.examplenew file mode 100644index 00000000..f5cfc066--- /dev/null+++ b/examples/agents_api/apps/data_analyst/.env.example@@ -0,0 +1,3 @@+OPENAI_API_KEY=sk-...+WAREHOUSE_URL=postgresql://[email protected]/analytics+# DATA_AGENT_CONTEXT=examples/agents_api/apps/data_analyst/context.example.jsondiff --git a/examples/agents_api/apps/data_analyst/README.md b/examples/agents_api/apps/data_analyst/README.mdnew file mode 100644index 00000000..b41cc79d--- /dev/null+++ b/examples/agents_api/apps/data_analyst/README.md@@ -0,0 +1,87 @@+# Data agent++Ask questions about your own business data. The agent finds relevant warehouse tables, checks metric definitions and past analyses, runs read-only SQL, and remembers useful corrections for future investigations.++```mermaid+sequenceDiagram+ participant Person+ participant App as Your application+ participant Agent as Agents API+ participant Warehouse as Read-only warehouse+ participant Memory as Analyst memory++ Person->>App: Why did paid conversions drop last week?+ App->>Agent: Start or resume the user's session+ Agent->>Warehouse: Discover tables and inspect their schemas+ Agent->>App: Check definitions, company knowledge, and past queries+ Agent->>Memory: Find saved analyst corrections+ Agent->>Warehouse: Execute and verify read-only SQL+ Agent-->>Person: Explain the findings, sources, and assumptions+ Person->>Agent: Remember to exclude manually provisioned accounts.+ Agent->>Memory: Save the correction for future analyses+```++## What you need++- Python 3.14+ and `uv`.+- An OpenAI API key.+- Read-only access to a PostgreSQL-compatible warehouse.++No execution sandbox is required. The agent uses an Agents API session without an environment, and your application controls every warehouse query.++## Connect your warehouse++From the repository root:++```bash+cp examples/agents_api/apps/data_analyst/.env.example examples/agents_api/apps/data_analyst/.env+```++Add your OpenAI API key and read-only `WAREHOUSE_URL` to `examples/agents_api/apps/data_analyst/.env`. The application loads this file automatically.++Optionally, uncomment `DATA_AGENT_CONTEXT` in `.env` and adapt the example context file with your team's table descriptions, metric definitions, previous queries, and company documents. Saved analyst corrections are stored in `examples/agents_api/apps/data_analyst/memories.json`.++## Run the data agent++```bash+uv run examples/agents_api/apps/data_analyst/main.py+```++Open [http://127.0.0.1:8000](http://127.0.0.1:8000) and ask:++```text+Why did paid conversions drop last week?+```++Then continue the same investigation:++```text+Only include enterprise customers.+```++Or ask a single question from the terminal:++```bash+uv run examples/agents_api/apps/data_analyst/main.py --prompt \+ "Why did paid conversions drop last week?"+```++## How it works++The agent has four focused tools:++- `search_tables` finds relevant tables and reads their actual columns.+- `search_context` retrieves metric definitions, prior queries, documents, and saved corrections.+- `query_warehouse` executes one read-only query and returns at most 100 rows.+- `save_memory` stores an explicitly requested correction for later.++The `save_memory` tool is discovered on demand with `tool_search`. Programmatic tool calling lets the agent combine metadata, business context, saved corrections, and multiple verified queries before responding.++Use a read-only warehouse role. The application also starts PostgreSQL connections in read-only mode, applies a query timeout, and shows every executed query. The included browser interface represents one local analyst. In a multi-user application, derive analyst identity from your authentication layer, not a request body or query parameter.++## Files++- [main.py](main.py): Web routes, UI, and the command-line entrypoint.+- [agent.py](agent.py): Agent configuration, tools, and conversation flow.+- [warehouse.py](warehouse.py): Read-only queries, schemas, and business context.+- [memory.py](memory.py): Saved personal and team corrections.diff --git a/examples/agents_api/apps/data_analyst/__init__.py b/examples/agents_api/apps/data_analyst/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/apps/data_analyst/agent.py b/examples/agents_api/apps/data_analyst/agent.pynew file mode 100644index 00000000..6d291137--- /dev/null+++ b/examples/agents_api/apps/data_analyst/agent.py@@ -0,0 +1,186 @@+"""Investigate warehouse questions with persistent Agents API sessions."""++from __future__ import annotations++import asyncio+import os+from collections.abc import Mapping+from typing import Any+from uuid import uuid4++from openai import AsyncOpenAI+from openai.lib.streaming.agents import AsyncToolHandler+from openai.types.beta import AgentToolParam+from openai.types.beta.agent_tool_param import AgentToolConfigParamFunction+from openai.types.beta.agents.session_create_params import Agent++from .warehouse import Warehouse++INSTRUCTIONS = """\+You are a careful business data analyst.+Find relevant warehouse tables and inspect their schemas.+Check business definitions, trusted prior queries, and saved analyst corrections.+Execute only read-only queries.+Explain your verified findings, sources, assumptions, and SQL.+Save a memory only when the user explicitly asks you to remember a correction.+"""+++def define_tool(+ name: str,+ description: str,+ properties: Mapping[str, dict[str, Any]],+ *,+ defer_loading: bool = False,+) -> AgentToolConfigParamFunction:+ tool: AgentToolConfigParamFunction = {+ "type": "function",+ "name": name,+ "description": description,+ "parameters": {+ "type": "object",+ "properties": dict(properties),+ "required": list(properties),+ "additionalProperties": False,+ },+ }+ if defer_loading:+ tool["defer_loading"] = True+ return tool+++TOOLS: list[AgentToolParam] = [+ define_tool(+ "search_tables",+ "Find relevant warehouse tables and inspect their actual columns and business context.",+ {"query": {"type": "string"}},+ ),+ define_tool(+ "search_context",+ "Find business definitions, reviewed queries, company documents, and analyst memories.",+ {"query": {"type": "string"}},+ ),+ define_tool(+ "query_warehouse",+ "Execute one read-only SQL query and return at most 100 rows.",+ {"sql": {"type": "string"}},+ ),+ define_tool(+ "save_memory",+ "Save a useful correction only when the user explicitly asks you to remember it.",+ {+ "note": {"type": "string"},+ "scope": {"type": "string", "enum": ["personal", "team"]},+ },+ defer_loading=True,+ ),+ {"type": "tool_search"},+ {"type": "programmatic_tool_calling", "enabled": True},+]+++class DataAnalyst:+ """Keep one Agents API session for each warehouse investigation."""++ def __init__(self, client: AsyncOpenAI, warehouse: Warehouse) -> None:+ self.client = client+ self.warehouse = warehouse+ self.model = os.environ.get("OPENAI_MODEL", "gpt-5.6-luna")+ self.sessions: dict[str, str] = {}+ self.owners: dict[str, str] = {}++ async def answer(+ self,+ question: str,+ conversation_id: str | None = None,+ *,+ user_id: str = "analyst",+ ) -> dict[str, Any]:+ conversation_id = conversation_id or uuid4().hex+ owner = self.owners.get(conversation_id)+ if owner is not None and owner != user_id:+ raise PermissionError(+ "Start a new conversation to use your own analyst context."+ )++ queries: list[str] = []++ def execute(arguments: dict[str, Any]) -> dict[str, Any]:+ result = self.warehouse.query(arguments)+ queries.append(str(result["sql"]))+ return result++ handlers: dict[str, AsyncToolHandler] = {+ "search_tables": self.warehouse.search_tables,+ "search_context": lambda arguments: self.warehouse.search_context(+ arguments, user_id=user_id+ ),+ "query_warehouse": execute,+ "save_memory": lambda arguments: self.warehouse.memory.save(+ arguments, user_id=user_id+ ),+ }++ if conversation_id in self.sessions:+ session = await self.client.beta.agents.sessions.retrieve(+ self.sessions[conversation_id]+ )+ else:+ agent: Agent = {+ "model": self.model,+ "instructions": INSTRUCTIONS,+ "reasoning": {"effort": "high"},+ "tools": TOOLS,+ }+ session = await self.client.beta.agents.sessions.create(+ agent=agent,+ environment={"type": "none"},+ )+ self.sessions[conversation_id] = session.id+ self.owners[conversation_id] = user_id++ session_id = session.id+ parts: list[str] = []+ async with self.client.beta.agents.sessions.stream(+ session_id, input=question, tool_handlers=handlers+ ) as events:+ async for event in events:+ if event.type == "agent.session.turn.output_text.delta":+ parts.append(event.delta)+ elif event.type == "agent.session.turn.output_text.done" and not parts:+ parts.append(event.text)+ elif event.type in {+ "agent.session.failed",+ "agent.session.turn.failed",+ "error",+ }:+ raise RuntimeError(f"Data investigation failed: {event.to_dict()}")+ elif event.type == "agent.session.turn.cancelled":+ raise RuntimeError("Data investigation was cancelled.")+ answer = "".join(parts)++ return {+ "answer": answer,+ "conversation_id": conversation_id,+ "session_id": session_id,+ "sql": queries[-1] if queries else None,+ "queries": queries,+ "memories": self.warehouse.memory.list(user_id=user_id),+ }++ async def close(self) -> None:+ try:+ results = await asyncio.gather(+ *(+ self.client.beta.agents.sessions.delete(sid)+ for sid in set(self.sessions.values())+ ),+ return_exceptions=True,+ )+ for result in results:+ if isinstance(result, BaseException):+ raise result+ finally:+ self.sessions.clear()+ self.owners.clear()+ self.warehouse.close()diff --git a/examples/agents_api/apps/data_analyst/context.example.json b/examples/agents_api/apps/data_analyst/context.example.jsonnew file mode 100644index 00000000..7d96a534--- /dev/null+++ b/examples/agents_api/apps/data_analyst/context.example.json@@ -0,0 +1,38 @@+{+ "tables": [+ {+ "name": "analytics.signups",+ "description": "One row per customer signup and acquisition channel.",+ "owner": "Growth Analytics",+ "freshness": "Updated hourly."+ },+ {+ "name": "analytics.subscriptions",+ "description": "Paid subscriptions used for customer conversion analysis.",+ "owner": "Revenue Analytics",+ "freshness": "Updated hourly."+ }+ ],+ "metrics": [+ {+ "name": "paid_conversion_rate",+ "definition": "Paid subscriptions divided by eligible signups.",+ "filters": [+ "Exclude employees and test accounts.",+ "Exclude the current incomplete day."+ ]+ }+ ],+ "query_history": [+ {+ "description": "All-time paid conversion by acquisition channel; add a signup date range for weekly comparisons.",+ "sql": "SELECT s.channel, COUNT(DISTINCT p.customer_id) * 1.0 / COUNT(DISTINCT s.customer_id) AS conversion_rate FROM analytics.signups s LEFT JOIN analytics.subscriptions p ON s.customer_id = p.customer_id WHERE s.is_internal = false AND s.is_test_account = false AND s.created_at < CURRENT_DATE GROUP BY s.channel"+ }+ ],+ "documents": [+ {+ "title": "Checkout tracking migration",+ "text": "Mobile checkout tracking changed on August 18. Exclude the current incomplete day from weekly conversion comparisons."+ }+ ]+}diff --git a/examples/agents_api/apps/data_analyst/index.html b/examples/agents_api/apps/data_analyst/index.htmlnew file mode 100644index 00000000..212aa282--- /dev/null+++ b/examples/agents_api/apps/data_analyst/index.html@@ -0,0 +1,205 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Data agent</title>+ <style>+ * { box-sizing: border-box; }+ body { margin: 0; background: #f6f8f7; color: #18241f; font: 14px/1.55 system-ui, sans-serif; }+ main { max-width: 1040px; margin: 72px auto; padding: 0 24px; }+ header { display: flex; align-items: center; justify-content: space-between; gap: 16px; }+ h1 { margin: 0; font-size: 32px; font-weight: 650; }+ h2 { margin: 0 0 16px; font-size: 16px; font-weight: 600; }+ .badge { display: inline-flex; align-items: center; gap: 8px; padding: 7px 11px; border: 1px solid #d6e8dd; border-radius: 6px; background: #eef7f1; color: #206c43; font-size: 12px; white-space: nowrap; }+ .badge::before { width: 7px; height: 7px; border-radius: 50%; background: #268651; content: ""; }+ .intro { max-width: 620px; margin: 8px 0 32px; color: #68746f; }+ .metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 18px; }+ .metric, .panel { background: #fff; border: 1px solid #e2e8e4; border-radius: 8px; }+ .metric { min-width: 0; padding: 17px 18px; }+ .metric span { display: block; margin-bottom: 5px; color: #718078; font-size: 12px; }+ .metric strong { display: block; overflow-wrap: anywhere; font-size: 21px; font-weight: 620; }+ .panel { padding: 22px; }+ form { display: flex; gap: 10px; }+ input { min-width: 0; flex: 1; padding: 11px 13px; border: 1px solid #d7dfda; border-radius: 6px; outline: none; color: inherit; font: inherit; }+ input:focus { border-color: #27945d; box-shadow: 0 0 0 3px #e6f3eb; }+ button { padding: 10px 16px; border: 1px solid transparent; border-radius: 6px; background: #167449; color: white; font: inherit; cursor: pointer; }+ button:hover { background: #115f3b; }+ button:disabled { cursor: wait; opacity: 0.65; }+ .ideas { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 13px; }+ .idea { padding: 6px 9px; border-color: #e1e7e3; background: #fff; color: #52625a; font-size: 12px; }+ .idea:hover { border-color: #cbded2; background: #f3f8f5; }+ #answer:not(:empty) { margin-top: 22px; padding-top: 20px; border-top: 1px solid #edf0ee; white-space: pre-wrap; }+ #sql:not(:empty) { margin-top: 14px; padding: 12px; border-radius: 6px; background: #f5f7f6; color: #52625a; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px/1.55 ui-monospace, monospace; }+ .memory { margin-top: 18px; }+ #memories { margin-bottom: 16px; }+ .memory-empty { margin: 0; color: #76827b; }+ .memory-item { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 11px 0; border-bottom: 1px solid #edf0ee; }+ .memory-item:first-child { padding-top: 0; }+ .memory-note { min-width: 0; overflow-wrap: anywhere; }+ .memory-scope { display: block; margin-top: 2px; color: #76827b; font-size: 11px; text-transform: capitalize; }+ .remove-memory { flex-shrink: 0; width: 28px; height: 28px; padding: 0; border-color: transparent; background: transparent; color: #76827b; font-size: 20px; line-height: 1; }+ .remove-memory:hover { border-color: #f0d9d7; background: #fff5f4; color: #ad3430; }+ @media (max-width: 640px) { main { margin: 36px auto; padding: 0 18px; } header { align-items: flex-start; flex-direction: column; } .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } .panel { padding: 17px; } form { flex-direction: column; } }+ </style>+ </head>+ <body>+ <main>+ <header><h1>Data agent</h1><span class="badge">Read-only warehouse access</span></header>+ <p class="intro">Ask about your business. Your agent finds relevant data, checks definitions, and shows the SQL behind every answer.</p>+ <section class="metrics">+ <div class="metric"><span>Data source</span><strong id="engine">Loading...</strong></div>+ <div class="metric"><span>Connected tables</span><strong id="tables">Loading...</strong></div>+ <div class="metric"><span>Business definitions</span><strong id="metrics">Loading...</strong></div>+ <div class="metric"><span>Saved memories</span><strong id="memory-count">Loading...</strong></div>+ </section>+ <section class="panel">+ <h2>Ask your data</h2>+ <form id="question-form"><input id="question" aria-label="Question about your data" placeholder="Why did paid conversions drop last week?" autocomplete="off" required /><button type="submit">Ask the agent</button></form>+ <div class="ideas"><button class="idea" type="button">Why did conversions drop last week?</button><button class="idea" type="button">Compare conversion by acquisition channel.</button><button class="idea" type="button">Only include enterprise customers.</button></div>+ <div id="answer" role="status"></div><div id="sql"></div>+ </section>+ <section class="panel memory">+ <h2>Analyst memory</h2>+ <div id="memories"><p class="memory-empty">No corrections saved yet.</p></div>+ <form id="memory-form"><input id="memory" aria-label="Correction to remember" placeholder="Enterprise conversion excludes manually provisioned accounts." autocomplete="off" required /><button type="submit">Save for the team</button></form>+ <p id="memory-status" role="status"></p>+ </section>+ </main>+ <script>+ let conversationId;+ let busy = false;+ const form = document.querySelector('#question-form');+ const question = document.querySelector('#question');+ const memoryStatus = document.querySelector('#memory-status');++ async function requestJSON(url, options) {+ const response = await fetch(url, options);+ if (!response.ok) throw new Error('The request failed. Please try again.');+ return response.json();+ }++ function showMemories(memories) {+ document.querySelector('#memory-count').textContent = memories.length.toLocaleString();+ const container = document.querySelector('#memories');+ container.replaceChildren();++ if (!memories.length) {+ const empty = document.createElement('p');+ empty.className = 'memory-empty';+ empty.textContent = 'No corrections saved yet.';+ container.append(empty);+ return;+ }++ memories.forEach((memory) => {+ const row = document.createElement('div');+ row.className = 'memory-item';++ const note = document.createElement('div');+ note.className = 'memory-note';+ note.textContent = memory.note;++ const scope = document.createElement('span');+ scope.className = 'memory-scope';+ scope.textContent = memory.scope;+ note.append(scope);++ const remove = document.createElement('button');+ remove.className = 'remove-memory';+ remove.type = 'button';+ remove.title = 'Remove memory';+ remove.setAttribute('aria-label', 'Remove memory');+ remove.innerHTML = '×';+ remove.addEventListener('click', async () => {+ remove.disabled = true;+ memoryStatus.textContent = '';+ try {+ const result = await requestJSON(`/api/memories/${encodeURIComponent(memory.id)}`, {+ method: 'DELETE',+ });+ showMemories(result.memories);+ } catch {+ memoryStatus.textContent = 'Could not remove that memory. Please try again.';+ remove.disabled = false;+ }+ });++ row.append(note, remove);+ container.append(row);+ });+ }++ requestJSON('/api/warehouse').then((warehouse) => {+ document.querySelector('#engine').textContent = warehouse.engine;+ document.querySelector('#tables').textContent = warehouse.tables.toLocaleString();+ document.querySelector('#metrics').textContent = warehouse.metrics.toLocaleString();+ document.querySelector('#memory-count').textContent = warehouse.memories.toLocaleString();+ }).catch(() => {+ document.querySelector('#engine').textContent = 'Unavailable';+ for (const id of ['tables', 'metrics', 'memory-count']) document.getElementById(id).textContent = '-';+ });+ requestJSON('/api/memories').then((result) => showMemories(result.memories)).catch(() => {+ memoryStatus.textContent = 'Could not load saved memories. Refresh to try again.';+ });++ document.querySelectorAll('.idea').forEach((button) => button.addEventListener('click', () => {+ question.value = button.textContent;+ form.requestSubmit();+ }));++ form.addEventListener('submit', async (event) => {+ event.preventDefault();+ if (busy) return;+ busy = true;+ const submit = form.querySelector('button[type="submit"]');+ const answer = document.querySelector('#answer');+ submit.disabled = true;+ document.querySelectorAll('.idea').forEach((button) => { button.disabled = true; });+ answer.textContent = 'Finding relevant tables and checking the numbers...';+ document.querySelector('#sql').textContent = '';++ try {+ const result = await requestJSON('/api/ask', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ question: question.value, conversation_id: conversationId }),+ });+ conversationId = result.conversation_id;+ answer.textContent = result.answer || result.detail || 'Something went wrong.';+ const queries = result.queries || [];+ document.querySelector('#sql').textContent = queries.length ? `Verified SQL:\n${queries.join('\n\n')}` : '';+ if (result.memories) showMemories(result.memories);+ } catch {+ answer.textContent = 'Could not reach the data agent. Please try again.';+ } finally {+ busy = false;+ submit.disabled = false;+ document.querySelectorAll('.idea').forEach((button) => { button.disabled = false; });+ }+ });++ document.querySelector('#memory-form').addEventListener('submit', async (event) => {+ event.preventDefault();+ const input = document.querySelector('#memory');+ const submit = event.currentTarget.querySelector('button');+ submit.disabled = true;+ memoryStatus.textContent = '';+ try {+ await requestJSON('/api/memories', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ note: input.value, scope: 'team' }),+ });+ input.value = '';+ const result = await requestJSON('/api/memories');+ showMemories(result.memories);+ } catch {+ memoryStatus.textContent = 'Could not save or refresh memories. Check the list before retrying.';+ } finally {+ submit.disabled = false;+ }+ });+ </script>+ </body>+</html>diff --git a/examples/agents_api/apps/data_analyst/main.py b/examples/agents_api/apps/data_analyst/main.pynew file mode 100644index 00000000..a1d041a3--- /dev/null+++ b/examples/agents_api/apps/data_analyst/main.py@@ -0,0 +1,146 @@+# /// script+# requires-python = ">=3.14"+# dependencies = [+# "openai>=3.12.0",+# "fastapi",+# "psycopg[binary]",+# "python-dotenv",+# "uvicorn",+# ]+# ///++"""Serve the data analyst UI or run a single question."""++from __future__ import annotations++import argparse+import asyncio+import sys+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Any, cast++from dotenv import load_dotenv+from fastapi import FastAPI, HTTPException+from fastapi.responses import HTMLResponse+from openai import AsyncOpenAI+from pydantic import BaseModel++# Support direct execution from any working directory.+if __package__ in {None, ""}:+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+++from examples.agents_api.apps.data_analyst.agent import DataAnalyst+from examples.agents_api.apps.data_analyst.warehouse import Warehouse++EXAMPLE_DIR = Path(__file__).resolve().parent+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncIterator[None]:+ async with AsyncOpenAI() as client:+ app.state.analyst = DataAnalyst(client, Warehouse())+ try:+ yield+ finally:+ await app.state.analyst.close()+++app = FastAPI(title="Data agent", lifespan=lifespan)+++class Question(BaseModel):+ question: str+ conversation_id: str | None = None+++class Memory(BaseModel):+ note: str+ scope: str = "personal"++[email protected]("/", response_class=HTMLResponse)+async def home() -> str:+ return (EXAMPLE_DIR / "index.html").read_text()++[email protected]("/api/warehouse")+async def warehouse_summary() -> dict[str, Any]:+ analyst: DataAnalyst = app.state.analyst+ return analyst.warehouse.summary()++[email protected]("/api/memories")+async def list_memories() -> dict[str, Any]:+ analyst: DataAnalyst = app.state.analyst+ return {"memories": analyst.warehouse.memory.list()}++[email protected]("/api/memories")+async def create_memory(memory: Memory) -> dict[str, Any]:+ analyst: DataAnalyst = app.state.analyst+ try:+ return analyst.warehouse.memory.save(+ {"note": memory.note, "scope": memory.scope}+ )+ except ValueError as error:+ raise HTTPException(status_code=400, detail=str(error)) from error++[email protected]("/api/memories/{memory_id}")+async def delete_memory(memory_id: str) -> dict[str, Any]:+ analyst: DataAnalyst = app.state.analyst+ try:+ analyst.warehouse.memory.delete(memory_id)+ except ValueError as error:+ raise HTTPException(status_code=404, detail=str(error)) from error+ return {"memories": analyst.warehouse.memory.list()}++[email protected]("/api/ask")+async def ask(question: Question) -> dict[str, Any]:+ analyst: DataAnalyst = app.state.analyst+ try:+ return await analyst.answer(question.question, question.conversation_id)+ except (PermissionError, ValueError) as error:+ raise HTTPException(status_code=400, detail=str(error)) from error+++async def run_prompt(prompt: str) -> None:+ async with AsyncOpenAI() as client:+ analyst = DataAnalyst(client, Warehouse())+ try:+ result = await analyst.answer(prompt)+ print(result["answer"])+ queries = cast(list[str], result["queries"])+ if queries:+ print("\nVerified SQL:")+ for query in queries:+ print(query)+ finally:+ await analyst.close()+++def main() -> None:+ load_dotenv(EXAMPLE_DIR / ".env")+ parser = argparse.ArgumentParser(+ description="Ask questions about a read-only data warehouse."+ )+ parser.add_argument(+ "--prompt", metavar="QUESTION", help="Run one warehouse investigation."+ )+ args = parser.parse_args()++ if args.prompt:+ asyncio.run(run_prompt(args.prompt))+ return++ import uvicorn++ uvicorn.run(app, host="127.0.0.1", port=8000)+++if __name__ == "__main__":+ main()diff --git a/examples/agents_api/apps/data_analyst/memory.py b/examples/agents_api/apps/data_analyst/memory.pynew file mode 100644index 00000000..b4d5a1d8--- /dev/null+++ b/examples/agents_api/apps/data_analyst/memory.py@@ -0,0 +1,94 @@+"""Search and persist personal or team analyst corrections."""++from __future__ import annotations++import json+import re+from datetime import UTC, datetime+from pathlib import Path+from typing import Any, cast+from uuid import uuid4+++def relevant(record: dict[str, Any], query: str) -> bool:+ terms = {word for word in re.findall(r"[a-z0-9_]+", query.lower()) if len(word) > 2}+ if not terms:+ return True+ text = json.dumps(record, default=str).lower()+ return any(term in text for term in terms)+++class MemoryStore:+ """Keep explicitly saved analyst corrections in a local JSON file."""++ def __init__(self, path: Path) -> None:+ self.path = path++ def list(self, *, user_id: str = "analyst") -> list[dict[str, Any]]:+ if not self.path.exists():+ return []+ memories = json.loads(self.path.read_text())+ if not isinstance(memories, list):+ return []+ return [+ cast(dict[str, Any], memory)+ for memory in memories+ if isinstance(memory, dict)+ and (memory.get("scope") == "team" or memory.get("user_id") == user_id)+ ]++ def search(+ self, arguments: dict[str, Any], *, user_id: str = "analyst"+ ) -> dict[str, Any]:+ query = str(arguments.get("query", ""))+ return {+ "memories": [+ memory+ for memory in self.list(user_id=user_id)+ if relevant(memory, query)+ ][:10]+ }++ def save(+ self, arguments: dict[str, Any], *, user_id: str = "analyst"+ ) -> dict[str, Any]:+ note = str(arguments.get("note", "")).strip()+ scope = str(arguments.get("scope", "personal"))+ if not note:+ raise ValueError("A saved memory must contain a note.")+ if scope not in {"personal", "team"}:+ raise ValueError("A memory scope must be personal or team.")++ memories = (+ cast(list[dict[str, Any]], json.loads(self.path.read_text()))+ if self.path.exists()+ else []+ )+ memory: dict[str, Any] = {+ "id": uuid4().hex,+ "note": note,+ "scope": scope,+ "user_id": user_id,+ "created_at": datetime.now(UTC).isoformat(),+ }+ memories.append(memory)+ self.path.parent.mkdir(parents=True, exist_ok=True)+ self.path.write_text(json.dumps(memories, indent=2) + "\n")+ return {"status": "saved", "memory": memory}++ def delete(self, memory_id: str, *, user_id: str = "analyst") -> dict[str, Any]:+ memory = next(+ (+ memory+ for memory in self.list(user_id=user_id)+ if memory.get("id") == memory_id+ ),+ None,+ )+ if memory is None:+ raise ValueError("Memory not found.")++ memories = cast(list[dict[str, Any]], json.loads(self.path.read_text()))+ memories = [item for item in memories if item.get("id") != memory_id]+ self.path.write_text(json.dumps(memories, indent=2) + "\n")+ return {"status": "deleted", "memory": memory}diff --git a/examples/agents_api/apps/data_analyst/warehouse.py b/examples/agents_api/apps/data_analyst/warehouse.pynew file mode 100644index 00000000..ef28a94a--- /dev/null+++ b/examples/agents_api/apps/data_analyst/warehouse.py@@ -0,0 +1,220 @@+"""Inspect warehouse schemas and run read-only queries."""++from __future__ import annotations++import importlib+import json+import os+import re+import sqlite3+from pathlib import Path+from typing import Any, cast+from urllib.parse import unquote, urlparse++from .memory import MemoryStore, relevant++EXAMPLE_DIR = Path(__file__).resolve().parent+MAX_ROWS = 100+++class Warehouse:+ """Expose an existing warehouse through a read-only, application-owned connection."""++ def __init__(+ self,+ url: str | None = None,+ *,+ context: dict[str, Any] | None = None,+ context_path: Path | None = None,+ memory_path: Path | None = None,+ ) -> None:+ self.url = url or os.environ.get("WAREHOUSE_URL")+ if not self.url:+ raise ValueError("Set WAREHOUSE_URL to a read-only PostgreSQL connection.")++ configured_context = os.environ.get("DATA_AGENT_CONTEXT")+ if context is not None:+ self.context = context+ elif context_path is not None or configured_context:+ path = context_path or Path(str(configured_context))+ self.context = cast(dict[str, Any], json.loads(path.read_text()))+ else:+ self.context = {}++ self.memory = MemoryStore(memory_path or EXAMPLE_DIR / "memories.json")++ parsed = urlparse(self.url)+ self.connection: Any+ if parsed.scheme in {"postgres", "postgresql"}:+ self.engine = "PostgreSQL"+ try:+ psycopg = importlib.import_module("psycopg")+ rows = importlib.import_module("psycopg.rows")+ except ModuleNotFoundError as error:+ raise RuntimeError(+ "PostgreSQL requires psycopg. Start the example with "+ "`uv run examples/agents_api/apps/data_analyst/main.py`."+ ) from error+ self.connection = psycopg.connect(+ self.url,+ autocommit=True,+ row_factory=rows.dict_row,+ options="-c default_transaction_read_only=on -c statement_timeout=30000",+ )+ elif parsed.scheme == "sqlite":+ self.engine = "SQLite"+ path = Path(unquote(parsed.path)).resolve()+ self.connection = sqlite3.connect(+ f"file:{path}?mode=ro", uri=True, check_same_thread=False+ )+ self.connection.row_factory = sqlite3.Row+ else:+ raise ValueError("WAREHOUSE_URL must use postgresql:// or sqlite:///.")++ def records(self, section: str) -> list[dict[str, Any]]:+ records = self.context.get(section, [])+ if not isinstance(records, list):+ return []+ return [+ cast(dict[str, Any], record)+ for record in records+ if isinstance(record, dict)+ ]++ def table_names(self) -> list[str]:+ cursor = self.connection.cursor()+ if self.engine == "PostgreSQL":+ cursor.execute(+ "SELECT table_schema, table_name FROM information_schema.tables "+ "WHERE table_schema NOT IN ('information_schema', 'pg_catalog') "+ "AND table_type IN ('BASE TABLE', 'VIEW') "+ "ORDER BY table_schema, table_name"+ )+ return [+ f"{row['table_schema']}.{row['table_name']}"+ for row in cursor.fetchall()+ ]++ cursor.execute(+ "SELECT name FROM sqlite_master "+ "WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' ORDER BY name"+ )+ return [str(row["name"]) for row in cursor.fetchall()]++ def table_context(self, name: str) -> dict[str, Any]:+ records = self.records("tables")+ for record in records:+ if record.get("name") == name:+ return record++ table_name = name.rsplit(".", maxsplit=1)[-1]+ return next(+ (+ record+ for record in records+ if str(record.get("name", "")).rsplit(".", maxsplit=1)[-1] == table_name+ ),+ {"name": name},+ )++ def search_tables(self, arguments: dict[str, Any]) -> dict[str, Any]:+ query = str(arguments.get("query", ""))+ names = [+ name+ for name in self.table_names()+ if relevant(self.table_context(name), query)+ ][:20]+ return {"tables": [self.inspect_table({"table": name}) for name in names]}++ def inspect_table(self, arguments: dict[str, Any]) -> dict[str, Any]:+ name = str(arguments.get("table", ""))+ if name not in self.table_names():+ raise ValueError(f"Unknown warehouse table: {name}")++ cursor = self.connection.cursor()+ if self.engine == "PostgreSQL":+ schema, table = name.split(".", maxsplit=1)+ cursor.execute(+ "SELECT column_name, data_type, is_nullable "+ "FROM information_schema.columns "+ "WHERE table_schema = %s AND table_name = %s ORDER BY ordinal_position",+ (schema, table),+ )+ columns: list[dict[str, Any]] = [+ {+ "name": str(row["column_name"]),+ "type": str(row["data_type"]),+ "nullable": row["is_nullable"] == "YES",+ }+ for row in cursor.fetchall()+ ]+ else:+ escaped = name.replace('"', '""')+ cursor.execute(f'PRAGMA table_info("{escaped}")')+ columns = [+ {+ "name": str(row["name"]),+ "type": str(row["type"]),+ "nullable": not bool(row["notnull"]),+ }+ for row in cursor.fetchall()+ ]++ return {**self.table_context(name), "name": name, "columns": columns}++ def search_query_history(self, arguments: dict[str, Any]) -> dict[str, Any]:+ query = str(arguments.get("query", ""))+ return {+ "queries": [+ record+ for record in self.records("query_history")+ if relevant(record, query)+ ][:10]+ }++ def search_company_knowledge(self, arguments: dict[str, Any]) -> dict[str, Any]:+ query = str(arguments.get("query", ""))+ return {+ "metrics": [+ record for record in self.records("metrics") if relevant(record, query)+ ][:10],+ "documents": [+ record+ for record in self.records("documents")+ if relevant(record, query)+ ][:10],+ }++ def search_context(+ self, arguments: dict[str, Any], *, user_id: str = "analyst"+ ) -> dict[str, Any]:+ return {+ **self.search_company_knowledge(arguments),+ **self.search_query_history(arguments),+ **self.memory.search(arguments, user_id=user_id),+ }++ def query(self, arguments: dict[str, Any]) -> dict[str, Any]:+ sql = str(arguments.get("sql", "")).strip().rstrip(";")+ if not re.match(r"^(SELECT|WITH)\b", sql, re.IGNORECASE) or ";" in sql:+ raise ValueError("Only one read-only SELECT query is allowed.")++ cursor = self.connection.cursor()+ cursor.execute(sql)+ rows = [dict(row) for row in cursor.fetchmany(MAX_ROWS)]+ serialized = cast(+ list[dict[str, Any]], json.loads(json.dumps(rows, default=str))+ )+ return {"sql": sql, "rows": serialized, "row_count": len(serialized)}++ def summary(self, *, user_id: str = "analyst") -> dict[str, Any]:+ return {+ "engine": self.engine,+ "tables": len(self.table_names()),+ "metrics": len(self.records("metrics")),+ "documents": len(self.records("documents")),+ "memories": len(self.memory.list(user_id=user_id)),+ }++ def close(self) -> None:+ self.connection.close()diff --git a/examples/agents_api/apps/document_review/.env.example b/examples/agents_api/apps/document_review/.env.examplenew file mode 100644index 00000000..ed6ed73b--- /dev/null+++ b/examples/agents_api/apps/document_review/.env.example@@ -0,0 +1 @@+OPENAI_API_KEY=sk-...diff --git a/examples/agents_api/apps/document_review/README.md b/examples/agents_api/apps/document_review/README.mdnew file mode 100644index 00000000..ec9d5753--- /dev/null+++ b/examples/agents_api/apps/document_review/README.md@@ -0,0 +1,107 @@+# Bulk invoice and contract review++Mount a folder of invoices and contracts alongside a reusable accounts-payable policy skill. A `gpt-5.6-luna` agent delegates each document to a specialist subagent, applies the discovered skill, writes individual reports plus a consolidated summary, and leaves every approval to a person.++```mermaid+sequenceDiagram+ participant Person+ participant App as Review command+ participant Agent as Agents API+ participant Reviewers as Specialist subagents+ participant Policy as Mounted review skill+ participant Workspace as Mounted input/output folders+ Person->>App: Submit a folder of invoices and contracts+ App->>Agent: Create one multi-agent session+ App->>Workspace: Mount input and policy read-only; output read-write+ Agent->>Reviewers: Delegate one document to each specialist+ Reviewers->>Policy: Discover and apply expense-review-policy+ Reviewers->>Workspace: Write individual JSON reports+ Agent->>Workspace: Write the consolidated summary+ App-->>Person: Write findings for human review+```++## What you need++- Python 3.14+ and `uv`.+- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).+- An OpenAI API key.++## 1. Set up the workspace++From the repository root:++```bash+cp examples/agents_api/apps/document_review/.env.example examples/agents_api/apps/document_review/.env+docker build -t agent-api-sandbox:latest examples/agents_api/sandboxes/application_managed/docker+```++Add your OpenAI API key to `examples/agents_api/apps/document_review/.env`. The application loads this file automatically.++You can replace local Docker with any compatible [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).++## 2. Review the document batch++```bash+uv run examples/agents_api/apps/document_review/main.py \+ --input examples/agents_api/apps/document_review/sample_documents \+ --output ./review-output+```++The input folder contains an invoice with a $900 overcharge and a contract with automatic renewal, unilateral price increases, unlimited liability, and unrestricted customer-data sharing. Specialist subagents apply the mounted policy to each document and write:++```text+review-output/+ contract.json+ invoice.json+ summary.json+ review-activity.json+```++The source folder and policy skill are mounted read-only; reports are written to `/workspace/output` and remain available on the host after the sandbox exits. With Docker Desktop, keep input and output directories under your home directory; system temporary directories may not be shared.++The command logs the session, sandbox, mounted directories, specialist subagents, and generated artifacts as the review progresses.++Use an empty output folder for each run and unique document stems, such as `invoice-104.txt` and `contract-208.txt`. The names `summary` and `review-activity` are reserved.++## Inspect retained command activity++Before deleting the session, the app exports retained commands and their turn IDs to `review-activity.json`. Retained item history currently includes coordinator commands, not the specialists' full activity. A `null` subagent ID identifies the coordinator.++```python+turn = await client.beta.agents.sessions.turns.retrieve(+ command["turn_id"], session_id=session.id+)+print(turn.subagent_id, command["command"])+```++These records come from API history, not model-written reviewer names. They are not a complete audit of specialist work. Protect this file like the reports: commands can contain document content.++## How the policy skill works++The included policy lives at:++```text+skills/expense-review-policy/SKILL.md+```++It is mounted at `/workspace/skills/expense-review-policy/SKILL.md` and discovered through the session's capability root:++```python+environment = {+ "type": "self_hosted",+ "workspace_directory": "/workspace",+ "capability_directories": ["/workspace/skills"],+}+```++Each specialist applies `$expense-review-policy` and includes its `policy_id` and `decision` in the generated report. Replace `SKILL.md` with your own review policy without rebuilding the sandbox image.++## Make it yours++Replace the included skill with your team's own accounts-payable or contract-review policy, and use your preferred sandbox provider when you deploy the application. Keep approval in your application: the agent can recommend a decision, but it should never make payments or accept contracts on its own.++## Files++- [main.py](main.py): Command-line arguments and the batch summary.+- [agent.py](agent.py): Specialist reviews, report validation, and activity export.+- [sandbox.py](sandbox.py): Document, artifact, and skill mounts.diff --git a/examples/agents_api/apps/document_review/__init__.py b/examples/agents_api/apps/document_review/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/apps/document_review/agent.py b/examples/agents_api/apps/document_review/agent.pynew file mode 100644index 00000000..d155eb61--- /dev/null+++ b/examples/agents_api/apps/document_review/agent.py@@ -0,0 +1,227 @@+"""Delegate document reviews and export their reports."""++from __future__ import annotations++import asyncio+import json+import logging+import os+from pathlib import Path+from typing import Any++from docker.models.containers import Container+from openai import AsyncOpenAI++from .sandbox import SKILLS_DIRECTORY, start_executor++logger = logging.getLogger(__name__)+INSTRUCTIONS = """\+You coordinate bulk invoice and contract reviews.+Before inspecting any document, spawn specialist subagents and assign them the files in+/workspace/input. Assign one document to each specialist when possible, or several for+larger batches. Do not review source documents yourself.++Each specialist must discover and apply $expense-review-policy before inspecting its+assigned documents. Follow the skill's arithmetic checks, decision rules, and required+report fields. Each specialist writes /workspace/output/<document-stem>.json.++Wait for every specialist to finish, then write /workspace/output/summary.json with+document_count, reviews, and recommendation. Never approve a payment or sign a contract.+"""+++async def review_activity(client: AsyncOpenAI, session_id: str) -> list[dict[str, Any]]:+ """Export sandbox commands available in retained item history."""+ commands: list[dict[str, Any]] = []+ owners: dict[str, str | None] = {}+ async for item in client.beta.agents.sessions.items.list(+ session_id, limit=100, order="asc"+ ):+ if item.type != "command_execution":+ continue+ turn_id = item.turn_id+ if turn_id not in owners:+ turn = await client.beta.agents.sessions.turns.retrieve(+ turn_id, session_id=session_id+ )+ owners[turn_id] = turn.subagent_id+ commands.append(+ {+ "item_id": item.id,+ "turn_id": turn_id,+ "subagent_id": owners[turn_id],+ "command": item.command,+ "status": item.status,+ }+ )+ return commands+++async def review_documents(+ input_directory: Path, output_directory: Path+) -> dict[str, Any]:+ documents = sorted(path for path in input_directory.iterdir() if path.is_file())+ if not documents:+ raise ValueError("The input directory does not contain any documents.")+ if len({document.stem for document in documents}) != len(documents):+ raise ValueError(+ "Document filenames must have unique stems for their JSON reports."+ )+ if any(document.stem == "summary" for document in documents):+ raise ValueError(+ "Rename summary.*; summary.json is reserved for the batch report."+ )+ if any(document.stem == "review-activity" for document in documents):+ raise ValueError(+ "Rename review-activity.*; that name is reserved for command attribution."+ )+ output_directory.mkdir(parents=True, exist_ok=True)+ if any(output_directory.iterdir()):+ raise ValueError(+ "Choose an empty output directory so earlier reports cannot be reused."+ )+ logger.info("Documents: %s", ", ".join(document.name for document in documents))+ logger.info(+ "Input mount: %s -> /workspace/input (read-only)", input_directory.resolve()+ )+ logger.info("Output mount: %s -> /workspace/output", output_directory.resolve())+ logger.info("Skills mount: %s -> /workspace/skills (read-only)", SKILLS_DIRECTORY)++ container: Container | None = None+ async with AsyncOpenAI() as client:+ session = await client.beta.agents.sessions.create(+ agent={+ "model": os.environ.get("OPENAI_MODEL", "gpt-5.6-luna"),+ "instructions": INSTRUCTIONS,+ "reasoning": {"effort": "high"},+ "multi_agent": {+ "enabled": True,+ "max_concurrent_subagents": min(len(documents), 8),+ },+ },+ environment={+ "type": "self_hosted",+ "workspace_directory": "/workspace",+ "capability_directories": ["/workspace/skills"],+ },+ )+ logger.info("Session created: %s", session.id)++ try:+ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError("Expected a self-hosted execution environment.")+ logger.info("Environment: %s", environment.id)+ logger.info("Starting document sandbox.")+ container = await asyncio.to_thread(+ start_executor,+ input_directory,+ output_directory,+ environment.id,+ environment.remote_url,+ )+ logger.info("Sandbox started: %s", container.short_id)+ parts: list[str] = []+ subagents = 0+ prompt = f"""\+Review all {len(documents)} documents in /workspace/input.+First spawn specialist subagents and assign the documents to them.+Each specialist must apply $expense-review-policy and include its policy_id and decision.+Wait for every review, write one JSON report per document and /workspace/output/summary.json,+and summarize the most important findings for the human approver.+"""+ async with client.beta.agents.sessions.stream(+ session.id, input=prompt+ ) as events:+ async for event in events:+ if event.type == "agent.session.subagent.created":+ subagents += 1+ logger.info(+ "Specialist started: %s/%s", subagents, len(documents)+ )+ elif (+ event.type == "agent.session.turn.item.done"+ and event.item is not None+ ):+ item_type = event.item.type+ if item_type not in {"reasoning", "message"}:+ logger.info("Sandbox item: %s", item_type)+ elif event.type == "agent.session.turn.output_text.delta":+ parts.append(event.delta)+ elif (+ event.type == "agent.session.turn.output_text.done"+ and not parts+ ):+ parts.append(event.text)+ if event.type in {+ "agent.session.failed",+ "agent.session.turn.failed",+ "error",+ }:+ raise RuntimeError(f"Document review failed: {event.to_dict()}")+ if event.type == "agent.session.turn.cancelled":+ raise RuntimeError(+ "Document review was cancelled; reports may be incomplete."+ )++ if len(documents) > 1 and subagents == 0:+ raise RuntimeError(+ "The document batch was not delegated to specialist subagents."+ )++ report_path = output_directory / "summary.json"+ if not report_path.exists():+ response = "".join(parts).strip()+ raise RuntimeError(+ "The agent did not create /workspace/output/summary.json."+ + (f" Agent response: {response}" if response else "")+ )++ reviews = []+ for document in documents:+ document_report = output_directory / f"{document.stem}.json"+ if not document_report.exists():+ raise RuntimeError(+ f"The agent did not create {document_report.name}."+ )+ report = json.loads(document_report.read_text())+ if not report.get("policy_id") or not report.get("decision"):+ raise RuntimeError(+ f"{document_report.name} does not include its policy decision."+ )+ reviews.append(+ {+ "document": document.name,+ "report": report,+ "status": "awaiting_approval",+ }+ )+ logger.info("Artifact created: %s", document_report)++ activity = await review_activity(client, session.id)+ activity_path = output_directory / "review-activity.json"+ activity_path.write_text(json.dumps(activity, indent=2) + "\n")+ logger.info(+ "Command attribution saved: %s (%s commands)",+ activity_path,+ len(activity),+ )++ return {+ "summary": "".join(parts),+ "report": json.loads(report_path.read_text()),+ "reviews": reviews,+ "status": "awaiting_approval",+ "session_id": session.id,+ "subagents": subagents,+ "activity": activity,+ "output_directory": str(output_directory),+ }+ finally:+ try:+ if container is not None:+ await asyncio.to_thread(container.stop)+ logger.info("Sandbox stopped: %s", container.short_id)+ finally:+ await client.beta.agents.sessions.delete(session.id)+ logger.info("Session deleted: %s", session.id)diff --git a/examples/agents_api/apps/document_review/main.py b/examples/agents_api/apps/document_review/main.pynew file mode 100644index 00000000..3ff2a43a--- /dev/null+++ b/examples/agents_api/apps/document_review/main.py@@ -0,0 +1,71 @@+# /// script+# requires-python = ">=3.14"+# dependencies = [+# "openai>=3.12.0",+# "docker",+# "python-dotenv",+# ]+# ///++"""Review a mounted document folder and print the resulting artifacts."""++from __future__ import annotations++import argparse+import asyncio+import logging+import sys+from pathlib import Path++from dotenv import load_dotenv++# Support direct execution from any working directory.+if __package__ in {None, ""}:+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+++from examples.agents_api.apps.document_review.agent import review_documents++EXAMPLE_DIR = Path(__file__).resolve().parent+++async def run_batch(input_directory: Path, output_directory: Path) -> None:+ batch = await review_documents(input_directory, output_directory)+ print(batch["summary"])+ print(f"\nPolicy applied: {batch['reviews'][0]['report']['policy_id']}")+ print(f"Documents reviewed: {len(batch['reviews'])}")+ print(f"Subagents created: {batch['subagents']}")+ print(f"Artifacts: {output_directory.resolve()}")+ for review in batch["reviews"]:+ print(f" - {review['document']}: {Path(review['document']).stem}.json")+ print(" - summary.json")+ print(" - review-activity.json (retained commands and turn IDs)")+ print("\nStatus: awaiting human approval")+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Review document batches in an isolated sandbox."+ )+ parser.add_argument(+ "--input",+ type=Path,+ required=True,+ metavar="DIRECTORY",+ help="Documents to review.",+ )+ parser.add_argument(+ "--output",+ type=Path,+ default=Path("review-output"),+ help="Output artifact directory.",+ )+ args = parser.parse_args()+ load_dotenv(EXAMPLE_DIR / ".env")+ logging.basicConfig(level=logging.INFO, format="%(message)s")+ logging.getLogger("httpx").setLevel(logging.WARNING)+ asyncio.run(run_batch(args.input, args.output))+++if __name__ == "__main__":+ main()diff --git a/examples/agents_api/apps/document_review/sample_documents/contract.txt b/examples/agents_api/apps/document_review/sample_documents/contract.txtnew file mode 100644index 00000000..99074aa2--- /dev/null+++ b/examples/agents_api/apps/document_review/sample_documents/contract.txt@@ -0,0 +1,14 @@+PROFESSIONAL SERVICES AGREEMENT++Customer: Northstar Studio+Provider: Canyon Consulting LLC+Start date: July 1, 2026+Initial term: 12 months+Monthly service fee: $4,500++The agreement automatically renews for an additional 24 months unless the+customer provides written notice at least 120 days before the renewal date.++The provider may increase fees at any time without advance notice.+The customer's total liability is unlimited.+The provider may share customer data with subcontractors without approval.diff --git a/examples/agents_api/apps/document_review/sample_documents/invoice.txt b/examples/agents_api/apps/document_review/sample_documents/invoice.txtnew file mode 100644index 00000000..f5227caf--- /dev/null+++ b/examples/agents_api/apps/document_review/sample_documents/invoice.txt@@ -0,0 +1,15 @@+INVOICE #INV-2048+Vendor: Cedar Office Supply+Invoice date: April 24, 2026+Payment due: May 1, 2026++Items+ 12 ergonomic chairs at $240 each: $2,880+ 6 standing desks at $410 each: $2,460++Subtotal: $5,340+Shipping: $180+Total amount due: $6,420++Purchase order: not provided+Payment instructions: Send funds to a new account before the end of the week.diff --git a/examples/agents_api/apps/document_review/sandbox.py b/examples/agents_api/apps/document_review/sandbox.pynew file mode 100644index 00000000..8be43cf1--- /dev/null+++ b/examples/agents_api/apps/document_review/sandbox.py@@ -0,0 +1,39 @@+"""Mount the input documents, output artifacts, and policy skill."""++from __future__ import annotations++import os+from pathlib import Path++import docker+from docker.models.containers import Container++EXAMPLE_DIR = Path(__file__).resolve().parent+SKILLS_DIRECTORY = EXAMPLE_DIR / "skills"+++def start_executor(+ input_directory: Path, output_directory: Path, environment_id: str, remote_url: str+) -> Container:+ return docker.from_env().containers.run(+ os.environ.get("AGENTS_SANDBOX_IMAGE", "agent-api-sandbox:latest"),+ [+ "codex",+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ],+ environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ volumes={+ str(input_directory.resolve()): {"bind": "/workspace/input", "mode": "ro"},+ str(output_directory.resolve()): {+ "bind": "/workspace/output",+ "mode": "rw",+ },+ str(SKILLS_DIRECTORY): {"bind": "/workspace/skills", "mode": "ro"},+ },+ detach=True,+ auto_remove=True,+ )diff --git a/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.md b/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.mdnew file mode 100644index 00000000..95816d7a--- /dev/null+++ b/examples/agents_api/apps/document_review/skills/expense-review-policy/SKILL.md@@ -0,0 +1,51 @@+---+name: expense-review-policy+description: Review invoices and contracts against accounts-payable policy before human approval.+---++# Expense review policy++Policy ID: `AP-104`.++Apply this policy to invoices, expense receipts, and service contracts.++## Invoices and expenses++- Read the entire invoice, including the vendor and every line item.+- Use Python to multiply quantities by unit prices and add every line total plus shipping.+- Strip currency separators, compare the result with `Total amount due`, and report the exact difference.+- Require a purchase order or another documented approval.+- Flag missing receipts, unsupported charges, and changed payment instructions.+- Escalate incorrect totals and unverified changes to bank details.++## Contracts++- Read every clause and report all matching risks, even when one already requires escalation.+- Flag automatic renewals and restrictive cancellation windows.+- Flag unilateral price increases and missing liability limits.+- Escalate customer-data sharing or subcontractor access without approval.+- Identify missing confidentiality, security, or termination terms.++## Review decision++- `needs_info`: Required documentation or supporting information is missing.+- `escalated`: Fraud indicators, financial discrepancies, or risky terms need review.+- `ready_for_approval`: No policy violations remain, but a human must still approve.++Write `/workspace/output/<document-stem>.json` with the following fields:++```json+{+ "document": "invoice.txt",+ "policy_id": "AP-104",+ "decision": "escalated",+ "vendor": "Cedar Office Supply",+ "amount": 6420,+ "issues": ["The claimed total exceeds the calculated total."],+ "recommendation": "Escalate for human review."+}+```++Every `issues` entry must be a plain-English string, not a nested object.++Never approve payments, sign contracts, or take external actions.diff --git a/examples/agents_api/apps/github_issues/.env.example b/examples/agents_api/apps/github_issues/.env.examplenew file mode 100644index 00000000..e0604530--- /dev/null+++ b/examples/agents_api/apps/github_issues/.env.example@@ -0,0 +1,3 @@+OPENAI_API_KEY=sk-...+GITHUB_TOKEN=github_pat_...+GITHUB_WEBHOOK_SECRET=...diff --git a/examples/agents_api/apps/github_issues/README.md b/examples/agents_api/apps/github_issues/README.mdnew file mode 100644index 00000000..92a676a2--- /dev/null+++ b/examples/agents_api/apps/github_issues/README.md@@ -0,0 +1,70 @@+# Turn a new GitHub issue into an investigation++Someone opens an issue. Your agent checks out the repository, reproduces the problem in an isolated sandbox, and posts a useful investigation back to GitHub.++```mermaid+sequenceDiagram+ participant User+ participant GitHub+ participant App as Webhook receiver+ participant Agent as Agents API+ participant Sandbox+ User->>GitHub: Open a new issue+ GitHub->>App: Send a signed issues.opened webhook+ App->>Agent: Create a self-hosted session+ App->>Sandbox: Clone the repository and start the executor+ Agent->>Sandbox: Inspect code and reproduce the bug+ Agent-->>App: Root cause and suggested fix+ App-->>GitHub: Post the investigation as a comment+```++## What you need++- Python 3.14+ and `uv`.+- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).+- An OpenAI API key.+- A GitHub token and webhook secret when you connect a real repository.++## 1. Set up the investigator++From the repository root:++```bash+cp examples/agents_api/apps/github_issues/.env.example examples/agents_api/apps/github_issues/.env+docker build -t agent-api-sandbox:latest examples/agents_api/sandboxes/application_managed/docker+```++Add your OpenAI API key to `examples/agents_api/apps/github_issues/.env`. You can also replace Docker with a compatible [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).++## 2. Investigate the included issue++```bash+uv run examples/agents_api/apps/github_issues/main.py --issue+```++The sample repository contains a real failing shipping test. The agent should identify why express orders accidentally qualify for free shipping and explain the smallest safe fix.++## 3. Connect a real repository++Set `GITHUB_WEBHOOK_SECRET` and `GITHUB_TOKEN` in `examples/agents_api/apps/github_issues/.env`, then start the receiver. The token needs repository read access and permission to post issue comments; it also authenticates private repository clones without appearing in the Git command:++```bash+uv run examples/agents_api/apps/github_issues/main.py+```++Expose the application through your normal hosting provider. In your GitHub repository's webhook settings:++1. Set the payload URL to `https://your-app.example/webhooks/github`.+2. Select `application/json` and enter the same webhook secret.+3. Subscribe to **Issues** events.+4. Open an issue and wait for the agent's investigation comment.++The receiver verifies GitHub signatures, ignores duplicate deliveries, and releases the sandbox after each investigation. The agent is instructed to inspect without editing; the application only posts an investigation comment and never opens a pull request.++For deployment, persist delivery IDs and use a durable job queue so failed investigations can be retried after a restart.++## Files++- [main.py](main.py): Webhook handling and the included-issue entrypoint.+- [agent.py](agent.py): Sandbox investigation and report collection.+- [github.py](github.py): Signature verification, repository cloning, and comments.diff --git a/examples/agents_api/apps/github_issues/__init__.py b/examples/agents_api/apps/github_issues/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/apps/github_issues/agent.py b/examples/agents_api/apps/github_issues/agent.pynew file mode 100644index 00000000..cea37cca--- /dev/null+++ b/examples/agents_api/apps/github_issues/agent.py@@ -0,0 +1,106 @@+"""Investigate a GitHub issue in an isolated Agents API sandbox."""++from __future__ import annotations++import asyncio+import os+from pathlib import Path+from typing import Any++import docker+from docker.models.containers import Container+from openai import AsyncOpenAI++INSTRUCTIONS = """\+Investigate GitHub issues by inspecting the repository and reproducing problems when practical.+Identify the likely cause and recommend the smallest fix.+Write your findings to /workspace/investigation.md.+Do not edit source files or contact external services.+"""+++def start_executor(workspace: Path, environment_id: str, remote_url: str) -> Container:+ return docker.from_env().containers.run(+ os.environ.get("AGENTS_SANDBOX_IMAGE", "agent-api-sandbox:latest"),+ [+ "codex",+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ],+ environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ volumes={str(workspace.resolve()): {"bind": "/workspace", "mode": "rw"}},+ detach=True,+ auto_remove=True,+ )+++async def investigate_issue(issue: dict[str, Any], workspace: Path) -> dict[str, Any]:+ container: Container | None = None+ async with AsyncOpenAI() as client:+ session = await client.beta.agents.sessions.create(+ agent={+ "model": os.environ.get("OPENAI_MODEL", "gpt-5.6-sol"),+ "instructions": INSTRUCTIONS,+ "reasoning": {"effort": "high"},+ },+ environment={"type": "self_hosted", "workspace_directory": "/workspace"},+ )++ try:+ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError("Expected a self-hosted execution environment.")+ container = await asyncio.to_thread(+ start_executor, workspace, environment.id, environment.remote_url+ )+ prompt = f"""\+Investigate GitHub issue #{issue.get("number", "?")}: {issue["title"]}++{issue.get("body", "")}++Inspect /workspace, run relevant tests, identify the root cause, and write+/workspace/investigation.md with your findings and a proposed fix.+"""+ parts: list[str] = []+ 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":+ parts.append(event.delta)+ elif (+ event.type == "agent.session.turn.output_text.done"+ and not parts+ ):+ parts.append(event.text)+ if event.type in {+ "agent.session.failed",+ "agent.session.turn.failed",+ "error",+ }:+ raise RuntimeError(+ f"Issue investigation failed: {event.to_dict()}"+ )+ if event.type == "agent.session.turn.cancelled":+ raise RuntimeError("Issue investigation was cancelled.")++ report = workspace / "investigation.md"+ if not report.exists():+ raise RuntimeError(+ "The agent did not create /workspace/investigation.md."+ )+ return {+ "issue_number": issue.get("number"),+ "session_id": session.id,+ "summary": "".join(parts),+ "findings": report.read_text(),+ }+ finally:+ try:+ if container is not None:+ await asyncio.to_thread(container.stop)+ finally:+ await client.beta.agents.sessions.delete(session.id)diff --git a/examples/agents_api/apps/github_issues/github.py b/examples/agents_api/apps/github_issues/github.pynew file mode 100644index 00000000..274cccfd--- /dev/null+++ b/examples/agents_api/apps/github_issues/github.py@@ -0,0 +1,59 @@+"""Verify GitHub deliveries, clone repositories, and post findings."""++from __future__ import annotations++import base64+import hashlib+import hmac+import os+import subprocess+from pathlib import Path+from typing import Any++import httpx+++def verify_signature(payload: bytes, signature: str, secret: str) -> bool:+ expected = (+ "sha256=" + hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()+ )+ return hmac.compare_digest(signature, expected)+++def clone_repository(url: str, workspace: Path) -> None:+ environment = os.environ.copy()+ if token := environment.get("GITHUB_TOKEN"):+ credentials = base64.b64encode(f"x-access-token:{token}".encode()).decode()+ environment.update(+ {+ "GIT_CONFIG_COUNT": "1",+ "GIT_CONFIG_KEY_0": "http.https://github.com/.extraheader",+ "GIT_CONFIG_VALUE_0": f"Authorization: Basic {credentials}",+ }+ )++ subprocess.run(+ ["git", "clone", "--depth", "1", url, str(workspace)],+ check=True,+ capture_output=True,+ text=True,+ env=environment,+ )+++async def post_findings(issue: dict[str, Any], findings: str) -> None:+ token = os.environ.get("GITHUB_TOKEN")+ comments_url = str(issue.get("comments_url", ""))+ if token and comments_url.startswith("https://api.github.com/"):+ async with httpx.AsyncClient() as http:+ response = await http.post(+ comments_url,+ json={"body": findings},+ headers={+ "Authorization": f"Bearer {token}",+ "Accept": "application/vnd.github+json",+ },+ )+ response.raise_for_status()+ else:+ print(findings)diff --git a/examples/agents_api/apps/github_issues/main.py b/examples/agents_api/apps/github_issues/main.pynew file mode 100644index 00000000..8cbfce10--- /dev/null+++ b/examples/agents_api/apps/github_issues/main.py@@ -0,0 +1,122 @@+# /// script+# requires-python = ">=3.14"+# dependencies = [+# "openai>=3.12.0",+# "docker",+# "fastapi",+# "python-dotenv",+# "uvicorn",+# ]+# ///++"""Receive GitHub issue webhooks or investigate the included issue."""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import shutil+import sys+import tempfile+from pathlib import Path+from typing import Any++from dotenv import load_dotenv+from fastapi import BackgroundTasks, FastAPI, HTTPException, Request++# Support direct execution from any working directory.+if __package__ in {None, ""}:+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+++from examples.agents_api.apps.github_issues.agent import investigate_issue+from examples.agents_api.apps.github_issues.github import (+ clone_repository,+ post_findings,+ verify_signature,+)++EXAMPLE_DIR = Path(__file__).resolve().parent+DELIVERIES: set[str] = set()+++async def handle_github_event(event: dict[str, Any]) -> None:+ issue = event["issue"]+ clone_url = event["repository"]["clone_url"]+ with tempfile.TemporaryDirectory(+ prefix=".agent-github-", dir=EXAMPLE_DIR+ ) as directory:+ workspace = Path(directory) / "repository"+ await asyncio.to_thread(clone_repository, clone_url, workspace)+ result = await investigate_issue(issue, workspace)++ await post_findings(issue, result["findings"])+++app = FastAPI(title="GitHub issue investigator")++[email protected]("/webhooks/github")+async def github_webhook(request: Request, tasks: BackgroundTasks) -> dict[str, str]:+ body = await request.body()+ secret = os.environ.get("GITHUB_WEBHOOK_SECRET", "")+ signature = request.headers.get("x-hub-signature-256", "")+ if not secret or not verify_signature(body, signature, secret):+ raise HTTPException(status_code=401, detail="Invalid webhook signature.")++ delivery = request.headers.get("x-github-delivery", "")+ if delivery and delivery in DELIVERIES:+ return {"status": "already_processed"}++ event = json.loads(body)+ event_name = request.headers.get("x-github-event", "")+ if event_name != "issues" or event.get("action") not in {+ "opened",+ "edited",+ "reopened",+ }:+ return {"status": "ignored"}++ if delivery:+ DELIVERIES.add(delivery)+ tasks.add_task(handle_github_event, event)+ return {"status": "accepted"}+++async def investigate_sample_issue() -> None:+ event = json.loads((EXAMPLE_DIR / "sample_event.json").read_text())+ with tempfile.TemporaryDirectory(+ prefix=".agent-github-", dir=EXAMPLE_DIR+ ) as directory:+ workspace = Path(directory) / "repository"+ shutil.copytree(+ EXAMPLE_DIR / "sample_repository",+ workspace,+ ignore=shutil.ignore_patterns("__pycache__"),+ )+ result = await investigate_issue(event["issue"], workspace)+ print(result["findings"])+++def main() -> None:+ parser = argparse.ArgumentParser(+ description="Investigate new GitHub issues with Agents API."+ )+ parser.add_argument(+ "--issue", action="store_true", help="Investigate the included issue."+ )+ args = parser.parse_args()+ load_dotenv(EXAMPLE_DIR / ".env")+ if args.issue:+ asyncio.run(investigate_sample_issue())+ return++ import uvicorn++ uvicorn.run(app, host="127.0.0.1", port=8002)+++if __name__ == "__main__":+ main()diff --git a/examples/agents_api/apps/github_issues/sample_event.json b/examples/agents_api/apps/github_issues/sample_event.jsonnew file mode 100644index 00000000..106921f3--- /dev/null+++ b/examples/agents_api/apps/github_issues/sample_event.json@@ -0,0 +1,13 @@+{+ "action": "opened",+ "issue": {+ "number": 42,+ "title": "Express shipping becomes free for orders over $100",+ "body": "Customers who select express shipping are not charged when their order subtotal exceeds $100. Standard shipping should be free above that threshold, but express shipping should always cost $15.",+ "comments_url": "https://api.github.com/repos/example/store/issues/42/comments"+ },+ "repository": {+ "full_name": "example/store",+ "clone_url": "https://github.com/example/store.git"+ }+}diff --git a/examples/agents_api/apps/github_issues/sample_repository/shipping.py b/examples/agents_api/apps/github_issues/sample_repository/shipping.pynew file mode 100644index 00000000..e8126fa7--- /dev/null+++ b/examples/agents_api/apps/github_issues/sample_repository/shipping.py@@ -0,0 +1,6 @@+def shipping_cost(subtotal: float, *, express: bool = False) -> float:+ if subtotal >= 100:+ return 0+ if express:+ return 15+ return 7diff --git a/examples/agents_api/apps/github_issues/sample_repository/test_shipping.py b/examples/agents_api/apps/github_issues/sample_repository/test_shipping.pynew file mode 100644index 00000000..3451bc47--- /dev/null+++ b/examples/agents_api/apps/github_issues/sample_repository/test_shipping.py@@ -0,0 +1,11 @@+import unittest++from shipping import shipping_cost # type: ignore[import-not-found]+++class ShippingTests(unittest.TestCase):+ def test_standard_shipping_is_free_over_100(self) -> None:+ self.assertEqual(shipping_cost(125), 0)++ def test_express_shipping_is_never_free(self) -> None:+ self.assertEqual(shipping_cost(125, express=True), 15)diff --git a/examples/agents_api/apps/sev_bot/.dockerignore b/examples/agents_api/apps/sev_bot/.dockerignorenew file mode 100644index 00000000..5d0f124f--- /dev/null+++ b/examples/agents_api/apps/sev_bot/.dockerignore@@ -0,0 +1,2 @@+*+!Dockerfilediff --git a/examples/agents_api/apps/sev_bot/.env.example b/examples/agents_api/apps/sev_bot/.env.examplenew file mode 100644index 00000000..6f163faa--- /dev/null+++ b/examples/agents_api/apps/sev_bot/.env.example@@ -0,0 +1,16 @@+OPENAI_API_KEY=sk-...+OPENAI_WEBHOOK_SECRET=+SLACK_BOT_TOKEN=xoxb-...+SLACK_SIGNING_SECRET=...++# Optional GitHub MCP: a repository-scoped token with read-only Contents and Pull requests.+# GITHUB_TOKEN=github_pat_...+# GITHUB_REPOSITORY=acme/checkout-api++# Optional production integrations.+# ALERT_WEBHOOK_TOKEN=...+# DEVOPS_AGENT_TOKEN=...+# DEVOPS_AGENT_REGION=us-east-1++# Map an incident.io subscription to one service in operations.json.+# INCIDENT_SERVICE=checkout-apidiff --git a/examples/agents_api/apps/sev_bot/Dockerfile b/examples/agents_api/apps/sev_bot/Dockerfilenew file mode 100644index 00000000..14ad6246--- /dev/null+++ b/examples/agents_api/apps/sev_bot/Dockerfile@@ -0,0 +1,13 @@+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 mkdir -p /workspace /codex-home+ENV CODEX_HOME=/codex-home+WORKDIR /workspace++RUN npx --yes skills add aws/agent-toolkit-for-aws/skills \+ --agent codex --copy --yesdiff --git a/examples/agents_api/apps/sev_bot/README.md b/examples/agents_api/apps/sev_bot/README.mdnew file mode 100644index 00000000..4b9e2d0a--- /dev/null+++ b/examples/agents_api/apps/sev_bot/README.md@@ -0,0 +1,209 @@+# SRE agent for incident response++An incident alert opens a Slack thread in `#oncall`. The agent investigates production telemetry, GitHub pull requests and commits, AWS infrastructure, and similar past incidents. It posts its findings and asks a responder to approve any rollback.++```mermaid+sequenceDiagram+ participant Alert as PagerDuty / incident.io+ participant Slack as Slack #oncall+ participant App as Incident bot+ participant Agent as Agents API+ participant Sandbox as Incident sandbox + AWS skills+ participant Evidence as GitHub + AWS + incident history+ Alert->>App: Send production incident+ App->>Slack: Open an incident thread+ App->>Agent: Create one persistent incident session+ App->>Sandbox: Start codex exec-server with preinstalled AWS skills+ Agent->>Sandbox: Read relevant skills and the mounted runbook+ Agent->>Evidence: Inspect code, infrastructure, and previous incidents+ Evidence-->>Agent: Return correlated operational evidence+ Agent-->>App: agent.session.action_required webhook+ App->>Agent: Retrieve the pending function call+ App->>Slack: Post rollback approval buttons+ Slack-->>App: Approve or reject+ App->>Agent: Submit the decision as a tool result+ Agent-->>Slack: Explain the decision and next steps+ Slack-->>App: Ask a follow-up+ App->>Agent: Reuse the incident session for follow-ups+ App->>Agent: Save the resolution and close the session+ App->>Sandbox: Remove the incident sandbox+```++## What you need++- Python 3.14+ and `uv`.+- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).+- An OpenAI API key.+- A Slack app installed in `#oncall`, with a bot token, signing secret, and message event subscriptions.+- PagerDuty, incident.io, or an Alertmanager-compatible monitoring system.+- Read access to the affected GitHub repository.+- AWS DevOps Agent credentials or another read-only AWS operational integration.++The first run uses bundled metrics, logs, deployments, GitHub changes, AWS telemetry, and incident history for `checkout-api`. Tool results label this sample data; it is not a live production diagnosis. Slack delivery is real. Replace the evidence tools when connecting your own incidents.++## Configure the Slack bot++From the repository root:++```bash+cp examples/agents_api/apps/sev_bot/.env.example examples/agents_api/apps/sev_bot/.env+docker build -t agent-api-sev-sandbox:latest examples/agents_api/apps/sev_bot+```++Create the Slack app from [`slack-app-manifest.yaml`](slack-app-manifest.yaml). Replace `https://your-app.example` with your application's HTTPS address, install the app, and invite it to `#oncall`.++Add `OPENAI_API_KEY`, `SLACK_BOT_TOKEN`, and `SLACK_SIGNING_SECRET` to `examples/agents_api/apps/sev_bot/.env`.++The manifest subscribes to `message.channels` and `message.groups` at `/slack/events`, and sends approval actions to `/slack/actions`. Slack must be able to reach both URLs over HTTPS. Posting the initial investigation only needs the bot token; follow-ups and approval buttons also require these callbacks.++Each incident gets a self-hosted sandbox running `codex exec-server`. The app passes your OpenAI API key as `CODEX_API_KEY` at runtime; it does not copy Slack, GitHub, or AWS credentials into the sandbox. Follow-ups reuse the sandbox, and resolution or application shutdown deletes it.++The app mounts [`runbooks/`](runbooks/) read-only at `/workspace/runbooks`. The agent reads `checkout-api.md` for mitigation steps and recovery checks. Add a runbook named after each service when connecting your own incidents.++## Connect Agents API approval webhooks++In [Project settings > Webhooks](https://platform.openai.com/settings/project/webhooks), register `https://your-app.example/webhooks/openai`, subscribe to `agent.session.action_required`, and add its signing secret as `OPENAI_WEBHOOK_SECRET` in `.env`.++With all four credentials configured, start the receiver:++```bash+uv run examples/agents_api/apps/sev_bot/main.py+```++The app verifies OpenAI's signature, retrieves the session's `required_actions`, and posts Slack buttons for `propose_rollback`. It saves the pending `turn_id` and `call_id` and ignores repeated deliveries for the same proposal. Read-only tools still run through the streaming handler; `propose_rollback` deliberately has no automatic handler.++The Slack callback returns the decision to the waiting call:++```python+import json++await client.beta.agents.sessions.events.create(+ session.id,+ events=[+ {+ "type": "agent.session.input.tool_result",+ "turn_id": action["turn_id"],+ "call_id": action["call_id"],+ "success": True,+ "output": json.dumps({"decision": "approved", "executed": False}),+ }+ ],+)+```++The agent continues after approval or rejection. Approval is not execution: the example never contacts a deployment system. Keep the app running to receive callbacks and stream the final update. OpenAI and Slack callbacks both require a reachable HTTPS address. Persist pending actions and use a durable worker when deploying beyond this single-process example.++## Send a sample incident++From another terminal, send the included alert to the receiver:++```bash+curl -X POST http://127.0.0.1:8003/webhooks/alerts \+ -H 'Content-Type: application/json' \+ --data-binary @examples/agents_api/apps/sev_bot/sample_alert.json+```++The agent posts its sample investigation to `#oncall`, tracing the outage to the fixture's pull request #418 and Redis pool exhaustion. Approve or reject the proposed rollback using the buttons in the Slack thread. Approval records a decision; it does not execute a deployment.++To inspect a real repository, configure GitHub MCP below.++## Connect incident alerts++Send incident webhooks through your authenticated ingress to:++```text+https://your-app.example/webhooks/alerts+```++For Alertmanager:++```yaml+receivers:+ - name: incident-bot+ webhook_configs:+ - url: https://your-app.example/webhooks/alerts+ http_config:+ authorization:+ credentials: your-shared-token+```++Set `ALERT_WEBHOOK_TOKEN` to the same value. Alertmanager sends it as a bearer token. Alert fingerprints deduplicate active incidents; a later alert can start a new investigation after the earlier incident is resolved.++For PagerDuty, subscribe to `incident.triggered` and `incident.resolved`, and match the PagerDuty service name to an entry in `operations.json`. For incident.io, subscribe to `public_incident.incident_created_v2` and `public_incident.incident_status_updated_v2`; set `INCIDENT_SERVICE` to the affected service for that subscription. Adapt this mapping for multi-service incidents.++The example parses these provider payloads but does not verify their native signatures. Your ingress must verify PagerDuty or incident.io signatures before forwarding them with `ALERT_WEBHOOK_TOKEN`. Slack signatures are verified by the application.++## Use AWS skills++The [Dockerfile](Dockerfile) installs the Codex CLI and all [AWS Agent Toolkit skills](https://github.com/aws/agent-toolkit-for-aws/tree/main/skills) during the image build. From `/workspace`, it runs:++```bash+npx --yes skills add aws/agent-toolkit-for-aws/skills \+ --agent codex --copy --yes+```++The skills are copied to `/workspace/.agents/skills` for automatic discovery. The agent selects relevant skills and loads their instructions as needed. Ask in the incident's Slack thread: "List the installed AWS skills and explain which ones help investigate Redis connection exhaustion."++Skills provide instructions, not AWS access. No cloud credentials are needed to read them. The sample evidence tools stay in the application; use read-only integrations for live AWS evidence. Rebuild the image to refresh its skills, and review third-party instructions before granting production access.++## Connect GitHub++Set `GITHUB_TOKEN` and `GITHUB_REPOSITORY` in `.env`. Use a fine-grained token limited to the affected repository, with read access to **Contents** and **Pull requests**.++The app connects to [GitHub MCP](https://github.com/github/github-mcp-server) through its read-only endpoint, `https://api.githubcopilot.com/mcp/readonly`. Its allowlist contains five tools: `list_commits`, `get_commit`, `list_pull_requests`, `pull_request_read`, and `get_file_contents`. Agents API calls these directly; no application handler or GitHub CLI installation is needed.++GitHub credentials stay outside the sandbox. If the configured MCP server cannot connect, the session fails rather than silently skipping repository inspection. Without `GITHUB_TOKEN`, `get_service_evidence` returns the bundled sample PRs and commits instead.++## Connect AWS++The [AWS Agent Toolkit](https://github.com/aws/agent-toolkit-for-aws) includes observability skills and an AWS DevOps Agent MCP server for infrastructure investigations. Uncomment `DEVOPS_AGENT_REGION` and `DEVOPS_AGENT_TOKEN` in `examples/agents_api/apps/sev_bot/.env`:++```text+DEVOPS_AGENT_REGION=us-east-1+DEVOPS_AGENT_TOKEN=...+```++The application registers the service-connected MCP server automatically:++```python+{+ "type": "mcp",+ "server_label": "aws_devops",+ "connection_origin": "service",+ "transport": {+ "type": "http",+ "server_url": "https://connect.aidevops.us-east-1.api.aws/mcp",+ "authorization": f"Bearer {token}",+ },+}+```++Without AWS MCP configured, `get_service_evidence` includes bundled CloudWatch, ECS, and ElastiCache telemetry. With `DEVOPS_AGENT_TOKEN` set, it omits that sample AWS data so the agent uses the MCP server for AWS evidence. The service metrics, logs, and deployments remain sample data until you connect your monitoring system.++## Incident memory++Memory works at two levels:++- **Within an incident:** The alert fingerprint and Slack thread map to one Agents API session and sandbox. Follow-up questions retain previous evidence, tool results, investigation context, and workspace files.+- **Across incidents:** `recall_incidents` searches prior reports for related symptoms, root causes, and resolutions. A resolved alert saves findings to `examples/agents_api/apps/sev_bot/incident_memory.json` before the session closes. The app reloads this file on startup, or starts with `incident_history.json` when no saved file exists.++The generated memory file is ignored by Git and replaced atomically on each save. Deleting it resets history to the bundled samples. Run one app process against this file; it is not a shared database.++Only resolved-incident history survives restarts. Active Slack threads, session IDs, pending approvals, and sandbox handles still live in memory. Approving a rollback records the decision; this example never deploys or changes production infrastructure.++## Investigation tools++- `get_service_evidence` returns metrics, recent error logs, and deployments together.+- `recall_incidents` retrieves relevant incident history and prior mitigations.+- `propose_rollback` requests human approval without changing production.++Only the first two have automatic handlers. The webhook and Slack callback complete `propose_rollback` after a responder decides. GitHub and AWS use MCP integrations; runbooks are files in the sandbox.++## Files++- [main.py](main.py): Webhook routes and application startup.+- [agent.py](agent.py): Incident investigation, approval, resolution, and cleanup.+- [alerts.py](alerts.py): Alert normalization and background task scheduling.+- [tools.py](tools.py): Service evidence and GitHub/AWS MCP tools.+- [slack.py](slack.py): Slack messages, buttons, and callback verification.+- [memory.py](memory.py): Incident history loading, search, and atomic saves.diff --git a/examples/agents_api/apps/sev_bot/__init__.py b/examples/agents_api/apps/sev_bot/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/apps/sev_bot/agent.py b/examples/agents_api/apps/sev_bot/agent.pynew file mode 100644index 00000000..024d8a6e--- /dev/null+++ b/examples/agents_api/apps/sev_bot/agent.py@@ -0,0 +1,564 @@+"""Investigate incidents and coordinate approval, resolution, and cleanup."""++from __future__ import annotations++import asyncio+import json+import logging+import os+from collections.abc import AsyncIterator+from dataclasses import dataclass, field+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++import docker+from docker.models.containers import Container+from openai import AsyncOpenAI+from openai.lib.streaming.agents import AsyncToolHandler+from openai.types.beta import AgentSessionEvent+from openai.types.beta.agents.session_create_params import Agent++from .memory import load_history, recall_incidents, save_history+from .slack import SLACK_CHANNEL, SlackChannel, approval_blocks+from .tools import PROGRESS, configured_tools, get_service, get_service_evidence++EXAMPLE_DIR = Path(__file__).resolve().parent+DOCKER_IMAGE = "agent-api-sev-sandbox:latest"+logger = logging.getLogger(__name__)+INSTRUCTIONS = """\+Investigate the incident using service evidence, GitHub, AWS, and past incidents.+Consult /workspace/runbooks/<service>.md and explain impact, likely cause, and next steps.+Use read-only tools; never install integrations or change infrastructure.+Clearly separate sample data from live findings.+If a rollout caused the incident, call propose_rollback once for the previous healthy version.+Approval records a decision, not an executed rollback.+"""+++def start_executor(environment_id: str, remote_url: str) -> Container:+ return docker.from_env().containers.run(+ DOCKER_IMAGE,+ [+ "codex",+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ],+ environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ volumes={+ str(EXAMPLE_DIR / "runbooks"): {"bind": "/workspace/runbooks", "mode": "ro"}+ },+ working_dir="/workspace",+ detach=True,+ )+++@dataclass+class Incident:+ id: str+ fingerprint: str+ service: str+ severity: str+ title: str+ team: str+ channel: str = SLACK_CHANNEL+ status: str = "investigating"+ session_id: str | None = None+ sandbox: Container | None = field(default=None, repr=False)+ slack_thread_ts: str | None = None+ slack_approval_ts: str | None = None+ analysis: str = ""+ action: dict[str, Any] | None = None+ timeline: list[dict[str, Any]] = field(default_factory=list)+ lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)+ approval_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)++ def record(self, message: str) -> None:+ self.timeline.append(+ {"time": datetime.now(UTC).strftime("%H:%M:%S UTC"), "message": message}+ )+++class IncidentBot:+ """Keep one Agents API session and approval boundary for each incident."""++ def __init__(+ self,+ client: AsyncOpenAI,+ operations: dict[str, Any] | None = None,+ *,+ slack: SlackChannel | None = None,+ history: list[dict[str, Any]] | None = None,+ history_path: Path = EXAMPLE_DIR / "incident_memory.json",+ ) -> None:+ self.client = client+ self.model = os.environ.get("OPENAI_MODEL", "gpt-5.6-sol")+ self.operations = (+ operations+ if operations is not None+ else json.loads((EXAMPLE_DIR / "operations.json").read_text())+ )+ self.slack = slack if slack is not None else SlackChannel()+ self.history_path = history_path+ if history is not None:+ self.history = [*history]+ else:+ self.history = load_history(history_path)+ self.next_incident_number = (+ max(+ [1041]+ + [+ int(str(record["id"]).removeprefix("INC-"))+ for record in self.history+ ]+ )+ + 1+ )+ self.incidents: dict[str, Incident] = {}+ self.fingerprints: dict[str, str] = {}+ self.slack_threads: dict[str, str] = {}+ self.slack_deliveries: set[str] = set()+ self.closed_sessions: set[str] = set()++ def service(self, name: str) -> dict[str, Any]:+ return get_service(self.operations, name)++ def start_incident(self, alert: dict[str, Any]) -> Incident:+ labels = alert.get("labels", {})+ annotations = alert.get("annotations", {})+ service = str(labels.get("service", ""))+ fingerprint = str(+ alert.get("fingerprint") or f"{service}:{labels.get('alertname', '')}"+ )+ existing = self.fingerprints.get(fingerprint)+ if existing is not None:+ return self.incidents[existing]++ service_info = self.service(service)+ severity = "SEV-1" if labels.get("severity") == "critical" else "SEV-2"+ incident = Incident(+ id=f"INC-{self.next_incident_number}",+ fingerprint=fingerprint,+ service=service,+ severity=severity,+ title=str(+ annotations.get("summary", labels.get("alertname", "Service alert"))+ ),+ team=str(service_info["team"]),+ )+ self.next_incident_number += 1+ incident.record(f"Received {severity} alert for {service}.")+ self.incidents[incident.id] = incident+ self.fingerprints[fingerprint] = incident.id+ return incident++ def get_service_evidence(self, arguments: dict[str, Any]) -> dict[str, Any]:+ return get_service_evidence(self.operations, arguments)++ def recall_incidents(self, arguments: dict[str, Any]) -> dict[str, Any]:+ return recall_incidents(self.history, arguments)++ def propose_rollback(+ self, incident: Incident, arguments: dict[str, Any]+ ) -> dict[str, Any]:+ service_name = str(arguments["service"])+ version = str(arguments["version"])+ if service_name != incident.service:+ raise ValueError("A rollback can only target the affected service.")++ deployments: list[dict[str, Any]] = self.service(service_name)["deployments"]+ healthy_versions = {+ str(deployment["version"])+ for deployment in deployments+ if deployment.get("status") == "previous_healthy"+ }+ if version not in healthy_versions:+ raise ValueError("A rollback must target a known healthy deployment.")++ if incident.action is None:+ incident.action = {+ "id": f"ACTION-{incident.id.removeprefix('INC-')}",+ "service": service_name,+ "version": version,+ "reason": str(arguments["reason"]),+ "status": "awaiting_approval",+ }+ incident.status = "awaiting_approval"+ incident.record(+ f"Requested approval to roll back {service_name} to {version}."+ )++ return incident.action++ async def publish(+ self,+ incident: Incident,+ text: str,+ *,+ blocks: list[dict[str, Any]] | None = None,+ ) -> dict[str, Any]:+ message = await self.slack.post(+ text, thread_ts=incident.slack_thread_ts, blocks=blocks+ )+ if incident.slack_thread_ts is None:+ incident.slack_thread_ts = str(message["ts"])+ self.slack_threads[incident.slack_thread_ts] = incident.id+ return message++ async def investigate(self, incident: Incident, question: str | None = None) -> str:+ async with incident.lock:+ if incident.status in {"resolved", "resolving"}:+ return "This incident is closing or already resolved."+ try:+ return await self._investigate(incident, question)+ except Exception as error:+ incident.status = "failed"+ incident.record(f"Investigation failed: {error}")+ await self.close_runtime(incident)+ raise++ async def _investigate(self, incident: Incident, question: str | None) -> str:+ handlers: dict[str, AsyncToolHandler] = {+ "get_service_evidence": self.get_service_evidence,+ "recall_incidents": self.recall_incidents,+ }+ prompt = (+ question+ or f"""\+Investigate {incident.severity}: {incident.title}+Affected service: {incident.service}++Inspect service health, production logs, recent deployments, GitHub pull requests and commits,+AWS infrastructure, related past incidents, and /workspace/runbooks/{incident.service}.md.+Correlate timestamps, quantify customer impact, and cite the responsible code.+If a rollout caused the incident, propose a rollback to the previous healthy version.+"""+ )++ if incident.session_id is not None:+ session = await self.client.beta.agents.sessions.retrieve(+ incident.session_id+ )+ incident.record("Received a follow-up question.")+ else:+ await self.publish(+ incident,+ f"*{incident.severity} {incident.id}* {incident.title}\n"+ f"Investigating `{incident.service}`.",+ )+ incident.record(f"Opened an incident thread in {incident.channel}.")+ agent: Agent = {+ "model": self.model,+ "instructions": INSTRUCTIONS,+ "reasoning": {"effort": "high"},+ "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},+ "tools": configured_tools(),+ }+ session = await self.client.beta.agents.sessions.create(+ agent=agent,+ environment={+ "type": "self_hosted",+ "workspace_directory": "/workspace",+ },+ )+ incident.session_id = session.id+ if incident.status == "resolving":+ return ""+ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError("Expected a self-hosted execution environment.")+ incident.sandbox = await asyncio.to_thread(+ start_executor, environment.id, environment.remote_url+ )+ incident.record("Started an incident sandbox with AWS skills.")+ logger.info(+ "%s: sandbox %s, session %s",+ incident.id,+ incident.sandbox.short_id,+ session.id,+ )++ # The webhook handles propose_rollback; do not auto-complete its tool call.+ if incident.status == "resolving":+ return ""+ async with self.client.beta.agents.sessions.stream(+ session.id, input=prompt, tool_handlers=handlers+ ) as events:+ answer = await self.collect(events, incident)+ if incident.status == "resolving":+ return answer+ if question is not None and incident.analysis:+ incident.analysis += f"\n\nFollow-up: {question}\n{answer}"+ else:+ incident.analysis = answer+ if incident.status in {"investigating", "failed"}:+ incident.status = "investigated"+ await self.publish(incident, f"*Incident update*\n{answer}")+ incident.record(f"Posted investigation results to {incident.channel}.")+ return answer++ async def collect(+ self, events: AsyncIterator[AgentSessionEvent], incident: Incident+ ) -> str:+ output: list[str] = []+ reported: set[str] = set()+ async for event in events:+ if incident.status == "resolving":+ return "".join(output)+ if event.type == "agent.session.environment.connected":+ incident.record("Connected the incident sandbox.")+ elif (+ event.type == "agent.session.turn.item.done" and event.item is not None+ ):+ if event.item.type == "command_execution":+ logger.info(+ "%s: sandbox command %s", incident.id, event.item.status+ )+ elif (+ event.type == "agent.session.turn.item.added"+ and event.item.type == "function_call"+ ):+ tool_name = event.item.name+ if tool_name in PROGRESS and tool_name not in reported:+ incident.record(PROGRESS[tool_name])+ reported.add(tool_name)+ elif (+ event.type == "agent.session.subagent.created"+ and "specialist" not in reported+ ):+ incident.record("Delegated part of the investigation to a specialist.")+ reported.add("specialist")+ elif event.type == "agent.session.turn.output_text.delta":+ output.append(event.delta)+ elif event.type == "agent.session.turn.output_text.done" and not output:+ output.append(event.text)+ elif event.type in {+ "agent.session.failed",+ "agent.session.turn.failed",+ "error",+ "agent.session.environment.failed",+ }:+ raise RuntimeError(f"Incident investigation failed: {event.to_dict()}")+ elif event.type == "agent.session.turn.cancelled":+ if incident.status == "resolving":+ return "".join(output)+ raise RuntimeError("Incident investigation was cancelled.")++ return "".join(output)++ async def request_approval(self, session_id: str) -> None:+ incident = next(+ (item for item in self.incidents.values() if item.session_id == session_id),+ None,+ )+ if incident is None:+ return+ # Independent of the stream's lock: the turn waits here for the Slack decision.+ async with incident.approval_lock:+ if incident.status in {"resolved", "resolving", "failed"}:+ return+ session = await self.client.beta.agents.sessions.retrieve(session_id)+ for action in session.required_actions:+ if action.type != "function_call" or action.name != "propose_rollback":+ continue+ if (+ incident.action is not None+ and incident.action.get("call_id") == action.call_id+ and incident.action.get("turn_id") == action.turn_id+ ):+ if incident.slack_approval_ts is not None:+ continue+ else:+ try:+ if incident.action is not None:+ raise ValueError(+ "A rollback has already been proposed for this incident."+ )+ arguments = action.arguments+ if isinstance(arguments, str):+ arguments = json.loads(arguments)+ if not isinstance(arguments, dict):+ raise ValueError("Rollback arguments must be an object.")+ incident.action = self.propose_rollback(incident, arguments)+ except (KeyError, ValueError):+ await self.client.beta.agents.sessions.events.create(+ session.id,+ events=[+ {+ "type": "agent.session.input.tool_result",+ "turn_id": action.turn_id,+ "call_id": action.call_id,+ "success": False,+ "error": "Invalid or duplicate rollback proposal.",+ }+ ],+ )+ continue+ incident.action.update(+ turn_id=action.turn_id, call_id=action.call_id+ )+ approval = await self.publish(+ incident,+ f"Approval required: {incident.action['reason']}\n"+ f"Roll back {incident.action['service']} to {incident.action['version']}?",+ blocks=approval_blocks(incident),+ )+ incident.slack_approval_ts = str(approval["ts"])++ async def decide_rollback(self, incident_id: str, approved: bool) -> dict[str, Any]:+ incident = self.incident(incident_id)+ async with incident.approval_lock:+ if incident.status in {"resolved", "resolving", "failed"}:+ raise ValueError("This incident is no longer awaiting a decision.")+ action = incident.action+ if action is None or incident.session_id is None:+ raise ValueError("No rollback is awaiting approval.")+ decision = "approved" if approved else "rejected"+ if action["status"] == decision:+ return action+ if action["status"] != "awaiting_approval":+ raise ValueError("This rollback request is no longer pending.")+ session = await self.client.beta.agents.sessions.retrieve(+ incident.session_id+ )+ if not any(+ pending.type == "function_call"+ and pending.call_id == action["call_id"]+ and pending.turn_id == action["turn_id"]+ for pending in session.required_actions+ ):+ raise ValueError("This rollback request is no longer pending.")+ await self.client.beta.agents.sessions.events.create(+ session.id,+ events=[+ {+ "type": "agent.session.input.tool_result",+ "turn_id": str(action["turn_id"]),+ "call_id": str(action["call_id"]),+ "success": True,+ "output": json.dumps(+ {+ "decision": decision,+ "executed": False,+ "service": action["service"],+ "version": action["version"],+ }+ ),+ }+ ],+ )+ action["status"] = decision+ incident.status = decision if approved else "investigated"+ incident.record(f"Rollback {decision}; returned the decision to the agent.")+ return action++ async def submit_slack_decision(self, incident_id: str, approved: bool) -> None:+ incident = self.incident(incident_id)+ try:+ decision = await self.decide_rollback(incident_id, approved)+ except Exception:+ logger.exception(+ "Could not submit the rollback decision for %s", incident_id+ )+ await self.publish(+ incident, "Could not submit the decision. Check the logs and retry."+ )+ return+ await self.publish(+ incident,+ f"Rollback {decision['status']}. The agent received the decision; no deployment ran.",+ )++ def incident(self, incident_id: str) -> Incident:+ incident = self.incidents.get(incident_id)+ if incident is None:+ raise ValueError(f"Unknown incident: {incident_id}")+ return incident++ async def resolve(self, incident_id: str) -> None:+ incident = self.incident(incident_id)+ async with incident.approval_lock:+ if incident.status == "resolved":+ return+ active = incident.lock.locked() or incident.status == "awaiting_approval"+ incident.status = "resolving"+ if active and incident.session_id is not None:+ await self.client.beta.agents.sessions.events.create(+ incident.session_id, events=[{"type": "agent.session.input.cancel"}]+ )+ async with incident.lock:+ await self._resolve(incident)++ async def _resolve(self, incident: Incident) -> None:+ if incident.status == "resolved":+ return+ history: list[dict[str, Any]] = [+ *self.history,+ {+ "id": incident.id,+ "service": incident.service,+ "summary": incident.title,+ "root_cause": incident.analysis[:1200],+ "resolution": (+ f"Rollback to {incident.action['version']} was approved; "+ "execution was not recorded."+ if incident.action is not None+ and incident.action["status"] == "approved"+ else "Resolved without a recorded rollback."+ ),+ },+ ]+ try:+ save_history(self.history_path, history)+ self.history = history+ incident.status = "resolved"+ if (+ incident.action is not None+ and incident.action["status"] == "awaiting_approval"+ ):+ incident.action["status"] = "expired"+ if incident.slack_thread_ts is not None:+ await self.publish(+ incident, f"Resolved {incident.id}; saved the incident findings."+ )+ except OSError:+ if incident.status != "resolved":+ incident.status = "failed"+ raise+ finally:+ if incident.status == "resolved":+ if incident.slack_thread_ts is not None:+ self.slack_threads.pop(incident.slack_thread_ts, None)+ self.fingerprints.pop(incident.fingerprint, None)+ await self.close_runtime(incident)+ incident.record("Closed the incident session and sandbox.")++ async def close_runtime(self, incident: Incident) -> None:+ try:+ if (+ incident.session_id is not None+ and incident.session_id not in self.closed_sessions+ ):+ await self.client.beta.agents.sessions.delete(incident.session_id)+ self.closed_sessions.add(incident.session_id)+ incident.session_id = None+ finally:+ if incident.sandbox is not None:+ await asyncio.to_thread(incident.sandbox.remove, force=True)+ logger.info(+ "%s: removed sandbox %s", incident.id, incident.sandbox.short_id+ )+ incident.sandbox = None++ async def close(self) -> None:+ errors: list[Exception] = []+ for incident in self.incidents.values():+ try:+ await self.close_runtime(incident)+ except Exception as error:+ errors.append(error)+ if errors:+ raise ExceptionGroup("Could not close all incident runtimes", errors)diff --git a/examples/agents_api/apps/sev_bot/alerts.py b/examples/agents_api/apps/sev_bot/alerts.pynew file mode 100644index 00000000..882920c3--- /dev/null+++ b/examples/agents_api/apps/sev_bot/alerts.py@@ -0,0 +1,160 @@+"""Normalize incident-provider alerts and schedule independent investigations."""++from __future__ import annotations++import asyncio+import logging+import os+from typing import Any++from fastapi import BackgroundTasks, HTTPException++from .agent import IncidentBot++logger = logging.getLogger(__name__)+++def normalize_alerts(payload: dict[str, Any]) -> list[dict[str, Any]]:+ alerts = payload.get("alerts")+ if isinstance(alerts, list):+ if not all(isinstance(alert, dict) for alert in alerts):+ raise HTTPException(status_code=400, detail="Each alert must be an object.")+ return [+ {+ **alert,+ "status": alert.get("status", payload.get("status", "firing")),+ "fingerprint": alert.get("fingerprint")+ or f"{alert.get('labels', {}).get('service', '')}:"+ f"{alert.get('labels', {}).get('alertname', '')}",+ }+ for alert in alerts+ ]++ event = payload.get("event")+ if isinstance(event, dict) and isinstance(event.get("data"), dict):+ event_type = str(event.get("event_type", ""))+ if event_type not in {"incident.triggered", "incident.resolved"}:+ return []+ data = event["data"]+ service = data.get("service", {})+ details = data.get("custom_details", {})+ service_name = (+ details.get("service") or service.get("name") or service.get("summary")+ )+ return [+ {+ "fingerprint": f"pagerduty:{data['id']}",+ "status": "resolved" if event_type.endswith(".resolved") else "firing",+ "labels": {+ "service": service_name,+ "severity": "critical"+ if data.get("urgency") == "high"+ else "warning",+ "alertname": event_type,+ },+ "annotations": {+ "summary": str(data.get("title") or data.get("summary", ""))+ },+ }+ ]++ incident_event_type = payload.get("event_type")+ if isinstance(incident_event_type, str):+ if incident_event_type not in {+ "public_incident.incident_created_v2",+ "public_incident.incident_status_updated_v2",+ }:+ return []+ data = payload[incident_event_type]+ data = data.get("incident", data)+ service_name = os.environ.get("INCIDENT_SERVICE")+ if not service_name:+ raise HTTPException(+ status_code=400,+ detail="Set INCIDENT_SERVICE for this incident.io subscription.",+ )+ category = data.get("incident_status", {}).get("category", "live")+ return [+ {+ "fingerprint": f"incidentio:{data['id']}",+ "status": (+ "resolved"+ if category+ in {"learning", "closed", "declined", "merged", "canceled"}+ else "firing"+ ),+ "labels": {+ "service": service_name,+ "severity": (+ "critical"+ if (data.get("severity") or {}).get("name", "").lower()+ in {"critical", "sev-1"}+ else "warning"+ ),+ "alertname": incident_event_type,+ },+ "annotations": {"summary": str(data.get("name", ""))},+ }+ ]++ raise HTTPException(+ status_code=400,+ detail="Expected an Alertmanager, PagerDuty, or incident.io incident webhook.",+ )+++async def run_incident_tasks(tasks: BackgroundTasks) -> None:+ # One incident waiting for approval must not hold up the rest of an alert batch.+ results = await asyncio.gather(+ *(task() for task in tasks.tasks), return_exceptions=True+ )+ for result in results:+ if isinstance(result, Exception):+ logger.error("Incident background task failed", exc_info=result)+++def queue_alerts(+ bot: IncidentBot, payload: dict[str, Any], tasks: BackgroundTasks+) -> dict[str, Any]:+ alerts = normalize_alerts(payload)+ incident_tasks = BackgroundTasks()++ accepted: list[str] = []+ duplicates: list[str] = []+ for alert in alerts:+ fingerprint = str(alert.get("fingerprint", ""))+ existing = bot.fingerprints.get(fingerprint)+ if alert.get("status") == "resolved":+ if existing is not None:+ incident_tasks.add_task(bot.resolve, existing)+ accepted.append(existing)+ continue++ if existing is not None:+ incident = bot.incident(existing)+ if incident.status == "failed":+ incident.status = "investigating"+ incident_tasks.add_task(bot.investigate, incident)+ accepted.append(existing)+ else:+ duplicates.append(existing)+ continue++ try:+ incident = bot.start_incident(alert)+ except ValueError as error:+ raise HTTPException(status_code=400, detail=str(error)) from error+ accepted.append(incident.id)+ incident_tasks.add_task(bot.investigate, incident)++ if incident_tasks.tasks:+ tasks.add_task(run_incident_tasks, incident_tasks)++ return {+ "status": "accepted"+ if accepted+ else "already_tracking"+ if duplicates+ else "ignored",+ "incidents": accepted or duplicates,+ }diff --git a/examples/agents_api/apps/sev_bot/incident_history.json b/examples/agents_api/apps/sev_bot/incident_history.jsonnew file mode 100644index 00000000..107efae8--- /dev/null+++ b/examples/agents_api/apps/sev_bot/incident_history.json@@ -0,0 +1,22 @@+[+ {+ "id": "INC-0931",+ "source": "bundled_sample",+ "service": "checkout-api",+ "date": "2026-07-14",+ "summary": "Checkout requests timed out after a Redis pool-size change.",+ "root_cause": "A deployment reduced max_connections below peak concurrent checkout requests.",+ "resolution": "Rolled back the deployment and restored the previous Redis pool size.",+ "follow_up": "Add a deployment check for Redis connection capacity."+ },+ {+ "id": "INC-0874",+ "source": "bundled_sample",+ "service": "checkout-api",+ "date": "2026-06-18",+ "summary": "Checkout latency increased while an upstream payment gateway was degraded.",+ "root_cause": "The payment gateway exceeded its response timeout.",+ "resolution": "Enabled the gateway circuit breaker until the upstream service recovered.",+ "follow_up": "Track gateway latency independently from Redis pool saturation."+ }+]diff --git a/examples/agents_api/apps/sev_bot/main.py b/examples/agents_api/apps/sev_bot/main.pynew file mode 100644index 00000000..cf103b60--- /dev/null+++ b/examples/agents_api/apps/sev_bot/main.py@@ -0,0 +1,168 @@+# /// script+# requires-python = ">=3.14"+# dependencies = [+# "openai>=3.12.0",+# "aiohttp",+# "docker",+# "fastapi",+# "python-dotenv",+# "slack-sdk",+# "uvicorn",+# ]+# ///++"""Receive incident alerts, Agents API webhooks, and Slack callbacks."""++from __future__ import annotations++import hmac+import json+import logging+import os+import sys+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Any+from urllib.parse import parse_qs++from dotenv import load_dotenv+from fastapi import BackgroundTasks, FastAPI, HTTPException, Request+from openai import AsyncOpenAI, InvalidWebhookSignatureError, OpenAI++# Support direct execution from any working directory.+if __package__ in {None, ""}:+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+++from examples.agents_api.apps.sev_bot.agent import IncidentBot+from examples.agents_api.apps.sev_bot.alerts import queue_alerts+from examples.agents_api.apps.sev_bot.slack import verify_slack_request++EXAMPLE_DIR = Path(__file__).resolve().parent+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncIterator[None]:+ if not os.environ.get("OPENAI_WEBHOOK_SECRET"):+ raise RuntimeError(+ "Configure the Agents API webhook and set OPENAI_WEBHOOK_SECRET."+ )+ async with AsyncOpenAI() as client:+ app.state.bot = IncidentBot(client)+ try:+ yield+ finally:+ await app.state.bot.close()+++app = FastAPI(title="SRE agent for incident response", lifespan=lifespan)++[email protected]("/webhooks/alerts")+async def receive_alert(request: Request, tasks: BackgroundTasks) -> dict[str, Any]:+ expected = os.environ.get("ALERT_WEBHOOK_TOKEN")+ authorization = request.headers.get("authorization", "")+ if expected and not hmac.compare_digest(authorization, f"Bearer {expected}"):+ raise HTTPException(status_code=401, detail="Invalid alert webhook token.")++ payload = await request.json()+ if not isinstance(payload, dict):+ raise HTTPException(+ status_code=400, detail="Expected an incident webhook payload."+ )+ return queue_alerts(app.state.bot, payload, tasks)++[email protected]("/webhooks/openai")+async def openai_webhook(request: Request) -> dict[str, Any]:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret:+ raise HTTPException(status_code=500, detail="Set OPENAI_WEBHOOK_SECRET.")+ body = await request.body()+ try:+ with OpenAI(webhook_secret=secret) as verifier:+ verifier.webhooks.verify_signature(payload=body, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError) as error:+ raise HTTPException(+ status_code=401, detail="Invalid OpenAI webhook signature."+ ) from error+ try:+ event = json.loads(body)+ except ValueError as error:+ raise HTTPException(status_code=400, detail="Invalid webhook JSON.") from error+ if event.get("type") == "agent.session.action_required":+ data = event["data"]+ if data.get("required_action", {}).get("type") == "function_call":+ # Finish before acknowledging so a failed Slack delivery can be retried.+ await app.state.bot.request_approval(data["id"])+ return {"status": "ok"}++[email protected]("/slack/events")+async def slack_events(request: Request, tasks: BackgroundTasks) -> dict[str, Any]:+ body = await request.body()+ verify_slack_request(body, request)+ payload = json.loads(body)+ if payload.get("type") == "url_verification":+ return {"challenge": str(payload["challenge"])}++ bot: IncidentBot = app.state.bot+ delivery = str(payload.get("event_id", ""))+ if delivery and delivery in bot.slack_deliveries:+ return {"status": "already_processed"}++ event = payload.get("event", {})+ if not isinstance(event, dict) or event.get("bot_id") or event.get("subtype"):+ return {"status": "ignored"}++ incident_id = bot.slack_threads.get(str(event.get("thread_ts", "")))+ if incident_id is None:+ return {"status": "ignored"}++ if delivery:+ bot.slack_deliveries.add(delivery)+ tasks.add_task(+ bot.investigate, bot.incident(incident_id), str(event.get("text", ""))+ )+ return {"status": "accepted"}++[email protected]("/slack/actions")+async def slack_actions(request: Request, tasks: BackgroundTasks) -> dict[str, Any]:+ body = await request.body()+ verify_slack_request(body, request)+ encoded = parse_qs(body.decode()).get("payload", [])+ if not encoded:+ raise HTTPException(status_code=400, detail="Missing Slack action payload.")++ payload = json.loads(encoded[0])+ action = payload["actions"][0]+ bot: IncidentBot = app.state.bot+ incident_id = str(action["value"])+ try:+ if action["action_id"] not in {"approve_rollback", "reject_rollback"}:+ raise ValueError("Unknown Slack approval action.")+ bot.incident(incident_id)+ except ValueError as error:+ raise HTTPException(status_code=400, detail=str(error)) from error++ tasks.add_task(+ bot.submit_slack_decision,+ incident_id,+ action["action_id"] == "approve_rollback",+ )+ return {"text": "Submitting your decision to the agent."}+++def main() -> None:+ import uvicorn++ load_dotenv(EXAMPLE_DIR / ".env")+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")+ logging.getLogger("httpx").setLevel(logging.WARNING)+ uvicorn.run(app, host="127.0.0.1", port=8003)+++if __name__ == "__main__":+ main()diff --git a/examples/agents_api/apps/sev_bot/memory.py b/examples/agents_api/apps/sev_bot/memory.pynew file mode 100644index 00000000..d71d4881--- /dev/null+++ b/examples/agents_api/apps/sev_bot/memory.py@@ -0,0 +1,37 @@+"""Load, search, and atomically save resolved incident history."""++from __future__ import annotations++import json+import re+from pathlib import Path+from typing import Any, cast+++def load_history(path: Path) -> list[dict[str, Any]]:+ source = (+ path if path.exists() else Path(__file__).with_name("incident_history.json")+ )+ return cast(list[dict[str, Any]], json.loads(source.read_text()))+++def save_history(path: Path, history: list[dict[str, Any]]) -> None:+ temporary = path.with_suffix(".json.tmp")+ temporary.write_text(json.dumps(history, indent=2) + "\n")+ temporary.replace(path)+++def recall_incidents(+ history: list[dict[str, Any]], arguments: dict[str, Any]+) -> dict[str, Any]:+ name = str(arguments["service"])+ words = set(re.findall(r"[a-z0-9]+", str(arguments["query"]).lower()))+ candidates = [record for record in history if record.get("service") == name]+ ranked = sorted(+ candidates,+ key=lambda record: len(+ words.intersection(re.findall(r"[a-z0-9]+", json.dumps(record).lower()))+ ),+ reverse=True,+ )+ return {"service": name, "incidents": ranked[:3]}diff --git a/examples/agents_api/apps/sev_bot/operations.json b/examples/agents_api/apps/sev_bot/operations.jsonnew file mode 100644index 00000000..e51aa372--- /dev/null+++ b/examples/agents_api/apps/sev_bot/operations.json@@ -0,0 +1,105 @@+{+ "checkout-api": {+ "team": "Payments SRE",+ "repository": "acme/checkout-api",+ "metrics": {+ "baseline": {+ "error_rate_percent": 0.4,+ "p95_latency_ms": 240,+ "requests_per_minute": 4200+ },+ "current": {+ "error_rate_percent": 18.7,+ "p95_latency_ms": 1960,+ "requests_per_minute": 4180,+ "affected_checkouts_per_minute": 782+ }+ },+ "logs": [+ {+ "time": "10:07:14 UTC",+ "level": "error",+ "message": "Redis connection pool exhausted: max_connections=8, waiting=143"+ },+ {+ "time": "10:07:19 UTC",+ "level": "error",+ "message": "Checkout request timed out while waiting for a Redis connection"+ },+ {+ "time": "10:08:03 UTC",+ "level": "warning",+ "message": "Payment retries increased after checkout-api deployment 2026.08.26.4"+ },+ {+ "time": "10:08:27 UTC",+ "level": "error",+ "message": "Redis pool wait exceeded 1800ms; checkout request aborted"+ }+ ],+ "deployments": [+ {+ "version": "2026.08.26.4",+ "time": "10:06 UTC",+ "status": "active",+ "change": "Reduced Redis max_connections from 64 to 8."+ },+ {+ "version": "2026.08.26.3",+ "time": "09:12 UTC",+ "status": "previous_healthy",+ "change": "Routine dependency updates; error rate remained below 0.5%."+ }+ ],+ "pull_requests": [+ {+ "number": 418,+ "title": "Reduce checkout Redis connection footprint",+ "merged_at": "10:05 UTC",+ "commit": "8c41f2e",+ "url": "https://github.com/acme/checkout-api/pull/418",+ "files": [+ {+ "filename": "config/redis.yaml",+ "patch": "- max_connections: 64\n+ max_connections: 8"+ }+ ]+ }+ ],+ "commits": [+ {+ "sha": "8c41f2e",+ "message": "Reduce checkout Redis connection footprint",+ "time": "10:05 UTC",+ "files": ["config/redis.yaml"]+ },+ {+ "sha": "b792d10",+ "message": "Update checkout service dependencies",+ "time": "09:12 UTC",+ "files": ["pyproject.toml"]+ }+ ],+ "aws": {+ "region": "us-east-1",+ "cloudwatch": {+ "alarm": "checkout-api-5xx-rate",+ "state": "ALARM",+ "error_rate_percent": 18.7,+ "p95_latency_ms": 1960+ },+ "ecs": {+ "cluster": "checkout-production",+ "service": "checkout-api",+ "deployment": "2026.08.26.4",+ "running_tasks": 6,+ "desired_tasks": 6+ },+ "elasticache": {+ "cluster": "checkout-redis",+ "connection_limit": 8,+ "waiting_requests": 143+ }+ }+ }+}diff --git a/examples/agents_api/apps/sev_bot/runbooks/checkout-api.md b/examples/agents_api/apps/sev_bot/runbooks/checkout-api.mdnew file mode 100644index 00000000..d2b6d53a--- /dev/null+++ b/examples/agents_api/apps/sev_bot/runbooks/checkout-api.md@@ -0,0 +1,13 @@+# Checkout API: Redis connection-pool exhaustion++Sample runbook for the bundled `checkout-api` incident.++## Mitigation++Roll back to the last healthy deployment after incident commander approval.+The example records approval but does not execute the rollback.++## Verification++After a responder performs the rollback, confirm the error rate drops below 1%+and p95 latency falls below 400 ms. Use fresh evidence before declaring recovery.diff --git a/examples/agents_api/apps/sev_bot/sample_alert.json b/examples/agents_api/apps/sev_bot/sample_alert.jsonnew file mode 100644index 00000000..22bdd6fc--- /dev/null+++ b/examples/agents_api/apps/sev_bot/sample_alert.json@@ -0,0 +1,20 @@+{+ "receiver": "sev-bot",+ "status": "firing",+ "alerts": [+ {+ "status": "firing",+ "labels": {+ "alertname": "CheckoutHighErrorRate",+ "service": "checkout-api",+ "severity": "critical"+ },+ "annotations": {+ "summary": "Checkout API error rate reached 18.7%",+ "description": "Customer checkout requests are timing out after a production rollout."+ },+ "startsAt": "2026-08-26T10:09:00Z",+ "fingerprint": "checkout-api-high-error-rate"+ }+ ]+}diff --git a/examples/agents_api/apps/sev_bot/slack-app-manifest.yaml b/examples/agents_api/apps/sev_bot/slack-app-manifest.yamlnew file mode 100644index 00000000..b9ed4a1c--- /dev/null+++ b/examples/agents_api/apps/sev_bot/slack-app-manifest.yaml@@ -0,0 +1,22 @@+display_information:+ name: SRE Agent+features:+ bot_user:+ display_name: SRE Agent+ always_online: false+oauth_config:+ scopes:+ bot:+ - chat:write+ - channels:history+ - groups:history+settings:+ event_subscriptions:+ request_url: https://your-app.example/slack/events+ bot_events:+ - message.channels+ - message.groups+ interactivity:+ is_enabled: true+ request_url: https://your-app.example/slack/actions+ socket_mode_enabled: falsediff --git a/examples/agents_api/apps/sev_bot/slack.py b/examples/agents_api/apps/sev_bot/slack.pynew file mode 100644index 00000000..d392125f--- /dev/null+++ b/examples/agents_api/apps/sev_bot/slack.py@@ -0,0 +1,99 @@+"""Publish incident messages and verify Slack callbacks."""++from __future__ import annotations++import hashlib+import hmac+import os+import time+from typing import TYPE_CHECKING, Any++from fastapi import HTTPException, Request+from slack_sdk.web.async_client import AsyncWebClient++if TYPE_CHECKING:+ from .agent import Incident++SLACK_CHANNEL = "#oncall"+++class SlackChannel:+ """Post incident updates and approval buttons to a Slack thread."""++ def __init__(self, token: str | None = None, channel: str = SLACK_CHANNEL) -> None:+ self.channel = channel+ self.client = AsyncWebClient(token=token or os.environ["SLACK_BOT_TOKEN"])++ async def post(+ self,+ text: str,+ *,+ thread_ts: str | None = None,+ blocks: list[dict[str, Any]] | None = None,+ ) -> dict[str, Any]:+ payload: dict[str, Any] = {"channel": self.channel, "text": text}+ if thread_ts is not None:+ payload["thread_ts"] = thread_ts+ if blocks is not None:+ payload["blocks"] = blocks+ response = await self.client.chat_postMessage(**payload)+ return {"channel": str(response["channel"]), "ts": str(response["ts"])}+++def approval_blocks(incident: Incident) -> list[dict[str, Any]]:+ if incident.action is None:+ raise ValueError("No rollback has been proposed.")+ return [+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": (+ "*Rollback approval required*\n"+ f"`{incident.action['service']}` to `{incident.action['version']}`\n"+ f"{incident.action['reason']}\n"+ "Approval records a decision; it does not execute a deployment."+ ),+ },+ },+ {+ "type": "actions",+ "elements": [+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "Approve proposal"},+ "style": "primary",+ "action_id": "approve_rollback",+ "value": incident.id,+ },+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "Reject"},+ "action_id": "reject_rollback",+ "value": incident.id,+ },+ ],+ },+ ]+++def verify_slack_request(body: bytes, request: Request) -> None:+ secret = os.environ.get("SLACK_SIGNING_SECRET")+ if not secret:+ raise HTTPException(status_code=500, detail="Set SLACK_SIGNING_SECRET.")++ timestamp = request.headers.get("x-slack-request-timestamp", "")+ signature = request.headers.get("x-slack-signature", "")+ try:+ if abs(time.time() - int(timestamp)) > 300:+ raise ValueError("Expired request.")+ except ValueError as error:+ raise HTTPException(+ status_code=401, detail="Invalid Slack request timestamp."+ ) from error++ digest = hmac.new(+ secret.encode(), b"v0:" + timestamp.encode() + b":" + body, hashlib.sha256+ ).hexdigest()+ if not hmac.compare_digest(signature, f"v0={digest}"):+ raise HTTPException(status_code=401, detail="Invalid Slack request signature.")diff --git a/examples/agents_api/apps/sev_bot/tools.py b/examples/agents_api/apps/sev_bot/tools.pynew file mode 100644index 00000000..2893656f--- /dev/null+++ b/examples/agents_api/apps/sev_bot/tools.py@@ -0,0 +1,129 @@+"""Configure incident tools and read service evidence."""++from __future__ import annotations++import os+from typing import Any, cast++from openai.types.beta import AgentToolParam+from openai.types.beta.agent_tool_param import (+ AgentToolConfigParamFunction,+ AgentToolConfigParamMcp,+)+++def define_tool(+ name: str, description: str, *fields: str+) -> AgentToolConfigParamFunction:+ return {+ "type": "function",+ "name": name,+ "description": description,+ "parameters": {+ "type": "object",+ "properties": {field: {"type": "string"} for field in fields},+ "required": list(fields),+ "additionalProperties": False,+ },+ }+++TOOLS: list[AgentToolParam] = [+ define_tool(+ "get_service_evidence",+ "Inspect service metrics, recent error logs, deployments, and bundled AWS evidence.",+ "service",+ ),+ define_tool(+ "recall_incidents",+ "Find related past incidents, root causes, and mitigations.",+ "service",+ "query",+ ),+ define_tool(+ "propose_rollback",+ "Request human approval to roll back to a known healthy deployment. Never executes it.",+ "service",+ "version",+ "reason",+ ),+ {"type": "programmatic_tool_calling", "enabled": True},+]+PROGRESS = {+ "get_service_evidence": "Checking service metrics, logs, and recent deployments.",+ "recall_incidents": "Retrieving related incident history.",+ "propose_rollback": "Preparing a rollback proposal for review.",+}+++def configured_tools() -> list[AgentToolParam]:+ tools = [*TOOLS]+ github_token = os.environ.get("GITHUB_TOKEN")+ if github_token:+ github_tool: AgentToolConfigParamMcp = {+ "type": "mcp",+ "server_label": "github",+ "connection_origin": "service",+ "required": True,+ "allowed_tools": [+ "list_commits",+ "get_commit",+ "list_pull_requests",+ "pull_request_read",+ "get_file_contents",+ ],+ "transport": {+ "type": "http",+ "server_url": "https://api.githubcopilot.com/mcp/readonly",+ "authorization": f"Bearer {github_token}",+ },+ }+ tools.append(github_tool)+ token = os.environ.get("DEVOPS_AGENT_TOKEN")+ if token:+ region = os.environ.get("DEVOPS_AGENT_REGION", "us-east-1")+ aws_tool: AgentToolConfigParamMcp = {+ "type": "mcp",+ "server_label": "aws_devops",+ "connection_origin": "service",+ "transport": {+ "type": "http",+ "server_url": f"https://connect.aidevops.{region}.api.aws/mcp",+ "authorization": f"Bearer {token}",+ },+ }+ tools.append(aws_tool)+ return tools+++def get_service(operations: dict[str, Any], name: str) -> dict[str, Any]:+ record = operations.get(name)+ if not isinstance(record, dict):+ raise ValueError(f"Unknown service: {name}")+ return cast(dict[str, Any], record)+++def get_service_evidence(+ operations: dict[str, Any], arguments: dict[str, Any]+) -> dict[str, Any]:+ name = str(arguments["service"])+ service = get_service(operations, name)+ evidence: dict[str, Any] = {+ "source": "bundled_sample",+ "service": name,+ "team": str(service["team"]),+ "metrics": service["metrics"],+ "logs": service["logs"][-20:],+ "deployments": service["deployments"],+ }+ if not os.environ.get("DEVOPS_AGENT_TOKEN"):+ evidence["aws"] = service["aws"]+ evidence["repository"] = str(service["repository"])+ if os.environ.get("GITHUB_TOKEN"):+ evidence["repository"] = os.environ.get(+ "GITHUB_REPOSITORY", str(service["repository"])+ )+ else:+ evidence["pull_requests"] = service["pull_requests"]+ evidence["commits"] = service["commits"]+ return evidencediff --git a/examples/agents_api/apps/slack_bot/.env.example b/examples/agents_api/apps/slack_bot/.env.examplenew file mode 100644index 00000000..e0308450--- /dev/null+++ b/examples/agents_api/apps/slack_bot/.env.example@@ -0,0 +1,15 @@+OPENAI_API_KEY=sk-...+SLACK_BOT_TOKEN=xoxb-...+SLACK_APP_TOKEN=xapp-...++# Optional shared workplace integrations.+NOTION_TOKEN=+GOOGLE_DRIVE_TOKEN=+GITHUB_TOKEN=++# Optional Google Drive OAuth refresh. Obtain the grant through your Google OAuth app.+GOOGLE_DRIVE_REFRESH_TOKEN=+GOOGLE_DRIVE_CLIENT_ID=+GOOGLE_DRIVE_CLIENT_SECRET=+# Access-token expiration as an ISO 8601 timestamp, when available.+GOOGLE_DRIVE_TOKEN_EXPIRES_AT=diff --git a/examples/agents_api/apps/slack_bot/README.md b/examples/agents_api/apps/slack_bot/README.mdnew file mode 100644index 00000000..a7b7f4d5--- /dev/null+++ b/examples/agents_api/apps/slack_bot/README.md@@ -0,0 +1,134 @@+# Build an AI teammate for Slack++Tag your bot in Slack to search conversations, investigate projects, analyze data,+or prepare a GitHub pull request. Each Slack thread gets its own Agents API+session and isolated workspace.++```mermaid+sequenceDiagram+ participant Person+ participant Slack+ participant Agent as Agents API+ participant Tools as Slack tools and shared apps+ participant Sandbox as Thread sandbox+ Person->>Slack: @Agent Teammate Investigate this issue+ Slack->>Agent: Create or resume the thread's session+ Agent->>Tools: Search Slack, Notion, Drive, or GitHub+ Agent->>Sandbox: Analyze data or prepare repository changes+ Agent-->>Slack: Stream progress and reply in the thread+ Person->>Slack: @Agent Teammate Open a pull request+ Slack->>Agent: Continue the same session+```++## What you need++- Python 3.14+ and `uv`.+- A sandbox: self-hosted Docker or a [third-party provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).+- An OpenAI API key.+- A Slack workspace where you can install an internal application.++## 1. Build the sandbox image++From the repository root:++```bash+cp examples/agents_api/apps/slack_bot/.env.example examples/agents_api/apps/slack_bot/.env+docker build -t agent-api-sandbox:latest examples/agents_api/sandboxes/application_managed/docker+```++Add your OpenAI API key to `examples/agents_api/apps/slack_bot/.env`. The application loads this file automatically.++For production, you can replace Docker with a hosted [sandbox provider](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#sandbox-providers).++## 2. Create the Slack app++1. Create an app using `examples/agents_api/apps/slack_bot/slack-app-manifest.yaml`.+2. Install it in your workspace and copy the **Bot User OAuth Token**.+3. Create an app-level token with the `connections:write` scope.++Add both tokens to `examples/agents_api/apps/slack_bot/.env`:++```bash+SLACK_BOT_TOKEN=xoxb-...+SLACK_APP_TOKEN=xapp-...+```++Start the bot:++```bash+uv run examples/agents_api/apps/slack_bot/main.py+```++Socket Mode receives messages without a public webhook or OAuth callback. The+bot can read only conversations it belongs to.++## 3. Tag the bot in Slack++Invite the bot to a channel, then mention it:++```text+@Agent Teammate Summarize this week's launch decisions and find the owner.+```++Follow up in the same Slack thread:++```text+Find the related GitHub issue and explain the likely cause.++Reproduce the problem, prepare a fix, and open a pull request.++Only include customer-facing changes.+```++The first message creates a `self_hosted` Agents API session and starts a Docker+container running `codex exec-server`. Replies reuse the same session and+workspace. Send `stop` to cancel an active request.++## Connect shared workplace tools++The bot already has tools for searching the current Slack channel, reading recent+messages, finding teammates, and listing shared files. Add any optional shared+workplace credentials to `.env`:++```bash+NOTION_TOKEN=...+GOOGLE_DRIVE_TOKEN=...+GITHUB_TOKEN=...+```++The application stores configured credentials in one shared vault for the Slack+workspace and connects the corresponding MCP servers:++- Notion: `https://mcp.notion.com/mcp`+- Google Drive: `https://drivemcp.googleapis.com/mcp/v1`+- GitHub: `https://api.githubcopilot.com/mcp/`++Notion and Google Drive require OAuth access tokens for the shared account;+Notion's hosted MCP server does not accept internal integration secrets. GitHub+accepts an appropriately scoped personal access token. Everyone who can use the+bot shares these connections, so grant the account access only to documents and+repositories intended for that audience. Opening a pull request also requires a+GitHub credential with the necessary repository permissions.++### Let Agents API refresh Google Drive access++Obtain a grant through your [Google OAuth app](https://developers.google.com/identity/protocols/oauth2/web-server#offline), requesting offline access and only the Drive scopes your bot needs. Add the grant to `.env`:++```bash+GOOGLE_DRIVE_TOKEN=...+GOOGLE_DRIVE_REFRESH_TOKEN=...+GOOGLE_DRIVE_CLIENT_ID=...+GOOGLE_DRIVE_CLIENT_SECRET=...+GOOGLE_DRIVE_TOKEN_EXPIRES_AT=2026-09-01T12:00:00Z+```++Use the access token's actual expiration, or leave that field empty if unknown. The bot creates a `mcp_oauth` vault credential with Google's token endpoint and refresh configuration. Agents API refreshes the access token when needed; your application owns the initial consent flow.++Restarting the bot reuses the stored OAuth credential instead of replacing refreshed tokens with old `.env` values. If this workspace already has a static Google Drive credential, archive it once before switching to OAuth refresh. Renew or revoke an existing grant through the vault credential APIs; editing `.env` does not replace it.++## Files++- [main.py](main.py): Slack events and application startup.+- [agent.py](agent.py): Agent sessions, sandboxes, streaming, and cleanup.+- [tools.py](tools.py): Slack search, channel, teammate, and file tools.+- [connections.py](connections.py): MCP connections and vault credentials.diff --git a/examples/agents_api/apps/slack_bot/__init__.py b/examples/agents_api/apps/slack_bot/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/apps/slack_bot/agent.py b/examples/agents_api/apps/slack_bot/agent.pynew file mode 100644index 00000000..7ee119a2--- /dev/null+++ b/examples/agents_api/apps/slack_bot/agent.py@@ -0,0 +1,216 @@+"""Run and reuse one Agents API sandbox per Slack thread."""++from __future__ import annotations++import asyncio+import os+from collections.abc import AsyncIterator, Awaitable, Callable++import docker+from docker.models.containers import Container+from openai import AsyncOpenAI+from openai.types.beta import AgentSessionEvent+from openai.types.beta.agents.session_create_params import Agent+from slack_sdk.web.async_client import AsyncWebClient++from .connections import Connections+from .tools import slack_handlers++INSTRUCTIONS = """\+You are a capable Slack teammate.+Search the current Slack conversation and connected Notion, Google Drive, and GitHub sources.+Cite the records behind your answer.+Use your workspace to analyze data, inspect repositories, and prepare changes.+Only modify external systems or create pull requests when the user explicitly asks.+Never reveal private information in a shared channel.+Delegate complex investigations when helpful.+"""+ProgressCallback = Callable[[str], Awaitable[None]]+++def start_executor(environment_id: str, remote_url: str) -> Container:+ return docker.from_env().containers.run(+ os.environ.get("AGENTS_SANDBOX_IMAGE", "agent-api-sandbox:latest"),+ [+ "codex",+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ],+ environment={"CODEX_API_KEY": os.environ["OPENAI_API_KEY"]},+ detach=True,+ auto_remove=True,+ init=True,+ )+++class SlackBot:+ """Keep one self-hosted Agents API session and sandbox per Slack thread."""++ def __init__(self, client: AsyncOpenAI, slack: AsyncWebClient) -> None:+ self.client = client+ self.slack = slack+ self.sessions: dict[str, str] = {}+ self.sandboxes: dict[str, Container] = {}+ self.connections = Connections(client)+ self.model = os.environ.get("OPENAI_MODEL", "gpt-5.6-sol")+ self.active: set[str] = set()+ self.seen_messages: set[str] = set()+ self.thread_locks: dict[str, asyncio.Lock] = {}++ async def answer(+ self,+ question: str,+ *,+ thread_id: str,+ team_id: str,+ channel_id: str,+ on_progress: ProgressCallback | None = None,+ ) -> str:+ async with self.thread_locks.setdefault(thread_id, asyncio.Lock()):+ return await self._answer(+ question, thread_id, team_id, channel_id, on_progress+ )++ async def _answer(+ self,+ question: str,+ thread_id: str,+ team_id: str,+ channel_id: str,+ on_progress: ProgressCallback | None,+ ) -> str:+ if thread_id in self.sessions:+ session = await self.client.beta.agents.sessions.retrieve(+ self.sessions[thread_id]+ )+ else:+ vault_id, tools = await self.connections.get(team_id)+ agent: Agent = {+ "model": self.model,+ "instructions": INSTRUCTIONS,+ "reasoning": {"effort": "medium"},+ "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},+ "tools": tools,+ }+ session = await self.client.beta.agents.sessions.create(+ agent=agent,+ environment={+ "type": "self_hosted",+ "workspace_directory": "/workspace",+ },+ vault_ids=[vault_id] if vault_id is not None else None,+ )++ try:+ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError("Expected a self-hosted execution environment.")+ sandbox = await asyncio.to_thread(+ start_executor, environment.id, environment.remote_url+ )+ except BaseException:+ await self.client.beta.agents.sessions.delete(session.id)+ raise++ self.sessions[thread_id] = session.id+ self.sandboxes[thread_id] = sandbox++ async with self.client.beta.agents.sessions.stream(+ session.id,+ input=question,+ tool_handlers=slack_handlers(self.slack, channel_id),+ ) as events:+ return await self._collect_reply(events, thread_id, on_progress)++ async def _collect_reply(+ self,+ events: AsyncIterator[AgentSessionEvent],+ thread_id: str,+ on_progress: ProgressCallback | None,+ ) -> str:+ parts: list[str] = []+ last_progress = ""+ self.active.add(thread_id)++ try:+ async for event in events:+ if (+ event.type == "agent.session.turn.item.added"+ and event.item is not None+ ):+ item = event.item.to_dict()+ label = str(item.get("server_label") or item.get("name", ""))+ progress = {+ "search_slack_messages": "Searching Slack conversations...",+ "read_slack_channel": "Reading the Slack channel...",+ "find_teammate": "Looking up a teammate...",+ "list_slack_files": "Checking shared files...",+ "notion": "Checking Notion...",+ "google_drive": "Searching Google Drive...",+ "github": "Checking GitHub...",+ }.get(label, "Working on your request...")+ if on_progress is not None and progress != last_progress:+ await on_progress(progress)+ last_progress = progress+ elif (+ event.type == "agent.session.subagent.created"+ and on_progress is not None+ ):+ await on_progress("A specialist is investigating...")++ if event.type == "agent.session.turn.output_text.delta":+ parts.append(event.delta)+ elif event.type == "agent.session.turn.output_text.done" and not parts:+ parts.append(event.text)+ elif event.type in {+ "agent.session.failed",+ "agent.session.turn.failed",+ "error",+ }:+ raise RuntimeError(f"Agent session failed: {event.to_dict()}")+ elif event.type == "agent.session.turn.cancelled":+ return "Request cancelled."+ finally:+ self.active.discard(thread_id)++ return "".join(parts)++ async def steer(self, thread_id: str, instructions: str) -> None:+ await self.client.beta.agents.sessions.events.create(+ self.sessions[thread_id],+ events=[+ {+ "type": "agent.session.input.message",+ "input": [+ {+ "role": "user",+ "content": [{"type": "input_text", "text": instructions}],+ }+ ],+ }+ ],+ )++ async def cancel(self, thread_id: str) -> None:+ await self.client.beta.agents.sessions.events.create(+ self.sessions[thread_id], events=[{"type": "agent.session.input.cancel"}]+ )++ async def close(self) -> None:+ errors: list[Exception] = []+ for thread_id, session_id in self.sessions.items():+ try:+ await self.client.beta.agents.sessions.delete(session_id)+ except Exception as error:+ errors.append(error)+ sandbox = self.sandboxes.get(thread_id)+ if sandbox is not None:+ try:+ await asyncio.to_thread(sandbox.stop)+ except Exception as error:+ errors.append(error)+ if errors:+ raise ExceptionGroup("Could not close all Slack runtimes", errors)diff --git a/examples/agents_api/apps/slack_bot/connections.py b/examples/agents_api/apps/slack_bot/connections.pynew file mode 100644index 00000000..a3eef911--- /dev/null+++ b/examples/agents_api/apps/slack_bot/connections.py@@ -0,0 +1,170 @@+"""Connect workplace MCP tools through vault credentials."""++from __future__ import annotations++import asyncio+import os++from openai import AsyncOpenAI+from openai.types.beta import AgentToolParam+from openai.types.beta.agent_tool_param import AgentToolConfigParamMcp+from openai.types.beta.agents.vaults.credential_auth_create_param import (+ CredentialAuthCreateParam,+)++from .tools import SLACK_TOOLS++NOTION_MCP_URL = "https://mcp.notion.com/mcp"+GOOGLE_DRIVE_MCP_URL = "https://drivemcp.googleapis.com/mcp/v1"+GITHUB_MCP_URL = "https://api.githubcopilot.com/mcp/"+++def mcp_server(label: str, url: str) -> AgentToolConfigParamMcp:+ return {+ "type": "mcp",+ "server_label": label,+ "transport": {"type": "http", "server_url": url},+ "connection_origin": "service",+ }+++class Connections:+ """Configure workplace tools once per Slack workspace."""++ def __init__(self, client: AsyncOpenAI) -> None:+ self.client = client+ self.vaults: dict[str, str] = {}+ self.lock = asyncio.Lock()++ async def get(self, team_id: str) -> tuple[str | None, list[AgentToolParam]]:+ async with self.lock:+ return await self._configure_tools(team_id)++ async def _configure_tools(+ self, team_id: str+ ) -> tuple[str | None, list[AgentToolParam]]:+ notion_token = os.environ.get("NOTION_TOKEN")+ google_drive_token = os.environ.get("GOOGLE_DRIVE_TOKEN")+ github_token = os.environ.get("GITHUB_TOKEN")+ google_refresh_token = os.environ.get("GOOGLE_DRIVE_REFRESH_TOKEN")+ if google_refresh_token:+ for name in (+ "GOOGLE_DRIVE_TOKEN",+ "GOOGLE_DRIVE_CLIENT_ID",+ "GOOGLE_DRIVE_CLIENT_SECRET",+ ):+ if not os.environ.get(name):+ raise ValueError(+ f"Set {name} when enabling Google Drive OAuth refresh."+ )+ tools: list[AgentToolParam] = [*SLACK_TOOLS, {"type": "web_search"}]+ if notion_token:+ tools.append(mcp_server("notion", NOTION_MCP_URL))+ if google_drive_token:+ tools.append(mcp_server("google_drive", GOOGLE_DRIVE_MCP_URL))+ if github_token:+ tools.append(mcp_server("github", GITHUB_MCP_URL))+ if not (notion_token or google_drive_token or github_token):+ return None, tools++ vault_id = self.vaults.get(team_id)+ if vault_id is not None:+ return vault_id, tools++ existing = [+ candidate+ async for candidate in self.client.beta.agents.vaults.list(limit=100)+ ]+ vault = next(+ (+ candidate+ for candidate in existing+ if candidate.metadata.get("slack_team_id") == team_id+ and candidate.metadata.get("owner") == "slack_bot"+ ),+ None,+ )+ if vault is None:+ vault = await self.client.beta.agents.vaults.create(+ name="Slack teammate integrations",+ metadata={"slack_team_id": team_id, "owner": "slack_bot"},+ )+ credentials = [+ item+ async for item in self.client.beta.agents.vaults.credentials.list(vault.id)+ ]++ async def save_credential(label: str, auth: CredentialAuthCreateParam) -> None:+ credential = next(+ (+ item+ for item in credentials+ if item.auth.mcp_server_url == auth["mcp_server_url"]+ ),+ None,+ )+ if credential is not None and credential.auth.type != auth["type"]:+ raise ValueError(+ f"Archive the existing {label} vault credential before changing auth type."+ )+ if credential is None:+ await self.client.beta.agents.vaults.credentials.create(+ vault.id,+ name=label.replace("_", " ").title(),+ auth=auth,+ )+ elif auth["type"] == "static_bearer":+ await self.client.beta.agents.vaults.credentials.update(+ credential.id,+ vault_id=vault.id,+ auth={"type": "static_bearer", "token": auth["token"]},+ )+ # Keep refreshed OAuth grants in the vault; .env only seeds a new credential.++ if notion_token:+ await save_credential(+ "notion",+ {+ "type": "static_bearer",+ "mcp_server_url": NOTION_MCP_URL,+ "token": notion_token,+ },+ )++ if google_drive_token:+ google_auth: CredentialAuthCreateParam = {+ "type": "static_bearer",+ "mcp_server_url": GOOGLE_DRIVE_MCP_URL,+ "token": google_drive_token,+ }+ if google_refresh_token:+ google_auth = {+ "type": "mcp_oauth",+ "mcp_server_url": GOOGLE_DRIVE_MCP_URL,+ "access_token": google_drive_token,+ "expires_at": os.environ.get("GOOGLE_DRIVE_TOKEN_EXPIRES_AT")+ or None,+ "refresh": {+ "token_endpoint": "https://oauth2.googleapis.com/token",+ "client_id": os.environ["GOOGLE_DRIVE_CLIENT_ID"],+ "refresh_token": google_refresh_token,+ "token_endpoint_auth": {+ "type": "client_secret_post",+ "client_secret": os.environ["GOOGLE_DRIVE_CLIENT_SECRET"],+ },+ },+ }+ await save_credential("google_drive", google_auth)++ if github_token:+ await save_credential(+ "github",+ {+ "type": "static_bearer",+ "mcp_server_url": GITHUB_MCP_URL,+ "token": github_token,+ },+ )++ self.vaults[team_id] = vault.id+ return vault.id, toolsdiff --git a/examples/agents_api/apps/slack_bot/main.py b/examples/agents_api/apps/slack_bot/main.pynew file mode 100644index 00000000..b333bc74--- /dev/null+++ b/examples/agents_api/apps/slack_bot/main.py@@ -0,0 +1,141 @@+# /// script+# requires-python = ">=3.14"+# dependencies = [+# "openai>=3.12.0",+# "aiohttp",+# "docker",+# "python-dotenv",+# "slack-bolt",+# ]+# ///++"""Start the Slack bot with Socket Mode."""++from __future__ import annotations++import asyncio+import logging+import os+import sys+from pathlib import Path+from typing import Any++from dotenv import load_dotenv+from openai import AsyncOpenAI++# Support direct execution from any working directory.+if __package__ in {None, ""}:+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+++from examples.agents_api.apps.slack_bot.agent import SlackBot++EXAMPLE_DIR = Path(__file__).resolve().parent+++async def run_slack() -> None:+ from slack_bolt.adapter.socket_mode.aiohttp import AsyncSocketModeHandler+ from slack_bolt.async_app import AsyncApp+ from slack_bolt.context.async_context import AsyncBoltContext+ from slack_bolt.context.say.async_say import AsyncSay++ app = AsyncApp(token=os.environ["SLACK_BOT_TOKEN"])++ async with AsyncOpenAI() as client:+ bot = SlackBot(client, app.client)++ async def handle_message(+ event: dict[str, Any], context: AsyncBoltContext, say: AsyncSay+ ) -> None:+ if event.get("bot_id"):+ return++ question = (+ str(event.get("text", ""))+ .replace(f"<@{context.bot_user_id}>", "")+ .strip()+ )+ if not question:+ return++ channel = str(event["channel"])+ thread_ts = str(event.get("thread_ts") or event["ts"])+ team_id = str(context.team_id or event.get("team", ""))+ thread_id = f"{team_id}:{channel}:{thread_ts}"+ message_id = f"{team_id}:{channel}:{event['ts']}"+ if message_id in bot.seen_messages:+ return+ bot.seen_messages.add(message_id)++ if thread_id in bot.active:+ if question.lower() in {"stop", "cancel", "stop this", "cancel this"}:+ await bot.cancel(thread_id)+ await say(text="Stopping your request.", thread_ts=thread_ts)+ else:+ await bot.steer(thread_id, question)+ await say(+ text="Got it. Updating your request.", thread_ts=thread_ts+ )+ return++ status = await say(text="Checking your request...", thread_ts=thread_ts)+ status_ts = str(status["ts"])++ async def update_progress(message: str) -> None:+ await context.client.chat_update(+ channel=channel, ts=status_ts, text=message+ )++ try:+ reply = await bot.answer(+ question,+ thread_id=thread_id,+ team_id=team_id,+ channel_id=channel,+ on_progress=update_progress,+ )+ except Exception:+ logging.exception("Slack request failed for thread %s", thread_id)+ await context.client.chat_update(+ channel=channel,+ ts=status_ts,+ text="I could not complete that request. Check the bot's logs and try again.",+ )+ return++ await context.client.chat_update(channel=channel, ts=status_ts, text=reply)++ @app.event("app_mention")+ async def reply_to_mention(+ event: dict[str, Any], context: AsyncBoltContext, say: AsyncSay+ ) -> None:+ await handle_message(event, context, say)++ @app.event("message")+ async def reply_to_message(+ event: dict[str, Any], context: AsyncBoltContext, say: AsyncSay+ ) -> None:+ if event.get("channel_type") != "im":+ thread_ts = event.get("thread_ts")+ if thread_ts is None:+ return+ thread_id = f"{context.team_id}:{event['channel']}:{thread_ts}"+ if thread_id not in bot.sessions:+ return+ await handle_message(event, context, say)++ try:+ await AsyncSocketModeHandler(+ app, os.environ["SLACK_APP_TOKEN"]+ ).start_async()+ finally:+ await bot.close()+++def main() -> None:+ load_dotenv(EXAMPLE_DIR / ".env")+ asyncio.run(run_slack())+++if __name__ == "__main__":+ main()diff --git a/examples/agents_api/apps/slack_bot/slack-app-manifest.yaml b/examples/agents_api/apps/slack_bot/slack-app-manifest.yamlnew file mode 100644index 00000000..eb9e1926--- /dev/null+++ b/examples/agents_api/apps/slack_bot/slack-app-manifest.yaml@@ -0,0 +1,26 @@+display_information:+ name: Agent Teammate+features:+ bot_user:+ display_name: Agent Teammate+ always_online: false+oauth_config:+ scopes:+ bot:+ - app_mentions:read+ - channels:history+ - chat:write+ - files:read+ - groups:history+ - im:history+ - users:read+settings:+ event_subscriptions:+ bot_events:+ - app_mention+ - message.channels+ - message.groups+ - message.im+ interactivity:+ is_enabled: true+ socket_mode_enabled: truediff --git a/examples/agents_api/apps/slack_bot/tools.py b/examples/agents_api/apps/slack_bot/tools.pynew file mode 100644index 00000000..74a01507--- /dev/null+++ b/examples/agents_api/apps/slack_bot/tools.py@@ -0,0 +1,107 @@+"""Read Slack messages, teammates, and shared files."""++from __future__ import annotations++from typing import Any++from openai.lib.streaming.agents import AsyncToolHandler+from openai.types.beta.agent_tool_param import AgentToolConfigParamFunction+from slack_sdk.web.async_client import AsyncWebClient+++def define_tool(+ name: str, description: str, *fields: str+) -> AgentToolConfigParamFunction:+ return {+ "type": "function",+ "name": name,+ "description": description,+ "parameters": {+ "type": "object",+ "properties": {field: {"type": "string"} for field in fields},+ "required": list(fields),+ "additionalProperties": False,+ },+ }+++SLACK_TOOLS: list[AgentToolConfigParamFunction] = [+ define_tool(+ "search_slack_messages",+ "Search recent messages in this Slack channel.",+ "query",+ ),+ define_tool("read_slack_channel", "Read recent messages in this Slack channel."),+ define_tool("find_teammate", "Find a Slack teammate by name.", "query"),+ define_tool("list_slack_files", "List files shared in this Slack channel."),+]+++def slack_handlers(+ slack: AsyncWebClient, channel_id: str+) -> dict[str, AsyncToolHandler]:+ async def search_slack_messages(arguments: dict[str, Any]) -> dict[str, Any]:+ query = str(arguments["query"]).casefold()+ response = await slack.conversations_history(channel=channel_id, limit=100)+ messages: list[dict[str, Any]] = response.get("messages", [])+ return {+ "messages": [+ {+ "user": str(message.get("user", "")),+ "text": str(message.get("text", "")),+ }+ for message in messages+ if query in str(message.get("text", "")).casefold()+ ][:20]+ }++ async def read_slack_channel(_arguments: dict[str, Any]) -> dict[str, Any]:+ response = await slack.conversations_history(channel=channel_id, limit=20)+ messages: list[dict[str, Any]] = response.get("messages", [])+ return {+ "messages": [+ {+ "user": str(message.get("user", "")),+ "text": str(message.get("text", "")),+ }+ for message in messages+ ]+ }++ async def find_teammate(arguments: dict[str, Any]) -> dict[str, Any]:+ query = str(arguments["query"]).casefold()+ response = await slack.users_list(limit=200)+ members: list[dict[str, Any]] = response.get("members", [])+ matches: list[dict[str, Any]] = []+ for member in members:+ if member.get("deleted") or member.get("is_bot"):+ continue+ profile = member.get("profile", {})+ name = str(profile.get("display_name") or member.get("real_name") or "")+ if (+ query in name.casefold()+ or query in str(member.get("name", "")).casefold()+ ):+ matches.append({"id": str(member.get("id", "")), "name": name})+ return {"users": matches[:20]}++ async def list_slack_files(_arguments: dict[str, Any]) -> dict[str, Any]:+ response = await slack.files_list(channel=channel_id, count=20)+ files: list[dict[str, Any]] = response.get("files", [])+ return {+ "files": [+ {+ "name": str(file.get("name", "")),+ "title": str(file.get("title", "")),+ "url": str(file.get("permalink", "")),+ }+ for file in files+ ]+ }++ return {+ "search_slack_messages": search_slack_messages,+ "read_slack_channel": read_slack_channel,+ "find_teammate": find_teammate,+ "list_slack_files": list_slack_files,+ }diff --git a/examples/agents_api/sandboxes/README.md b/examples/agents_api/sandboxes/README.mdnew file mode 100644index 00000000..0c6afda9--- /dev/null+++ b/examples/agents_api/sandboxes/README.md@@ -0,0 +1,39 @@+# Self-hosted sandbox examples++Choose how your application starts sandbox compute. Both modes run the agent in+OpenAI's cloud and connect the sandbox through `codex exec-server`.++| Mode | Your application | Sandbox provisioning |+| --- | --- | --- |+| [Application-managed](application_managed/README.md) | Run a provider-specific `main.py`. It calls both the Agents API and the sandbox provider. | Your application starts and stops compute directly; no webhook handler. |+| [Webhook-managed](webhook_managed/README.md) | Run the shared `client.py`. It calls only the Agents API. | 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 stop+provider compute; each example documents cleanup of both.++```text+sandboxes/+├── application_managed/+│ ├── blaxel/main.py+│ ├── cloudflare/ # Python application + provisioning Worker+│ ├── daytona/main.py+│ ├── digitalocean/ # Python application + sandbox manifest+│ ├── docker/main.py # Application + Docker provisioning+│ ├── e2b/main.py+│ ├── modal/main.py # Application + Modal provisioning+│ ├── oci/main.py # Application + OCI provisioning+│ ├── runloop/main.py # Application + Runloop provisioning+│ └── vercel/main.py+└── webhook_managed/+ ├── client.py # Shared application; Agents API only+ ├── modal/ # Deployable provider handler+ ├── vercel/ # Deployable provider handler+ ├── cloudflare/ # Deployable provider handler+ ├── blaxel/ # Deployable provider handler+ ├── daytona/ # Deployable provider handler+ ├── digitalocean/ # Deployable provider handler+ └── e2b/ # Deployable provider handler+```++Start with the README for your chosen mode, then the provider README. Run commands+from the Cookbook repository root unless a provider README says otherwise.diff --git a/examples/agents_api/sandboxes/__init__.py b/examples/agents_api/sandboxes/__init__.pynew file mode 100644index 00000000..8b137891--- /dev/null+++ b/examples/agents_api/sandboxes/__init__.py@@ -0,0 +1 @@+diff --git a/examples/agents_api/sandboxes/application_managed/README.md b/examples/agents_api/sandboxes/application_managed/README.mdnew file mode 100644index 00000000..444e8a57--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/README.md@@ -0,0 +1,32 @@+# Application-managed sandboxes++Your application calls both the Agents API and the sandbox provider. Run one+provider-specific `main.py` locally or in your own cloud; no webhook handler is+deployed.++## How it works++Each example creates an API session, starts the sandbox and executor, submits+input, streams the result, then cleans up both the sandbox and session.++## Choose an example++| Provider | Application and provisioning code | Setup |+| --- | --- | --- |+| Blaxel | [blaxel/main.py](blaxel/main.py) | [Run with Blaxel](blaxel/README.md) |+| Cloudflare | [cloudflare/main.py](cloudflare/main.py) + Worker | [Run with Cloudflare](cloudflare/README.md) |+| Daytona | [daytona/main.py](daytona/main.py) | [Run with Daytona](daytona/README.md) |+| DigitalOcean | [digitalocean/main.py](digitalocean/main.py) | [Run with DigitalOcean](digitalocean/README.md) |+| Docker | [docker/main.py](docker/main.py) | [Run locally](docker/README.md) |+| E2B | [e2b/main.py](e2b/main.py) | [Run with E2B](e2b/README.md) |+| Modal | [modal/main.py](modal/main.py) | [Run with Modal](modal/README.md) |+| Runloop | [runloop/main.py](runloop/main.py) | [Run with Runloop](runloop/README.md) |+| Oracle Cloud Infrastructure (OCI) | [oci/main.py](oci/main.py) | [Run with OCI](oci/README.md) |+| Vercel | [vercel/main.py](vercel/main.py) | [Run with Vercel](vercel/README.md) |++Each provider directory includes its sample and setup instructions.+Run the example from the Cookbook repository root.++For an application that only calls the Agents API, use+[webhook-managed sandboxes](../webhook_managed/README.md) instead. Do not attach a+provisioning webhook handler to sessions already managed by these examples.diff --git a/examples/agents_api/sandboxes/application_managed/__init__.py b/examples/agents_api/sandboxes/application_managed/__init__.pynew file mode 100644index 00000000..c5dbaac1--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/__init__.py@@ -0,0 +1 @@+"""Examples where the application owns sandbox provisioning."""diff --git a/examples/agents_api/sandboxes/application_managed/blaxel/README.md b/examples/agents_api/sandboxes/application_managed/blaxel/README.mdnew file mode 100644index 00000000..86415f19--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/blaxel/README.md@@ -0,0 +1,32 @@+# Application-managed Blaxel sandbox++The application creates an Agents API session and a Blaxel sandbox, starts+`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.+It prints the plan, deletes the sandbox, and deletes the session.++## Run++Set `BL_API_KEY`, `BL_WORKSPACE`, `OPENAI_API_KEY`, and a separate restricted+`OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the same owner,+organization, and project. Only the executor key enters the sandbox.+Set `BL_REGION` to choose a region; the default is `us-pdx-1`.++From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/blaxel/main.py+```++Dependencies are declared inline. The script allows six minutes for setup and+execution and attempts both cleanup operations on failure. The sandbox has a+ten-minute TTL. If creation times out before returning a sandbox, check Blaxel+for `agents-api-<last 12 characters of the printed session ID>` before retrying.++For follow-up turns, keep both resources until the application is finished.+Do not attach a provisioning webhook handler to these sessions.++## References++- [Blaxel sandbox documentation](https://docs.blaxel.ai/Sandboxes/Overview)+- [Blaxel Python SDK](https://github.com/blaxel-ai/sdk-python)+- [Webhook-managed example](../../webhook_managed/blaxel/README.md)diff --git a/examples/agents_api/sandboxes/application_managed/blaxel/main.py b/examples/agents_api/sandboxes/application_managed/blaxel/main.pynew file mode 100644index 00000000..63c3c493--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/blaxel/main.py@@ -0,0 +1,109 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "blaxel>=0.4.3",+# ]+# ///++"""Run an Agents API task in a Blaxel sandbox and clean up both resources."""++import asyncio+import os+import shlex++from blaxel.core.sandbox import SandboxInstance+from openai import AsyncOpenAI++WORKSPACE = "/workspace"+BRIEF = "Migrate a synchronous Python service to async without changing its API.\n"+++async def main() -> None:+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ async with AsyncOpenAI(timeout=360) as client:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ sandbox = None+ print(f"Session: {session.id}", flush=True)+ try:+ assert session.environment.type == "self_hosted"+ executor_args = [+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ async with asyncio.timeout(360):+ sandbox = await SandboxInstance.create(+ {+ "name": f"agents-api-{session.id[-12:]}",+ "image": "blaxel/node:latest",+ "region": os.environ.get("BL_REGION", "us-pdx-1"),+ "ttl": "10m",+ }+ )+ print(f"Sandbox: {sandbox.metadata.name}", flush=True)+ setup = await sandbox.process.exec(+ {+ "command": "mkdir -p /workspace && npm install -g @openai/codex@alpha",+ "wait_for_completion": True,+ "timeout": 180,+ }+ )+ if setup.exit_code != 0:+ raise RuntimeError("Executor installation failed")+ await sandbox.fs.write(f"{WORKSPACE}/brief.txt", BRIEF)+ await sandbox.process.exec(+ {+ "command": shlex.join(["codex", *executor_args]),+ "working_dir": WORKSPACE,+ "env": {"CODEX_API_KEY": executor_key},+ "wait_for_completion": False,+ "keep_alive": True,+ "timeout": 600,+ }+ )++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ plan = await sandbox.fs.read(f"{WORKSPACE}/plan.md")+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if sandbox is not None:+ async with asyncio.timeout(30):+ await SandboxInstance.delete(sandbox.metadata.name)+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/.dockerignore b/examples/agents_api/sandboxes/application_managed/cloudflare/.dockerignorenew file mode 100644index 00000000..073e02da--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/.dockerignore@@ -0,0 +1,3 @@+node_modules+.wrangler+.dev.varsdiff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/.gitignore b/examples/agents_api/sandboxes/application_managed/cloudflare/.gitignorenew file mode 100644index 00000000..a933f108--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/.gitignore@@ -0,0 +1,3 @@+node_modules/+.wrangler/+.dev.varsdiff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/Dockerfile b/examples/agents_api/sandboxes/application_managed/cloudflare/Dockerfilenew file mode 100644index 00000000..6711bed7--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/Dockerfile@@ -0,0 +1,5 @@+FROM docker.io/cloudflare/sandbox:0.12.9+RUN apt-get update && apt-get install -y --no-install-recommends util-linux \+ && npm install -g @openai/codex@alpha \+ && mkdir -p /workspace \+ && rm -rf /var/lib/apt/lists/*diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/README.md b/examples/agents_api/sandboxes/application_managed/cloudflare/README.mdnew file mode 100644index 00000000..322924be--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/README.md@@ -0,0 +1,53 @@+# Application-managed Cloudflare sandbox++The Python application creates an Agents API session and calls your Cloudflare+Worker to start a sandbox. The Worker runs `codex exec-server` and returns the+agent's generated `plan.md`. The application then destroys the sandbox and+deletes the session. Provisioning is driven by the application, not webhooks.++Cloudflare's sandbox SDK runs inside a Worker. The small Worker in this example+provides authenticated start, file-read, and destroy routes for the Python client.++## Deploy the Worker++You need Cloudflare Workers Paid with Containers enabled, Node.js, and Docker+running for the image build.++```bash+cd examples/agents_api/sandboxes/application_managed/cloudflare+npm ci+npx wrangler login+npm run deploy+npx wrangler secret put OPENAI_EXECUTOR_API_KEY+npx wrangler secret put SANDBOX_CONTROL_TOKEN+```++Use a restricted executor key and a separate random control token. Keep the+application's `OPENAI_API_KEY` outside the Worker and sandbox. The OpenAI keys+must have the same owner, organization, and project.++## Run the application++Set `OPENAI_API_KEY`, `SANDBOX_CONTROL_TOKEN` (the same value stored in the+Worker), and `CLOUDFLARE_SANDBOX_WORKER_URL` to the deployed Worker URL.+From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/cloudflare/main.py+```++Python dependencies are declared inline. The script allows six minutes for+setup and execution and attempts both cleanup operations on failure. The Worker+also sets a ten-minute idle timeout. If the application is interrupted, send an+authenticated `DELETE /sandboxes/<printed session ID>` to the Worker and delete+the Agents API session.++For follow-up turns, keep both resources until the application is finished.+Do not attach a provisioning webhook handler to these sessions. When finished+with this deployment, run `npx wrangler delete` from the Worker directory.++## References++- [Cloudflare Sandbox documentation](https://developers.cloudflare.com/sandbox/)+- [Background processes](https://developers.cloudflare.com/sandbox/guides/background-processes/)+- [Webhook-managed example](../../webhook_managed/cloudflare/README.md)diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/main.py b/examples/agents_api/sandboxes/application_managed/cloudflare/main.pynew file mode 100644index 00000000..5f1b3d86--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/main.py@@ -0,0 +1,83 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["openai>=3.12.0", "httpx>=0.27"]+# ///++"""Provision a Cloudflare sandbox through your Worker, without webhooks."""++import asyncio+import os++import httpx+from openai import AsyncOpenAI+++async def main() -> None:+ async with (+ AsyncOpenAI(timeout=360) as client,+ httpx.AsyncClient(+ base_url=os.environ["CLOUDFLARE_SANDBOX_WORKER_URL"],+ headers={"Authorization": f"Bearer {os.environ['SANDBOX_CONTROL_TOKEN']}"},+ timeout=180,+ ) as worker,+ ):+ 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)+ path = f"/sandboxes/{session.id}"+ try:+ assert session.environment.type == "self_hosted"+ async with asyncio.timeout(360):+ response = await worker.post(+ path,+ json={+ "environment_id": session.environment.id,+ "remote_url": session.environment.remote_url,+ },+ )+ response.raise_for_status()+ print(f"Sandbox: {session.id}", flush=True)++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ response = await worker.get(f"{path}/plan")+ response.raise_for_status()+ plan = response.text+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ async with asyncio.timeout(30):+ response = await worker.delete(path)+ response.raise_for_status()+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/package-lock.json b/examples/agents_api/sandboxes/application_managed/cloudflare/package-lock.jsonnew file mode 100644index 00000000..66b6c8a6--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/package-lock.json@@ -0,0 +1,1666 @@+{+ "name": "agents-api-application-cloudflare",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "agents-api-application-cloudflare",+ "dependencies": {+ "@cloudflare/sandbox": ">=0.12.8 <1"+ },+ "devDependencies": {+ "@cloudflare/workers-types": ">=4.20260702.1",+ "typescript": ">=5.9 <6",+ "wrangler": ">=4.90.0 <5"+ }+ },+ "node_modules/@cloudflare/containers": {+ "version": "0.3.7",+ "resolved": "https://registry.npmjs.org/@cloudflare/containers/-/containers-0.3.7.tgz",+ "integrity": "sha512-DM9dm3FnIBSyiSJ1FLavKwl/lk3oAmTaynCzZQ9pZR0ncRPquSxkxd8Nu2MFILxmDDsPkxKsSNEh9mHHMty4Fw==",+ "license": "MIT OR Apache-2.0"+ },+ "node_modules/@cloudflare/kv-asset-handler": {+ "version": "0.5.0",+ "resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",+ "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@cloudflare/sandbox": {+ "version": "0.12.9",+ "resolved": "https://registry.npmjs.org/@cloudflare/sandbox/-/sandbox-0.12.9.tgz",+ "integrity": "sha512-JlCQ8adVaHT3TrZO13X6US2LJTyQ4YvoEZpfh5EewRqcxPfMHZNJPB/1dsRdiFqmtzpz+lMxGazSUa2H/g2IKg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@cloudflare/containers": "^0.3.5",+ "aws4fetch": "^1.0.20",+ "capnweb": "^0.8.0",+ "hono": "^4.13.0"+ },+ "peerDependencies": {+ "@openai/agents": "^0.3.3",+ "@opencode-ai/sdk": "^1.1.40",+ "@xterm/xterm": ">=5.0.0"+ },+ "peerDependenciesMeta": {+ "@openai/agents": {+ "optional": true+ },+ "@opencode-ai/sdk": {+ "optional": true+ },+ "@xterm/xterm": {+ "optional": true+ }+ }+ },+ "node_modules/@cloudflare/unenv-preset": {+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz",+ "integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "peerDependencies": {+ "unenv": "2.0.0-rc.24",+ "workerd": ">1.20260305.0 <2.0.0-0"+ },+ "peerDependenciesMeta": {+ "workerd": {+ "optional": true+ }+ }+ },+ "node_modules/@cloudflare/workerd-darwin-64": {+ "version": "1.20260831.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260831.1.tgz",+ "integrity": "sha512-oyZ8xhu+gYTvoxV/sn6NRmTHK95RhEO1Dk54/6oPb0Uu70w7ZeRoCjkJ5aNmfS8Vrkdu6+oL0HNg6EcC61uQ2Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-darwin-arm64": {+ "version": "1.20260831.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260831.1.tgz",+ "integrity": "sha512-s6Go53KPnoXZ1sTGBZ3en3otfHDuMPJhiwXMYWU21JkJQkpoeRt6HFUwM0GPhK3YhXWm+8baGMvCGZYS/KA9eA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-linux-64": {+ "version": "1.20260831.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260831.1.tgz",+ "integrity": "sha512-WxNKBgjKgeYTolW3yl1Lt3Lu67UlxdeyzWYi9MIqrKBdyQcz+UNG36RevSBf8rv1sTWapRW234VX2keZ+wXapA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-linux-arm64": {+ "version": "1.20260831.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260831.1.tgz",+ "integrity": "sha512-JTF9+9clUT3gaCq7Xnmd+Q/wEMaitpngSTOec/Ffb/r3xexA9XwNJVFSOKfk6q61flHGjAYJ4H9B7Mu5Qur49w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-windows-64": {+ "version": "1.20260831.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260831.1.tgz",+ "integrity": "sha512-do+KDYw0PABwsrKUQIccWBZB70kqKcADoSnvzJ8pvMaWUVB4qaCspEZYfm97WNdtY1wt8mlKYqIJyYUNOkTvQg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workers-types": {+ "version": "5.20260902.1",+ "resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-5.20260902.1.tgz",+ "integrity": "sha512-FpgVlUNWBLPtC51m/t9Eo8DzbFoOg05MSicoPQRS3eitvPRznJxkxuCy0P23unP2CjLIAczLR5nFNRWlKMJvrA==",+ "dev": true,+ "license": "MIT OR Apache-2.0"+ },+ "node_modules/@cspotcode/source-map-support": {+ "version": "0.8.1",+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "0.3.9"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.3",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.2.tgz",+ "integrity": "sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.2.tgz",+ "integrity": "sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-freebsd-wasm32": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.2.tgz",+ "integrity": "sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==",+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "dependencies": {+ "@img/sharp-wasm32": "0.35.2"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.1.tgz",+ "integrity": "sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.1.tgz",+ "integrity": "sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.1.tgz",+ "integrity": "sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.1.tgz",+ "integrity": "sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.1.tgz",+ "integrity": "sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.1.tgz",+ "integrity": "sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.1.tgz",+ "integrity": "sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.1.tgz",+ "integrity": "sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.1.tgz",+ "integrity": "sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.1.tgz",+ "integrity": "sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.2.tgz",+ "integrity": "sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.2.tgz",+ "integrity": "sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.2.tgz",+ "integrity": "sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.2.tgz",+ "integrity": "sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.2.tgz",+ "integrity": "sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.2.tgz",+ "integrity": "sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.2.tgz",+ "integrity": "sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.2.tgz",+ "integrity": "sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.3.1"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.2.tgz",+ "integrity": "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==",+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.11.1"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-webcontainers-wasm32": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.2.tgz",+ "integrity": "sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==",+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "dependencies": {+ "@img/sharp-wasm32": "0.35.2"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.2.tgz",+ "integrity": "sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.2.tgz",+ "integrity": "sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.2.tgz",+ "integrity": "sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.9",+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.0.3",+ "@jridgewell/sourcemap-codec": "^1.4.10"+ }+ },+ "node_modules/@poppinss/colors": {+ "version": "4.1.6",+ "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",+ "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "kleur": "^4.1.5"+ }+ },+ "node_modules/@poppinss/dumper": {+ "version": "0.6.5",+ "resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",+ "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@sindresorhus/is": "^7.0.2",+ "supports-color": "^10.0.0"+ }+ },+ "node_modules/@poppinss/exception": {+ "version": "1.2.3",+ "resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",+ "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@sindresorhus/is": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",+ "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@speed-highlight/core": {+ "version": "1.2.24",+ "resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.24.tgz",+ "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/aws4fetch": {+ "version": "1.0.20",+ "resolved": "https://registry.npmjs.org/aws4fetch/-/aws4fetch-1.0.20.tgz",+ "integrity": "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g==",+ "license": "MIT"+ },+ "node_modules/blake3-wasm": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",+ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/capnweb": {+ "version": "0.8.0",+ "resolved": "https://registry.npmjs.org/capnweb/-/capnweb-0.8.0.tgz",+ "integrity": "sha512-BK/TuXUiyfLSKsmjojn70yN7oYG/JJzoURZ3tckjg5Zj2KcygPm0A5jyOlswK7SYB4f0Gh9tt+RZ132b80iLfA==",+ "license": "MIT"+ },+ "node_modules/cookie": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/error-stack-parser-es": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",+ "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/hono": {+ "version": "4.13.5",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.5.tgz",+ "integrity": "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/kleur": {+ "version": "4.1.5",+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/miniflare": {+ "version": "5.20260831.0-alpha",+ "resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20260831.0-alpha.tgz",+ "integrity": "sha512-Hwgh1VDUiPCPGQKODQfUmy7hRAje1D55icB+9png3ueiM64rlSM87nSrtqpxAD+DlLWI4ehnYBuECaXV43zGmQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cspotcode/source-map-support": "0.8.1",+ "sharp": "0.35.2",+ "undici": "7.29.0",+ "workerd": "1.20260831.1",+ "ws": "8.21.0",+ "youch": "4.1.0-beta.10"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/path-to-regexp": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",+ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/semver": {+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/sharp": {+ "version": "0.35.2",+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.2.tgz",+ "integrity": "sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@img/colour": "^1.1.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.8.4"+ },+ "engines": {+ "node": ">=20.9.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.35.2",+ "@img/sharp-darwin-x64": "0.35.2",+ "@img/sharp-freebsd-wasm32": "0.35.2",+ "@img/sharp-libvips-darwin-arm64": "1.3.1",+ "@img/sharp-libvips-darwin-x64": "1.3.1",+ "@img/sharp-libvips-linux-arm": "1.3.1",+ "@img/sharp-libvips-linux-arm64": "1.3.1",+ "@img/sharp-libvips-linux-ppc64": "1.3.1",+ "@img/sharp-libvips-linux-riscv64": "1.3.1",+ "@img/sharp-libvips-linux-s390x": "1.3.1",+ "@img/sharp-libvips-linux-x64": "1.3.1",+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.1",+ "@img/sharp-libvips-linuxmusl-x64": "1.3.1",+ "@img/sharp-linux-arm": "0.35.2",+ "@img/sharp-linux-arm64": "0.35.2",+ "@img/sharp-linux-ppc64": "0.35.2",+ "@img/sharp-linux-riscv64": "0.35.2",+ "@img/sharp-linux-s390x": "0.35.2",+ "@img/sharp-linux-x64": "0.35.2",+ "@img/sharp-linuxmusl-arm64": "0.35.2",+ "@img/sharp-linuxmusl-x64": "0.35.2",+ "@img/sharp-webcontainers-wasm32": "0.35.2",+ "@img/sharp-win32-arm64": "0.35.2",+ "@img/sharp-win32-ia32": "0.35.2",+ "@img/sharp-win32-x64": "0.35.2"+ }+ },+ "node_modules/supports-color": {+ "version": "10.2.2",+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "dev": true,+ "license": "0BSD",+ "optional": true+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },+ "node_modules/unenv": {+ "version": "2.0.0-rc.24",+ "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",+ "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pathe": "^2.0.3"+ }+ },+ "node_modules/workerd": {+ "version": "1.20260831.1",+ "resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260831.1.tgz",+ "integrity": "sha512-A2LwrkBel/FnKABPfeBAMiL6v70+rugnunqQRfWsWZjlhsTZoBScWUVunMy/xLCGLjWCQL2zp39AVR6aO0jurQ==",+ "dev": true,+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "bin": {+ "workerd": "bin/workerd"+ },+ "engines": {+ "node": ">=16"+ },+ "optionalDependencies": {+ "@cloudflare/workerd-darwin-64": "1.20260831.1",+ "@cloudflare/workerd-darwin-arm64": "1.20260831.1",+ "@cloudflare/workerd-linux-64": "1.20260831.1",+ "@cloudflare/workerd-linux-arm64": "1.20260831.1",+ "@cloudflare/workerd-windows-64": "1.20260831.1"+ }+ },+ "node_modules/wrangler": {+ "version": "4.128.0",+ "resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.128.0.tgz",+ "integrity": "sha512-jNXy9e8/pbx8iqTzXPiuflnitKJZoAfEUSUUDLW87bwyeMvJ7kb3yQMSbxEcfNdfHqJW38KRcKaLljOYV4N/4w==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "dependencies": {+ "@cloudflare/kv-asset-handler": "0.5.0",+ "@cloudflare/unenv-preset": "2.16.1",+ "blake3-wasm": "2.1.5",+ "esbuild": "0.28.1",+ "miniflare": "5.20260831.0-alpha",+ "path-to-regexp": "6.3.0",+ "unenv": "2.0.0-rc.24",+ "workerd": "1.20260831.1"+ },+ "bin": {+ "cf-wrangler": "bin/cf-wrangler.js",+ "wrangler": "bin/wrangler.js",+ "wrangler2": "bin/wrangler.js"+ },+ "engines": {+ "node": ">=22.0.0"+ },+ "optionalDependencies": {+ "fsevents": "2.3.3"+ },+ "peerDependencies": {+ "@cloudflare/workers-types": "^5.20260831.1"+ },+ "peerDependenciesMeta": {+ "@cloudflare/workers-types": {+ "optional": true+ }+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/youch": {+ "version": "4.1.0-beta.10",+ "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",+ "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@poppinss/dumper": "^0.6.4",+ "@speed-highlight/core": "^1.2.7",+ "cookie": "^1.0.2",+ "youch-core": "^0.3.3"+ }+ },+ "node_modules/youch-core": {+ "version": "0.3.3",+ "resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",+ "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/exception": "^1.2.2",+ "error-stack-parser-es": "^1.0.5"+ }+ }+ }+}diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/package.json b/examples/agents_api/sandboxes/application_managed/cloudflare/package.jsonnew file mode 100644index 00000000..b811b91c--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/package.json@@ -0,0 +1,17 @@+{+ "name": "agents-api-application-cloudflare",+ "private": true,+ "type": "module",+ "scripts": {+ "check": "tsc --noEmit",+ "deploy": "wrangler deploy"+ },+ "dependencies": {+ "@cloudflare/sandbox": ">=0.12.8 <1"+ },+ "devDependencies": {+ "@cloudflare/workers-types": ">=4.20260702.1",+ "typescript": ">=5.9 <6",+ "wrangler": ">=4.90.0 <5"+ }+}diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/src/index.ts b/examples/agents_api/sandboxes/application_managed/cloudflare/src/index.tsnew file mode 100644index 00000000..53c3dedb--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/src/index.ts@@ -0,0 +1,60 @@+import { getSandbox, type Sandbox as SandboxType } from "@cloudflare/sandbox";++export { Sandbox } from "@cloudflare/sandbox";++interface Env {+ Sandbox: DurableObjectNamespace<SandboxType>;+ OPENAI_EXECUTOR_API_KEY: string;+ SANDBOX_CONTROL_TOKEN: string;+}++export default {+ async fetch(request: Request, env: Env): Promise<Response> {+ if (+ !env.SANDBOX_CONTROL_TOKEN ||+ request.headers.get("authorization") !== `Bearer ${env.SANDBOX_CONTROL_TOKEN}`+ ) {+ return new Response("Unauthorized", { status: 401 });+ }+ const match = new URL(request.url).pathname.match(+ /^\/sandboxes\/(sess_[A-Za-z0-9_-]+)(\/plan)?$/,+ );+ if (!match) return new Response("Not found", { status: 404 });++ const sandbox = getSandbox(env.Sandbox, match[1], {+ sleepAfter: "10m",+ });+ if (request.method === "DELETE" && !match[2]) {+ await sandbox.destroy();+ return Response.json({ deleted: true });+ }+ if (request.method === "GET" && match[2]) {+ const file = await sandbox.readFile("/workspace/plan.md");+ return new Response(file.content, {+ headers: { "content-type": "text/plain; charset=utf-8" },+ });+ }+ if (request.method !== "POST" || match[2]) {+ return new Response("Method not allowed", { status: 405 });+ }+ const { environment_id, remote_url } = (await request.json()) as {+ environment_id?: string;+ remote_url?: string;+ };+ if (!environment_id || !/^ccarenv_[A-Za-z0-9_-]+$/.test(environment_id)) {+ return new Response("Invalid environment_id", { status: 400 });+ }+ if (!remote_url || !/^https:\/\/api\.openai\.com\/[A-Za-z0-9/_-]+$/.test(remote_url)) {+ return new Response("Invalid remote_url", { status: 400 });+ }+ await sandbox.writeFile(+ "/workspace/brief.txt",+ "Migrate a synchronous Python service to async without changing its API.\n",+ );+ await sandbox.startProcess(+ `flock -n /tmp/executor.lock codex exec-server --remote ${remote_url} --environment-id ${environment_id}`,+ { cwd: "/workspace", env: { CODEX_API_KEY: env.OPENAI_EXECUTOR_API_KEY } },+ );+ return Response.json({ started: match[1] });+ },+};diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/tsconfig.json b/examples/agents_api/sandboxes/application_managed/cloudflare/tsconfig.jsonnew file mode 100644index 00000000..1d566bd4--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "skipLibCheck": true,+ "noEmit": true,+ "types": ["@cloudflare/workers-types"],+ "lib": ["ES2022"]+ },+ "include": ["src/**/*.ts"]+}diff --git a/examples/agents_api/sandboxes/application_managed/cloudflare/wrangler.jsonc b/examples/agents_api/sandboxes/application_managed/cloudflare/wrangler.jsoncnew file mode 100644index 00000000..a8a39379--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/cloudflare/wrangler.jsonc@@ -0,0 +1,15 @@+{+ "$schema": "node_modules/wrangler/config-schema.json",+ "name": "agents-api-application-cloudflare",+ "main": "src/index.ts",+ "compatibility_date": "2026-05-07",+ "compatibility_flags": ["nodejs_compat"],+ "containers": [+ { "class_name": "Sandbox", "image": "./Dockerfile", "max_instances": 4 },+ ],+ "durable_objects": {+ "bindings": [{ "name": "Sandbox", "class_name": "Sandbox" }],+ },+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Sandbox"] }],+ "observability": { "enabled": true },+}diff --git a/examples/agents_api/sandboxes/application_managed/daytona/README.md b/examples/agents_api/sandboxes/application_managed/daytona/README.mdnew file mode 100644index 00000000..a627d038--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/daytona/README.md@@ -0,0 +1,31 @@+# Application-managed Daytona sandbox++The application creates an Agents API session and a Daytona sandbox, starts+`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.+It downloads the plan, deletes the sandbox, and deletes the session.++## Run++Set `DAYTONA_API_KEY`, `OPENAI_API_KEY`, and a separate restricted+`OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the same owner,+organization, and project. Only the executor key enters the sandbox.++From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/daytona/main.py+```++Dependencies are declared inline. The script allows six minutes for setup and+execution and attempts both cleanup operations on failure. The sandbox has a+ten-minute TTL. If creation times out before returning a sandbox, check Daytona+for `agents-api-<last 12 characters of the printed session ID>` before retrying.++For follow-up turns, keep both resources until the application is finished.+Do not attach a provisioning webhook handler to these sessions.++## References++- [Daytona documentation](https://www.daytona.io/docs/)+- [Daytona Python SDK](https://www.daytona.io/docs/en/python-sdk/)+- [Webhook-managed example](../../webhook_managed/daytona/README.md)diff --git a/examples/agents_api/sandboxes/application_managed/daytona/main.py b/examples/agents_api/sandboxes/application_managed/daytona/main.pynew file mode 100644index 00000000..ce052f5e--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/daytona/main.py@@ -0,0 +1,110 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "daytona>=0.207.0",+# ]+# ///++"""Run an Agents API task in a Daytona sandbox and clean up both resources."""++import asyncio+import os+import shlex++from daytona import AsyncDaytona, CreateSandboxFromSnapshotParams, SessionExecuteRequest+from openai import AsyncOpenAI++WORKSPACE = "/workspace"+BRIEF = "Migrate a synchronous Python service to async without changing its API.\n"+++async def main() -> None:+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ async with AsyncOpenAI(timeout=360) as client, AsyncDaytona() as daytona:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ sandbox = None+ print(f"Session: {session.id}", flush=True)+ try:+ assert session.environment.type == "self_hosted"+ executor_args = [+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ async with asyncio.timeout(360):+ sandbox = await daytona.create(+ CreateSandboxFromSnapshotParams(+ name=f"agents-api-{session.id[-12:]}",+ language="javascript",+ env_vars={"CODEX_API_KEY": executor_key},+ auto_stop_interval=0,+ ttl_minutes=10,+ ),+ timeout=90,+ )+ print(f"Sandbox: {sandbox.id}", flush=True)+ setup = await sandbox.process.exec(+ "sudo install -d -o daytona -g daytona /workspace && "+ "npm install -g --prefix /home/daytona/.local @openai/codex@alpha",+ timeout=180,+ )+ if setup.exit_code != 0:+ raise RuntimeError("Executor installation failed")+ await sandbox.fs.upload_file(BRIEF.encode(), f"{WORKSPACE}/brief.txt")+ await sandbox.process.create_session("executor")+ command = shlex.join(["/home/daytona/.local/bin/codex", *executor_args])+ await sandbox.process.execute_session_command(+ "executor",+ SessionExecuteRequest(+ command=f"cd {WORKSPACE} && exec {command}",+ run_async=True,+ ),+ )++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ plan = (await sandbox.fs.download_file(f"{WORKSPACE}/plan.md")).decode(+ "utf-8"+ )+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if sandbox is not None:+ async with asyncio.timeout(30):+ await daytona.delete(sandbox, wait=True)+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/digitalocean/README.md b/examples/agents_api/sandboxes/application_managed/digitalocean/README.mdnew file mode 100644index 00000000..8409537e--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/digitalocean/README.md@@ -0,0 +1,39 @@+# Application-managed DigitalOcean sandbox++The application creates an Agents API session and starts a DigitalOcean sandbox+using the `codex-agentapi` template. The template runs `codex exec-server`;+OpenAI runs the agent. The application downloads the generated `plan.md`,+destroys the sandbox, and deletes the session.++## Run++You need access to DigitalOcean's Agent Harness Runtime preview and the+`codex-agentapi` template. This example uses the [PyDo beta SDK](https://github.com/digitalocean/pydo/releases/tag/v0.40.0-beta.7).++Set `DIGITALOCEAN_TOKEN`, `OPENAI_API_KEY`, and a separate restricted+`OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the same owner,+organization, and project. Only the executor key is passed to DigitalOcean.++From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/digitalocean/main.py+```++Dependencies are declared inline. The script reads the flat [agents.yaml](agents.yaml)+manifest and supplies the environment ID and executor key at runtime. Do not+log or save the resolved manifest: it contains the executor key.++The script allows ten minutes for setup and execution, then attempts both+cleanup operations. If creation times out before returning an ID, check+DigitalOcean for `agents-api-<last 12 characters of the printed session ID>`+before retrying.++For follow-up turns, keep both resources until the application is finished.+Do not attach a provisioning webhook handler to these sessions.++## References++- [DigitalOcean sandbox setup example](https://github.com/digitalocean/pydo/tree/v0.40.0-beta.7/examples/agents/doc_python_sdk)+- [DigitalOcean Python SDK](https://github.com/digitalocean/pydo)+- [Webhook-managed example](../../webhook_managed/digitalocean/README.md)diff --git a/examples/agents_api/sandboxes/application_managed/digitalocean/agents.yaml b/examples/agents_api/sandboxes/application_managed/digitalocean/agents.yamlnew file mode 100644index 00000000..5ee6c21c--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/digitalocean/agents.yaml@@ -0,0 +1,15 @@+name: {name}+agent: codex-agentapi+config:+ agent:+ model: gpt-5.6-sol+ environment:+ type: self_hosted+ workspace_directory: /workspace+secrets:+ CODEX_API_KEY: ${EXECUTOR_API_KEY}+env:+ CODEX_ENVIRONMENT_ID: ${ENVIRONMENT_ID}+egress:+ - api.openai.com+ - codex-cloud-environments.chatgpt.comdiff --git a/examples/agents_api/sandboxes/application_managed/digitalocean/main.py b/examples/agents_api/sandboxes/application_managed/digitalocean/main.pynew file mode 100644index 00000000..900879cb--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/digitalocean/main.py@@ -0,0 +1,96 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "pydo[aio]>=0.40.0b7",+# ]+# pydo = { url = "https://github.com/digitalocean/pydo/releases/download/v0.40.0-beta.7/pydo-0.40.0b7-py3-none-any.whl" }+# ///++"""Run an Agents API task in a DigitalOcean sandbox and clean up both resources."""++import asyncio+import os+from pathlib import Path++from openai import AsyncOpenAI+from pydo.aio import Client++WORKSPACE = "/workspace"+MANIFEST = Path(__file__).with_name("agents.yaml")+++async def main() -> None:+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ async with (+ AsyncOpenAI(timeout=360) as client,+ Client(token=os.environ["DIGITALOCEAN_TOKEN"]) as digitalocean,+ ):+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ sandbox_id = None+ print(f"Session: {session.id}", flush=True)+ try:+ assert session.environment.type == "self_hosted"+ async with asyncio.timeout(600):+ response = await digitalocean.agents.create_session(+ params={"openai_session_id": session.id},+ body={+ "manifest": MANIFEST.read_text().replace(+ "{name}", f"agents-api-{session.id[-12:]}"+ ),+ "variables": {+ "ENVIRONMENT_ID": session.environment.id,+ "EXECUTOR_API_KEY": executor_key,+ },+ },+ timeout=180,+ )+ sandbox_id = response["session"]["session_id"]+ print(f"Sandbox: {sandbox_id}", flush=True)++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Write a five-step plan to migrate a synchronous Python service "+ "to async without changing its API. Save it to /workspace/plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ download = await digitalocean.agents.sessions.workspace_download(+ sandbox_id, path="plan.md", timeout=60+ )+ plan = (await download.read()).decode("utf-8")+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if sandbox_id is not None:+ async with asyncio.timeout(30):+ await digitalocean.agents.destroy_session(session_id=sandbox_id)+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/docker/Dockerfile b/examples/agents_api/sandboxes/application_managed/docker/Dockerfilenew file mode 100644index 00000000..3577ff14--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/docker/Dockerfile@@ -0,0 +1,16 @@+FROM python:3.14-slim+++RUN apt-get update \+ && apt-get install --yes --no-install-recommends ca-certificates curl file git nodejs npm poppler-utils ripgrep \+ && npm install --global @openai/codex@alpha \+ && rm -rf /var/lib/apt/lists/*++RUN mkdir -p /workspace /codex-home++ENV CODEX_HOME=/codex-home++WORKDIR /workspace++# Copy a local, non-sensitive sample into the sandbox workspace.+COPY sample_report.txt /workspace/sample_report.txtdiff --git a/examples/agents_api/sandboxes/application_managed/docker/README.md b/examples/agents_api/sandboxes/application_managed/docker/README.mdnew file mode 100644index 00000000..16de84dc--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/docker/README.md@@ -0,0 +1,20 @@+# Application-managed Docker sandbox++The application builds a local image, starts the executor, runs the agent against+`sample_report.txt`, and cleans up the container and API session.++## Run++Start Docker and set `OPENAI_API_KEY` and a separate restricted+`OPENAI_EXECUTOR_API_KEY`. Use keys with the same owner, organization, and project.+From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/docker/main.py+```++The [Dockerfile](Dockerfile) installs Codex and copies the sample into `/workspace`.+This is a local development example, not a hardened multi-tenant sandbox.++To manage cloud compute through OpenAI webhooks, use the+[webhook-managed examples](../../webhook_managed/README.md).diff --git a/examples/agents_api/sandboxes/application_managed/docker/__init__.py b/examples/agents_api/sandboxes/application_managed/docker/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/examples/agents_api/sandboxes/application_managed/docker/main.py b/examples/agents_api/sandboxes/application_managed/docker/main.pynew file mode 100644index 00000000..9109a3ec--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/docker/main.py@@ -0,0 +1,499 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# ]+# ///++from __future__ import annotations++"""Self-hosted Agents API example using a local Docker container."""++import asyncio+import os+import re+import shlex+import shutil+import subprocess+import sys+import time+import uuid+from contextlib import suppress+from contextvars import ContextVar+from pathlib import Path++from openai import AsyncOpenAI+from openai.types.beta import AgentSession, AgentSessionEvent++WORKSPACE = "/workspace"+REPORT_PATH = f"{WORKSPACE}/sample_report.txt"+DEFAULT_DOCKER_IMAGE = "agent-api-sandbox:latest"+EXAMPLE_DIR = Path(__file__).resolve().parent+EXECUTOR_HEALTHCHECK_INTERVAL_SECONDS = 5.0+STREAM_NO_PROGRESS_TIMEOUT_SECONDS = 60.0+STREAM_EXECUTION_TIMEOUT_SECONDS = 300.0+OVERALL_EXECUTION_TIMEOUT_SECONDS = 360.0+SESSION_CREATE_TIMEOUT_SECONDS = 30.0+SESSION_DELETE_TIMEOUT_SECONDS = 15.0+CLEANUP_RESERVED_SECONDS = 25.0+DOCKER_IMAGE_BUILD_TIMEOUT_SECONDS = 240.0+DOCKER_EXECUTOR_START_TIMEOUT_SECONDS = 30.0+DOCKER_PROVISION_TIMEOUT_SECONDS = (+ DOCKER_IMAGE_BUILD_TIMEOUT_SECONDS + DOCKER_EXECUTOR_START_TIMEOUT_SECONDS+)+DOCKER_HEALTHCHECK_TIMEOUT_SECONDS = 5.0+DOCKER_CLEANUP_TIMEOUT_SECONDS = 10.0+_EXECUTION_DEADLINE: ContextVar[float | None] = ContextVar(+ "docker_example_execution_deadline", default=None+)+++class _DockerProvisioning:+ def __init__(self, container_name: str) -> None:+ self.container_name = container_name+ self.container_started = False+ self.aborted = False+++_DOCKER_PROVISIONING: ContextVar[_DockerProvisioning | None] = ContextVar(+ "docker_example_provisioning", default=None+)+++async def main() -> int:+ api_key = os.environ["OPENAI_API_KEY"]+ executor_api_key = os.environ.get("OPENAI_EXECUTOR_API_KEY", api_key)+ container_name: str | None = None+ provisioner: asyncio.Task[str] | None = None+ session: AgentSession | None = None+ started_at = time.monotonic()+ overall_deadline = started_at + OVERALL_EXECUTION_TIMEOUT_SECONDS+ cleanup_reserve = min(+ CLEANUP_RESERVED_SECONDS, OVERALL_EXECUTION_TIMEOUT_SECONDS / 4+ )+ execution_deadline = overall_deadline - cleanup_reserve+ deadline_token = _EXECUTION_DEADLINE.set(execution_deadline)+ provisioning = _DockerProvisioning(f"agent-api-{uuid.uuid4().hex[:12]}")+ provisioning_token = _DOCKER_PROVISIONING.set(provisioning)++ try:+ async with AsyncOpenAI(api_key=api_key) as client:+ try:+ try:+ async with asyncio.timeout_at(execution_deadline):+ try:+ async with asyncio.timeout(+ min(+ SESSION_CREATE_TIMEOUT_SECONDS,+ _remaining(execution_deadline),+ )+ ):+ session = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-sol",+ "instructions": (+ "Create the requested report using files available in "+ "/workspace. Inspect the source file directly, then "+ "cite concrete details and caveats."+ ),+ },+ environment={+ "type": "self_hosted",+ "workspace_directory": WORKSPACE,+ },+ )+ except TimeoutError as error:+ provisioning.aborted = True+ raise RuntimeError(+ "agent session creation exceeded "+ f"{SESSION_CREATE_TIMEOUT_SECONDS:g}-second timeout"+ ) from error++ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError(+ f"expected self-hosted environment, got {environment.type}"+ )+ environment_id = environment.id+ print(f"created session {session.id}")+ print(f"environment id: {environment_id}")++ try:+ async with asyncio.timeout(+ min(+ DOCKER_PROVISION_TIMEOUT_SECONDS,+ _remaining(execution_deadline),+ )+ ):+ provisioner = asyncio.create_task(+ asyncio.to_thread(+ start_docker_sandbox,+ executor_api_key,+ environment_id,+ environment.remote_url,+ )+ )+ container_name = await asyncio.shield(provisioner)+ except TimeoutError as error:+ provisioning.aborted = True+ raise RuntimeError(+ "Docker sandbox provisioning exceeded "+ f"{DOCKER_PROVISION_TIMEOUT_SECONDS:g}-second timeout"+ ) from error++ prompt = (+ f"Create a short report from {REPORT_PATH}. Summarize the main ideas, "+ "mention caveats, and include the sandbox path you inspected."+ )++ print("\nagent output:\n")+ await stream_agent_output(+ client, session, container_name, prompt+ )++ final_session = await client.beta.agents.sessions.retrieve(+ session.id+ )+ print(f"\nfinal status: {final_session.status}")+ return 0 if final_session.status == "idle" else 2+ except TimeoutError as error:+ raise RuntimeError(+ "agent session exceeded "+ f"{OVERALL_EXECUTION_TIMEOUT_SECONDS:g}-second overall execution timeout"+ ) from error+ finally:+ original_error = sys.exc_info()[1]+ cleanup_errors: list[BaseException] = []+ if provisioner is not None and not provisioner.done():+ provisioning.aborted = True+ try:+ async with asyncio.timeout(+ min(+ DOCKER_CLEANUP_TIMEOUT_SECONDS,+ _remaining(overall_deadline),+ )+ ):+ container_name = await provisioner+ except TimeoutError as error:+ cleanup_errors.append(+ RuntimeError(+ "Docker provisioning did not stop before cleanup."+ ).with_traceback(error.__traceback__)+ )+ except Exception as error:+ if original_error is None:+ cleanup_errors.append(error)+ else:+ original_error.add_note(+ f"Docker provisioning also failed: {error}"+ )++ if container_name is None and provisioning.container_started:+ container_name = provisioning.container_name+ if container_name is not None:+ try:+ async with asyncio.timeout(+ min(+ DOCKER_CLEANUP_TIMEOUT_SECONDS,+ _remaining(overall_deadline),+ )+ ):+ await asyncio.to_thread(remove_container, container_name)+ except TimeoutError as error:+ cleanup_errors.append(+ RuntimeError(+ "Docker container cleanup exceeded "+ f"{DOCKER_CLEANUP_TIMEOUT_SECONDS:g}-second timeout"+ ).with_traceback(error.__traceback__)+ )+ except Exception as error:+ cleanup_errors.append(error)++ if session is not None:+ try:+ async with asyncio.timeout(+ min(+ SESSION_DELETE_TIMEOUT_SECONDS,+ _remaining(overall_deadline),+ )+ ):+ await client.beta.agents.sessions.delete(session.id)+ except TimeoutError as error:+ cleanup_errors.append(+ RuntimeError(+ "agent session deletion exceeded "+ f"{SESSION_DELETE_TIMEOUT_SECONDS:g}-second timeout"+ ).with_traceback(error.__traceback__)+ )+ except Exception as error:+ cleanup_errors.append(error)++ if cleanup_errors:+ if original_error is not None:+ for cleanup_error in cleanup_errors:+ original_error.add_note(+ f"Cleanup also failed: {cleanup_error}"+ )+ elif len(cleanup_errors) == 1:+ raise cleanup_errors[0]+ else:+ raise BaseExceptionGroup(+ "self-hosted cleanup failed", cleanup_errors+ )+ finally:+ _DOCKER_PROVISIONING.reset(provisioning_token)+ _EXECUTION_DEADLINE.reset(deadline_token)+++def _remaining(deadline: float) -> float:+ return max(deadline - time.monotonic(), 0.001)+++def start_docker_sandbox(api_key: str, environment_id: str, remote_url: str) -> str:+ if shutil.which("docker") is None:+ raise RuntimeError("Docker CLI is not installed or not on PATH")++ build_docker_image()++ provisioning = _DOCKER_PROVISIONING.get()+ if provisioning is not None and provisioning.aborted:+ raise RuntimeError(+ "Docker sandbox provisioning was cancelled before container startup"+ )+ container_name = (+ provisioning.container_name+ if provisioning is not None+ else f"agent-api-{uuid.uuid4().hex[:12]}"+ )+ command = [+ "docker",+ "run",+ "--detach",+ "--rm",+ "--name",+ container_name,+ "--init",+ "-e",+ "CODEX_API_KEY",+ DEFAULT_DOCKER_IMAGE,+ "codex",+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ]++ print("starting exec server:")+ print(f" {shlex.join(command)}")++ env = os.environ.copy()+ env["CODEX_API_KEY"] = api_key+ if provisioning is not None and provisioning.aborted:+ raise RuntimeError(+ "Docker sandbox provisioning was cancelled before container startup"+ )+ if provisioning is not None:+ provisioning.container_started = True+ try:+ container_id = run_command(+ command, env=env, timeout=DOCKER_EXECUTOR_START_TIMEOUT_SECONDS+ )+ if provisioning is not None and provisioning.aborted:+ raise RuntimeError(+ "Docker sandbox provisioning was cancelled after container startup"+ )+ except Exception as error:+ try:+ remove_container(container_name)+ except Exception as cleanup_error:+ error.add_note(f"Partial Docker container cleanup failed: {cleanup_error}")+ raise+ print(f"started Docker container {container_id[:12]}")+ return container_name+++def build_docker_image() -> None:+ command = [+ "docker",+ "build",+ "--tag",+ DEFAULT_DOCKER_IMAGE,+ str(EXAMPLE_DIR),+ ]++ print("building Docker image:")+ print(f" {shlex.join(command)}")+ run_command(command, echo=True, timeout=DOCKER_IMAGE_BUILD_TIMEOUT_SECONDS)+++async def stream_agent_output(+ client: AsyncOpenAI,+ session: AgentSession,+ container_name: str,+ prompt: str,+) -> None:+ saw_text_delta = False+ loop = asyncio.get_running_loop()+ async with client.beta.agents.sessions.stream(session.id, input=prompt) as events:+ next_event = asyncio.create_task(anext(events))+ try:+ async with asyncio.timeout(STREAM_EXECUTION_TIMEOUT_SECONDS):+ last_progress = loop.time()+ while True:+ completed, _ = await asyncio.wait(+ {next_event}, timeout=EXECUTOR_HEALTHCHECK_INTERVAL_SECONDS+ )+ if not completed:+ await asyncio.to_thread(+ ensure_container_running, container_name+ )+ if (+ loop.time() - last_progress+ >= STREAM_NO_PROGRESS_TIMEOUT_SECONDS+ ):+ raise RuntimeError(+ "agent session made no progress for "+ f"{STREAM_NO_PROGRESS_TIMEOUT_SECONDS:g} seconds"+ )+ continue+ try:+ event = next_event.result()+ except StopAsyncIteration:+ break+ last_progress = loop.time()+ await asyncio.to_thread(ensure_container_running, container_name)+ if event.type == "agent.session.environment.connected":+ print("environment connected")+ if event.type == "agent.session.environment.failed":+ raise RuntimeError(+ f"environment failed: {event.environment.error}"+ )+ if event.type == "agent.session.turn.failed":+ error = (+ event.turn.error.message+ if event.turn.error is not None+ else "unknown error"+ )+ raise RuntimeError(f"session turn failed: {error}")+ if event.type == "agent.session.turn.cancelled":+ raise RuntimeError("session turn was cancelled")+ saw_text_delta = print_event(event, saw_text_delta)+ if event.type == "agent.session.failed":+ raise RuntimeError(f"session failed: {event.to_dict()}")+ if event.type == "error":+ raise RuntimeError(event.error.message)+ next_event = asyncio.create_task(anext(events))+ except TimeoutError as error:+ raise RuntimeError(+ "agent session exceeded "+ f"{STREAM_EXECUTION_TIMEOUT_SECONDS:g}-second execution timeout"+ ) from error+ finally:+ next_event.cancel()+ with suppress(asyncio.CancelledError, StopAsyncIteration):+ await next_event+ print()+++def print_event(event: AgentSessionEvent, saw_text_delta: bool) -> bool:+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ return True+ if event.type == "agent.session.turn.output_text.done" and not saw_text_delta:+ print(event.text)+ return saw_text_delta+++def ensure_container_running(container_name: str) -> None:+ result = subprocess.run(+ ["docker", "inspect", "--format", "{{.State.Running}}", container_name],+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ timeout=DOCKER_HEALTHCHECK_TIMEOUT_SECONDS,+ )+ if result.returncode == 0 and result.stdout.strip() == "true":+ return++ logs = subprocess.run(+ ["docker", "logs", "--tail", "80", container_name],+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=DOCKER_HEALTHCHECK_TIMEOUT_SECONDS,+ ).stdout+ raise RuntimeError(f"Docker sandbox {container_name} is not running:\n{logs}")+++def remove_container(container_name: str) -> None:+ try:+ result = subprocess.run(+ ["docker", "rm", "-f", container_name],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ check=False,+ timeout=DOCKER_CLEANUP_TIMEOUT_SECONDS,+ )+ except subprocess.TimeoutExpired as error:+ raise RuntimeError(+ f"Docker sandbox {container_name} removal exceeded "+ f"{DOCKER_CLEANUP_TIMEOUT_SECONDS:g}-second timeout"+ ) from error++ if result.returncode == 0:+ return++ detail = (result.stderr or result.stdout or "").strip()+ if re.fullmatch(+ r"(?:error response from daemon:\s*|error:\s*)?"+ r"no such (?:container|object):\s*['\"]?"+ + re.escape(container_name)+ + r"['\"]?",+ detail,+ flags=re.IGNORECASE,+ ):+ return++ reason = detail or "Docker returned no diagnostic output."+ raise RuntimeError(+ f"Could not remove Docker sandbox {container_name} "+ f"(exit status {result.returncode}): {reason}"+ )+++def run_command(+ command: list[str],+ env: dict[str, str] | None = None,+ echo: bool = False,+ timeout: float = DOCKER_EXECUTOR_START_TIMEOUT_SECONDS,+) -> str:+ deadline = _EXECUTION_DEADLINE.get()+ if deadline is not None:+ timeout = min(timeout, _remaining(deadline))+ try:+ result = subprocess.run(+ command,+ check=False,+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=timeout,+ )+ except subprocess.TimeoutExpired as error:+ raise RuntimeError(+ f"Command exceeded its {timeout:g}-second timeout: {shlex.join(command)}"+ ) from error+ if result.returncode != 0:+ raise RuntimeError(f"Command failed: {shlex.join(command)}\n{result.stdout}")+ if echo and result.stdout:+ print(result.stdout, end="")+ return result.stdout.strip()+++if __name__ == "__main__":+ raise SystemExit(asyncio.run(main()))diff --git a/examples/agents_api/sandboxes/application_managed/docker/sample_report.txt b/examples/agents_api/sandboxes/application_managed/docker/sample_report.txtnew file mode 100644index 00000000..55d235a1--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/docker/sample_report.txt@@ -0,0 +1,8 @@+Quarterly product review++The team reduced median task latency by 18 percent while holding the error rate+below 1 percent. The largest remaining constraint is cold-start time for newly+provisioned environments. The next milestone is to cut cold starts by half and+add automated regression checks for the three most common workflows.++This file contains synthetic example content only.diff --git a/examples/agents_api/sandboxes/application_managed/e2b/README.md b/examples/agents_api/sandboxes/application_managed/e2b/README.mdnew file mode 100644index 00000000..cff63f79--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/e2b/README.md@@ -0,0 +1,31 @@+# Application-managed E2B sandbox++The application creates an Agents API session and an E2B sandbox, starts+`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.+It prints the plan, kills the sandbox, and deletes the session.++## Run++Set `E2B_API_KEY`, `OPENAI_API_KEY`, and a separate restricted+`OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the same owner,+organization, and project. Only the executor key enters the sandbox.++From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/e2b/main.py+```++Dependencies are declared inline. The script allows six minutes for setup and+execution and attempts both cleanup operations on failure. The sandbox has a+ten-minute timeout. If creation times out before returning an ID, check E2B for+the `agents-session-id` metadata matching the printed session ID before retrying.++For follow-up turns, keep both resources until the application is finished.+Do not attach a provisioning webhook handler to these sessions.++## References++- [E2B documentation](https://e2b.dev/docs)+- [E2B SDK reference](https://e2b.dev/docs/sdk-reference)+- [Webhook-managed example](../../webhook_managed/e2b/README.md)diff --git a/examples/agents_api/sandboxes/application_managed/e2b/main.py b/examples/agents_api/sandboxes/application_managed/e2b/main.pynew file mode 100644index 00000000..6bd8ac6c--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/e2b/main.py@@ -0,0 +1,100 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "e2b>=2.45.1",+# ]+# ///++"""Run an Agents API task in an E2B sandbox and clean up both resources."""++import asyncio+import os+import shlex++from e2b import AsyncSandbox+from openai import AsyncOpenAI++WORKSPACE = "/workspace"+BRIEF = "Migrate a synchronous Python service to async without changing its API.\n"+++async def main() -> None:+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ async with AsyncOpenAI(timeout=360) as client:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ sandbox = None+ print(f"Session: {session.id}", flush=True)+ try:+ assert session.environment.type == "self_hosted"+ executor_args = [+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ async with asyncio.timeout(360):+ sandbox = await AsyncSandbox.create(+ timeout=600,+ metadata={"agents-session-id": session.id},+ network={"allow_public_traffic": False},+ )+ print(f"Sandbox: {sandbox.sandbox_id}", flush=True)+ await sandbox.commands.run(+ "mkdir -p /workspace && npm install -g @openai/codex@alpha",+ user="root",+ timeout=180,+ )+ await sandbox.files.write(f"{WORKSPACE}/brief.txt", BRIEF, user="root")+ await sandbox.commands.run(+ shlex.join(["codex", *executor_args]),+ envs={"CODEX_API_KEY": executor_key},+ user="root",+ cwd=WORKSPACE,+ background=True,+ timeout=0,+ )++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ plan = await sandbox.files.read(f"{WORKSPACE}/plan.md", user="root")+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if sandbox is not None:+ async with asyncio.timeout(30):+ await sandbox.kill()+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/modal/README.md b/examples/agents_api/sandboxes/application_managed/modal/README.mdnew file mode 100644index 00000000..85efe75f--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/modal/README.md@@ -0,0 +1,21 @@+# Application-managed Modal sandbox++The application builds an image remotely, starts a Modal sandbox, connects the+executor, runs the agent against `sample_report.txt`, and cleans up both resources.++## Run++Set `OPENAI_API_KEY` and a separate restricted `OPENAI_EXECUTOR_API_KEY`. Use keys+with the same owner, organization, and project. From the Cookbook repository root:++```bash+uv tool run --from 'modal[api-proxy-support]>=1.3.4,<2' modal setup+uv run examples/agents_api/sandboxes/application_managed/modal/main.py+```++The Modal SDK uses the active profile in `~/.modal.toml`; `MODAL_TOKEN_ID` and+`MODAL_TOKEN_SECRET` override it when set. The sandbox has a 15-minute maximum+lifetime and no inbound port: `codex exec-server` connects outbound to OpenAI.++For a Modal-hosted handler that provisions compute from OpenAI webhooks, use the+[webhook-managed Modal example](../../webhook_managed/modal/README.md).diff --git a/examples/agents_api/sandboxes/application_managed/modal/__init__.py b/examples/agents_api/sandboxes/application_managed/modal/__init__.pynew file mode 100644index 00000000..8b137891--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/modal/__init__.py@@ -0,0 +1 @@+diff --git a/examples/agents_api/sandboxes/application_managed/modal/main.py b/examples/agents_api/sandboxes/application_managed/modal/main.pynew file mode 100644index 00000000..92c83dd2--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/modal/main.py@@ -0,0 +1,365 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "modal[api-proxy-support]>=1.3.4,<2",+# ]+# ///++from __future__ import annotations++"""Self-hosted Agents API example using a Modal Sandbox."""++import asyncio+import os+import shlex+import sys+import time+from contextlib import suppress+from pathlib import Path+from typing import TYPE_CHECKING++from openai import AsyncOpenAI+from openai.types.beta import AgentSession, AgentSessionEvent++if TYPE_CHECKING:+ import modal++WORKSPACE = "/workspace"+REPORT_PATH = f"{WORKSPACE}/sample_report.txt"+DEFAULT_MODAL_APP_NAME = "agents-api-self-hosted-example"+MODAL_SANDBOX_TIMEOUT_SECONDS = 15 * 60+EXAMPLE_DIR = Path(__file__).resolve().parent+EXECUTOR_HEALTHCHECK_INTERVAL_SECONDS = 5.0+STREAM_NO_PROGRESS_TIMEOUT_SECONDS = 60.0+STREAM_EXECUTION_TIMEOUT_SECONDS = 300.0+OVERALL_EXECUTION_TIMEOUT_SECONDS = 360.0+SESSION_CREATE_TIMEOUT_SECONDS = 30.0+SESSION_DELETE_TIMEOUT_SECONDS = 15.0+SANDBOX_CLEANUP_TIMEOUT_SECONDS = 15.0+CLEANUP_RESERVED_SECONDS = 30.0+SANDBOX_STARTUP_TIMEOUT_SECONDS = 120.0+++async def main() -> int:+ api_key = os.environ["OPENAI_API_KEY"]+ executor_api_key = os.environ.get("OPENAI_EXECUTOR_API_KEY", api_key)+ sandbox: modal.Sandbox | None = None+ session: AgentSession | None = None+ overall_deadline = time.monotonic() + OVERALL_EXECUTION_TIMEOUT_SECONDS+ cleanup_reserve = min(+ CLEANUP_RESERVED_SECONDS, OVERALL_EXECUTION_TIMEOUT_SECONDS / 4+ )+ execution_deadline = overall_deadline - cleanup_reserve++ async with AsyncOpenAI(api_key=api_key) as client:+ try:+ try:+ async with asyncio.timeout_at(execution_deadline):+ try:+ async with asyncio.timeout(+ min(+ SESSION_CREATE_TIMEOUT_SECONDS,+ _remaining(execution_deadline),+ )+ ):+ session = await client.beta.agents.sessions.create(+ agent={+ "model": "gpt-5.6-sol",+ "instructions": (+ "Create the requested report using files available in "+ "/workspace. Inspect the source file directly, then "+ "cite concrete details and caveats."+ ),+ },+ environment={+ "type": "self_hosted",+ "workspace_directory": WORKSPACE,+ },+ )+ except TimeoutError as error:+ raise RuntimeError(+ "agent session creation exceeded "+ f"{SESSION_CREATE_TIMEOUT_SECONDS:g}-second timeout"+ ) from error++ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError(+ f"expected self-hosted environment, got {environment.type}"+ )+ environment_id = environment.id+ print(f"created session {session.id}")+ print(f"environment id: {environment_id}")++ try:+ async with asyncio.timeout(+ min(+ SANDBOX_STARTUP_TIMEOUT_SECONDS,+ _remaining(execution_deadline),+ )+ ):+ sandbox = await start_modal_sandbox(+ executor_api_key, environment_id, environment.remote_url+ )+ except TimeoutError as error:+ raise RuntimeError(+ "Modal sandbox startup exceeded "+ f"{SANDBOX_STARTUP_TIMEOUT_SECONDS:g}-second timeout"+ ) from error+ prompt = (+ f"Create a short report from {REPORT_PATH}. Summarize the main ideas, "+ "mention caveats, and include the sandbox path you inspected."+ )++ print("\nagent output:\n")+ await stream_agent_output(client, session, sandbox, prompt)++ final_session = await client.beta.agents.sessions.retrieve(+ session.id+ )+ print(f"\nfinal status: {final_session.status}")+ return 0 if final_session.status == "idle" else 2+ except TimeoutError as error:+ raise RuntimeError(+ "agent session exceeded "+ f"{OVERALL_EXECUTION_TIMEOUT_SECONDS:g}-second overall execution timeout"+ ) from error+ finally:+ original_error = sys.exc_info()[1]+ cleanup_errors: list[BaseException] = []+ if sandbox is not None:+ try:+ async with asyncio.timeout(+ min(+ SANDBOX_CLEANUP_TIMEOUT_SECONDS,+ _remaining(overall_deadline),+ )+ ):+ await stop_modal_sandbox(sandbox)+ except TimeoutError as error:+ failure = RuntimeError(+ "Modal sandbox cleanup exceeded "+ f"{SANDBOX_CLEANUP_TIMEOUT_SECONDS:g}-second timeout"+ )+ for detail in getattr(error, "__notes__", ()):+ failure.add_note(detail)+ cleanup_errors.append(failure.with_traceback(error.__traceback__))+ except Exception as error:+ cleanup_errors.append(error)++ if session is not None:+ try:+ async with asyncio.timeout(+ min(+ SESSION_DELETE_TIMEOUT_SECONDS, _remaining(overall_deadline)+ )+ ):+ await client.beta.agents.sessions.delete(session.id)+ except TimeoutError as error:+ cleanup_errors.append(+ RuntimeError(+ "agent session deletion exceeded "+ f"{SESSION_DELETE_TIMEOUT_SECONDS:g}-second timeout"+ ).with_traceback(error.__traceback__)+ )+ except Exception as error:+ cleanup_errors.append(error)++ if cleanup_errors:+ if original_error is not None:+ for cleanup_error in cleanup_errors:+ original_error.add_note(f"Cleanup also failed: {cleanup_error}")+ for detail in getattr(cleanup_error, "__notes__", ()):+ original_error.add_note(f"Cleanup detail: {detail}")+ elif len(cleanup_errors) == 1:+ raise cleanup_errors[0]+ else:+ raise BaseExceptionGroup(+ "self-hosted cleanup failed", cleanup_errors+ )+++def _remaining(deadline: float) -> float:+ return max(deadline - time.monotonic(), 0.001)+++async def start_modal_sandbox(+ api_key: str, environment_id: str, remote_url: str+) -> modal.Sandbox:+ try:+ import modal+ except ImportError as exc:+ raise RuntimeError(+ "The Modal example dependency is not installed. "+ "Run: uv run examples/agents_api/sandboxes/application_managed/modal/main.py"+ ) from exc++ app = await modal.App.lookup.aio(DEFAULT_MODAL_APP_NAME, create_if_missing=True)+ image = (+ modal.Image.debian_slim(python_version="3.14")+ .apt_install(+ "ca-certificates",+ "curl",+ "file",+ "git",+ "nodejs",+ "npm",+ "poppler-utils",+ "ripgrep",+ )+ .run_commands(+ "mkdir -p /workspace /codex-home",+ "npm install --global @openai/codex@alpha",+ )+ .env({"CODEX_HOME": "/codex-home"})+ .workdir(WORKSPACE)+ .add_local_file(EXAMPLE_DIR / "sample_report.txt", REPORT_PATH, copy=True)+ )+ command = exec_server_command(environment_id, remote_url)++ print("starting exec server in Modal:")+ print(f" {shlex.join(command)}")++ with modal.enable_output():+ sandbox = await modal.Sandbox.create.aio(+ *command,+ app=app,+ image=image,+ # The environment ID selects the target; exec-server separately+ # authenticates its registration request with CODEX_API_KEY.+ secrets=[modal.Secret.from_dict({"CODEX_API_KEY": api_key})],+ timeout=MODAL_SANDBOX_TIMEOUT_SECONDS,+ workdir=WORKSPACE,+ )+ print(f"started Modal sandbox {sandbox.object_id}")+ return sandbox+++def exec_server_command(environment_id: str, remote_url: str) -> list[str]:+ return [+ "codex",+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ]+++async def stream_agent_output(+ client: AsyncOpenAI,+ session: AgentSession,+ sandbox: modal.Sandbox,+ prompt: str,+) -> None:+ saw_text_delta = False+ loop = asyncio.get_running_loop()+ async with client.beta.agents.sessions.stream(session.id, input=prompt) as events:+ next_event = asyncio.create_task(anext(events))+ try:+ async with asyncio.timeout(STREAM_EXECUTION_TIMEOUT_SECONDS):+ last_progress = loop.time()+ while True:+ completed, _ = await asyncio.wait(+ {next_event}, timeout=EXECUTOR_HEALTHCHECK_INTERVAL_SECONDS+ )+ if not completed:+ await ensure_modal_sandbox_running(sandbox)+ if (+ loop.time() - last_progress+ >= STREAM_NO_PROGRESS_TIMEOUT_SECONDS+ ):+ raise RuntimeError(+ "agent session made no progress for "+ f"{STREAM_NO_PROGRESS_TIMEOUT_SECONDS:g} seconds"+ )+ continue+ try:+ event = next_event.result()+ except StopAsyncIteration:+ break+ last_progress = loop.time()+ await ensure_modal_sandbox_running(sandbox)+ if event.type == "agent.session.environment.connected":+ print("environment connected")+ if event.type == "agent.session.environment.failed":+ raise RuntimeError(+ f"environment failed: {event.environment.error}"+ )+ if event.type == "agent.session.turn.failed":+ error = (+ event.turn.error.message+ if event.turn.error is not None+ else "unknown error"+ )+ raise RuntimeError(f"session turn failed: {error}")+ if event.type == "agent.session.turn.cancelled":+ raise RuntimeError("session turn was cancelled")+ saw_text_delta = print_event(event, saw_text_delta)+ if event.type == "agent.session.failed":+ raise RuntimeError(f"session failed: {event.to_dict()}")+ if event.type == "error":+ raise RuntimeError(event.error.message)+ next_event = asyncio.create_task(anext(events))+ except TimeoutError as error:+ raise RuntimeError(+ "agent session exceeded "+ f"{STREAM_EXECUTION_TIMEOUT_SECONDS:g}-second execution timeout"+ ) from error+ finally:+ next_event.cancel()+ with suppress(asyncio.CancelledError, StopAsyncIteration):+ await next_event+ print()+++def print_event(event: AgentSessionEvent, saw_text_delta: bool) -> bool:+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ return True+ if event.type == "agent.session.turn.output_text.done" and not saw_text_delta:+ print(event.text)+ return saw_text_delta+++async def ensure_modal_sandbox_running(sandbox: modal.Sandbox) -> None:+ exit_code = await sandbox.poll.aio()+ if exit_code is None:+ return++ stdout, stderr = await asyncio.gather(+ sandbox.stdout.read.aio(),+ sandbox.stderr.read.aio(),+ )+ logs = "\n".join(part.strip() for part in (stdout, stderr) if part.strip())+ if not logs:+ logs = "(no sandbox logs)"+ raise RuntimeError(+ f"Modal sandbox {sandbox.object_id} exited with code {exit_code}:\n{logs}"+ )+++async def stop_modal_sandbox(sandbox: modal.Sandbox) -> None:+ termination_error: BaseException | None = None+ try:+ async with asyncio.timeout(SANDBOX_CLEANUP_TIMEOUT_SECONDS / 2):+ await sandbox.terminate.aio(wait=True)+ except BaseException as error:+ termination_error = error+ finally:+ try:+ async with asyncio.timeout(SANDBOX_CLEANUP_TIMEOUT_SECONDS / 2):+ await sandbox.detach.aio()+ except BaseException as detach_error:+ if termination_error is None:+ raise+ detail = str(detach_error) or type(detach_error).__name__+ termination_error.add_note(f"Modal sandbox detach also failed: {detail}")++ if termination_error is not None:+ raise termination_error+++if __name__ == "__main__":+ raise SystemExit(asyncio.run(main()))diff --git a/examples/agents_api/sandboxes/application_managed/modal/sample_report.txt b/examples/agents_api/sandboxes/application_managed/modal/sample_report.txtnew file mode 100644index 00000000..55d235a1--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/modal/sample_report.txt@@ -0,0 +1,8 @@+Quarterly product review++The team reduced median task latency by 18 percent while holding the error rate+below 1 percent. The largest remaining constraint is cold-start time for newly+provisioned environments. The next milestone is to cut cold starts by half and+add automated regression checks for the three most common workflows.++This file contains synthetic example content only.diff --git a/examples/agents_api/sandboxes/application_managed/oci/README.md b/examples/agents_api/sandboxes/application_managed/oci/README.mdnew file mode 100644index 00000000..ea6f3641--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/oci/README.md@@ -0,0 +1,88 @@+# Application-managed OCI GenAI Sandbox++Your application creates an Agents API session and an OCI GenAI Sandbox, starts+`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.+It prints the plan, stops and deletes the sandbox, and deletes the session.++## Before you begin++OCI GenAI Sandboxes are in beta. Contact your Oracle account manager to request+access for your account.++Get the beta Python SDK from Oracle. Create a sandbox-enabled Generative AI+Project and save its OCID.++Grant your OCI group permission to manage projects and sandboxes in the chosen+compartment:++```text+allow group <group-name> to manage generative-ai-sandbox in compartment <compartment-name>+allow group <group-name> to manage generative-ai-project in compartment <compartment-name>+```++Use a runtime with Node.js and npm. Allow outbound HTTPS to `registry.npmjs.org`+and `api.openai.com`, plus WebSocket connections to+`codex-cloud-environments.chatgpt.com`. Allow any additional hosts your task needs.++## Configure access++Authenticate an OCI security-token profile with the OCI CLI:++```bash+uv tool run --from oci-cli oci session authenticate --profile-name Sandbox --region us-chicago-1+```++Set `OPENAI_API_KEY` and a separate restricted `OPENAI_EXECUTOR_API_KEY`.+The keys must have the same owner, organization, and project. Only the executor+key enters the sandbox as `CODEX_API_KEY`. See+[executor authentication](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).++Set your project OCID and the path to the beta SDK wheel from Oracle:++```bash+export OCI_SANDBOX_PROJECT_ID="ocid1.generativeaiproject..."+export OCI_SANDBOX_SDK_WHEEL="/path/to/oci-<beta-version>-py3-none-any.whl"+```++The script uses the `Sandbox` profile and `us-chicago-1` region. Optional settings:++| Variable | Default |+| --- | --- |+| `OCI_SANDBOX_PROFILE` | `Sandbox` |+| `OCI_SANDBOX_REGION` | `us-chicago-1` |+| `OCI_SANDBOX_ENDPOINT` | `https://inference.generativeai.<region>.oci.oraclecloud.com` |+| `OCI_SANDBOX_RUNTIME` | `python-3.11` |+| `OCI_SANDBOX_SHAPE` | `SMALL` |+| `OCI_SANDBOX_EXPIRATION` | `PT30M` |++Confirm the runtime, shape, region, and endpoint with your beta onboarding+instructions. The runtime must include npm or support installing it.++## Run++From the Cookbook repository root, run with [uv](https://docs.astral.sh/uv/):++```bash+uv run --with "$OCI_SANDBOX_SDK_WHEEL" examples/agents_api/sandboxes/application_managed/oci/main.py+```++The script declares the Agents API dependency inline and loads Oracle's beta SDK+through `--with`. The beta SDK must provide `oci.generative_ai_sandbox`; use the+package Oracle supplies for your tenancy.++The example waits up to two minutes for sandbox startup and six minutes for the+agent turn. It requests a 30-minute sandbox expiration and attempts cleanup of+both resources in `finally`. If cleanup fails, use the printed IDs to remove the+remaining resources.++Keep the session and sandbox alive for follow-up turns. Do not attach a+provisioning webhook handler to sessions this application manages.++## References++- [OCI Generative AI documentation](https://docs.oracle.com/en-us/iaas/Content/generative-ai/)+- [OCI Python SDK](https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/pythonsdk.htm)+- [OCI TypeScript SDK](https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/typescriptsdk.htm)+- [OCI CLI authentication](https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/clitoken.htm)++The SDK links cover OCI generally. Use Oracle's beta Python SDK for this example.diff --git a/examples/agents_api/sandboxes/application_managed/oci/__init__.py b/examples/agents_api/sandboxes/application_managed/oci/__init__.pynew file mode 100644index 00000000..96a06e1a--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/oci/__init__.py@@ -0,0 +1 @@+"""Application-managed OCI GenAI Sandbox example."""diff --git a/examples/agents_api/sandboxes/application_managed/oci/main.py b/examples/agents_api/sandboxes/application_managed/oci/main.pynew file mode 100644index 00000000..20012603--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/oci/main.py@@ -0,0 +1,278 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["openai>=3.12.0"]+# ///++"""Run an Agents API task in an application-managed OCI GenAI Sandbox."""++from __future__ import annotations++import asyncio+import io+import os+import shlex+import time+from pathlib import Path+from typing import Any++from openai import AsyncOpenAI++WORKSPACE = "/workspace"+CODEX = f"{WORKSPACE}/.local/bin/codex"+DEFAULT_PROFILE = "Sandbox"+DEFAULT_REGION = "us-chicago-1"+SANDBOX_STARTUP_TIMEOUT_SECONDS = 120+SANDBOX_STOP_TIMEOUT_SECONDS = 60+++def build_sandbox_client() -> Any:+ """Build the OCI client with the security-token profile from OCI config."""+ try:+ import oci+ from oci.generative_ai_sandbox import GenerativeAiSandboxClient+ except (ImportError, AttributeError) as error:+ raise RuntimeError(+ "The OCI GenAI Sandboxes preview SDK is not installed. "+ "Follow this example's README to install it from Oracle's beta SDK package."+ ) from error++ profile = os.environ.get("OCI_SANDBOX_PROFILE", DEFAULT_PROFILE)+ region = os.environ.get("OCI_SANDBOX_REGION", DEFAULT_REGION)+ endpoint = os.environ.get(+ "OCI_SANDBOX_ENDPOINT",+ f"https://inference.generativeai.{region}.oci.oraclecloud.com",+ )+ config = oci.config.from_file(profile_name=profile)++ try:+ private_key = oci.signer.load_private_key_from_file(config["key_file"])+ token_path = Path(config["security_token_file"]).expanduser()+ except KeyError as error:+ raise RuntimeError(+ f"OCI profile {profile!r} has no security token. Run: "+ f"oci session authenticate --profile-name {profile} --region {region}"+ ) from error++ signer = oci.auth.signers.SecurityTokenSigner(+ token_path.read_text(encoding="utf-8"), private_key+ )+ client = GenerativeAiSandboxClient(+ config=config,+ service_endpoint=endpoint,+ signer=signer,+ timeout=(10, 60),+ )+ return client+++def wait_for_sandbox_state(+ client: Any,+ sandbox_id: str,+ target_state: str,+ timeout_seconds: float,+) -> None:+ deadline = time.monotonic() + timeout_seconds+ last_state = "unknown"+ while time.monotonic() < deadline:+ last_state = str(client.get_sandbox(sandbox_id).data.lifecycle_state).upper()+ if last_state == target_state:+ return+ time.sleep(1)+ raise TimeoutError(+ f"OCI sandbox {sandbox_id} did not reach {target_state}; last state was {last_state}"+ )+++def create_sandbox(client: Any, project_id: str) -> str:+ from oci.generative_ai_sandbox.models import CreateSandboxDetails++ response = client.create_sandbox(+ project_id,+ CreateSandboxDetails(+ display_name=f"agents-api-{int(time.time())}",+ runtime=os.environ.get("OCI_SANDBOX_RUNTIME", "python-3.11"),+ shape=os.environ.get("OCI_SANDBOX_SHAPE", "SMALL"),+ expiration_duration=os.environ.get("OCI_SANDBOX_EXPIRATION", "PT30M"),+ ),+ )+ return str(response.data.id)+++def install_executor(client: Any, sandbox_id: str) -> None:+ from oci.generative_ai_sandbox.models import RunSandboxCommandDetails++ command = (+ "command -v npm >/dev/null || "+ "{ echo 'This OCI sandbox runtime needs Node.js and npm.' >&2; exit 127; }; "+ f"mkdir -p {WORKSPACE}/.local && "+ f"npm install --global --prefix {WORKSPACE}/.local @openai/codex@alpha"+ )+ output = client.run_sandbox_command_and_wait(+ sandbox_id,+ RunSandboxCommandDetails(command=command, timeout="PT10M"),+ ).data.output+ if output.exit_code != 0:+ detail = output.stderr or output.stdout or "no command output"+ raise RuntimeError(f"Codex installation failed: {detail}")+++def write_brief(client: Any, sandbox_id: str) -> None:+ content = (+ b"Migrate a synchronous Python service to async without changing its API.\n"+ )+ client.write_sandbox_file(+ sandbox_id,+ f"{WORKSPACE}/brief.txt",+ io.BytesIO(content),+ )+++def start_executor(+ client: Any,+ sandbox_id: str,+ environment_id: str,+ executor_key: str,+ remote_url: str,+) -> str:+ from oci.generative_ai_sandbox.models import (+ EnvironmentVariable,+ RunSandboxCommandDetails,+ )++ inner_command = "cd /workspace && exec " + shlex.join(+ [+ CODEX,+ "exec-server",+ "--remote",+ remote_url,+ "--environment-id",+ environment_id,+ ]+ )+ response = client.run_sandbox_command(+ sandbox_id,+ RunSandboxCommandDetails(+ command=f"sh -lc {shlex.quote(inner_command)}",+ environment_variables=[+ EnvironmentVariable(name="CODEX_API_KEY", value=executor_key),+ ],+ timeout="PT30M",+ ),+ )+ return str(response.data.id)+++def read_text_file(client: Any, sandbox_id: str, path: str) -> str:+ content = client.read_sandbox_file(sandbox_id, path).data.content+ if isinstance(content, bytes):+ return content.decode("utf-8")+ return str(content)+++def stop_and_delete_sandbox(client: Any, sandbox_id: str) -> None:+ from oci.generative_ai_sandbox.models import StopSandboxDetails++ try:+ state = str(client.get_sandbox(sandbox_id).data.lifecycle_state).upper()+ if state not in {"STOPPED", "STOPPING"}:+ client.stop_sandbox(sandbox_id, StopSandboxDetails(is_force=False))+ if state != "STOPPED":+ wait_for_sandbox_state(+ client,+ sandbox_id,+ "STOPPED",+ SANDBOX_STOP_TIMEOUT_SECONDS,+ )+ client.delete_sandbox(sandbox_id)+ except Exception as error:+ if getattr(error, "status", None) != 404:+ raise+++async def main() -> None:+ project_id = os.environ["OCI_SANDBOX_PROJECT_ID"]+ application_key = os.environ["OPENAI_API_KEY"]+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ sandbox_client = build_sandbox_client()++ async with AsyncOpenAI(api_key=application_key, timeout=360) as client:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ sandbox_id: str | None = None+ print(f"Session: {session.id}", flush=True)+ try:+ environment = session.environment+ if environment.type != "self_hosted":+ raise RuntimeError(+ f"Expected a self-hosted environment, got {environment.type}"+ )++ sandbox_id = await asyncio.to_thread(+ create_sandbox, sandbox_client, project_id+ )+ print(f"OCI sandbox: {sandbox_id}", flush=True)+ await asyncio.to_thread(+ wait_for_sandbox_state,+ sandbox_client,+ sandbox_id,+ "RUNNING",+ SANDBOX_STARTUP_TIMEOUT_SECONDS,+ )+ await asyncio.to_thread(install_executor, sandbox_client, sandbox_id)+ await asyncio.to_thread(write_brief, sandbox_client, sandbox_id)+ command_id = await asyncio.to_thread(+ start_executor,+ sandbox_client,+ sandbox_id,+ environment.id,+ executor_key,+ environment.remote_url,+ )+ print(f"Executor command: {command_id}", flush=True)++ async with (+ asyncio.timeout(360),+ client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events,+ ):+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ plan = await asyncio.to_thread(+ read_text_file, sandbox_client, sandbox_id, f"{WORKSPACE}/plan.md"+ )+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if sandbox_id is not None:+ await asyncio.to_thread(+ stop_and_delete_sandbox, sandbox_client, sandbox_id+ )+ finally:+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/runloop/README.md b/examples/agents_api/sandboxes/application_managed/runloop/README.mdnew file mode 100644index 00000000..ba106b33--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/runloop/README.md@@ -0,0 +1,32 @@+# Application-managed Runloop sandbox++The application creates an Agents API session and a Runloop devbox, starts+`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.+It prints the plan, shuts down the devbox, and deletes the session.++## Run++Set `RUNLOOP_API_KEY`, `OPENAI_API_KEY`, and a separate restricted+`OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the same owner,+organization, and project. Only the executor key enters the devbox. See+[executor authentication](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).++From the Cookbook repository root, run with [uv](https://docs.astral.sh/uv/):++```bash+uv run examples/agents_api/sandboxes/application_managed/runloop/main.py+```++The script declares its dependencies inline, including the Agents API SDK.+It allows five minutes for setup and execution, then attempts cleanup of both+resources. The devbox also has a ten-minute lifetime as a fallback if the+application exits unexpectedly.++This example uses application-managed provisioning. Do not attach a provisioning+webhook handler to its sessions. For follow-up turns, keep the session and devbox+alive until the application is finished.++## References++- [Runloop documentation](https://docs.runloop.ai/)+- [Runloop Python SDK](https://runloopai.github.io/api-client-python/)diff --git a/examples/agents_api/sandboxes/application_managed/runloop/main.py b/examples/agents_api/sandboxes/application_managed/runloop/main.pynew file mode 100644index 00000000..c8bd7d8d--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/runloop/main.py@@ -0,0 +1,104 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "runloop-api-client>=1.31.0",+# ]+# ///++"""Run an Agents API task in a Runloop devbox and clean up both resources."""++import asyncio+import os+import shlex++from openai import AsyncOpenAI+from runloop_api_client import AsyncRunloopSDK++WORKSPACE = "/home/user/workspace"+CODEX = "/home/user/.codex-runtime/node_modules/.bin/codex"+++async def main() -> None:+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ async with AsyncOpenAI(timeout=360) as client, AsyncRunloopSDK() as runloop:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ devbox = None+ print(f"Session: {session.id}", flush=True)+ try:+ assert session.environment.type == "self_hosted"+ async with asyncio.timeout(300):+ devbox = await runloop.devbox.create(+ name=f"agents-api-{session.id[-12:]}",+ environment_variables={"CODEX_API_KEY": executor_key},+ launch_parameters={"keep_alive_time_seconds": 600},+ )+ print(f"Devbox: {devbox.id}", flush=True)+ setup = await devbox.cmd.exec(+ f"mkdir -p {WORKSPACE} && "+ "npm install --prefix /home/user/.codex-runtime @openai/codex@alpha"+ )+ if setup.exit_code != 0:+ raise RuntimeError(+ f"Executor installation failed: {await setup.stderr()}"+ )+ await devbox.file.write(+ file_path=f"{WORKSPACE}/brief.txt",+ contents="Migrate a synchronous Python service to async without changing its API.\n",+ )+ await devbox.cmd.exec_async(+ f"cd {WORKSPACE} && exec "+ + shlex.join(+ [+ CODEX,+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ )+ )++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ plan = await devbox.file.read(file_path=f"{WORKSPACE}/plan.md")+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if devbox is not None:+ async with asyncio.timeout(30):+ await devbox.shutdown()+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/application_managed/vercel/README.md b/examples/agents_api/sandboxes/application_managed/vercel/README.mdnew file mode 100644index 00000000..7effb7c8--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/vercel/README.md@@ -0,0 +1,32 @@+# Application-managed Vercel sandbox++The application creates an Agents API session and a Vercel sandbox, starts+`codex exec-server`, and asks the agent to turn `brief.txt` into `plan.md`.+It prints the plan, destroys the sandbox, and deletes the session.++## Run++Set `VERCEL_TOKEN`, `VERCEL_TEAM_ID`, `VERCEL_PROJECT_ID`, `OPENAI_API_KEY`, and+a separate restricted `OPENAI_EXECUTOR_API_KEY`. The OpenAI keys must have the+same owner, organization, and project. Only the executor key enters the sandbox.++From the Cookbook repository root:++```bash+uv run examples/agents_api/sandboxes/application_managed/vercel/main.py+```++Dependencies are declared inline. The script allows six minutes for setup and+execution and attempts both cleanup operations on failure. It creates a+non-persistent sandbox with a ten-minute execution limit. If creation times out,+check Vercel for `agents-api-<last 12 characters of the printed session ID>`+before retrying.++For follow-up turns, keep both resources until the application is finished.+Do not attach a provisioning webhook handler to these sessions.++## References++- [Vercel Sandbox documentation](https://vercel.com/docs/sandbox)+- [Vercel Sandbox SDK reference](https://vercel.com/docs/sandbox/sdk-reference)+- [Webhook-managed example](../../webhook_managed/vercel/README.md)diff --git a/examples/agents_api/sandboxes/application_managed/vercel/main.py b/examples/agents_api/sandboxes/application_managed/vercel/main.pynew file mode 100644index 00000000..f76eb3dc--- /dev/null+++ b/examples/agents_api/sandboxes/application_managed/vercel/main.py@@ -0,0 +1,110 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "vercel>=0.10.0",+# ]+# ///++"""Run an Agents API task in a Vercel sandbox and clean up both resources."""++import asyncio+import os+import shlex++from openai import AsyncOpenAI+from vercel.sandbox import create_sandbox++WORKSPACE = "/vercel/sandbox/workspace"+BRIEF = "Migrate a synchronous Python service to async without changing its API.\n"+++async def main() -> None:+ executor_key = os.environ["OPENAI_EXECUTOR_API_KEY"]+ async with AsyncOpenAI(timeout=360) as client:+ session = await client.beta.agents.sessions.create(+ agent={"model": "gpt-5.6-sol"},+ environment={"type": "self_hosted", "workspace_directory": WORKSPACE},+ )+ sandbox = None+ print(f"Session: {session.id}", flush=True)+ try:+ assert session.environment.type == "self_hosted"+ executor_args = [+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ async with asyncio.timeout(360):+ sandbox = await create_sandbox(+ name=f"agents-api-{session.id[-12:]}",+ execution_time_limit=600,+ persistent=False,+ )+ print(f"Sandbox: {sandbox.name}", flush=True)+ setup = await sandbox.run_process(+ "bash",+ [+ "-lc",+ f"mkdir -p {WORKSPACE} && npm install --prefix /vercel/sandbox/.codex-runtime @openai/codex@alpha",+ ],+ kill_after=180,+ capture_output=True,+ )+ if setup.returncode != 0:+ raise RuntimeError("Executor installation failed")+ await sandbox.fs.write_text(f"{WORKSPACE}/brief.txt", BRIEF)+ command = shlex.join(+ [+ "/vercel/sandbox/.codex-runtime/node_modules/.bin/codex",+ *executor_args,+ ]+ )+ await sandbox.create_process(+ "bash",+ ["-lc", f"cd {WORKSPACE} && exec {command}"],+ env={"CODEX_API_KEY": executor_key},+ kill_after=600,+ )++ async with client.beta.agents.sessions.stream(+ session.id,+ input="Read brief.txt and write a five-step migration plan to plan.md.",+ ) as events:+ async for event in events:+ if event.type in {+ "error",+ "agent.session.environment.failed",+ "agent.session.failed",+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if (+ event.type == "agent.session.turn.completed"+ and event.turn.subagent_id is None+ ):+ break+ else:+ raise RuntimeError("Stream ended without a completed turn")++ plan = await sandbox.fs.read_text(f"{WORKSPACE}/plan.md")+ if not plan.strip():+ raise RuntimeError("The agent did not write a migration plan")+ print(f"\n\nplan.md:\n{plan}")+ finally:+ try:+ if sandbox is not None:+ async with asyncio.timeout(30):+ await sandbox.destroy()+ finally:+ async with asyncio.timeout(30):+ await client.beta.agents.sessions.delete(session.id)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/webhook_managed/.gitignore b/examples/agents_api/sandboxes/webhook_managed/.gitignorenew file mode 100644index 00000000..aa25a1ba--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/.gitignore@@ -0,0 +1,6 @@+.env*+!.env.example+.wrangler/+.vercel/+node_modules/+.controller.jsondiff --git a/examples/agents_api/sandboxes/webhook_managed/README.md b/examples/agents_api/sandboxes/webhook_managed/README.mdnew file mode 100644index 00000000..2093a125--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/README.md@@ -0,0 +1,136 @@+# Webhook-managed sandboxes++Run the agent through the Agents API and let a webhook handler in your sandbox+provider account start and reconnect its sandbox.++## How it works++- **Application:** [client.py](client.py) creates sessions, sends input, and streams+ results. The same client works with every provider below; it imports no provider SDK.+- **Provider handler:** deployed once, it receives OpenAI webhooks and starts or+ reconnects the sandbox executor when an environment connection is required.++## Choose a handler++| Provider | Handler code | Setup |+| --- | --- | --- |+| Modal | [handler.py](modal/handler.py) | [Deploy](modal/README.md) |+| Vercel | [api/webhook.ts](vercel/api/webhook.ts) and [api/provision.ts](vercel/api/provision.ts) | [Deploy](vercel/README.md) |+| Cloudflare | [src/index.ts](cloudflare/src/index.ts) | [Deploy](cloudflare/README.md) |+| Blaxel | [handler.py](blaxel/handler.py) | [Deploy](blaxel/README.md) |+| Daytona | [handler.py](daytona/handler.py) | [Deploy](daytona/README.md) |+| E2B | [handler.py](e2b/handler.py) | [Deploy](e2b/README.md) |+| DigitalOcean | [handler.py](digitalocean/handler.py) | [Deploy](digitalocean/README.md) |++Complete the setup below, deploy one provider's handler, then run the shared+client. For direct provisioning from your application, use+[application-managed sandboxes](../application_managed/README.md).++## Set up once++1. Install [uv](https://docs.astral.sh/uv/getting-started/installation/) and run the+ commands below from the Cookbook repository root. Each Python script declares its+ dependencies inline; `uv run` installs them automatically.+2. Set your application's `OPENAI_API_KEY`, then create an agent:++ ```bash+ uv run examples/agents_api/sandboxes/webhook_managed/client.py --create-agent sandbox-demo+ ```++ Example output:++ ```json+ {"agent_id": "agent_..."}+ ```++ Set `OPENAI_AGENT_ID` to the returned `agent_id`, replacing the placeholder below.+ If you already have an agent, use its ID instead.++ ```bash+ export OPENAI_AGENT_ID="agent_..."+ ```++ Use the same ID in your application and handler. `OPENAI_AGENT_ID` is a filter+ specific to these examples: the handler ignores sessions for other agents.+ The default model is `gpt-5.6-sol`; use `--model` when creating an agent with a+ different supported model.+3. Follow one provider's README to configure credentials, deploy its handler, and+ register the webhook. Enable `agent.session.action_required` and+ `agent.session.failed`, then install the signing secret before running a session.++### Credentials++| Variable | Where it is used |+| --- | --- |+| `OPENAI_API_KEY` | Application and controller. The application creates sessions; the controller reads their current state. |+| `OPENAI_EXECUTOR_API_KEY` | Passed to each worker as `CODEX_API_KEY`. Grant **List models → Read** and set other permissions to **None**. |+| `OPENAI_WEBHOOK_SECRET` | Controller only. Verifies deliveries from your OpenAI project. |++The two API keys must have the same organization, project, and user or service-account+owner. Your network policies must allow API requests from the sandbox provider.+Keep the application key and signing secret out of worker sandboxes. Configure+provider credentials as described in its README.++When changing either API key, update the provider's stored credentials and redeploy+the handler. Keep the existing webhook signing secret. A key from the same project+but a different user or service account cannot register the session's executor.++## Run and reconnect++```bash+uv run examples/agents_api/sandboxes/webhook_managed/client.py \+ --agent-id "$OPENAI_AGENT_ID" \+ --input "Use the shell to write hello to /workspace/hello.txt, then read it."+```++The client prints the session ID; save it as `SESSION_ID` for follow-up input.+To reconnect after stopping or pausing the sandbox, keep the API session and run:++```bash+uv run examples/agents_api/sandboxes/webhook_managed/client.py \+ --session-id "$SESSION_ID" \+ --input "Run a shell command to print hello again."+```++If the executor is offline, the new input triggers a connection-required webhook.+The handler resumes or replaces the sandbox, depending on the provider. The input+request waits for the executor; do not submit it again while it is waiting.+OpenAI waits up to five minutes; this client uses a ten-minute HTTP timeout.++## Use multiple providers++Each handler manages sessions for one `OPENAI_AGENT_ID`. If you deploy more than+one provider in the same OpenAI project, assign a different agent to each. Do not+let multiple handlers provision the same session.++## Lifecycle and cleanup++- `action_required` with `environment_connection`: retrieve current state, then+ start or reconnect only if that action still exists.+- `failed`: clean up the sandbox only if the current session is still failed.+- Other events: ignored. These examples do not shut down on `idle`.++Workers have a 30-minute lifetime or timeout by default. This can interrupt an+active turn; set limits above your expected task duration. E2B refreshes its+running timeout on reconnect; Daytona's TTL counts from creation. See each+provider's README for persistence behavior. Replacing a sandbox does not restore+its files or replay interrupted commands.++The Blaxel, Daytona, and E2B controllers also have time limits. Keep the controller+available while sessions need it. For a long-running deployment, provide persistent+controller hosting and queue storage, monitor provisioning failures, and reconcile+jobs that exhaust their retries.++When finished, stop/delete provider compute **and** delete the API session:++```bash+uv run examples/agents_api/sandboxes/webhook_managed/client.py --session-id "$SESSION_ID" --delete+```++Stop new input before cleanup. There is no session-deletion webhook, so removing+the API session does not release provider resources. When retiring a controller,+remove its OpenAI webhook first. Handle input timeouts in your application; the+wakeup webhook does not guarantee recovery of a pending input after an API restart.++See [Manage Sandbox Lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle)+for the shared protocol and recovery limits.diff --git a/examples/agents_api/sandboxes/webhook_managed/blaxel/README.md b/examples/agents_api/sandboxes/webhook_managed/blaxel/README.mdnew file mode 100644index 00000000..b5f5e51f--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/blaxel/README.md@@ -0,0 +1,47 @@+# Blaxel webhook-managed sandbox++A controller sandbox exposes a signature-verified FastAPI endpoint. It saves work+to SQLite before returning `200`; one background worker starts session sandboxes.+The queue survives controller process restarts, but not deletion of the controller.++## Deploy++Create an agent using the [shared setup](../README.md#set-up-once). Run the+deployment command below from the Cookbook repository root.++Provide these environment variables through your secret manager:++- `BL_API_KEY`, `BL_WORKSPACE`: Blaxel account credentials.+- `BL_REGION`: optional region; defaults to `us-pdx-1` for controller and workers.+- `OPENAI_API_KEY`: controller/session-read credential.+- `OPENAI_AGENT_ID`: agent ID from the shared setup.+- `OPENAI_EXECUTOR_API_KEY`: restricted worker credential.+- `OPENAI_WEBHOOK_SECRET`: signing secret, once the webhook has been registered.++```bash+uv run examples/agents_api/sandboxes/webhook_managed/blaxel/deploy.py+```++The deployment creates a controller and prints its public webhook URL. Until the+signing secret is configured, the endpoint returns `503`. Register the URL with+OpenAI, set the real signing secret, and rerun deployment. Then use the+[shared client](../README.md#run-and-reconnect).++Rerun deployment after changing credentials; keep the same signing secret unless+you rotate it in OpenAI.++Only the controller receives the application and Blaxel credentials. Session+workers receive only the restricted executor key. Failed provisioning gets up to+five attempts. The controller expires after two hours. For a long-running service,+provide persistent hosting and queue storage for the controller.++## Stop or clean up++The handler logs each session's sandbox name. Delete that worker in the Blaxel+dashboard to release compute after a turn. A replacement starts with a fresh filesystem.+For final cleanup, delete the API session too.++When finished, remove the OpenAI webhook, then delete the+`agents-api-webhook-controller` sandbox and any remaining+workers created by this example. Do not delete other workspace sandboxes. Workers+are also labeled with their Agents API session ID and have a 30-minute TTL.diff --git a/examples/agents_api/sandboxes/webhook_managed/blaxel/deploy.py b/examples/agents_api/sandboxes/webhook_managed/blaxel/deploy.pynew file mode 100644index 00000000..3b0fab46--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/blaxel/deploy.py@@ -0,0 +1,96 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "blaxel",+# ]+# ///++"""Deploy the webhook controller. Keep all credentials in environment variables."""++from __future__ import annotations++import asyncio+import os+from pathlib import Path++from blaxel.core.sandbox import SandboxInstance++NAME = "agents-api-webhook-controller"+++async def main() -> None:+ required = [+ "OPENAI_API_KEY",+ "OPENAI_EXECUTOR_API_KEY",+ "OPENAI_AGENT_ID",+ "BL_API_KEY",+ "BL_WORKSPACE",+ ]+ values = {key: os.environ[key] for key in required}+ values["BL_REGION"] = os.environ.get("BL_REGION", "us-pdx-1")+ values["OPENAI_WEBHOOK_SECRET"] = os.environ.get(+ "OPENAI_WEBHOOK_SECRET", "pending-webhook-registration"+ )+ sandbox = await SandboxInstance.create_if_not_exists(+ {+ "name": NAME,+ "image": "blaxel/node:latest",+ "region": values["BL_REGION"],+ "memory": 2048,+ "ttl": "2h",+ "ports": [+ {"name": "sandbox-api", "target": 8080, "protocol": "HTTP"},+ {"name": "webhook", "target": 8000, "protocol": "HTTP"},+ ],+ }+ )+ setup = await sandbox.process.exec(+ {+ "command": "apk add --no-cache python3 py3-pip && python3 -m venv /opt/controller && /opt/controller/bin/pip install uv && mkdir -p /app",+ "wait_for_completion": True,+ "timeout": 180,+ }+ )+ if setup.exit_code != 0:+ raise RuntimeError("Controller dependency installation failed")+ await sandbox.fs.write(+ "/app/handler.py", Path(__file__).with_name("handler.py").read_text()+ )+ install = await sandbox.process.exec(+ {+ "command": "/opt/controller/bin/uv pip install --python /opt/controller/bin/python -r /app/handler.py",+ "wait_for_completion": True,+ "timeout": 180,+ }+ )+ if install.exit_code != 0:+ raise RuntimeError("Controller dependency installation failed")+ # A redeploy replaces only this controller process, retaining the disk-backed queue.+ for process in await sandbox.process.list():+ if process.name == "webhook-controller":+ await sandbox.process.kill(process.name)+ await sandbox.process.exec(+ {+ "name": "webhook-controller",+ "command": "/opt/controller/bin/uvicorn handler:app --host 0.0.0.0 --port 8000",+ "working_dir": "/app",+ "env": values,+ "wait_for_completion": False,+ "keep_alive": True,+ "timeout": 7200,+ }+ )+ preview = await sandbox.previews.create_if_not_exists(+ {+ "metadata": {"name": "webhook"},+ "spec": {"port": 8000, "public": True},+ }+ )+ if preview.spec is None or not preview.spec.url:+ raise RuntimeError("Controller preview URL is unavailable")+ print(f"Webhook: {preview.spec.url}/webhook")+ print(f"Controller: {NAME} (expires after two hours)")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.py b/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.pynew file mode 100644index 00000000..28630f3c--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/blaxel/handler.py@@ -0,0 +1,195 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "blaxel",+# "fastapi[standard]",+# "httpx",+# "openai>=3.12.0",+# "uvicorn",+# ]+# ///++"""A small, single-process webhook controller running in a Blaxel sandbox."""++from __future__ import annotations++import asyncio+import hashlib+import json+import os+import shlex+import sqlite3+import time+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from blaxel.core.sandbox import SandboxInstance+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from openai import AsyncOpenAI, InvalidWebhookSignatureError, NotFoundError, OpenAI++DB_PATH = os.environ.get("QUEUE_PATH", "/app/pending.sqlite3")+++def sandbox_name(session_id: str) -> str:+ return f"agents-webhook-{hashlib.sha256(session_id.encode()).hexdigest()[:24]}"+++async def reconcile(session_id: str) -> None:+ async with AsyncOpenAI(timeout=30) as client:+ try:+ session = await client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ return+ if (+ session.environment.type != "self_hosted"+ or session.agent.id != os.environ["OPENAI_AGENT_ID"]+ ):+ return+ name = sandbox_name(session_id)+ if session.status == "failed":+ try:+ await SandboxInstance.delete(name)+ except Exception as error:+ if getattr(error, "status_code", None) != 404:+ raise+ return+ action = next(+ (a for a in session.required_actions if a.type == "environment_connection"),+ None,+ )+ if action is None:+ return+ sandbox = await SandboxInstance.create_if_not_exists(+ {+ "name": name,+ "image": "blaxel/node:latest",+ "region": os.environ.get("BL_REGION", "us-pdx-1"),+ "ttl": "30m",+ "labels": {"agents-session-id": session_id},+ }+ )+ setup = await sandbox.process.exec(+ {+ "command": "mkdir -p /workspace && (command -v codex || npm install -g @openai/codex@alpha) && (command -v rg || apk add --no-cache ripgrep util-linux)",+ "wait_for_completion": True,+ "timeout": 120,+ }+ )+ if setup.exit_code != 0:+ raise RuntimeError("Executor setup failed")+ # The controller serializes jobs; flock also prevents duplicate executors.+ command = shlex.join(+ [+ "flock",+ "-n",+ "/tmp/codex-executor.lock",+ "codex",+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ )+ await sandbox.process.exec(+ {+ "command": command,+ "working_dir": "/workspace",+ "wait_for_completion": False,+ "keep_alive": True,+ "timeout": 1800,+ "env": {"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},+ }+ )+ print(+ json.dumps(+ {"session_id": session_id, "sandbox_name": name, "action": "started"}+ ),+ flush=True,+ )+++async def drain_queue(db: sqlite3.Connection) -> None:+ while True:+ row = db.execute(+ "SELECT session_id, attempts FROM jobs WHERE retry_at <= ? LIMIT 1",+ (time.time(),),+ ).fetchone()+ if row is None:+ await asyncio.sleep(1)+ continue+ session_id, attempts = row+ try:+ await reconcile(session_id)+ except Exception as error:+ # Persist retries across controller process restarts; never log secrets.+ if attempts >= 4:+ db.execute("DELETE FROM jobs WHERE session_id = ?", (session_id,))+ else:+ db.execute(+ "UPDATE jobs SET attempts = ?, retry_at = ? WHERE session_id = ?",+ (attempts + 1, time.time() + 10, session_id),+ )+ print(+ json.dumps(+ {"session_id": session_id, "error_type": type(error).__name__}+ ),+ flush=True,+ )+ else:+ db.execute("DELETE FROM jobs WHERE session_id = ?", (session_id,))+ db.commit()+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncIterator[None]:+ db = sqlite3.connect(DB_PATH)+ db.execute(+ "CREATE TABLE IF NOT EXISTS jobs (session_id TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, retry_at REAL DEFAULT 0)"+ )+ app.state.db = db+ task = asyncio.create_task(drain_queue(db))+ try:+ yield+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ db.close()+++app = FastAPI(lifespan=lifespan)++[email protected]("/health")+async def health() -> dict[str, bool]:+ return {"ok": True}++[email protected]("/webhook")+async def webhook(request: Request) -> JSONResponse:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret or secret == "pending-webhook-registration":+ return JSONResponse({"error": "Webhook not configured"}, status_code=503)+ payload = (await request.body()).decode()+ with OpenAI(api_key="unused", webhook_secret=secret) as verifier:+ try:+ verifier.webhooks.verify_signature(payload=payload, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError):+ return JSONResponse({"error": "Invalid signature"}, status_code=400)+ event = json.loads(payload)+ if event["type"] == "agent.session.failed" or (+ event["type"] == "agent.session.action_required"+ and event["data"]["required_action"]["type"] == "environment_connection"+ ):+ request.app.state.db.execute(+ "INSERT OR IGNORE INTO jobs(session_id) VALUES (?)", (event["data"]["id"],)+ )+ request.app.state.db.commit()+ return JSONResponse({"ok": True})+++if __name__ == "__main__":+ import uvicorn++ uvicorn.run(app, host="0.0.0.0", port=8000)diff --git a/examples/agents_api/sandboxes/webhook_managed/client.py b/examples/agents_api/sandboxes/webhook_managed/client.pynew file mode 100644index 00000000..edf86605--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/client.py@@ -0,0 +1,83 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# ]+# ///++"""Use Agents API without importing a sandbox provider SDK."""++from __future__ import annotations++import argparse+import asyncio+import json++from openai import AsyncOpenAI+++async def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--create-agent", metavar="NAME")+ parser.add_argument("--agent-id")+ parser.add_argument("--session-id")+ parser.add_argument("--delete", action="store_true")+ parser.add_argument("--model", default="gpt-5.6-sol")+ parser.add_argument("--workspace", default="/workspace")+ parser.add_argument(+ "--input", default="Run a shell command to print hello from the sandbox."+ )+ args = parser.parse_args()++ async with AsyncOpenAI(timeout=600) as client:+ if args.create_agent:+ agent = await client.beta.agents.create(+ model=args.model, name=args.create_agent+ )+ print(json.dumps({"agent_id": agent.id}))+ return+ if args.delete:+ if not args.session_id:+ parser.error(+ "--delete requires --session-id; stop provider compute separately"+ )+ await client.beta.agents.sessions.delete(args.session_id)+ print(json.dumps({"deleted": args.session_id}))+ return+ if args.session_id:+ session = await client.beta.agents.sessions.retrieve(args.session_id)+ else:+ if not args.agent_id:+ parser.error(+ "Pass --agent-id from --create-agent, or an existing --session-id"+ )+ session = await client.beta.agents.sessions.create(+ agent_id=args.agent_id,+ environment={+ "type": "self_hosted",+ "workspace_directory": args.workspace,+ },+ )+ print(json.dumps({"session_id": session.id}), flush=True)+ completed = False+ async with client.beta.agents.sessions.stream(+ session.id, input=args.input+ ) as events:+ async for event in events:+ if event.type in {+ "agent.session.turn.failed",+ "agent.session.turn.cancelled",+ "agent.session.failed",+ }:+ raise RuntimeError(f"Agent failed: {event.type}")+ if event.type == "agent.session.turn.output_text.delta":+ print(event.delta, end="", flush=True)+ if event.type == "agent.session.turn.completed":+ completed = True+ if not completed:+ raise RuntimeError("Stream ended without a completed turn")+ print()+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/.dockerignore b/examples/agents_api/sandboxes/webhook_managed/cloudflare/.dockerignorenew file mode 100644index 00000000..5d0f124f--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/.dockerignore@@ -0,0 +1,2 @@+*+!Dockerfilediff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/Dockerfile b/examples/agents_api/sandboxes/webhook_managed/cloudflare/Dockerfilenew file mode 100644index 00000000..26fb19a0--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/Dockerfile@@ -0,0 +1,4 @@+FROM docker.io/cloudflare/sandbox:0.12.8+RUN apt-get update && apt-get install -y --no-install-recommends ripgrep util-linux \+ && npm install -g @openai/codex@alpha \+ && rm -rf /var/lib/apt/lists/*diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/README.md b/examples/agents_api/sandboxes/webhook_managed/cloudflare/README.mdnew file mode 100644index 00000000..a39ba5e1--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/README.md@@ -0,0 +1,57 @@+# Cloudflare webhook-managed sandbox++The Worker verifies the signature and persists a wakeup in a per-session Durable+Object. Its alarm starts the Sandbox executor. Durable storage handles retries;+the session ID identifies the sandbox, and an OS lock prevents duplicate executors.++## Deploy++Use a Cloudflare account with Workers and Containers access, Node.js, and Docker.+Create the agent using the [shared setup](../README.md#set-up-once). In this directory:++```bash+npm ci+npx wrangler login+```++Set `OPENAI_AGENT_ID` in `wrangler.jsonc` to the agent ID from the shared setup.+Add secrets using the CLI's prompts:++```bash+npx wrangler secret put OPENAI_API_KEY+npx wrangler secret put OPENAI_EXECUTOR_API_KEY+npx wrangler secret put OPENAI_WEBHOOK_SECRET+npx wrangler secret put SANDBOX_CONTROL_TOKEN+npm run deploy+```++Use a separate random control token for the cleanup endpoint. For the first+deployment only, the signing value may be `pending-webhook-registration`; the+receiver rejects it. The SDK and Dockerfile use matching Sandbox versions.++Register `https://YOUR_WORKER.workers.dev/webhook` with OpenAI. Set the real signing+secret using `wrangler secret put OPENAI_WEBHOOK_SECRET`, then deploy again.+Run the [shared client](../README.md#run-and-reconnect).++Keep `OPENAI_AGENT_ID` set when redeploying; sessions for other agents are ignored.++## Stop or clean up++Call the authenticated cleanup endpoint after a turn finishes:++```python+import os+import httpx++response = httpx.delete(+ f"{os.environ['WORKER_URL']}/sandboxes/{os.environ['SESSION_ID']}",+ headers={"Authorization": f"Bearer {os.environ['SANDBOX_CONTROL_TOKEN']}"},+ timeout=60,+)+response.raise_for_status()+```++A following input triggers a new connection. Final cleanup also requires deleting+the API session. The controller schedules a maximum-lifetime cleanup alarm because+the executor keeps the container alive. Replacement containers have a fresh filesystem.+Remove the OpenAI webhook before deleting the Worker and its containers.diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/package-lock.json b/examples/agents_api/sandboxes/webhook_managed/cloudflare/package-lock.jsonnew file mode 100644index 00000000..94c28d52--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/package-lock.json@@ -0,0 +1,1568 @@+{+ "name": "agents-api-webhook-cloudflare",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "agents-api-webhook-cloudflare",+ "dependencies": {+ "@cloudflare/sandbox": ">=0.12.8",+ "openai": ">=7.5.0"+ },+ "devDependencies": {+ "@cloudflare/workers-types": ">=4.20260702.1",+ "typescript": "^5.9",+ "wrangler": ">=4.90.0"+ }+ },+ "node_modules/@cloudflare/containers": {+ "version": "0.3.7",+ "integrity": "sha512-DM9dm3FnIBSyiSJ1FLavKwl/lk3oAmTaynCzZQ9pZR0ncRPquSxkxd8Nu2MFILxmDDsPkxKsSNEh9mHHMty4Fw==",+ "license": "MIT OR Apache-2.0"+ },+ "node_modules/@cloudflare/kv-asset-handler": {+ "version": "0.5.0",+ "integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/@cloudflare/sandbox": {+ "version": "0.12.8",+ "integrity": "sha512-xrmVqqfCBN6jNIRthICs/AwF2uUL9eH4yavjXHr9cFWpKalcPFsZY85CGddAG58Anx5WcEWTKHcM9w7Imf1eKA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@cloudflare/containers": "^0.3.5",+ "aws4fetch": "^1.0.20",+ "capnweb": "^0.8.0",+ "hono": "^4.13.0"+ },+ "peerDependencies": {+ "@openai/agents": "^0.3.3",+ "@opencode-ai/sdk": "^1.1.40",+ "@xterm/xterm": ">=5.0.0"+ },+ "peerDependenciesMeta": {+ "@openai/agents": {+ "optional": true+ },+ "@opencode-ai/sdk": {+ "optional": true+ },+ "@xterm/xterm": {+ "optional": true+ }+ }+ },+ "node_modules/@cloudflare/unenv-preset": {+ "version": "2.16.1",+ "integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "peerDependencies": {+ "unenv": "2.0.0-rc.24",+ "workerd": ">1.20260305.0 <2.0.0-0"+ },+ "peerDependenciesMeta": {+ "workerd": {+ "optional": true+ }+ }+ },+ "node_modules/@cloudflare/workerd-darwin-64": {+ "version": "1.20260507.1",+ "integrity": "sha512-S85aMwcaPJUjKWDiG6iMMnioKWtPLACa6m0j/EhHR1GYfVpnxb974cBc6d25L+sf7jHWHJI2u5hGp0UTJ7MtXQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-darwin-arm64": {+ "version": "1.20260507.1",+ "integrity": "sha512-GMEBu8Zp9Q97HLnf7bWJN4KjWpN5MxpeqdvHjBGWNl8UYprJI0k+Jkp89+Wh5S8vIon+HoVbDfOzPa7VwgL6Eg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-linux-64": {+ "version": "1.20260507.1",+ "integrity": "sha512-QlrKEBdgA3uVc0Ok0Q3+0/CW0CTjgj5ySir1i1YY5FXVv0X6GpwtnB5umjunjF2MFprss+L+iFGZzxcSvMC1nA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-linux-arm64": {+ "version": "1.20260507.1",+ "integrity": "sha512-eGbbupEtK2nh9V9Dhcx3vv3GTKeXqSVNgAEYVCCN0NGS9tl9HbMoHRX/4JL181FKXROMigWBCQVL//qPhsAzBQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workerd-windows-64": {+ "version": "1.20260507.1",+ "integrity": "sha512-dmClJ/E0BAcuDetQIZFqbeAXejWrG5pysGRMQ6T83Y0IW/7IAamY2zFEkAJ10I5xwZsdHuYsZtzlOxpEXpJs7A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=16"+ }+ },+ "node_modules/@cloudflare/workers-types": {+ "version": "4.20260702.1",+ "integrity": "sha512-mOhf5TUEB1m2vPrxtqoIGfz0fUC9xyxRDx5gWHy5s+OCo6dcV+g7wI1R7gYCMFohhqF/2y2xeKVwMwCJjfn/WA==",+ "dev": true,+ "license": "MIT OR Apache-2.0"+ },+ "node_modules/@cspotcode/source-map-support": {+ "version": "0.8.1",+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/trace-mapping": "0.3.9"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.3",+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.3",+ "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.3",+ "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.3",+ "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.3",+ "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.3",+ "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.3",+ "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.3",+ "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.3",+ "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.3",+ "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.3",+ "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.3",+ "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.3",+ "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.3",+ "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.3",+ "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.3",+ "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.3",+ "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.3",+ "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.3",+ "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.3",+ "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/colour": {+ "version": "1.1.0",+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@img/sharp-darwin-arm64": {+ "version": "0.34.5",+ "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-darwin-x64": {+ "version": "0.34.5",+ "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-darwin-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-arm64": {+ "version": "1.2.4",+ "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-darwin-x64": {+ "version": "1.2.4",+ "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "darwin"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm": {+ "version": "1.2.4",+ "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-arm64": {+ "version": "1.2.4",+ "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-ppc64": {+ "version": "1.2.4",+ "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-riscv64": {+ "version": "1.2.4",+ "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-s390x": {+ "version": "1.2.4",+ "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linux-x64": {+ "version": "1.2.4",+ "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {+ "version": "1.2.4",+ "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {+ "version": "1.2.4",+ "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "linux"+ ],+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-linux-arm": {+ "version": "0.34.5",+ "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-arm64": {+ "version": "0.34.5",+ "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-ppc64": {+ "version": "0.34.5",+ "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-ppc64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-riscv64": {+ "version": "0.34.5",+ "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-riscv64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-s390x": {+ "version": "0.34.5",+ "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-s390x": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linux-x64": {+ "version": "0.34.5",+ "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "glibc"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linux-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-arm64": {+ "version": "0.34.5",+ "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-linuxmusl-x64": {+ "version": "0.34.5",+ "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "libc": [+ "musl"+ ],+ "license": "Apache-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4"+ }+ },+ "node_modules/@img/sharp-wasm32": {+ "version": "0.34.5",+ "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/runtime": "^1.7.0"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-arm64": {+ "version": "0.34.5",+ "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-ia32": {+ "version": "0.34.5",+ "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@img/sharp-win32-x64": {+ "version": "0.34.5",+ "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "Apache-2.0 AND LGPL-3.0-or-later",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ }+ },+ "node_modules/@jridgewell/resolve-uri": {+ "version": "3.1.2",+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6.0.0"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@jridgewell/trace-mapping": {+ "version": "0.3.9",+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/resolve-uri": "^3.0.3",+ "@jridgewell/sourcemap-codec": "^1.4.10"+ }+ },+ "node_modules/@poppinss/colors": {+ "version": "4.1.6",+ "integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "kleur": "^4.1.5"+ }+ },+ "node_modules/@poppinss/dumper": {+ "version": "0.6.5",+ "integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@sindresorhus/is": "^7.0.2",+ "supports-color": "^10.0.0"+ }+ },+ "node_modules/@poppinss/exception": {+ "version": "1.2.3",+ "integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@sindresorhus/is": {+ "version": "7.2.0",+ "integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/is?sponsor=1"+ }+ },+ "node_modules/@speed-highlight/core": {+ "version": "1.2.24",+ "integrity": "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw==",+ "dev": true,+ "license": "CC0-1.0"+ },+ "node_modules/aws4fetch": {+ "version": "1.0.20",+ "integrity": "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g==",+ "license": "MIT"+ },+ "node_modules/blake3-wasm": {+ "version": "2.1.5",+ "integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/capnweb": {+ "version": "0.8.0",+ "integrity": "sha512-BK/TuXUiyfLSKsmjojn70yN7oYG/JJzoURZ3tckjg5Zj2KcygPm0A5jyOlswK7SYB4f0Gh9tt+RZ132b80iLfA==",+ "license": "MIT"+ },+ "node_modules/cookie": {+ "version": "1.1.1",+ "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/error-stack-parser-es": {+ "version": "1.0.5",+ "integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/antfu"+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.3",+ "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.3",+ "@esbuild/android-arm": "0.27.3",+ "@esbuild/android-arm64": "0.27.3",+ "@esbuild/android-x64": "0.27.3",+ "@esbuild/darwin-arm64": "0.27.3",+ "@esbuild/darwin-x64": "0.27.3",+ "@esbuild/freebsd-arm64": "0.27.3",+ "@esbuild/freebsd-x64": "0.27.3",+ "@esbuild/linux-arm": "0.27.3",+ "@esbuild/linux-arm64": "0.27.3",+ "@esbuild/linux-ia32": "0.27.3",+ "@esbuild/linux-loong64": "0.27.3",+ "@esbuild/linux-mips64el": "0.27.3",+ "@esbuild/linux-ppc64": "0.27.3",+ "@esbuild/linux-riscv64": "0.27.3",+ "@esbuild/linux-s390x": "0.27.3",+ "@esbuild/linux-x64": "0.27.3",+ "@esbuild/netbsd-arm64": "0.27.3",+ "@esbuild/netbsd-x64": "0.27.3",+ "@esbuild/openbsd-arm64": "0.27.3",+ "@esbuild/openbsd-x64": "0.27.3",+ "@esbuild/openharmony-arm64": "0.27.3",+ "@esbuild/sunos-x64": "0.27.3",+ "@esbuild/win32-arm64": "0.27.3",+ "@esbuild/win32-ia32": "0.27.3",+ "@esbuild/win32-x64": "0.27.3"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/hono": {+ "version": "4.13.4",+ "integrity": "sha512-AGEwKIyRMHRv1t8Wjwa3LHxQ61X5CqrdFT+4BRNTpqS5aJNnpl5WLjADb7vFlJzI/8uK7T5QLVApCMQKNa3LgQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },+ "node_modules/kleur": {+ "version": "4.1.5",+ "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/miniflare": {+ "version": "4.20260507.1",+ "integrity": "sha512-PSXBiLExTdZ4UGO/raKCHQauUpYL7F880ZRB7j0+78Rv8h7TsdN2E/iEDK9sK2Y+SPQ5wJSeAa+rDeVKoZZoEw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@cspotcode/source-map-support": "0.8.1",+ "sharp": "^0.34.5",+ "undici": "7.24.8",+ "workerd": "1.20260507.1",+ "ws": "8.18.0",+ "youch": "4.1.0-beta.10"+ },+ "bin": {+ "miniflare": "bootstrap.js"+ },+ "engines": {+ "node": ">=22.0.0"+ }+ },+ "node_modules/openai": {+ "version": "7.5.0",+ "integrity": "sha512-ZbDBz8FSB8Mv8fFYIUvzTFMdV5vl93/octp1MdtK2lfYepSpfv/ewmeugpKz/cwGtFSx+YuUM4NwpZ2P55YiPA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22.0.0"+ },+ "peerDependencies": {+ "@aws-sdk/credential-provider-node": ">=3.972.0 <4",+ "@smithy/hash-node": ">=4.3.0 <5",+ "@smithy/signature-v4": ">=5.4.0 <6",+ "ws": "^8.18.0",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@aws-sdk/credential-provider-node": {+ "optional": true+ },+ "@smithy/hash-node": {+ "optional": true+ },+ "@smithy/signature-v4": {+ "optional": true+ },+ "ws": {+ "optional": true+ },+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/path-to-regexp": {+ "version": "6.3.0",+ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/semver": {+ "version": "7.8.5",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/sharp": {+ "version": "0.34.5",+ "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@img/colour": "^1.0.0",+ "detect-libc": "^2.1.2",+ "semver": "^7.7.3"+ },+ "engines": {+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/libvips"+ },+ "optionalDependencies": {+ "@img/sharp-darwin-arm64": "0.34.5",+ "@img/sharp-darwin-x64": "0.34.5",+ "@img/sharp-libvips-darwin-arm64": "1.2.4",+ "@img/sharp-libvips-darwin-x64": "1.2.4",+ "@img/sharp-libvips-linux-arm": "1.2.4",+ "@img/sharp-libvips-linux-arm64": "1.2.4",+ "@img/sharp-libvips-linux-ppc64": "1.2.4",+ "@img/sharp-libvips-linux-riscv64": "1.2.4",+ "@img/sharp-libvips-linux-s390x": "1.2.4",+ "@img/sharp-libvips-linux-x64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.4",+ "@img/sharp-libvips-linuxmusl-x64": "1.2.4",+ "@img/sharp-linux-arm": "0.34.5",+ "@img/sharp-linux-arm64": "0.34.5",+ "@img/sharp-linux-ppc64": "0.34.5",+ "@img/sharp-linux-riscv64": "0.34.5",+ "@img/sharp-linux-s390x": "0.34.5",+ "@img/sharp-linux-x64": "0.34.5",+ "@img/sharp-linuxmusl-arm64": "0.34.5",+ "@img/sharp-linuxmusl-x64": "0.34.5",+ "@img/sharp-wasm32": "0.34.5",+ "@img/sharp-win32-arm64": "0.34.5",+ "@img/sharp-win32-ia32": "0.34.5",+ "@img/sharp-win32-x64": "0.34.5"+ }+ },+ "node_modules/supports-color": {+ "version": "10.2.2",+ "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/supports-color?sponsor=1"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "dev": true,+ "license": "0BSD",+ "optional": true+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici": {+ "version": "7.24.8",+ "integrity": "sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },+ "node_modules/unenv": {+ "version": "2.0.0-rc.24",+ "integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "pathe": "^2.0.3"+ }+ },+ "node_modules/workerd": {+ "version": "1.20260507.1",+ "integrity": "sha512-z7JhsFSe6+X1b5fUHaVpo15VM1IRMJiLofEkq8iKdCo+Veqc+FUg5lIsuz8NwePxuSKrXtO4ZQpGkQLbPVXFhg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "Apache-2.0",+ "bin": {+ "workerd": "bin/workerd"+ },+ "engines": {+ "node": ">=16"+ },+ "optionalDependencies": {+ "@cloudflare/workerd-darwin-64": "1.20260507.1",+ "@cloudflare/workerd-darwin-arm64": "1.20260507.1",+ "@cloudflare/workerd-linux-64": "1.20260507.1",+ "@cloudflare/workerd-linux-arm64": "1.20260507.1",+ "@cloudflare/workerd-windows-64": "1.20260507.1"+ }+ },+ "node_modules/wrangler": {+ "version": "4.90.0",+ "integrity": "sha512-bmNIykl59TfCUn5xQgU7IWylSsPx3LQaPLMSAq2VQHt89CBrcj9qXQ0eYfjBCWA5XTBVgten391evt7xxtXwcA==",+ "dev": true,+ "license": "MIT OR Apache-2.0",+ "dependencies": {+ "@cloudflare/kv-asset-handler": "0.5.0",+ "@cloudflare/unenv-preset": "2.16.1",+ "blake3-wasm": "2.1.5",+ "esbuild": "0.27.3",+ "miniflare": "4.20260507.1",+ "path-to-regexp": "6.3.0",+ "unenv": "2.0.0-rc.24",+ "workerd": "1.20260507.1"+ },+ "bin": {+ "wrangler": "bin/wrangler.js",+ "wrangler2": "bin/wrangler.js"+ },+ "engines": {+ "node": ">=22.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.2"+ },+ "peerDependencies": {+ "@cloudflare/workers-types": "^4.20260507.1"+ },+ "peerDependenciesMeta": {+ "@cloudflare/workers-types": {+ "optional": true+ }+ }+ },+ "node_modules/ws": {+ "version": "8.18.0",+ "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",+ "devOptional": true,+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/youch": {+ "version": "4.1.0-beta.10",+ "integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/colors": "^4.1.5",+ "@poppinss/dumper": "^0.6.4",+ "@speed-highlight/core": "^1.2.7",+ "cookie": "^1.0.2",+ "youch-core": "^0.3.3"+ }+ },+ "node_modules/youch-core": {+ "version": "0.3.3",+ "integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@poppinss/exception": "^1.2.2",+ "error-stack-parser-es": "^1.0.5"+ }+ }+ }+}diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/package.json b/examples/agents_api/sandboxes/webhook_managed/cloudflare/package.jsonnew file mode 100644index 00000000..6473fc28--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/package.json@@ -0,0 +1,18 @@+{+ "name": "agents-api-webhook-cloudflare",+ "private": true,+ "type": "module",+ "scripts": {+ "check": "tsc --noEmit",+ "deploy": "wrangler deploy"+ },+ "dependencies": {+ "@cloudflare/sandbox": ">=0.12.8",+ "openai": ">=7.5.0"+ },+ "devDependencies": {+ "@cloudflare/workers-types": ">=4.20260702.1",+ "typescript": "^5.9",+ "wrangler": ">=4.90.0"+ }+}diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts b/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.tsnew file mode 100644index 00000000..6191ad11--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/src/index.ts@@ -0,0 +1,180 @@+import { DurableObject } from "cloudflare:workers";+import { getSandbox, type Sandbox as SandboxType } from "@cloudflare/sandbox";+import OpenAI from "openai";++export { Sandbox } from "@cloudflare/sandbox";++interface Env {+ Sandbox: DurableObjectNamespace<SandboxType>;+ Sessions: DurableObjectNamespace<SessionController>;+ OPENAI_API_KEY: string;+ OPENAI_EXECUTOR_API_KEY: string;+ OPENAI_WEBHOOK_SECRET: string;+ OPENAI_AGENT_ID: string;+ SANDBOX_CONTROL_TOKEN: string;+}++type Job = {+ sessionId: string;+ version: number;+ attempts: number;+ pending: boolean;+};++// Durable Object storage and alarms provide the small provisioning queue.+export class SessionController extends DurableObject<Env> {+ async wake(sessionId: string) {+ const previous = await this.ctx.storage.get<Job>("job");+ await this.ctx.storage.put("job", {+ ...previous,+ sessionId,+ version: (previous?.version ?? 0) + 1,+ attempts: 0,+ pending: true,+ });+ await this.ctx.storage.setAlarm(Date.now());+ }++ async stop(sessionId: string) {+ await getSandbox(this.env.Sandbox, sessionId).destroy();+ await this.ctx.storage.deleteAlarm();+ await this.ctx.storage.deleteAll();+ }++ async alarm() {+ const job = await this.ctx.storage.get<Job>("job");+ if (!job) return;+ const expiresAt = await this.ctx.storage.get<number>("expiresAt");+ if (expiresAt && Date.now() >= expiresAt) return this.stop(job.sessionId);+ if (!job.pending) return;+ try {+ await this.reconcile(job.sessionId);+ const current = await this.ctx.storage.get<Job>("job");+ if (current?.version !== job.version) return; // A newer wakeup already scheduled an alarm.+ job.pending = false;+ await this.ctx.storage.put("job", job);+ const deadline = await this.ctx.storage.get<number>("expiresAt");+ if (deadline) await this.ctx.storage.setAlarm(deadline);+ } catch (error) {+ console.error(+ JSON.stringify({+ session_id: job.sessionId,+ error_type: (error as Error).name,+ }),+ );+ const current = await this.ctx.storage.get<Job>("job");+ if (current?.version !== job.version) return;+ if (++job.attempts >= 5) job.pending = false;+ await this.ctx.storage.put("job", job);+ if (job.pending) await this.ctx.storage.setAlarm(Date.now() + 10_000);+ else {+ const deadline = await this.ctx.storage.get<number>("expiresAt");+ if (deadline) await this.ctx.storage.setAlarm(deadline);+ }+ }+ }++ private async reconcile(sessionId: string): Promise<boolean> {+ const response = await fetch(+ `https://api.openai.com/v1/agents/sessions/${encodeURIComponent(sessionId)}`,+ {+ headers: { Authorization: `Bearer ${this.env.OPENAI_API_KEY}` },+ signal: AbortSignal.timeout(30_000),+ },+ );+ if (response.status === 404) return false;+ if (!response.ok)+ throw new Error(`Session lookup failed: ${response.status}`);+ const session = (await response.json()) as {+ status: string;+ agent: { id: string };+ environment: { type: string };+ required_actions: { type: string; environment_id?: string }[];+ };+ if (+ session.environment.type !== "self_hosted" ||+ session.agent.id !== this.env.OPENAI_AGENT_ID+ )+ return false;+ const sandbox = getSandbox(this.env.Sandbox, sessionId, {+ enableDefaultSession: false,+ keepAlive: true,+ });+ if (session.status === "failed") {+ await sandbox.destroy();+ await this.ctx.storage.delete("expiresAt");+ return false;+ }+ const action = session.required_actions.find(+ (a) => a.type === "environment_connection",+ );+ if (!action?.environment_id) return false;+ // Record the cleanup deadline before provisioning, including partial failures.+ if (!(await this.ctx.storage.get("expiresAt")))+ await this.ctx.storage.put("expiresAt", Date.now() + 30 * 60_000);+ // A deterministic sandbox ID and an OS lock prevent duplicate executors.+ const command = [+ "flock",+ "-n",+ "/tmp/codex-executor.lock",+ "codex",+ "exec-server",+ "--remote",+ "https://api.openai.com/v1/agents/api",+ "--environment-id",+ action.environment_id,+ ]+ .map((arg) => `'${arg.replaceAll("'", "'\\''")}'`)+ .join(" ");+ await sandbox.startProcess(command, {+ cwd: "/workspace",+ env: { CODEX_API_KEY: this.env.OPENAI_EXECUTOR_API_KEY },+ });+ console.log(JSON.stringify({ session_id: sessionId, action: "started" }));+ return true;+ }+}++export default {+ async fetch(request: Request, env: Env): Promise<Response> {+ const path = new URL(request.url).pathname;+ if (request.method === "GET" && path === "/health")+ return Response.json({ ok: true });+ if (request.method === "DELETE" && path.startsWith("/sandboxes/")) {+ if (+ !env.SANDBOX_CONTROL_TOKEN ||+ request.headers.get("authorization") !==+ `Bearer ${env.SANDBOX_CONTROL_TOKEN}`+ )+ return new Response("Unauthorized", { status: 401 });+ const sessionId = decodeURIComponent(path.slice("/sandboxes/".length));+ await env.Sessions.getByName(sessionId).stop(sessionId);+ return Response.json({ stopped: sessionId });+ }+ if (request.method !== "POST" || path !== "/webhook")+ return new Response("Not found", { status: 404 });+ if (+ !env.OPENAI_WEBHOOK_SECRET ||+ env.OPENAI_WEBHOOK_SECRET === "pending-webhook-registration"+ )+ return new Response("Webhook not configured", { status: 503 });+ const payload = await request.text();+ const verifier = new OpenAI({+ apiKey: "unused",+ webhookSecret: env.OPENAI_WEBHOOK_SECRET,+ });+ try {+ await verifier.webhooks.verifySignature(payload, request.headers);+ } catch {+ return new Response("Invalid signature", { status: 400 });+ }+ const event = JSON.parse(payload);+ if (+ event.type === "agent.session.failed" ||+ (event.type === "agent.session.action_required" &&+ event.data.required_action.type === "environment_connection")+ )+ await env.Sessions.getByName(event.data.id).wake(event.data.id);+ return Response.json({ ok: true });+ },+};diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/tsconfig.json b/examples/agents_api/sandboxes/webhook_managed/cloudflare/tsconfig.jsonnew file mode 100644index 00000000..1d566bd4--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "skipLibCheck": true,+ "noEmit": true,+ "types": ["@cloudflare/workers-types"],+ "lib": ["ES2022"]+ },+ "include": ["src/**/*.ts"]+}diff --git a/examples/agents_api/sandboxes/webhook_managed/cloudflare/wrangler.jsonc b/examples/agents_api/sandboxes/webhook_managed/cloudflare/wrangler.jsoncnew file mode 100644index 00000000..9dcd9013--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/cloudflare/wrangler.jsonc@@ -0,0 +1,21 @@+{+ "$schema": "node_modules/wrangler/config-schema.json",+ "name": "agents-api-webhook-cloudflare",+ "main": "src/index.ts",+ "compatibility_date": "2026-05-07",+ "compatibility_flags": ["nodejs_compat"],+ "vars": { "OPENAI_AGENT_ID": "set-your-agent-id" },+ "containers": [+ { "class_name": "Sandbox", "image": "./Dockerfile", "max_instances": 4 },+ ],+ "durable_objects": {+ "bindings": [+ { "name": "Sandbox", "class_name": "Sandbox" },+ { "name": "Sessions", "class_name": "SessionController" },+ ],+ },+ "migrations": [+ { "tag": "v1", "new_sqlite_classes": ["Sandbox", "SessionController"] },+ ],+ "observability": { "enabled": true },+}diff --git a/examples/agents_api/sandboxes/webhook_managed/daytona/README.md b/examples/agents_api/sandboxes/webhook_managed/daytona/README.mdnew file mode 100644index 00000000..958a742a--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/daytona/README.md@@ -0,0 +1,65 @@+# Daytona webhook-managed sandbox++A controller in a dedicated Daytona sandbox receives OpenAI webhooks and queues+work in SQLite. It starts or reconnects a separate worker sandbox for each API+session. Agent commands run only in the worker sandbox.++Workers use Daytona's default JavaScript snapshot. Setup creates `/workspace` for+the `daytona` user and installs the Codex alpha under that user's `.local` directory.++## Deploy++Create an agent using the [shared setup](../README.md#set-up-once). Run the+deployment command below from the Cookbook repository root.++Set `OPENAI_AGENT_ID` to the agent ID from the shared setup. Provide it alongside+`DAYTONA_API_KEY`, `OPENAI_API_KEY`, and `OPENAI_EXECUTOR_API_KEY` through your secret+manager. The two OpenAI keys must match the session owner's organization, project,+and user or service account. Optional `DAYTONA_API_URL` and `DAYTONA_TARGET` are+passed to the controller.++```bash+uv run examples/agents_api/sandboxes/webhook_managed/daytona/deploy.py+```++Register the printed URL in **OpenAI project settings → Webhooks**, subscribing to+`agent.session.action_required` and `agent.session.failed`. Set the generated+`OPENAI_WEBHOOK_SECRET` locally and run the deployment command again. Use the+[shared client](../README.md#run-and-reconnect) to create sessions and submit work.++Do not register this URL in Daytona's Webhooks page: that page sends Daytona+lifecycle notifications outward, rather than receiving OpenAI events.++The public endpoint rejects requests until the signing secret is installed and+checks every delivery's signature. Only the controller receives application and+Daytona credentials; session sandboxes receive only the restricted executor key.+Run one controller process. Its queue survives process restarts, not controller+deletion. Failed provisioning gets up to five attempts.++## Lifecycle++| Current state | Handler action |+| --- | --- |+| Connection required, no worker | Create a worker and launch the executor. |+| Connection required, stopped worker | Start the same worker and relaunch the executor. |+| Session failed | Delete its worker. |+| Other agent, resolved action, or idle event | Do not provision or stop compute. |++## Stop or clean up++The controller logs each session's sandbox ID. To release compute between turns,+stop that sandbox in Daytona. The next input wakes it through the+webhook. Stopping retains its filesystem but ends running processes. Deleting it+instead causes the next input to create a fresh sandbox without previous files.++For final cleanup, delete the API session and its Daytona sandbox separately.+Remove the OpenAI webhook before deleting the `agents-api-webhook-daytona`+controller. Worker sandboxes have a 30-minute wall-clock TTL; the controller has+a two-hour TTL, extended on redeployment. Expiration destroys the sandbox and+its local queue and files. For a long-running service, provide persistent hosting+and queue storage for the controller.+If the controller expires, redeploy it and update the OpenAI webhook with the new URL.+See [Daytona lifecycle settings](https://www.daytona.io/docs/sandboxes#wall-clock-ttl).++Controller logs are in `/app/controller.log`; executor logs are in+`/tmp/codex-executor.log` inside each worker.diff --git a/examples/agents_api/sandboxes/webhook_managed/daytona/deploy.py b/examples/agents_api/sandboxes/webhook_managed/daytona/deploy.pynew file mode 100644index 00000000..286d9298--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/daytona/deploy.py@@ -0,0 +1,95 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "daytona>=0.207.0",+# ]+# ///++"""Deploy a signature-protected controller in a dedicated Daytona sandbox."""++from __future__ import annotations++import asyncio+import os+from pathlib import Path++from daytona import (+ AsyncDaytona,+ CreateSandboxFromImageParams,+ DaytonaNotFoundError,+ Image,+ SessionExecuteRequest,+)++NAME = "agents-api-webhook-daytona"+ROOT = Path(__file__).parent+++async def main() -> None:+ values = {+ key: os.environ[key]+ for key in [+ "OPENAI_API_KEY",+ "OPENAI_EXECUTOR_API_KEY",+ "OPENAI_AGENT_ID",+ "DAYTONA_API_KEY",+ ]+ }+ for key in ["DAYTONA_API_URL", "DAYTONA_TARGET"]:+ if key in os.environ:+ values[key] = os.environ[key]+ values["OPENAI_WEBHOOK_SECRET"] = os.environ.get(+ "OPENAI_WEBHOOK_SECRET", "pending-webhook-registration"+ )+ async with AsyncDaytona() as daytona:+ try:+ sandbox = await daytona.get(NAME)+ except DaytonaNotFoundError:+ sandbox = await daytona.create(+ CreateSandboxFromImageParams(+ name=NAME,+ image=Image.base("python:3.12-slim").run_commands("mkdir -p /app"),+ os_user="root",+ public=True,+ env_vars=values,+ labels={"agents-webhook-controller": "daytona"},+ auto_stop_interval=0,+ ttl_minutes=120,+ ),+ timeout=300,+ )+ else:+ if sandbox.state != "started":+ await sandbox.start(timeout=90)+ await sandbox.update_env(values)+ await sandbox.set_ttl(120)+ await sandbox.fs.upload_file(+ ROOT.joinpath("handler.py").read_bytes(), "/app/handler.py"+ )+ install = await sandbox.process.exec(+ "python -m pip install uv && uv pip install --system -r /app/handler.py",+ timeout=180,+ )+ if install.exit_code != 0:+ raise RuntimeError("Controller dependency installation failed")+ try:+ await sandbox.process.get_session("webhook-controller")+ except DaytonaNotFoundError:+ pass+ else:+ await sandbox.process.delete_session("webhook-controller")+ await sandbox.process.create_session("webhook-controller")+ await sandbox.process.execute_session_command(+ "webhook-controller",+ SessionExecuteRequest(+ command="cd /app && python -m uvicorn handler:app --host 0.0.0.0 --port 8000 >> /app/controller.log 2>&1",+ run_async=True,+ ),+ )+ preview = await sandbox.get_preview_link(8000)+ print(f"Webhook: {preview.url}/webhook")+ print(f"Controller: {sandbox.id} (expires after two hours; redeploy to extend)")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/webhook_managed/daytona/handler.py b/examples/agents_api/sandboxes/webhook_managed/daytona/handler.pynew file mode 100644index 00000000..9adc6324--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/daytona/handler.py@@ -0,0 +1,227 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "daytona>=0.207.0",+# "fastapi>=0.115,<1",+# "uvicorn>=0.30,<1",+# "httpx>=0.27,<1",+# "openai>=3.12.0",+# ]+# ///++"""A single-process OpenAI webhook controller hosted in a Daytona sandbox."""++from __future__ import annotations++import asyncio+import hashlib+import json+import os+import shlex+import sqlite3+import time+import traceback+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from daytona import (+ AsyncDaytona,+ CreateSandboxFromSnapshotParams,+ DaytonaNotFoundError,+ SessionExecuteRequest,+)+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from openai import AsyncOpenAI, InvalidWebhookSignatureError, NotFoundError, OpenAI++DB_PATH = os.environ.get("QUEUE_PATH", "/app/pending.sqlite3")+++def sandbox_name(session_id: str) -> str:+ return f"agents-webhook-{hashlib.sha256(session_id.encode()).hexdigest()[:24]}"+++async def reconcile(session_id: str) -> None:+ async with AsyncOpenAI(timeout=30) as client:+ try:+ session = await client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ return+ if (+ session.environment.type != "self_hosted"+ or session.agent.id != os.environ["OPENAI_AGENT_ID"]+ ):+ return+ action = next(+ (a for a in session.required_actions if a.type == "environment_connection"),+ None,+ )+ if session.status != "failed" and action is None:+ return+ async with AsyncDaytona() as daytona:+ try:+ sandbox = await daytona.get(sandbox_name(session_id))+ except DaytonaNotFoundError:+ sandbox = None+ if session.status == "failed":+ if sandbox is not None:+ await daytona.delete(sandbox, wait=True)+ return+ assert action is not None+ if sandbox is None:+ sandbox = await daytona.create(+ CreateSandboxFromSnapshotParams(+ name=sandbox_name(session_id),+ language="javascript",+ labels={"agents-session-id": session_id},+ env_vars={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},+ auto_stop_interval=0,+ ttl_minutes=30,+ ),+ timeout=90,+ )+ elif sandbox.state != "started":+ await sandbox.start(timeout=90)+ setup = await sandbox.process.exec(+ "sudo install -d -o daytona -g daytona /workspace && (test -x /home/daytona/.local/bin/codex || npm install -g --prefix /home/daytona/.local @openai/codex@alpha) && command -v flock",+ timeout=180,+ )+ if setup.exit_code != 0:+ raise RuntimeError("Executor setup failed")+ try:+ await sandbox.process.get_session("executor")+ except DaytonaNotFoundError:+ await sandbox.process.create_session("executor")+ command = shlex.join(+ [+ "flock",+ "-n",+ "/tmp/codex-executor.lock",+ "/home/daytona/.local/bin/codex",+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ )+ # flock makes repeated or retried provisioning safe while the executor is running.+ await sandbox.process.execute_session_command(+ "executor",+ SessionExecuteRequest(+ command=f"cd /workspace && {command} >> /tmp/codex-executor.log 2>&1",+ run_async=True,+ ),+ )+ print(+ json.dumps(+ {+ "session_id": session_id,+ "sandbox_id": sandbox.id,+ "action": "started",+ }+ ),+ flush=True,+ )+++async def drain_queue(db: sqlite3.Connection) -> None:+ while True:+ row = db.execute(+ "SELECT session_id, attempts FROM jobs WHERE retry_at <= ? LIMIT 1",+ (time.time(),),+ ).fetchone()+ if row is None:+ await asyncio.sleep(1)+ continue+ session_id, attempts = row+ try:+ await reconcile(session_id)+ except Exception as error:+ # Persist retries across controller process restarts; never log secrets.+ if attempts >= 4:+ db.execute("DELETE FROM jobs WHERE session_id = ?", (session_id,))+ else:+ db.execute(+ "UPDATE jobs SET attempts = ?, retry_at = ? WHERE session_id = ?",+ (attempts + 1, time.time() + 10, session_id),+ )+ print(+ json.dumps(+ {+ "session_id": session_id,+ "error_type": type(error).__name__,+ "error_at": [+ f"{frame.name}:{frame.lineno}"+ for frame in traceback.extract_tb(error.__traceback__)+ ],+ }+ ),+ flush=True,+ )+ else:+ db.execute("DELETE FROM jobs WHERE session_id = ?", (session_id,))+ db.commit()+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncIterator[None]:+ db = sqlite3.connect(DB_PATH)+ db.execute(+ "CREATE TABLE IF NOT EXISTS jobs (session_id TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, retry_at REAL DEFAULT 0)"+ )+ app.state.db = db+ task = asyncio.create_task(drain_queue(db))+ try:+ yield+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ db.close()+++app = FastAPI(lifespan=lifespan)++[email protected]("/health")+async def health() -> dict[str, bool]:+ return {"ok": True}++[email protected]("/webhook")+async def webhook(request: Request) -> JSONResponse:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret or secret == "pending-webhook-registration":+ return JSONResponse({"error": "Webhook not configured"}, status_code=503)+ payload = (await request.body()).decode()+ with OpenAI(api_key="unused", webhook_secret=secret) as verifier:+ try:+ verifier.webhooks.verify_signature(payload=payload, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError):+ return JSONResponse({"error": "Invalid signature"}, status_code=400)+ event = json.loads(payload)+ if event["type"] == "agent.session.failed" or (+ event["type"] == "agent.session.action_required"+ and event["data"]["required_action"]["type"] == "environment_connection"+ ):+ request.app.state.db.execute(+ "INSERT OR IGNORE INTO jobs(session_id) VALUES (?)", (event["data"]["id"],)+ )+ request.app.state.db.commit()+ print(+ json.dumps(+ {+ "event_id": event["id"],+ "session_id": event["data"]["id"],+ "action": "enqueued",+ }+ ),+ flush=True,+ )+ return JSONResponse({"ok": True})+++if __name__ == "__main__":+ import uvicorn++ uvicorn.run(app, host="0.0.0.0", port=8000)diff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/Dockerfile b/examples/agents_api/sandboxes/webhook_managed/digitalocean/Dockerfilenew file mode 100644index 00000000..c97ee796--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/Dockerfile@@ -0,0 +1,9 @@+FROM python:3.14-slim++WORKDIR /app+COPY examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py ./examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py+RUN python -m pip install --no-cache-dir uv \+ && uv pip install --system -r examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py++EXPOSE 8080+CMD ["python", "examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py"]diff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.md b/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.mdnew file mode 100644index 00000000..a4986583--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/README.md@@ -0,0 +1,99 @@+# DigitalOcean webhook-managed sandbox++The endpoint verifies the signature and provisions a DigitalOcean Managed Agents+Runtime Service (MARS) sandbox for the session that needs one. MARS boots a+Firecracker microVM from a published image that already contains the Codex CLI+and starts the executor itself, so this handler never runs `codex exec-server`+and never manages a container.++The sandbox is named after the OpenAI session ID, and the controller checks all+matching pages before provisioning. A process-local lock serializes webhook+reconciliation. Run **one controller worker and one replica**; multiple replicas+or overlapping deployments need distributed coordination or provider-side+idempotency. A restart reuses sandboxes visible in DigitalOcean's listing, but+an ambiguous create timeout still needs reconciliation before retrying.+Idle sandboxes are paused automatically and resumed on reconnect.++## Deploy++Use Python 3.11+ and a DigitalOcean account with MARS access. Create the agent+using the [shared setup](../README.md#set-up-once).++MARS session support ships in the pydo pre-release. Install it explicitly —+without `--pre`, pip resolves to a stable release whose client has no `agents`+resource:++```bash+pip install "pydo[aio]==0.40.0b7" --pre+```++App Platform deploys from a Git repository. Push a copy of these examples+to your own repository, preserving the `examples/agents_api/` paths. Set+`github.repo` in [app.yaml](app.yaml) to it, then create the app. The+[Dockerfile](Dockerfile) builds from the repository root and installs dependencies+at build time; credentials are available only at runtime.++This recipe requires the upcoming OpenAI Python SDK release with `beta.agents`.+Do not add API keys or Git tokens to the Dockerfile or build context.++```bash+doctl apps create --spec examples/agents_api/sandboxes/webhook_managed/digitalocean/app.yaml+```++Configure these variables on the service:++- `OPENAI_API_KEY`: controller/session-read credential.+- `OPENAI_AGENT_ID`: agent ID from the shared setup.+- `OPENAI_EXECUTOR_API_KEY`: restricted executor credential, scoped to+ `api.agent.environment.connect`.+- `OPENAI_WEBHOOK_SECRET`: generated by OpenAI when registering the endpoint.+- `DIGITALOCEAN_TOKEN`: API token that can manage MARS sessions.++For the first deployment only, use `pending-webhook-registration` as the signing+value; the receiver rejects it with `503`.++`doctl apps list` prints the deployed URL. The webhook URL is+`https://YOUR_APP.ondigitalocean.app/webhook`, and OpenAI must be able to reach+it without a login. Register the webhook, enable `agent.session.action_required`+and `agent.session.failed`, replace the signing value with the real secret, and+redeploy. Then use the [shared client](../README.md#run-and-reconnect).++Environment-variable changes require a new deployment.++### Run the controller locally++```bash+uv run examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py+```++Expose port 8080 with a tunnel and register that URL. On macOS python.org+builds, requests to `api.digitalocean.com` can fail with+`CERTIFICATE_VERIFY_FAILED`; run `Install Certificates.command`, or export+`SSL_CERT_FILE="$(python -c 'import certifi; print(certifi.where())')"`.++## Configure the sandbox++The manifest in [handler.py](handler.py) is the unit of configuration. Two+fields matter most:++- `agent: codex-agentapi` selects the image that runs the executor.+- `config` is passed through to OpenAI when the session is created, and is+ required.++Credentials belong under `secrets`, not `env`; the create API rejects a+credential-shaped `env` value. `egress` accepts a host allowlist as shown, or+`unrestricted` to leave destinations open. To size the sandbox or pin a region,+add the corresponding manifest fields — see `doctl harness-runtime sizes`.++## Stop or clean up++The sandbox name is `mars-` followed by the API session ID.++```bash+doctl harness-runtime remove mars-SESSION_ID+```++Sandboxes persist files between turns; a destroyed sandbox starts fresh. There+is no session-deletion webhook, so deleting the API session does not release the+sandbox — delete both. Remove the OpenAI webhook before deleting the App+Platform app.diff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/app.yaml b/examples/agents_api/sandboxes/webhook_managed/digitalocean/app.yamlnew file mode 100644index 00000000..2e4484d7--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/app.yaml@@ -0,0 +1,30 @@+name: agents-api-webhook-digitalocean+services:+ - name: controller+ instance_count: 1+ instance_size_slug: apps-s-1vcpu-0.5gb+ http_port: 8080+ source_dir: /+ dockerfile_path: examples/agents_api/sandboxes/webhook_managed/digitalocean/Dockerfile+ github:+ repo: <your-org>/<your-repo>+ branch: main+ deploy_on_push: true+ health_check:+ http_path: /health+ envs:+ - key: OPENAI_API_KEY+ type: SECRET+ scope: RUN_TIME+ - key: OPENAI_AGENT_ID+ scope: RUN_TIME+ - key: OPENAI_EXECUTOR_API_KEY+ type: SECRET+ scope: RUN_TIME+ - key: OPENAI_WEBHOOK_SECRET+ type: SECRET+ scope: RUN_TIME+ value: pending-webhook-registration+ - key: DIGITALOCEAN_TOKEN+ type: SECRET+ scope: RUN_TIMEdiff --git a/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py b/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.pynew file mode 100644index 00000000..4f99e8d9--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/digitalocean/handler.py@@ -0,0 +1,195 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "pydo[aio]>=0.40.0b7,!=0.40.0",+# "fastapi[standard]",+# ]+# ///++"""A single-process OpenAI webhook controller for DigitalOcean MARS sandboxes.++DigitalOcean's Managed Agents Runtime Service boots a Firecracker microVM from+a published image that already contains the Codex CLI and starts the executor+itself, so provisioning is a single API call and there is no `codex exec-server`+command anywhere below. The manifest's `agent: codex-agentapi` selects the image+that runs it.++The sandbox is named after the OpenAI session ID so reconnects can find it.+Reconciliation is serialized within this process; run only one controller+worker. Multiple replicas require distributed coordination or provider-side+idempotency. Idle sandboxes are paused automatically and resumed on reconnect.+"""++from __future__ import annotations++import asyncio+import json+import os+from typing import Any++from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from openai import APIStatusError, AsyncOpenAI, InvalidWebhookSignatureError, OpenAI+from pydo.aio import Client as DOClient++# `${ENV_ID}` and `${OPENAI_API_KEY}` are substituted from `variables` below.+# Credentials belong under `secrets:`, not `env:` — the create API rejects a+# credential-shaped `env` value. `config` is passed through to OpenAI verbatim+# and is required even when attaching to an existing session.+MANIFEST = """+name: {name}+agent: codex-agentapi+config:+ agent:+ model: gpt-5.6-sol+ environment:+ type: self_hosted+ workspace_directory: /workspace+secrets:+ CODEX_API_KEY: ${{OPENAI_API_KEY}}+env:+ CODEX_ENVIRONMENT_ID: ${{ENV_ID}}+egress:+ - api.openai.com+ - codex-cloud-environments.chatgpt.com+"""++# A session in one of these is gone for good; a new one must be created.+TERMINAL_STATUSES = {+ "SESSION_STATUS_DESTROYED",+ "SESSION_STATUS_FAILED",+ "SESSION_STATUS_UNSPECIFIED",+}+++def do_session_name(openai_session_id: str) -> str:+ """Derive the DO session name that identifies this OpenAI session."""+ return f"mars-{openai_session_id}"+++async def find_do_session(do: Any, name: str) -> dict[str, Any] | None:+ """Return the newest non-terminal DO session with *name*, if any."""+ sessions: list[dict[str, Any]] = []+ page_token = None+ while True:+ response = await do.agents.sessions.list(name=name, page_token=page_token)+ sessions.extend((response or {}).get("sessions") or [])+ page_token = (response or {}).get("next_page_token")+ if not page_token:+ break+ live = [s for s in sessions if s.get("status") not in TERMINAL_STATUSES]+ if not live:+ return None+ return max(live, key=lambda s: s.get("created_at") or "")+++async def reconcile(openai_session_id: str) -> None:+ async with AsyncOpenAI(timeout=30) as client:+ try:+ session = await client.beta.agents.sessions.retrieve(openai_session_id)+ except APIStatusError as error:+ if error.status_code == 404:+ return+ raise+ info = session+ environment = info.environment+ if (+ environment.type != "self_hosted"+ or info.agent.id != os.environ["OPENAI_AGENT_ID"]+ ):+ return++ name = do_session_name(openai_session_id)+ do = DOClient(token=os.environ["DIGITALOCEAN_TOKEN"])+ async with do:+ assert do.agents is not None, "Install a pydo release with Agents support"+ existing = await find_do_session(do, name)++ if info.status == "failed":+ if existing is not None:+ await do.agents.destroy_session(session_id=existing["session_id"])+ _log(openai_session_id, name, "destroyed")+ return++ if not any(a.type == "environment_connection" for a in info.required_actions):+ return++ if existing is not None:+ # Already provisioned. Resume it if DigitalOcean paused it while+ # idle; otherwise it is starting or already connected, and creating+ # a second sandbox for one session would be the real failure.+ if existing.get("status") == "SESSION_STATUS_PAUSED":+ await do.agents.sessions.resume(existing["session_id"])+ _log(openai_session_id, name, "resumed")+ return++ # `create_session` is the flat-manifest path: it substitutes+ # `variables` and posts the manifest as written. (`agents.start()`+ # expects the legacy `spec.runtime.adapter` envelope instead.)+ response = await do.agents.create_session(+ params={"openai_session_id": openai_session_id},+ body={+ "manifest": MANIFEST.format(name=name),+ "variables": {+ "ENV_ID": environment.id,+ "OPENAI_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"],+ },+ },+ )+ _log(+ openai_session_id,+ name,+ "started",+ (response or {}).get("session", {}).get("session_id"),+ )+++def _log(+ openai_session_id: str, name: str, action: str, do_session_id: str | None = None+) -> None:+ payload = {+ "openai_session_id": openai_session_id,+ "do_name": name,+ "action": action,+ }+ if do_session_id:+ payload["do_session_id"] = do_session_id+ print(json.dumps(payload), flush=True)+++app = FastAPI()+reconcile_lock = asyncio.Lock()++[email protected]("/health")+async def health() -> dict[str, bool]:+ return {"ok": True}++[email protected]("/webhook")+async def webhook(request: Request) -> JSONResponse:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret or secret == "pending-webhook-registration":+ return JSONResponse({"error": "Webhook not configured"}, status_code=503)+ payload = (await request.body()).decode()+ with OpenAI(api_key="unused", webhook_secret=secret) as verifier:+ try:+ verifier.webhooks.verify_signature(payload=payload, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError):+ return JSONResponse({"error": "Invalid signature"}, status_code=400)+ event = json.loads(payload)+ if event["type"] == "agent.session.failed" or (+ event["type"] == "agent.session.action_required"+ and event["data"]["required_action"]["type"] == "environment_connection"+ ):+ # Hold the lock across the state read, lookup, and provision/cleanup.+ async with reconcile_lock:+ await reconcile(event["data"]["id"])+ return JSONResponse({"ok": True})+++if __name__ == "__main__":+ import uvicorn++ uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8080")))diff --git a/examples/agents_api/sandboxes/webhook_managed/e2b/README.md b/examples/agents_api/sandboxes/webhook_managed/e2b/README.mdnew file mode 100644index 00000000..d022af15--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/e2b/README.md@@ -0,0 +1,65 @@+# E2B webhook-managed sandbox++A controller in a dedicated E2B sandbox receives OpenAI webhooks and queues work+in SQLite. It starts or reconnects a separate worker sandbox for each API session.+Agent commands run only in the worker sandbox.++## Deploy++Create an agent using the [shared setup](../README.md#set-up-once). Run the+deployment command below from the Cookbook repository root.++Set `OPENAI_AGENT_ID` to the agent ID from the shared setup. Provide it alongside+`E2B_API_KEY`, `OPENAI_API_KEY`, and `OPENAI_EXECUTOR_API_KEY` through your secret+manager. The two OpenAI keys must match the session owner's organization, project,+and user or service account.++```bash+uv run examples/agents_api/sandboxes/webhook_managed/e2b/deploy.py+```++The deployment saves the controller ID in the ignored `.controller.json` beside+`deploy.py`. Keep that file to redeploy the same controller and retain its queue.+If the controller expires, remove this file before creating a replacement; its+URL changes, so update the OpenAI webhook too.++Register the printed URL in **OpenAI project settings → Webhooks**, subscribing to+`agent.session.action_required` and `agent.session.failed`. Set the generated+`OPENAI_WEBHOOK_SECRET` locally and redeploy. Then use the+[shared client](../README.md#run-and-reconnect).++E2B's Webhooks page is for outgoing sandbox lifecycle notifications; it is not+where you register this OpenAI receiver.++The public webhook endpoint verifies each delivery's signature. Worker+sandboxes disable public inbound traffic and receive only the restricted executor+key. The application key, E2B key, and signing secret stay in the controller.+Run one controller process. Its queue survives process restarts, not controller+deletion. Failed provisioning gets up to five attempts.++## Lifecycle++| Current state | Handler action |+| --- | --- |+| Connection required, no worker | Create a worker and launch the executor. |+| Connection required, paused worker | Resume the same worker and ensure its executor is running. |+| Session failed | Kill its worker, including a paused worker. |+| Other agent, resolved action, or idle event | Do not provision or stop compute. |++## Stop or clean up++The controller logs each session's sandbox ID. To release compute between turns,+pause the sandbox through E2B; the next input makes the handler resume+it. Killing it instead causes the next input to create a fresh sandbox, without+previous files. The handler finds workers by their `agents-session-id` metadata.++For final cleanup, delete the API session and kill its E2B sandbox separately,+including paused workers. Remove the OpenAI webhook before killing the controller.+Worker sandboxes have a 30-minute running timeout, refreshed on reconnect; the+controller has a one-hour timeout, extended on redeployment. The example does not+automatically pause or auto-resume the controller. Its SQLite queue survives a+process restart, not sandbox deletion. For a long-running service, provide+persistent hosting and queue storage for the controller.++Controller logs are in `/app/controller.log`; executor logs are in+`/tmp/codex-executor.log` inside each worker.diff --git a/examples/agents_api/sandboxes/webhook_managed/e2b/deploy.py b/examples/agents_api/sandboxes/webhook_managed/e2b/deploy.pynew file mode 100644index 00000000..1729567f--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/e2b/deploy.py@@ -0,0 +1,75 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "e2b>=2.45.1",+# ]+# ///++"""Deploy a signature-protected controller in a dedicated E2B sandbox."""++from __future__ import annotations++import asyncio+import json+import os+from pathlib import Path++from e2b import AsyncSandbox++ROOT = Path(__file__).parent+STATE = ROOT / ".controller.json"+++async def main() -> None:+ values = {+ key: os.environ[key]+ for key in [+ "OPENAI_API_KEY",+ "OPENAI_EXECUTOR_API_KEY",+ "OPENAI_AGENT_ID",+ "E2B_API_KEY",+ ]+ }+ values["OPENAI_WEBHOOK_SECRET"] = os.environ.get(+ "OPENAI_WEBHOOK_SECRET", "pending-webhook-registration"+ )+ if STATE.exists():+ sandbox = await AsyncSandbox.connect(+ json.loads(STATE.read_text())["sandbox_id"], timeout=3600+ )+ else:+ sandbox = await AsyncSandbox.create(+ timeout=3600,+ metadata={"agents-webhook-controller": "e2b"},+ network={"allow_public_traffic": True},+ )+ STATE.write_text(json.dumps({"sandbox_id": sandbox.sandbox_id}) + "\n")+ await sandbox.commands.run("mkdir -p /app", user="root")+ await sandbox.files.write(+ "/app/handler.py", ROOT.joinpath("handler.py").read_text(), user="root"+ )+ await sandbox.commands.run(+ "python -m venv /opt/controller && /opt/controller/bin/pip install uv && /opt/controller/bin/uv pip install --python /opt/controller/bin/python -r /app/handler.py",+ user="root",+ timeout=180,+ )+ await sandbox.commands.run(+ "pkill -f '^/opt/controller/bin/python -m uvicorn handler:app' || true",+ user="root",+ )+ await sandbox.commands.run(+ "exec /opt/controller/bin/python -m uvicorn handler:app --host 0.0.0.0 --port 8000 >> /app/controller.log 2>&1",+ cwd="/app",+ user="root",+ envs=values,+ background=True,+ timeout=0,+ )+ print(f"Webhook: https://{sandbox.get_host(8000)}/webhook")+ print(+ f"Controller: {sandbox.sandbox_id} (expires after one hour; redeploy to extend)"+ )+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/agents_api/sandboxes/webhook_managed/e2b/handler.py b/examples/agents_api/sandboxes/webhook_managed/e2b/handler.pynew file mode 100644index 00000000..61dc2cd3--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/e2b/handler.py@@ -0,0 +1,213 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "e2b>=2.45.1",+# "fastapi>=0.115,<1",+# "uvicorn>=0.30,<1",+# "httpx>=0.27,<1",+# "openai>=3.12.0",+# ]+# ///++"""A single-process OpenAI webhook controller hosted in an E2B sandbox."""++from __future__ import annotations++import asyncio+import json+import os+import shlex+import sqlite3+import time+import traceback+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from e2b import AsyncSandbox, SandboxQuery, SandboxState+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse+from openai import AsyncOpenAI, InvalidWebhookSignatureError, NotFoundError, OpenAI++DB_PATH = os.environ.get("QUEUE_PATH", "/app/pending.sqlite3")+++async def find_sandbox(session_id: str) -> str | None:+ items = await AsyncSandbox.list(+ query=SandboxQuery(+ metadata={"agents-session-id": session_id},+ state=[SandboxState.RUNNING, SandboxState.PAUSED],+ ),+ limit=1,+ ).next_items()+ return items[0].sandbox_id if items else None+++async def reconcile(session_id: str) -> None:+ async with AsyncOpenAI(timeout=30) as client:+ try:+ session = await client.beta.agents.sessions.retrieve(session_id)+ except NotFoundError:+ return+ if (+ session.environment.type != "self_hosted"+ or session.agent.id != os.environ["OPENAI_AGENT_ID"]+ ):+ return+ action = next(+ (a for a in session.required_actions if a.type == "environment_connection"),+ None,+ )+ if session.status != "failed" and action is None:+ return+ sandbox_id = await find_sandbox(session_id)+ if session.status == "failed":+ if sandbox_id is not None:+ await AsyncSandbox.kill(sandbox_id)+ return+ assert action is not None+ if sandbox_id is None:+ sandbox = await AsyncSandbox.create(+ timeout=1800,+ metadata={"agents-session-id": session_id},+ envs={"CODEX_API_KEY": os.environ["OPENAI_EXECUTOR_API_KEY"]},+ network={"allow_public_traffic": False},+ )+ else:+ sandbox = await AsyncSandbox.connect(sandbox_id, timeout=1800)+ await sandbox.commands.run(+ "mkdir -p /workspace && (command -v codex || npm install -g @openai/codex@alpha) && command -v flock",+ user="root",+ timeout=180,+ )+ command = shlex.join(+ [+ "flock",+ "-n",+ "/tmp/codex-executor.lock",+ "codex",+ "exec-server",+ "--remote",+ session.environment.remote_url,+ "--environment-id",+ session.environment.id,+ ]+ )+ await sandbox.commands.run(+ f"{command} >> /tmp/codex-executor.log 2>&1",+ user="root",+ cwd="/workspace",+ background=True,+ timeout=0,+ )+ print(+ json.dumps(+ {+ "session_id": session_id,+ "sandbox_id": sandbox.sandbox_id,+ "action": "started",+ }+ ),+ flush=True,+ )+++async def drain_queue(db: sqlite3.Connection) -> None:+ while True:+ row = db.execute(+ "SELECT session_id, attempts FROM jobs WHERE retry_at <= ? LIMIT 1",+ (time.time(),),+ ).fetchone()+ if row is None:+ await asyncio.sleep(1)+ continue+ session_id, attempts = row+ try:+ await reconcile(session_id)+ except Exception as error:+ # Persist retries across controller process restarts; never log secrets.+ if attempts >= 4:+ db.execute("DELETE FROM jobs WHERE session_id = ?", (session_id,))+ else:+ db.execute(+ "UPDATE jobs SET attempts = ?, retry_at = ? WHERE session_id = ?",+ (attempts + 1, time.time() + 10, session_id),+ )+ print(+ json.dumps(+ {+ "session_id": session_id,+ "error_type": type(error).__name__,+ "error_at": [+ f"{frame.name}:{frame.lineno}"+ for frame in traceback.extract_tb(error.__traceback__)+ ],+ }+ ),+ flush=True,+ )+ else:+ db.execute("DELETE FROM jobs WHERE session_id = ?", (session_id,))+ db.commit()+++@asynccontextmanager+async def lifespan(app: FastAPI) -> AsyncIterator[None]:+ db = sqlite3.connect(DB_PATH)+ db.execute(+ "CREATE TABLE IF NOT EXISTS jobs (session_id TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, retry_at REAL DEFAULT 0)"+ )+ app.state.db = db+ task = asyncio.create_task(drain_queue(db))+ try:+ yield+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ db.close()+++app = FastAPI(lifespan=lifespan)++[email protected]("/health")+async def health() -> dict[str, bool]:+ return {"ok": True}++[email protected]("/webhook")+async def webhook(request: Request) -> JSONResponse:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret or secret == "pending-webhook-registration":+ return JSONResponse({"error": "Webhook not configured"}, status_code=503)+ payload = (await request.body()).decode()+ with OpenAI(api_key="unused", webhook_secret=secret) as verifier:+ try:+ verifier.webhooks.verify_signature(payload=payload, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError):+ return JSONResponse({"error": "Invalid signature"}, status_code=400)+ event = json.loads(payload)+ if event["type"] == "agent.session.failed" or (+ event["type"] == "agent.session.action_required"+ and event["data"]["required_action"]["type"] == "environment_connection"+ ):+ request.app.state.db.execute(+ "INSERT OR IGNORE INTO jobs(session_id) VALUES (?)", (event["data"]["id"],)+ )+ request.app.state.db.commit()+ print(+ json.dumps(+ {+ "event_id": event["id"],+ "session_id": event["data"]["id"],+ "action": "enqueued",+ }+ ),+ flush=True,+ )+ return JSONResponse({"ok": True})+++if __name__ == "__main__":+ import uvicorn++ uvicorn.run(app, host="0.0.0.0", port=8000)diff --git a/examples/agents_api/sandboxes/webhook_managed/modal/README.md b/examples/agents_api/sandboxes/webhook_managed/modal/README.mdnew file mode 100644index 00000000..8a7ce67b--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/modal/README.md@@ -0,0 +1,64 @@+# Modal webhook-managed sandbox++The endpoint verifies OpenAI signatures and queues work for a Modal function.+One provisioning worker processes requests in order and reuses named sandboxes.++## Deploy++From the Cookbook repository root:++```bash+uvx modal setup+```++Create the agent using the [shared setup](../README.md#set-up-once), then create+these secrets in Modal's dashboard:++| Secret name | Variables |+| --- | --- |+| `agents-api-webhook-modal-controller` | `OPENAI_API_KEY`, `OPENAI_AGENT_ID` — agent ID from the shared setup |+| `agents-api-webhook-modal-executor` | `CODEX_API_KEY` — the restricted executor key |+| `agents-api-webhook-modal-signing` | `OPENAI_WEBHOOK_SECRET` |++Use `pending-webhook-registration` for the signing value only while obtaining the+endpoint URL. The handler explicitly rejects this placeholder. Never put real+credentials in source files.++```bash+uv run examples/agents_api/sandboxes/webhook_managed/modal/handler.py+```++Register the printed URL with OpenAI, store the generated signing secret, and run+the deployment command again. Then use the [shared client](../README.md#run-and-reconnect).++When rotating keys, edit the existing secrets and redeploy. With the CLI, use+`uvx modal secret create --force` to replace values; the Python API's+`allow_existing=True` does not update an existing secret.++## Stop or clean up++The sandbox name is the API session ID. Terminate it in the Modal dashboard, or+run this with Modal credentials available:++```python+import asyncio+import os+import modal+++async def stop():+ try:+ sandbox = await modal.Sandbox.from_name.aio(+ "agents-api-webhook-modal", os.environ["SESSION_ID"]+ )+ except modal.exception.NotFoundError:+ return+ await sandbox.terminate.aio()+++asyncio.run(stop())+```++For final cleanup, also delete the API session. Remove the OpenAI webhook before+stopping the deployed Modal app. Replacement sandboxes start with a fresh filesystem;+the example does not attach a persistent volume.diff --git a/examples/agents_api/sandboxes/webhook_managed/modal/handler.py b/examples/agents_api/sandboxes/webhook_managed/modal/handler.pynew file mode 100644index 00000000..7d8d9004--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/modal/handler.py@@ -0,0 +1,123 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "openai>=3.12.0",+# "modal>=1.5.4,<2",+# "fastapi[standard]",+# ]+# ///++"""Deploy with: uv run examples/agents_api/sandboxes/webhook_managed/modal/handler.py."""++from __future__ import annotations++import json+import os++import modal+from fastapi import Request+from fastapi.responses import JSONResponse+from openai import APIStatusError, AsyncOpenAI, InvalidWebhookSignatureError, OpenAI++APP_NAME = "agents-api-webhook-modal"+WORKSPACE = "/workspace"+app = modal.App(APP_NAME)+executor_image = (+ modal.Image.debian_slim(python_version="3.12")+ .apt_install("nodejs", "npm", "git", "ripgrep")+ .run_commands("npm install -g @openai/codex@alpha", f"mkdir -p {WORKSPACE}")+ .workdir(WORKSPACE)+)+controller_image = executor_image.pip_install("fastapi[standard]", "openai>=3.12.0")+++ image=controller_image,+ secrets=[modal.Secret.from_name(f"{APP_NAME}-controller")],+ max_containers=1,+ timeout=180,+ retries=2,+)+async def reconcile(session_id: str) -> None:+ # One worker serializes this small example. The sandbox name survives retries.+ async with AsyncOpenAI(timeout=30) as client:+ try:+ session = await client.beta.agents.sessions.retrieve(session_id)+ except APIStatusError as error:+ if error.status_code == 404:+ return+ raise+ info = session+ environment = info.environment+ if (+ environment.type != "self_hosted"+ or info.agent.id != os.environ["OPENAI_AGENT_ID"]+ ):+ return+ try:+ sandbox = await modal.Sandbox.from_name.aio(APP_NAME, session_id)+ except modal.exception.NotFoundError:+ sandbox = None+ if info.status == "failed":+ if sandbox is not None:+ await sandbox.terminate.aio()+ return+ if not any(+ action.type == "environment_connection" for action in info.required_actions+ ):+ return+ if sandbox is not None:+ return # Already starting or connected; never create a duplicate.+ sandbox = await modal.Sandbox.create.aio(+ "codex",+ "exec-server",+ "--remote",+ environment.remote_url,+ "--environment-id",+ environment.id,+ app=app,+ name=session_id,+ image=executor_image,+ secrets=[modal.Secret.from_name(f"{APP_NAME}-executor")],+ workdir=WORKSPACE,+ timeout=30 * 60,+ )+ await sandbox.detach.aio()+ print(+ json.dumps(+ {+ "session_id": session_id,+ "sandbox_id": sandbox.object_id,+ "action": "started",+ }+ )+ )+++ image=controller_image,+ secrets=[modal.Secret.from_name(f"{APP_NAME}-signing")],+)[email protected]_endpoint(method="POST")+async def webhook(request: Request) -> JSONResponse:+ secret = os.environ.get("OPENAI_WEBHOOK_SECRET")+ if not secret or secret == "pending-webhook-registration":+ return JSONResponse({"error": "Webhook not configured"}, status_code=503)+ payload = (await request.body()).decode()+ with OpenAI(api_key="unused", webhook_secret=secret) as verifier:+ try:+ verifier.webhooks.verify_signature(payload=payload, headers=request.headers)+ except (InvalidWebhookSignatureError, ValueError):+ return JSONResponse({"error": "Invalid signature"}, status_code=400)+ event = json.loads(payload)+ if event["type"] == "agent.session.failed" or (+ event["type"] == "agent.session.action_required"+ and event["data"]["required_action"]["type"] == "environment_connection"+ ):+ await reconcile.spawn.aio(event["data"]["id"])+ return JSONResponse({"ok": True})+++if __name__ == "__main__":+ with modal.enable_output():+ app.deploy()diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/README.md b/examples/agents_api/sandboxes/webhook_managed/vercel/README.mdnew file mode 100644index 00000000..9d656537--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/README.md@@ -0,0 +1,52 @@+# Vercel webhook-managed sandbox++The endpoint verifies the signature and sends the session ID to Vercel Queues.+The consumer retrieves current session state and starts a named sandbox. OS locks+prevent concurrent jobs from installing twice or starting duplicate executors.++## Deploy++Use Node.js 24+ and a dedicated Vercel project with Sandbox and Queues access.+Create the agent using the [shared setup](../README.md#set-up-once), then run from+this directory:++```bash+npm ci+npx vercel link+```++In the project's production environment variables, configure:++- `OPENAI_API_KEY`: controller/session-read credential.+- `OPENAI_AGENT_ID`: agent ID from the shared setup.+- `OPENAI_EXECUTOR_API_KEY`: restricted executor credential.+- `OPENAI_WEBHOOK_SECRET`: generated by OpenAI when registering the endpoint.++For the first deployment only, use `pending-webhook-registration` as the signing+value; the receiver rejects it with `503`.++```bash+npx vercel --prod+```++The webhook URL is `https://YOUR_PROJECT.vercel.app/api/webhook`. OpenAI must be able+to reach it without a login. Use a dedicated project and its production URL;+configure deployment protection so OpenAI can reach the receiver. The webhook+signature authenticates requests, and Vercel's queue trigger invokes the consumer.++Register the webhook, replace the signing value with the real secret, and redeploy.+Then use the [shared client](../README.md#run-and-reconnect).++Environment-variable changes require a new deployment.++## Stop or clean up++The sandbox name is `agents-` followed by the API session ID. Stop it in the Vercel+Sandbox dashboard to release compute between turns; delete it and its snapshots+for final cleanup.+Deleting a sandbox does not delete retained snapshots. Also delete the API session.++Named sandboxes preserve files between runs; processes must be restarted.+The executor is installed on first use. For regular use, bake it into a sandbox+snapshot to reduce connection latency. Remove the OpenAI webhook before deleting the+example project.diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts b/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.tsnew file mode 100644index 00000000..185d5bb9--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/api/provision.ts@@ -0,0 +1,82 @@+import { QueueClient } from "@vercel/queue";+import { APIError, Sandbox } from "@vercel/sandbox";++const queue = new QueueClient({ region: "iad1" });++export default queue.handleNodeCallback<{ sessionId: string }>(+ async ({ sessionId }) => {+ const response = await fetch(+ `https://api.openai.com/v1/agents/sessions/${encodeURIComponent(sessionId)}`,+ {+ headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },+ signal: AbortSignal.timeout(30_000),+ },+ );+ if (response.status === 404) return;+ if (!response.ok)+ throw new Error(`Session lookup failed: ${response.status}`);+ const session = await response.json();+ if (+ session.environment.type !== "self_hosted" ||+ session.agent.id !== process.env.OPENAI_AGENT_ID+ )+ return;+ const name = `agents-${sessionId}`;+ if (session.status === "failed") {+ try {+ await (await Sandbox.get({ name })).delete();+ } catch (error) {+ if (!(error instanceof APIError && error.response.status === 404))+ throw error;+ }+ return;+ }+ const action = session.required_actions.find(+ (a: { type: string }) => a.type === "environment_connection",+ );+ if (!action) return;+ const sandbox = await Sandbox.getOrCreate({+ name,+ runtime: "node24",+ timeout: 30 * 60_000,+ });+ // Locks make retried/concurrent jobs harmless, including a retry after creation.+ const setup = await sandbox.runCommand({+ cmd: "flock",+ args: [+ "-w",+ "120",+ "/tmp/codex-setup.lock",+ "sh",+ "-c",+ "mkdir -p /workspace && chown vercel-sandbox /workspace && (command -v codex || npm install -g @openai/codex@alpha)",+ ],+ sudo: true,+ });+ if (setup.exitCode !== 0) throw new Error("Executor setup failed");+ await sandbox.runCommand({+ cmd: "flock",+ args: [+ "-n",+ "/tmp/codex-executor.lock",+ "codex",+ "exec-server",+ "--remote",+ "https://api.openai.com/v1/agents/api",+ "--environment-id",+ action.environment_id,+ ],+ cwd: "/workspace",+ detached: true,+ env: { CODEX_API_KEY: process.env.OPENAI_EXECUTOR_API_KEY! },+ });+ console.log(+ JSON.stringify({+ session_id: sessionId,+ sandbox_name: name,+ action: "started",+ }),+ );+ },+ { visibilityTimeoutSeconds: 240 },+);diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/api/webhook.ts b/examples/agents_api/sandboxes/webhook_managed/vercel/api/webhook.tsnew file mode 100644index 00000000..6be0dea5--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/api/webhook.ts@@ -0,0 +1,42 @@+import type { IncomingMessage, ServerResponse } from "node:http";+import OpenAI from "openai";+import { QueueClient } from "@vercel/queue";++const queue = new QueueClient({ region: "iad1" });++export default async function webhook(+ req: IncomingMessage,+ res: ServerResponse,+) {+ if (req.method !== "POST") return res.writeHead(405).end();+ const secret = process.env.OPENAI_WEBHOOK_SECRET;+ if (!secret || secret === "pending-webhook-registration")+ return res.writeHead(503).end("Webhook not configured");+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ const payload = Buffer.concat(chunks).toString("utf8");+ const headers = new Headers();+ for (const [name, value] of Object.entries(req.headers)) {+ if (value !== undefined)+ headers.set(name, Array.isArray(value) ? value.join(",") : value);+ }+ const verifier = new OpenAI({ apiKey: "unused", webhookSecret: secret });+ try {+ await verifier.webhooks.verifySignature(payload, headers);+ } catch {+ return res.writeHead(400).end("Invalid signature");+ }+ const event = JSON.parse(payload);+ if (+ event.type === "agent.session.failed" ||+ (event.type === "agent.session.action_required" &&+ event.data.required_action.type === "environment_connection")+ ) {+ await queue.send(+ "sandbox-wakeup",+ { sessionId: event.data.id },+ { idempotencyKey: event.id },+ );+ }+ res.writeHead(200).end("ok");+}diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/package-lock.json b/examples/agents_api/sandboxes/webhook_managed/vercel/package-lock.jsonnew file mode 100644index 00000000..4afce0df--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/package-lock.json@@ -0,0 +1,546 @@+{+ "name": "agents-api-webhook-vercel",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "agents-api-webhook-vercel",+ "dependencies": {+ "@vercel/queue": ">=0.5.0",+ "@vercel/sandbox": ">=3.1.0-beta.1",+ "openai": ">=7.5.0"+ },+ "devDependencies": {+ "@types/node": "^24",+ "typescript": "^5.9"+ }+ },+ "node_modules/@types/node": {+ "version": "24.13.3",+ "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~7.18.0"+ }+ },+ "node_modules/@vercel/cli-config": {+ "version": "0.2.4",+ "integrity": "sha512-kZ5SojbrV06GHoU6QIWGwDXLov+s9rWZ7QqdqKfJfBGCNUieGfgaCjeeenNy8Y+QC0bwC0dZ2B4l5Hvdmrgpdw==",+ "license": "Apache-2.0",+ "dependencies": {+ "xdg-app-paths": "5",+ "zod": "4.1.11"+ }+ },+ "node_modules/@vercel/cli-exec": {+ "version": "1.0.1",+ "integrity": "sha512-g9XerViJ/paZujufXYcu5XYI2vU2rtB4sgdpjUHde5RnOkdmpu0ngH46LCFGHoPXO/C+qDPSczIHIRN+8Q2YKQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "execa": "5.1.1"+ },+ "engines": {+ "node": ">= 18"+ }+ },+ "node_modules/@vercel/oidc": {+ "version": "3.8.5",+ "integrity": "sha512-RwXYtnt6za+5UO4IaLywN/6B95AlLqynPRUWRJxeJ/qufwkcLUbZNUxYtzT0uMpuraWhlNcGqPNGkTnZr4BGBw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@vercel/cli-config": "0.2.4",+ "@vercel/cli-exec": "1.0.1",+ "jose": "^5.9.6"+ },+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@vercel/queue": {+ "version": "0.5.0",+ "integrity": "sha512-TqvoMuhZK9Hw2yal6ee6EZ+wQw55+qPrpev6O6jJrpJMC1myrCrt7bLZvb9GQDIR35h40EiETVaMZT4eFWBVpA==",+ "license": "MIT",+ "dependencies": {+ "@vercel/oidc": "^3.0.5",+ "minimatch": "^10.2.4",+ "mixpart": "0.0.6",+ "picocolors": "^1.1.1"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.0.0"+ },+ "peerDependenciesMeta": {+ "@opentelemetry/api": {+ "optional": true+ }+ }+ },+ "node_modules/@vercel/sandbox": {+ "version": "3.1.0-beta.1",+ "integrity": "sha512-rkota0zmKS0nkD9EeuRP4bdztsYpZc7A6wpBeAnpDWlZNsjUYOlJqS2ICmsBfEpW5a6aU7VGoBSYwCJ2nUKzdA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@vercel/oidc": "3.2.0",+ "@workflow/serde": "4.1.0-beta.2",+ "async-retry": "1.3.3",+ "jose": "6.2.3",+ "jsonlines": "0.1.1",+ "lru-cache": "^10.4.3",+ "ms": "2.1.3",+ "picocolors": "^1.1.1",+ "tar-stream": "3.1.7",+ "undici": "^7.27.1",+ "xdg-app-paths": "5.1.0",+ "zod": "^4.1.1"+ }+ },+ "node_modules/@vercel/sandbox/node_modules/@vercel/oidc": {+ "version": "3.2.0",+ "integrity": "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@vercel/sandbox/node_modules/jose": {+ "version": "6.2.3",+ "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/@vercel/sandbox/node_modules/xdg-app-paths": {+ "version": "5.1.0",+ "integrity": "sha512-RAQ3WkPf4KTU1A8RtFx3gWywzVKe00tfOPFfl2NDGqbIFENQO4kqAJp7mhQjNj/33W5x5hiWWUdyfPq/5SU3QA==",+ "license": "MIT",+ "dependencies": {+ "xdg-portable": "^7.0.0"+ },+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/@workflow/serde": {+ "version": "4.1.0-beta.2",+ "integrity": "sha512-8kkeoQKLDaKXefjV5dbhBj2aErfKp1Mc4pb6tj8144cF+Em5SPbyMbyLCHp+BVrFfFVCBluCtMx+jjvaFVZGww==",+ "license": "Apache-2.0"+ },+ "node_modules/async-retry": {+ "version": "1.3.3",+ "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==",+ "license": "MIT",+ "dependencies": {+ "retry": "0.13.1"+ }+ },+ "node_modules/b4a": {+ "version": "1.8.1",+ "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==",+ "license": "Apache-2.0",+ "peerDependencies": {+ "react-native-b4a": "*"+ },+ "peerDependenciesMeta": {+ "react-native-b4a": {+ "optional": true+ }+ }+ },+ "node_modules/balanced-match": {+ "version": "4.0.4",+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",+ "license": "MIT",+ "engines": {+ "node": "18 || 20 || >=22"+ }+ },+ "node_modules/bare-events": {+ "version": "2.9.1",+ "integrity": "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==",+ "license": "Apache-2.0",+ "peerDependencies": {+ "bare-abort-controller": "*"+ },+ "peerDependenciesMeta": {+ "bare-abort-controller": {+ "optional": true+ }+ }+ },+ "node_modules/brace-expansion": {+ "version": "5.0.9",+ "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^4.0.2"+ },+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/cross-spawn": {+ "version": "7.0.6",+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.1.0",+ "shebang-command": "^2.0.0",+ "which": "^2.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/events-universal": {+ "version": "1.0.1",+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",+ "license": "Apache-2.0",+ "dependencies": {+ "bare-events": "^2.7.0"+ }+ },+ "node_modules/execa": {+ "version": "5.1.1",+ "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==",+ "license": "MIT",+ "dependencies": {+ "cross-spawn": "^7.0.3",+ "get-stream": "^6.0.0",+ "human-signals": "^2.1.0",+ "is-stream": "^2.0.0",+ "merge-stream": "^2.0.0",+ "npm-run-path": "^4.0.1",+ "onetime": "^5.1.2",+ "signal-exit": "^3.0.3",+ "strip-final-newline": "^2.0.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/execa?sponsor=1"+ }+ },+ "node_modules/fast-fifo": {+ "version": "1.3.2",+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",+ "license": "MIT"+ },+ "node_modules/get-stream": {+ "version": "6.0.1",+ "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/human-signals": {+ "version": "2.1.0",+ "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=10.17.0"+ }+ },+ "node_modules/is-stream": {+ "version": "2.0.1",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/isexe": {+ "version": "2.0.0",+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",+ "license": "ISC"+ },+ "node_modules/jose": {+ "version": "5.10.0",+ "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },+ "node_modules/jsonlines": {+ "version": "0.1.1",+ "integrity": "sha512-ekDrAGso79Cvf+dtm+mL8OBI2bmAOt3gssYs833De/C9NmIpWDWyUO4zPgB5x2/OhY366dkhgfPMYfwZF7yOZA==",+ "license": "MIT"+ },+ "node_modules/lru-cache": {+ "version": "10.4.3",+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",+ "license": "ISC"+ },+ "node_modules/merge-stream": {+ "version": "2.0.0",+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",+ "license": "MIT"+ },+ "node_modules/mimic-fn": {+ "version": "2.1.0",+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/minimatch": {+ "version": "10.2.6",+ "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",+ "license": "BlueOak-1.0.0",+ "dependencies": {+ "brace-expansion": "^5.0.8"+ },+ "engines": {+ "node": "18 || 20 || >=22"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/mixpart": {+ "version": "0.0.6",+ "integrity": "sha512-CRdXtgfQH2jARmtNmPR0Q7jL20fiESbaYk1b0KvLD0jCdUuemepREtsbd8nbiY6BHV9OGGddAZITNXklupUPUQ==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/npm-run-path": {+ "version": "4.0.1",+ "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==",+ "license": "MIT",+ "dependencies": {+ "path-key": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/onetime": {+ "version": "5.1.2",+ "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",+ "license": "MIT",+ "dependencies": {+ "mimic-fn": "^2.1.0"+ },+ "engines": {+ "node": ">=6"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/openai": {+ "version": "7.5.0",+ "integrity": "sha512-ZbDBz8FSB8Mv8fFYIUvzTFMdV5vl93/octp1MdtK2lfYepSpfv/ewmeugpKz/cwGtFSx+YuUM4NwpZ2P55YiPA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22.0.0"+ },+ "peerDependencies": {+ "@aws-sdk/credential-provider-node": ">=3.972.0 <4",+ "@smithy/hash-node": ">=4.3.0 <5",+ "@smithy/signature-v4": ">=5.4.0 <6",+ "ws": "^8.18.0",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@aws-sdk/credential-provider-node": {+ "optional": true+ },+ "@smithy/hash-node": {+ "optional": true+ },+ "@smithy/signature-v4": {+ "optional": true+ },+ "ws": {+ "optional": true+ },+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/os-paths": {+ "version": "4.4.0",+ "integrity": "sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg==",+ "license": "MIT",+ "engines": {+ "node": ">= 6.0"+ }+ },+ "node_modules/path-key": {+ "version": "3.1.1",+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "license": "ISC"+ },+ "node_modules/retry": {+ "version": "0.13.1",+ "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/shebang-command": {+ "version": "2.0.0",+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",+ "license": "MIT",+ "dependencies": {+ "shebang-regex": "^3.0.0"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/shebang-regex": {+ "version": "3.0.0",+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/signal-exit": {+ "version": "3.0.7",+ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",+ "license": "ISC"+ },+ "node_modules/streamx": {+ "version": "2.28.0",+ "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==",+ "license": "MIT",+ "dependencies": {+ "events-universal": "^1.0.0",+ "fast-fifo": "^1.3.2",+ "text-decoder": "^1.1.0"+ }+ },+ "node_modules/strip-final-newline": {+ "version": "2.0.0",+ "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/tar-stream": {+ "version": "3.1.7",+ "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==",+ "license": "MIT",+ "dependencies": {+ "b4a": "^1.6.4",+ "fast-fifo": "^1.2.0",+ "streamx": "^2.15.0"+ }+ },+ "node_modules/text-decoder": {+ "version": "1.2.7",+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "b4a": "^1.6.4"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici": {+ "version": "7.29.0",+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },+ "node_modules/undici-types": {+ "version": "7.18.2",+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/which": {+ "version": "2.0.2",+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",+ "license": "ISC",+ "dependencies": {+ "isexe": "^2.0.0"+ },+ "bin": {+ "node-which": "bin/node-which"+ },+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/xdg-app-paths": {+ "version": "5.5.1",+ "integrity": "sha512-hI3flOB4PLZIy5prbtTpirobtPE2ZtZ52szO+2mM9Efp6ErM398La+C1lIpNWDfNoQk+6Lsi6nMcCwVB7pxeMQ==",+ "license": "MIT",+ "dependencies": {+ "os-paths": "^4.0.1",+ "xdg-portable": "^7.2.0"+ },+ "engines": {+ "node": ">= 6.0"+ }+ },+ "node_modules/xdg-portable": {+ "version": "7.3.0",+ "integrity": "sha512-sqMMuL1rc0FmMBOzCpd0yuy9trqF2yTTVe+E9ogwCSWQCdDEtQUwrZPT6AxqtsFGRNxycgncbP/xmOOSPw5ZUw==",+ "license": "MIT",+ "dependencies": {+ "os-paths": "^4.0.1"+ },+ "engines": {+ "node": ">= 6.0"+ }+ },+ "node_modules/zod": {+ "version": "4.1.11",+ "integrity": "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/package.json b/examples/agents_api/sandboxes/webhook_managed/vercel/package.jsonnew file mode 100644index 00000000..5c921970--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/package.json@@ -0,0 +1,18 @@+{+ "name": "agents-api-webhook-vercel",+ "private": true,+ "type": "module",+ "scripts": {+ "check": "tsc --noEmit",+ "deploy": "vercel --prod"+ },+ "dependencies": {+ "@vercel/sandbox": ">=3.1.0-beta.1",+ "@vercel/queue": ">=0.5.0",+ "openai": ">=7.5.0"+ },+ "devDependencies": {+ "@types/node": "^24",+ "typescript": "^5.9"+ }+}diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/tsconfig.json b/examples/agents_api/sandboxes/webhook_managed/vercel/tsconfig.jsonnew file mode 100644index 00000000..d772a2f3--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/tsconfig.json@@ -0,0 +1,11 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "strict": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["api/**/*.ts", "lib/**/*.ts"]+}diff --git a/examples/agents_api/sandboxes/webhook_managed/vercel/vercel.json b/examples/agents_api/sandboxes/webhook_managed/vercel/vercel.jsonnew file mode 100644index 00000000..3a88db43--- /dev/null+++ b/examples/agents_api/sandboxes/webhook_managed/vercel/vercel.json@@ -0,0 +1,12 @@+{+ "regions": ["iad1"],+ "functions": {+ "api/webhook.ts": { "maxDuration": 30 },+ "api/provision.ts": {+ "maxDuration": 180,+ "experimentalTriggers": [+ { "type": "queue/v2beta", "topic": "sandbox-wakeup" }+ ]+ }+ }+}diff --git a/registry.yaml b/registry.yamlindex 9597c4b0..d50eec15 100644--- a/registry.yaml+++ b/registry.yaml@@ -4,6 +4,18 @@# should build pages for, and indicates metadata such as tags, creation date and# authors for each page.+- title: Agents API applications and sandbox integrations+ path: examples/agents_api/README.md+ slug: agents-api-examples+ description: Explore complete Agents API applications and application-managed or webhook-managed sandbox integrations.+ date: 2026-09-10+ authors:+ - alfozan+ tags:+ - agents-api+ - agents+ - sandbox+- title: Combining security scanners with the Agents SDKpath: examples/agents_sdk/security_scanners_with_agents_sdk.ipynbslug: evidence-grounded-security-review-swarm