{
  "canonical_name": "openai/openai-agents-js",
  "compilation_id": "pack_f09ac41359e24ca98c863994b41d4cc9",
  "created_at": "2026-05-18T04:46:10.810116+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=skill, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=skill, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npm install @openai/agents` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npm install @openai/agents",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_fd8d2bee09b748119edad6c045dbf9f0"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_60fdd071c559b644c3d053afcbc973ac",
    "canonical_name": "openai/openai-agents-js",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/openai/openai-agents-js",
    "slug": "openai-agents-js",
    "source_packet_id": "phit_594733dbd6b2480fb8abe5f2c1a7d7cd",
    "source_validation_id": "dval_536af9c378e94ca28f7c1cd57210eead"
  },
  "merchandising": {
    "best_for": "需要流程自动化能力，并使用 chatgpt的用户",
    "github_forks": 767,
    "github_stars": 3047,
    "one_liner_en": "A lightweight, powerful framework for multi-agent workflows and voice agents",
    "one_liner_zh": "A lightweight, powerful framework for multi-agent workflows and voice agents",
    "primary_category": {
      "category_id": "workflow-automation",
      "confidence": "medium",
      "name_en": "Workflow Automation",
      "name_zh": "流程自动化",
      "reason": "matched_keywords:workflow, agent"
    },
    "target_user": "使用 chatgpt 等宿主 AI 的用户",
    "title_en": "openai-agents-js",
    "title_zh": "openai-agents-js 能力包",
    "visible_tags": [
      {
        "label_en": "Security & Permissions",
        "label_zh": "安全审查与权限治理",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-security-permissions",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_594733dbd6b2480fb8abe5f2c1a7d7cd",
  "page_model": {
    "artifacts": {
      "artifact_slug": "openai-agents-js",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npm install @openai/agents",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/openai/openai-agents-js#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "结构化数据提取",
        "断点恢复流程",
        "开源工具"
      ],
      "eyebrow": "流程自动化",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要流程自动化能力，并使用 chatgpt的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "A lightweight, powerful framework for multi-agent workflows and voice agents"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "chatgpt",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "skill, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "仓库名 `openai-agents-js` 与安装入口 `@openai/agents` 不完全一致。",
            "category": "身份坑",
            "evidence": [
              "identity.distribution | github_repo:993521808 | https://github.com/openai/openai-agents-js | repo=openai-agents-js; install=@openai/agents"
            ],
            "severity": "medium",
            "suggested_check": "在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。",
            "title": "仓库名和安装名不一致",
            "user_impact": "用户照着仓库名搜索包或照着包名找仓库时容易走错入口。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:993521808 | https://github.com/openai/openai-agents-js | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 89,
        "forks": 767,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 3047
      },
      "source_url": "https://github.com/openai/openai-agents-js",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "A lightweight, powerful framework for multi-agent workflows and voice agents",
      "title": "openai-agents-js 能力包",
      "trial_prompt": "# openai-agents-js - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for openai/openai-agents-js.\n\nProject:\n- Name: openai-agents-js\n- Repository: https://github.com/openai/openai-agents-js\n- Summary: A lightweight, powerful framework for multi-agent workflows and voice agents\n- Host target: chatgpt\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: A lightweight, powerful framework for multi-agent workflows and voice agents\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to OpenAI Agents SDK. Produce one small intermediate artifact and wait for confirmation.\n2. examples-overview: Examples and Patterns. Produce one small intermediate artifact and wait for confirmation.\n3. agents: Creating and Running Agents. Produce one small intermediate artifact and wait for confirmation.\n4. tools: Tools and Tool Use. Produce one small intermediate artifact and wait for confirmation.\n5. sandbox-architecture: Sandbox Agents Architecture. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/openai/openai-agents-js\n- https://github.com/openai/openai-agents-js#readme\n- .agents/skills/changeset-validation/SKILL.md\n- .agents/skills/code-change-verification/SKILL.md\n- .agents/skills/docs-sync/SKILL.md\n- .agents/skills/examples-auto-run/SKILL.md\n- .agents/skills/final-release-review/SKILL.md\n- .agents/skills/implementation-strategy/SKILL.md\n- .agents/skills/integration-tests/SKILL.md\n- .agents/skills/openai-knowledge/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_release: v0.11.4（https://github.com/openai/openai-agents-js/releases/tag/v0.11.4）；github/github_release: v0.11.3（https://github.com/openai/openai-agents-js/releases/tag/v0.11.3）；github/github_release: v0.11.2（https://github.com/openai/openai-agents-js/releases/tag/v0.11.2）；github/github_release: v0.11.1（https://github.com/openai/openai-agents-js/releases/tag/v0.11.1）；github/github_release: v0.11.0（https://github.com/openai/openai-agents-js/releases/tag/v0.11.0）；github/github_release: v0.10.1（https://github.com/openai/openai-agents-js/releases/tag/v0.10.1）；github/github_release: v0.10.0（https://github.com/openai/openai-agents-js/releases/tag/v0.10.0）；github/github_release: v0.9.1（https://github.com/openai/openai-agents-js/releases/tag/v0.9.1）；github/github_release: v0.9.0（https://github.com/openai/openai-agents-js/releases/tag/v0.9.0）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.11.4",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.11.4"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.11.3",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.11.3"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.11.2",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.11.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.11.1",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.11.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.11.0",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.11.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.10.1",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.10.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.10.0",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.10.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.9.1",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.9.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.9.0",
              "url": "https://github.com/openai/openai-agents-js/releases/tag/v0.9.0"
            }
          ],
          "status": "已收录 9 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "流程自动化",
      "desc": "A lightweight, powerful framework for multi-agent workflows and voice agents",
      "effort": "安装已验证",
      "forks": 767,
      "icon": "bolt",
      "name": "openai-agents-js 能力包",
      "risk": "可发布",
      "slug": "openai-agents-js",
      "stars": 3047,
      "tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "结构化数据提取",
        "断点恢复流程",
        "开源工具"
      ],
      "thumb": "gray",
      "type": "Skill Pack"
    },
    "manual": {
      "markdown": "# https://github.com/openai/openai-agents-js 项目说明书\n\n生成时间：2026-05-18 04:44:56 UTC\n\n## 目录\n\n- [Introduction to OpenAI Agents SDK](#introduction)\n- [Installation and Setup](#installation)\n- [Examples and Patterns](#examples-overview)\n- [Creating and Running Agents](#agents)\n- [Tools and Tool Use](#tools)\n- [Guardrails and Input/Output Validation](#guardrails)\n- [Handoffs and Multi-Agent Systems](#handoffs)\n- [Sandbox Agents Architecture](#sandbox-architecture)\n- [Sandbox Providers and Extensions](#sandbox-providers)\n- [Voice Agents and Realtime Communication](#voice-realtime)\n\n<a id='introduction'></a>\n\n## Introduction to OpenAI Agents SDK\n\n### 相关页面\n\n相关主题：[Installation and Setup](#installation), [Creating and Running Agents](#agents), [Examples and Patterns](#examples-overview)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/openai/openai-agents-js/blob/main/README.md)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/README.md)\n- [packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n- [packages/agents-extensions/package.json](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/package.json)\n- [packages/agents-realtime/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/README.md)\n- [examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n- [examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n</details>\n\n# Introduction to OpenAI Agents SDK\n\nThe OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows in JavaScript/TypeScript. It provides developers with primitives for creating AI agents that can use tools, handle complex conversations, manage handoffs between agents, and integrate with guardrails for input/output validation.\n\n## Overview\n\nThe SDK is designed to simplify the development of agentic applications by providing:\n\n- **Agent abstraction**: A core `Agent` class that encapsulates instructions, tools, and behaviors\n- **Tool system**: Built-in support for various tool types including function calling, web search, file search, and code execution\n- **Multi-agent orchestration**: Handoff mechanisms for routing conversations between specialized agents\n- **Guardrails**: Input and output validation to ensure safe and appropriate agent responses\n- **Tracing**: Comprehensive span-based telemetry for monitoring agent execution\n- **Streaming support**: Real-time response streaming for interactive applications\n\nThe framework is modular and extensible, allowing developers to pick and choose components based on their use case.\n\n## Package Architecture\n\nThe SDK is organized into multiple packages within a monorepo structure:\n\n```mermaid\ngraph TD\n    A[Application] --> B[@openai/agents]\n    A --> C[@openai/agents-core]\n    A --> D[@openai/agents-extensions]\n    A --> E[@openai/agents-realtime]\n    \n    B --> C\n    B --> D\n    \n    C --> F[agents-openai]\n    \n    D --> G[AI SDK Integration]\n    D --> H[Codex Tool]\n    D --> I[Daytona Sandbox]\n    \n    E --> C\n```\n\n### Package Matrix\n\n| Package | Purpose | Installation |\n|---------|---------|--------------|\n| `@openai/agents` | Main SDK bundle with all features | `npm install @openai/agents` |\n| `@openai/agents-core` | Core agent primitives and interfaces | `npm install @openai/agents` |\n| `@openai/agents-extensions` | Extension features (AI SDK UI, Codex, Sandbox) | `npm install @openai/agents-extensions` |\n| `@openai/agents-realtime` | Voice agent capabilities for realtime sessions | `npm install @openai/agents` |\n| `@openai/agents-openai` | OpenAI-specific implementations | `npm install @openai/agents` |\n\n资料来源：[packages/agents-core/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/README.md), [packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n\n## Core Agent Class\n\nThe `Agent` class is the fundamental building block of the SDK. It extends `AgentHooks` and implements `AgentConfiguration`, providing a comprehensive interface for agent configuration.\n\n资料来源：[packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n\n### Agent Configuration\n\nAgents are configured with the following key options:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | The agent's identifier |\n| `instructions` | `string \\| function` | System prompt or dynamic instruction generator |\n| `tools` | `Tool[]` | Collection of tools the agent can invoke |\n| `handoffs` | `Agent[] \\| Handoff[]` | Agents available for handoff |\n| `outputType` | `AgentOutputType` | Expected output format |\n| `model` | `string \\| Model` | The model to use for this agent |\n| `modelSettings` | `ModelSettings` | Model-specific configuration |\n| `inputGuardrails` | `Guardrail[]` | Validation for incoming messages |\n| `outputGuardrails` | `Guardrail[]` | Validation for agent responses |\n\n资料来源：[packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n\n### Creating an Agent\n\n```typescript\nimport { Agent } from '@openai/agents';\n\nconst agent = new Agent({\n  name: 'Assistant',\n  instructions: 'You are a helpful assistant that responds in concise sentences.',\n  tools: [/* your tools here */],\n});\n```\n\n## Tool System\n\nThe SDK provides a flexible tool system that allows agents to interact with external systems and perform actions.\n\n### Built-in Tool Categories\n\n| Category | Tools | Use Case |\n|----------|-------|----------|\n| **Web** | `webSearchTool`, `webSearchToolWithFilters` | General web queries and filtered searches |\n| **Files** | `fileSearchTool`, `fileSearchWithReferencesTool` | Vector-based file searching |\n| **Code** | `codeInterpreterTool`, `localShellTool`, `containerShellTool` | Code execution and shell commands |\n| **Images** | `imageGenerationTool` | AI image generation |\n| **Computer** | `computerTool` | Browser automation with Playwright |\n| **Codex** | `codexTool` | Code editing and task execution via Codex CLI |\n\n资料来源：[examples/tools/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/tools/README.md)\n\n### Tool Configuration Options\n\nWhen defining tools for an agent, the following options are available:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `toolName` | `string` | Custom name for the tool (defaults to agent name) |\n| `toolDescription` | `string` | Human-readable description of tool behavior |\n| `parameters` | `TParameters` | Zod schema for tool input validation |\n| `needsApproval` | `boolean \\| function` | Require human approval before execution |\n| `customOutputExtractor` | `function` | Custom logic to extract output from tool result |\n| `inputBuilder` | `AgentToolInputBuilder` | Build nested agent input from structured data |\n\n资料来源：[packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n\n## Agent Patterns\n\nThe SDK supports various agent orchestration patterns demonstrated in the examples directory.\n\n资料来源：[examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n\n### Common Patterns\n\n| Pattern | Example | Description |\n|---------|---------|-------------|\n| **Agents as Tools** | `agents-as-tools.ts` | Wrap agents as callable tools for orchestration |\n| **Structured Input** | `agents-as-tools-structured.ts` | Use `Agent.asTool()` with structured input schemas |\n| **Conditional Tools** | `agents-as-tools-conditional.ts` | Enable/disable tools based on context |\n| **Deterministic Flow** | `deterministic.ts` | Fixed agent flow with gating and quality checks |\n| **Human-in-the-Loop** | `human-in-the-loop.ts` | Manual approval for sensitive operations |\n| **Guardrails** | `input-guardrails.ts`, `output-guardrails.ts` | Validate inputs and block unsafe outputs |\n| **LLM as Judge** | `llm-as-a-judge.ts` | Use LLM to evaluate agent outputs |\n\n### Workflow Example\n\n```mermaid\ngraph LR\n    A[User Input] --> B[Input Guardrails]\n    B --> C[Agent Processing]\n    C --> D{Tool Call?}\n    D -->|Yes| E[Execute Tool]\n    E --> C\n    D -->|No| F[Output Guardrails]\n    F --> G[Response to User]\n```\n\n## Extensions Package\n\nThe `@openai/agents-extensions` package provides additional features beyond the core SDK.\n\n资料来源：[packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n\n### Available Exports\n\n| Export | Purpose |\n|--------|---------|\n| `./ai-sdk` | AI SDK integration utilities |\n| `./ai-sdk-ui` | UI framework adapters (Next.js, etc.) |\n| `./experimental/codex` | Experimental Codex CLI tool wrapper |\n\n资料来源：[packages/agents-extensions/package.json](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/package.json)\n\n### AI SDK UI Integration\n\nFor Next.js and similar frameworks, the SDK provides streaming response helpers:\n\n```typescript\nimport { Agent, run } from '@openai/agents';\nimport { createAiSdkTextStreamResponse } from '@openai/agents-extensions/ai-sdk-ui';\n\nexport async function POST() {\n  const agent = new Agent({\n    name: 'Assistant',\n    instructions: 'Reply with a short answer.',\n  });\n\n  const stream = await run(agent, 'Hello there.', { stream: true });\n  return createAiSdkTextStreamResponse(stream);\n}\n```\n\n资料来源：[examples/ai-sdk-ui/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/ai-sdk-ui/README.md)\n\n## Basic Examples\n\nThe SDK includes numerous example scripts demonstrating core functionality:\n\n资料来源：[examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n\n| Example | Command | Demonstrates |\n|---------|---------|--------------|\n| `hello-world.ts` | `pnpm -F basic start:hello-world` | Basic agent that responds in haiku |\n| `chat.ts` | `pnpm -F basic start:chat` | Interactive CLI chat with weather handoff |\n| `stream-text.ts` | `pnpm -F basic start:stream-text` | Plain text response streaming |\n| `stream-items.ts` | `pnpm -F basic start:stream-items` | Event streaming with tool usage |\n| `stream-ws.ts` | `pnpm -F basic start:stream-ws` | WebSocket streaming with HITL approval |\n| `dynamic-system-prompt.ts` | `pnpm -F basic start:dynamic-system-prompt` | Dynamic instructions per run |\n| `lifecycle-example.ts` | `pnpm -F basic start:lifecycle-example` | Detailed lifecycle events and usage |\n| `local-image.ts` | `pnpm -F basic start:local-image` | Sending local images to agents |\n| `image-tool-output.ts` | `pnpm -F basic start:image-tool-output` | Image return from tools |\n\n## Running Examples\n\nThe repository uses `pnpm` as its package manager with workspace-based organization.\n\n```bash\n# Install dependencies\npnpm install\n\n# Run a specific example\npnpm -F basic start:hello-world\npnpm -F basic start:chat\npnpm -F basic start:stream-text\n\n# Run agent pattern examples\npnpm examples:agents-as-tools\npnpm examples:human-in-the-loop\n\n# Run tool integration examples\npnpm examples:tools-web-search\npnpm examples:tools-file-search\npnpm examples:tools-codex\n```\n\n## Installation\n\nThe SDK can be installed via npm:\n\n```bash\n# Core package (includes agents-core, agents-openai)\nnpm install @openai/agents\n\n# Extensions package (requires agents-core)\nnpm install @openai/agents @openai/agents-extensions\n```\n\n资料来源：[README.md](https://github.com/openai/openai-agents-js/blob/main/README.md), [packages/agents-core/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/README.md)\n\n## Summary\n\nThe OpenAI Agents SDK provides a comprehensive framework for building agentic applications:\n\n- **Lightweight and modular**: Pick only the components you need\n- **Type-safe**: Full TypeScript support with generic types\n- **Extensible**: Create custom tools, guardrails, and hooks\n- **Observable**: Built-in tracing with customizable span types\n- **Production-ready**: MIT licensed with streaming and error handling support\n\n---\n\n<a id='installation'></a>\n\n## Installation and Setup\n\n### 相关页面\n\n相关主题：[Introduction to OpenAI Agents SDK](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n- [examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n- [examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n- [examples/sandbox/extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/sandbox/extensions/README.md)\n- [examples/ai-sdk-ui/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/ai-sdk-ui/README.md)\n</details>\n\n# Installation and Setup\n\n## Overview\n\nThe OpenAI Agents SDK provides a modular JavaScript/TypeScript framework for building AI-powered agent applications. The SDK is organized into multiple packages that can be installed independently or together depending on your use case.\n\n资料来源：[packages/agents-extensions/README.md:1-8]()\n\n## Package Architecture\n\nThe SDK consists of several packages published to npm:\n\n| Package | Description | Core Dependency |\n|---------|-------------|-----------------|\n| `@openai/agents` | Main agent runtime and CLI | Yes |\n| `@openai/agents-core` | Core agent abstractions and types | Yes |\n| `@openai/agents-extensions` | Extension features and integrations | No |\n| `@openai/agents-openai` | OpenAI-specific model integrations | No |\n| `@openai/agents-realtime` | Realtime voice agent capabilities | No |\n\n资料来源：[packages/agents-extensions/README.md:1-12]()\n\n## Installation Methods\n\n### Standard Installation\n\nFor most use cases, install the core packages:\n\n```bash\nnpm install @openai/agents @openai/agents-extensions\n```\n\n资料来源：[packages/agents-extensions/README.md:6]()\n\n### With Extensions\n\nInstall additional extension packages based on your requirements:\n\n```bash\n# For AI SDK UI integration\nnpm install @openai/agents-extensions/ai-sdk-ui\n\n# For sandbox execution\nnpm install @openai/agents-extensions/sandbox\n```\n\n资料来源：[examples/ai-sdk-ui/README.md:1-15]()\n\n### Running Examples\n\nThe repository uses `pnpm` as the package manager for running example scripts:\n\n```bash\n# Run a basic example\npnpm -F basic start:hello-world\n\n# Run an agent pattern example\npnpm examples:agents-as-tools\n\n# Run with streaming\npnpm examples:streamed:human-in-the-loop\n```\n\n资料来源：[examples/basic/README.md:1-30]()\n资料来源：[examples/agent-patterns/README.md:1-20]()\n\n## Environment Configuration\n\n### Required Environment Variables\n\n#### OpenAI API Key\n\nSet your OpenAI API key before running any agent:\n\n```bash\nexport OPENAI_API_KEY=sk-...\n```\n\n#### Sandbox Extensions (Optional)\n\nFor sandbox execution features, additional environment variables are required:\n\n```bash\nexport BL_API_KEY=...\nexport BL_WORKSPACE=...\nexport BL_REGION=us-pdx-1\n```\n\n资料来源：[examples/sandbox/extensions/README.md:1-60]()\n\n### Environment File Setup\n\nCreate a `.env.local` file for local development:\n\n```bash\ncat > .env.local <<'EOF'\nOPENAI_API_KEY=your-api-key\nBL_WORKSPACE=your-workspace\nBL_API_KEY=your-api-key\nBL_REGION=us-pdx-1\nEOF\n\nset -a\nsource .env.local\nset +a\n```\n\n资料来源：[examples/sandbox/extensions/README.md:40-58]()\n\n## Project Structure\n\nWhen using the SDK in your project, the typical structure is:\n\n```mermaid\ngraph TD\n    A[Your Project] --> B[Install SDK]\n    B --> C[Configure Environment]\n    C --> D[Create Agent Instance]\n    D --> E[Add Tools & Guardrails]\n    E --> F[Run Agent]\n    \n    G[agents-core] --> H[Core Abstractions]\n    G --> I[Tool Definitions]\n    G --> J[Runner Logic]\n    \n    K[agents-extensions] --> L[Sandbox Integration]\n    K --> M[AI SDK UI]\n    K --> N[Daytona Support]\n```\n\n## Quick Start Workflow\n\n```mermaid\ngraph LR\n    A[Initialize Agent] --> B[Configure Model]\n    B --> C[Add Instructions]\n    C --> D[Register Tools]\n    D --> E[Execute Run]\n    E --> F[Process Output]\n    \n    A1[Agent Class] --> |config| B1\n    B1[Model Settings] --> |settings| C1\n    C1[Instructions] --> |prompt| D1\n    D1[Tools] --> |functions| E1\n    E1[Runner.run] --> |stream| F1\n```\n\n## TypeScript Configuration\n\nThe SDK is written in TypeScript and ships with type definitions. Ensure your `tsconfig.json` includes:\n\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"esModuleInterop\": true\n  }\n}\n```\n\n## Verifying Installation\n\nAfter installation, verify the setup by running a basic example:\n\n```bash\npnpm -F basic start:hello-world\n```\n\nExpected output: A response from the agent in haiku format.\n\n资料来源：[examples/basic/README.md:5-7]()\n\n## SDK Package Dependencies\n\n### Core Packages\n\nThe `agents` package depends on `agents-core`:\n\n```json\n{\n  \"dependencies\": {\n    \"@openai/agents-core\": \"workspace:*\"\n  }\n}\n```\n\n### Extension Packages\n\nExtensions are designed to be optional and do not require `agents-core` directly:\n\n```mermaid\ngraph TD\n    A[Your App] --> B[@openai/agents]\n    A --> C[@openai/agents-extensions]\n    B --> D[@openai/agents-core]\n    C --> D\n    C --> E[Optional: AI SDK]\n```\n\n## Next Steps\n\nAfter completing installation and setup:\n\n1. Review the [Agent Configuration](./agent-configuration.md) documentation\n2. Explore available [Tools](./tools.md)\n3. Implement [Guardrails](./guardrails.md) for input/output validation\n4. Set up [Handoffs](./handoffs.md) for multi-agent orchestration\n\n---\n\n<a id='examples-overview'></a>\n\n## Examples and Patterns\n\n### 相关页面\n\n相关主题：[Introduction to OpenAI Agents SDK](#introduction), [Creating and Running Agents](#agents), [Tools and Tool Use](#tools)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n- [examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n- [examples/tools/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/tools/README.md)\n- [examples/research-bot/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/research-bot/README.md)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/tool.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/tool.ts)\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n- [packages/agents-realtime/src/realtimeAgent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeAgent.ts)\n</details>\n\n# Examples and Patterns\n\nThis page documents the example applications and architectural patterns demonstrated in the OpenAI Agents SDK for JavaScript/TypeScript. These examples serve as practical guides for building AI-powered applications using the `@openai/agents-core` package.\n\n## Overview\n\nThe repository organizes examples into distinct categories that demonstrate different aspects of agent development:\n\n| Category | Location | Purpose |\n|----------|----------|---------|\n| Basic Examples | `examples/basic/` | Core functionality and getting started |\n| Agent Patterns | `examples/agent-patterns/` | Common architectural patterns |\n| Tool Integrations | `examples/tools/` | Hosted tool usage |\n| Research Bot | `examples/research-bot/` | Multi-agent orchestration |\n| MCP Examples | `examples/mcp/` | Model Context Protocol integration |\n\n## Basic Examples\n\nThe Basic Examples directory provides foundational examples for understanding the Agents SDK core concepts.\n\n### Hello World\n\nA minimal agent that responds with a haiku, demonstrating the simplest possible agent setup.\n\n```bash\npnpm -F basic start:hello-world\n```\n\nThis example shows:\n- Creating an `Agent` instance with instructions\n- Running the agent with `run()` \n- Basic text output handling\n\n### Interactive Chat\n\nAn interactive CLI chat application that demonstrates:\n- Real-time user input handling\n- Streaming responses\n- Handoff integration with weather queries\n\n```bash\npnpm -F basic start:chat\n```\n\n### Streaming Examples\n\nThe SDK supports multiple streaming modes for different use cases:\n\n| Example | Command | Description |\n|---------|---------|-------------|\n| stream-text | `pnpm -F basic start:stream-text` | Plain text streaming |\n| stream-items | `pnpm -F basic start:stream-items` | Event streaming with tool usage |\n| stream-ws | `pnpm -F basic start:stream-ws` | WebSocket streaming with HITL approval |\n\n```bash\npnpm -F basic start:stream-text\npnpm -F basic start:stream-items\npnpm -F basic start:stream-ws\n```\n\n### Dynamic System Prompt\n\nDemonstrates runtime instruction modification using the `input_guardrails` pattern to pick instructions dynamically per run.\n\n```bash\npnpm -F basic start:dynamic-system-prompt\n```\n\n### Lifecycle Hooks\n\nTwo examples demonstrate the event hook system:\n\n- `lifecycle-example.ts` - Logs detailed lifecycle events and usage statistics\n- `agent-lifecycle-example.ts` - Minimal lifecycle hooks demonstration\n\n```bash\npnpm -F basic start:lifecycle-example\npnpm -F basic start:agent-lifecycle-example\n```\n\n### Image Handling\n\n| Example | Purpose |\n|---------|---------|\n| `local-image.ts` | Send local images to the agent |\n| `image-tool-output.ts` | Return images from tools for agent analysis |\n\n```bash\npnpm -F basic start:local-image\npnpm -F basic start:image-tool-output\n```\n\n## Agent Patterns\n\nThe Agent Patterns directory demonstrates common architectural patterns for building sophisticated AI applications.\n\n### Agents as Tools Pattern\n\nThe most important pattern - enabling agents to be used as tools by other agents. This enables hierarchical agent architectures.\n\n```bash\npnpm examples:agents-as-tools\n```\n\n#### Key Files\n\n- `agents-as-tools.ts` - Orchestrate translator agents using them as tools\n- `agents-as-tools-structured.ts` - Use structured tool input with `Agent.asTool()`\n- `agents-as-tools-conditional.ts` - Enable language tools based on user preference\n\n#### Implementation Pattern\n\n```typescript\n// From agents-as-tools.ts - Agents can be wrapped as tools\nconst translatorAgent = Agent.make({\n  name: 'translator',\n  instructions: 'Translate text between languages',\n});\n\nconst translatorTool = translatorAgent.asTool({\n  toolName: 'translate',\n  toolDescription: 'Translate text to a target language',\n});\n```\n\n资料来源：[examples/agent-patterns/agents-as-tools.ts]()\n\nThe `Agent.asTool()` method creates a `FunctionTool` that wraps the agent, allowing other agents to invoke it with typed parameters.\n\n### Deterministic Flow Pattern\n\nFixed agent flow with gating and quality checks for controlled execution paths.\n\n```bash\npnpm examples:deterministic\n```\n\n### Tool Forcing Pattern\n\nRequires specific tools to be called before final output is generated.\n\n```bash\npnpm -F agent-patterns start:forcing-tool-use\n```\n\n### Human-in-the-Loop (HITL) Pattern\n\nHuman approval integration for sensitive operations:\n\n| Example | Command | Use Case |\n|---------|---------|----------|\n| `human-in-the-loop.ts` | `pnpm examples:human-in-the-loop` | Manual approval |\n| `human-in-the-loop-stream.ts` | `pnpm examples:streamed:human-in-the-loop` | Streaming approval |\n\n```bash\npnpm examples:human-in-the-loop\npnpm examples:streamed:human-in-the-loop\n```\n\n### Guardrails Pattern\n\nInput and output validation to control agent behavior:\n\n| Example | Purpose |\n|---------|---------|\n| `input-guardrails.ts` | Reject unwanted requests before processing |\n| `output-guardrails.ts` | Block unsafe output |\n\n```bash\npnpm examples:input-guardrails\npnpm examples:output-guardrails\n```\n\n### LLM-as-Judge Pattern\n\nSelf-evaluation and iteration using a secondary LLM to judge outputs.\n\n```bash\npnpm -F agent-patterns start:llm-as-a-judge\n```\n\n## Tool Integrations\n\nThe Tools Examples directory demonstrates hosted tools provided by the SDK.\n\n### Computer Use Tool\n\nBrowser automation using Playwright for GUI interaction:\n\n```bash\npnpm examples:tools-computer-use\n```\n\n### File Search Tool\n\nVector search integration for document retrieval:\n\n```bash\npnpm examples:tools-file-search\n```\n\n### Tool Search (Deferred Loading)\n\nDemonstrates namespace loading and selective tool loading:\n\n```bash\npnpm examples:tools-tool-search\n```\n\nKey concepts:\n- `deferLoading: true` for lazy tool loading\n- Namespace-based tool organization\n- Selective tool loading per context\n\n### Codex Tool\n\nCode execution and analysis using the Codex CLI:\n\n| Example | Purpose |\n|---------|---------|\n| `codex.ts` | Streaming event logs and skill usage |\n| `codex-same-thread.ts` | Reuse Codex thread across turns |\n\n```bash\npnpm examples:tools-codex\npnpm examples:tools-codex-same-thread\n```\n\nEnvironment variables:\n- `CODEX_API_KEY` - Primary API key\n- `OPENAI_API_KEY` - Fallback API key\n- `CODEX_PATH` - Override Codex CLI path\n\n### Web Search Tool\n\nGeneral web queries using `webSearchTool`:\n\n```bash\npnpm examples:tools-web-search\n```\n\n### Code Interpreter\n\nSecure code execution environment:\n\n```bash\npnpm -F tools start:code-interpreter\n```\n\n### Image Generation\n\nDALL-E integration for image generation:\n\n```bash\npnpm examples:tools-image-generation\n```\n\n## Multi-Agent Orchestration\n\n### Research Bot Example\n\nA complete example demonstrating multi-agent coordination to produce research reports.\n\n#### Architecture\n\n```mermaid\ngraph TD\n    A[User Query] --> B[ResearchManager]\n    B --> C[Planner Agent]\n    C -->|Search Terms| D[Search Agent]\n    D --> E[Web Search Tool]\n    E --> D\n    D -->|Summaries| B\n    B --> F[Writer Agent]\n    F -->|Research Report| A\n```\n\n#### Components\n\n| File | Role |\n|------|------|\n| `main.ts` | CLI entrypoint |\n| `manager.ts` | Coordinates workflow stages |\n| `agents.ts` | Agent definitions |\n\n资料来源：[examples/research-bot/README.md]()\n\n#### Usage\n\n```bash\npnpm examples:research-bot\n```\n\n## Realtime Agents\n\nSpecialized agents for voice applications using the Realtime API.\n\n### Configuration Differences\n\nRealtime agents have limited configuration compared to standard agents:\n\n| Supported | Not Supported |\n|-----------|---------------|\n| `name` | `model` |\n| `handoffs` | `modelSettings` |\n| `voice` | `toolUseBehavior` |\n| | `outputGuardrails` |\n| | `inputGuardrails` |\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts]()\n\n## Lifecycle Events\n\nThe SDK provides comprehensive event hooks for monitoring agent execution:\n\n### Agent-Level Events\n\n| Event | Parameters | Description |\n|-------|------------|-------------|\n| `agent_start` | `context, agent, turnInput?` | Agent begins execution |\n| `agent_end` | `context, agent, output` | Agent completes |\n| `agent_handoff` | `context, fromAgent, toAgent` | Agent transfers control |\n| `agent_tool_start` | `context, agent, tool, details` | Tool invocation begins |\n| `agent_tool_end` | `context, agent, tool, result, details` | Tool invocation completes |\n\n资料来源：[packages/agents-core/src/lifecycle.ts]()\n\n### Event Handler Pattern\n\n```typescript\nagent.addHook('agent_start', async (context, agent) => {\n  console.log(`Starting agent: ${agent.name}`);\n});\n```\n\n## Common Patterns Summary\n\n### Pattern: Agent-as-Tool Hierarchy\n\n```mermaid\ngraph BT\n    A[Orchestrator Agent] -->|calls| B[Specialist Agent 1]\n    A -->|calls| C[Specialist Agent 2]\n    B -->|uses| D[Tool: Translation]\n    C -->|uses| E[Tool: Search]\n```\n\n### Pattern: Human-in-the-Loop\n\n```mermaid\ngraph LR\n    A[Agent] -->|tool call| B{Approval Gate}\n    B -->|approve| C[Execute Tool]\n    B -->|reject| D[Return Error]\n    C --> E[Continue Run]\n```\n\n### Pattern: Error Handling with Handlers\n\nThe SDK supports custom error handlers for:\n\n- `MaxTurnsExceededError` - Turn limit exceeded\n- `ModelRefusalError` - Model refused to respond\n\n```typescript\ntype RunErrorHandler<TContext, TAgent> = (input: {\n  error: MaxTurnsExceededError | ModelRefusalError;\n  context: RunContext<TContext>;\n  runData: RunErrorData<TContext, TAgent>;\n}) => RunErrorHandlerResult<TAgent> | void;\n```\n\n资料来源：[packages/agents-core/src/runner/errorHandlers.ts]()\n\n## Running Examples\n\nAll examples use `pnpm` for execution:\n\n```bash\n# From repository root\npnpm examples:<example-name>\n\n# Or with package-specific commands\npnpm -F <package-name> start:<script-name>\n```\n\n### Example Commands Reference\n\n| Category | Example | Command |\n|----------|---------|---------|\n| Basic | Hello World | `pnpm -F basic start:hello-world` |\n| Basic | Chat | `pnpm -F basic start:chat` |\n| Basic | Streaming | `pnpm -F basic start:stream-items` |\n| Patterns | Agents as Tools | `pnpm examples:agents-as-tools` |\n| Patterns | Human in Loop | `pnpm examples:human-in-the-loop` |\n| Patterns | Guardrails | `pnpm examples:input-guardrails` |\n| Tools | Web Search | `pnpm examples:tools-web-search` |\n| Tools | Code Interpreter | `pnpm -F tools start:code-interpreter` |\n| Research | Multi-Agent | `pnpm examples:research-bot` |\n\n## Key APIs Demonstrated\n\n### Agent Creation\n\n```typescript\nconst agent = Agent.make({\n  name: 'agent-name',\n  instructions: 'System prompt or instructions',\n  handoffs: [otherAgent],\n  tools: [someTool],\n  outputType: TextOutput,\n});\n```\n\n### Tool Creation\n\n```typescript\nconst tool = tool({\n  name: 'tool-name',\n  description: 'What this tool does',\n  parameters: z.object({ ... }),\n  strict: true,\n})(async (context, { param }) => {\n  return 'result';\n});\n```\n\n### Handoff Configuration\n\n```typescript\nconst handoff = new Handoff(agent, {\n  onHandoff: async (context, input) => {\n    // Custom handoff logic\n  },\n});\n```\n\n资料来源：[packages/agents-core/src/handoff.ts]()\n\n## See Also\n\n- [Agent SDK Documentation](https://github.com/openai/openai-agents-js)\n- [@openai/agents-core Package](packages/agents-core/)\n- [@openai/agents-realtime Package](packages/agents-realtime/)\n- [API Reference](packages/agents-core/src/)\n\n---\n\n<a id='agents'></a>\n\n## Creating and Running Agents\n\n### 相关页面\n\n相关主题：[Tools and Tool Use](#tools), [Guardrails and Input/Output Validation](#guardrails), [Handoffs and Multi-Agent Systems](#handoffs)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/run.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/run.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/tool.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/tool.ts)\n- [packages/agents-core/src/runner/errorHandlers.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/errorHandlers.ts)\n</details>\n\n# Creating and Running Agents\n\n## Overview\n\nAgents are the core building blocks of the OpenAI Agents SDK. An agent is an AI model configured with instructions (system prompt), tools, guardrails, handoffs, and other settings that determine its behavior during execution. The SDK provides a flexible `Agent` class that supports various configuration options for different use cases.\n\nAgents are designed to be composable — they can be chained together through handoffs, used as tools by other agents, and integrated into complex workflows. Each agent maintains its own configuration and can emit lifecycle events for monitoring and debugging.\n\n资料来源：[packages/agents-core/src/agent.ts:117-127]()\n\n## Agent Architecture\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Agent Runner]\n    B --> C[Model Execution]\n    C --> D{Tool Calls?}\n    D -->|Yes| E[Tool Executor]\n    E --> F[Tool Result]\n    F --> C\n    D -->|No| G[Output Generation]\n    G --> H[Final Output]\n    \n    subgraph \"Agent Components\"\n        I[Instructions/System Prompt]\n        J[Tools]\n        K[Handoffs]\n        L[Guardrails]\n        M[Output Type]\n    end\n    \n    B -.->|configures| I\n    B -.->|uses| J\n    B -.->|enables| K\n    B -.->|validates via| L\n    B -.->|produces| M\n```\n\n## Agent Configuration\n\n### Basic Configuration Parameters\n\nThe `Agent` class accepts a configuration object that defines its behavior. The main configuration interface is `AgentConfiguration<TContext, TOutput>`.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `name` | `string` | Yes | A unique identifier for the agent |\n| `instructions` | `string \\| function` | Recommended | The system prompt that guides agent behavior |\n| `handoffDescription` | `string` | No | Human-readable description for handoffs |\n| `tools` | `Tool[]` | No | Array of tools the agent can use |\n| `handoffs` | `Agent[] \\| Handoff[]` | No | Other agents the agent can transfer control to |\n| `outputType` | `AgentOutputType` | No | Expected output format |\n| `model` | `string` | No | The model to use (defaults to `gpt-4o`) |\n| `modelSettings` | `ModelSettings` | No | Additional model configuration |\n| `inputGuardrails` | `InputGuardrail[]` | No | Validation before agent execution |\n| `outputGuardrails` | `OutputGuardrail[]` | No | Validation after agent execution |\n\n资料来源：[packages/agents-core/src/agent.ts:1-150]()\n\n### Output Types\n\nAgents support different output types defined by the `AgentOutputType` union:\n\n| Output Type | Description |\n|-------------|-------------|\n| `TextOutput` | Plain text response (default) |\n| `JsonOutput` | Structured JSON response |\n| Custom types | User-defined output schemas |\n\n```typescript\nimport { Agent, TextOutput, JsonOutput } from '@openai/agents';\n\n// Text output agent (default)\nconst textAgent = new Agent({ name: 'text-agent', instructions: '...' });\n\n// JSON output agent\nconst jsonAgent = new Agent({\n  name: 'json-agent',\n  instructions: '...',\n  outputType: JsonOutput,\n});\n```\n\n## Creating an Agent\n\n### Basic Agent Creation\n\nThe simplest agent requires only a name and instructions:\n\n```typescript\nimport { Agent } from '@openai/agents';\n\nconst agent = new Agent({\n  name: 'my-agent',\n  instructions: 'You are a helpful assistant.',\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:128-150]()\n\n### Agent with Tools\n\nTools extend agent capabilities by allowing it to perform actions:\n\n```typescript\nimport { Agent, Tool } from '@openai/agents';\n\nconst myTool = Tool.from({\n  name: 'calculator',\n  description: 'Perform mathematical calculations',\n  parameters: {\n    type: 'object',\n    properties: {\n      expression: { type: 'string', description: 'Math expression' },\n    },\n    required: ['expression'],\n  },\n  invoke: async (runContext, input) => {\n    const { expression } = JSON.parse(input);\n    return eval(expression).toString();\n  },\n});\n\nconst agentWithTools = new Agent({\n  name: 'math-assistant',\n  instructions: 'Use the calculator for complex math.',\n  tools: [myTool],\n});\n```\n\n资料来源：[packages/agents-core/src/tool.ts:1-80]()\n\n### Agent with Handoffs\n\nHandoffs enable transfer of control between agents:\n\n```typescript\nimport { Agent, Handoff } from '@openai/agents';\n\nconst salesAgent = new Agent({\n  name: 'sales',\n  instructions: 'Handle sales inquiries.',\n});\n\nconst supportAgent = new Agent({\n  name: 'support',\n  instructions: 'Handle support requests.',\n});\n\nconst routerAgent = new Agent({\n  name: 'router',\n  instructions: 'Route to the appropriate department.',\n  handoffs: [salesAgent, supportAgent],\n});\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:1-80]()\n\n### Handoff Configuration\n\nThe `HandoffConfig` type provides additional options for handoff behavior:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `toolNameOverride` | `string` | Custom name for the handoff tool |\n| `toolDescriptionOverride` | `string` | Custom description for the handoff |\n| `onHandoff` | `OnHandoffCallback` | Callback function executed during handoff |\n| `inputJsonSchema` | `JsonSchema` | Schema for handoff input validation |\n\n```typescript\nimport { Handoff } from '@openai/agents';\n\nconst configuredHandoff = new Handoff(supportAgent, async (context) => {\n  console.log(`Handing off to support for session ${context.threadId}`);\n  return supportAgent;\n});\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:80-120]()\n\n### Agents as Tools\n\nAgents can be used as tools by other agents using `Agent.asTool()`:\n\n```typescript\nconst translatorAgent = new Agent({\n  name: 'translator',\n  instructions: 'Translate text to the target language.',\n});\n\nconst mainAgent = new Agent({\n  name: 'main',\n  instructions: 'Use the translator for language tasks.',\n  tools: [\n    translatorAgent.asTool({\n      toolName: 'translate',\n      toolDescription: 'Translate text between languages',\n      parameters: {\n        type: 'object',\n        properties: {\n          text: { type: 'string' },\n          targetLanguage: { type: 'string' },\n        },\n      },\n    }),\n  ],\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:150-200]()\n\n## Running Agents\n\n### Basic Run\n\nExecute an agent using the `run()` function:\n\n```typescript\nimport { Agent, run } from '@openai/agents';\n\nconst agent = new Agent({\n  name: 'hello-agent',\n  instructions: 'Respond in haiku format.',\n});\n\nconst result = await run(agent, 'Tell me about dogs');\nconsole.log(result.finalOutput);\n```\n\n### Run with Options\n\nThe `run()` function accepts additional options:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `context` | `TContext` | Mutable context object passed to tools |\n| `stream` | `boolean` | Enable streaming response |\n| `maxTurns` | `number` | Maximum agent turns before stopping |\n| `model` | `string` | Override the agent's default model |\n| `modelSettings` | `ModelSettings` | Override model settings |\n| `tools` | `Tool[]` | Additional tools to include |\n| `outputType` | `AgentOutputType` | Override output type |\n\n```typescript\nconst result = await run(agent, 'Process this request', {\n  context: { userId: '123' },\n  maxTurns: 10,\n  modelSettings: { temperature: 0.7 },\n});\n```\n\n### Streaming Responses\n\nEnable streaming for real-time output:\n\n```typescript\nconst stream = await run(agent, 'Generate a long story', { stream: true });\n\nfor await (const event of stream) {\n  if (event.type === 'agent_update') {\n    console.log(event.data);\n  }\n}\n```\n\n## Agent Lifecycle\n\n### Lifecycle Events\n\nAgents emit events throughout their execution lifecycle. The `AgentHooks` class extends `EventEmitterDelegate` to provide event handling.\n\n```mermaid\nstateDiagram-v2\n    [*] --> start: agent_start\n    start --> tool_use: tool call required\n    start --> end: direct response\n    tool_use --> tool_execution: agent_tool_start\n    tool_execution --> tool_complete: agent_tool_end\n    tool_complete --> start: continue\n    tool_complete --> end: no more tools\n    end --> [*]: agent_end\n    \n    start --> handoff: handoff trigger\n    handoff --> [*]: agent_handoff\n```\n\n### Available Lifecycle Events\n\n| Event | Parameters | Description |\n|-------|------------|-------------|\n| `agent_start` | `context, agent, turnInput?` | Fired when agent execution begins |\n| `agent_end` | `context, agent, output` | Fired when agent execution completes |\n| `agent_handoff` | `context, fromAgent, toAgent` | Fired during agent transfer |\n| `agent_tool_start` | `context, tool, details` | Fired when a tool begins |\n| `agent_tool_end` | `context, tool, result, details` | Fired when a tool completes |\n\n```typescript\nconst agent = new Agent({\n  name: 'monitored-agent',\n  instructions: 'You are helpful.',\n});\n\nagent.on('agent_start', (context, agent) => {\n  console.log(`Starting agent: ${agent.name}`);\n});\n\nagent.on('agent_tool_start', (context, tool, details) => {\n  console.log(`Tool called: ${tool.name}`);\n});\n\nagent.on('agent_end', (context, agent, output) => {\n  console.log(`Agent finished with: ${output}`);\n});\n```\n\n资料来源：[packages/agents-core/src/lifecycle.ts:1-100]()\n\n### Run-Level Hooks\n\nIn addition to agent hooks, you can register hooks at the run level:\n\n```typescript\nimport { Agent, run, RunHookEvents } from '@openai/agents';\n\nconst hooks: RunHookEvents = {\n  onAgentStart: async (context, agent) => {\n    console.log(`Run starting with agent: ${agent.name}`);\n  },\n  onAgentEnd: async (context, agent, output) => {\n    console.log(`Run completed with output: ${output}`);\n  },\n};\n\nconst result = await run(agent, input, { hooks });\n```\n\n## Context Management\n\n### Run Context\n\nThe `RunContext` provides a mechanism to pass and share state across tools, guardrails, and handoffs:\n\n```typescript\nimport { Agent, run, RunContext } from '@openai/agents';\n\ninterface MyContext {\n  userId: string;\n  sessionData: Record<string, any>;\n}\n\nconst agent = new Agent<MyContext>({\n  name: 'context-agent',\n  instructions: 'You are a personalized assistant.',\n});\n\nconst result = await run(agent, 'Hello', {\n  context: {\n    userId: 'user-123',\n    sessionData: { lastVisit: Date.now() },\n  },\n});\n\n// Access context in tools\nconst myTool = Tool.from({\n  name: 'user-info',\n  description: 'Get user information',\n  invoke: async (runContext, input) => {\n    return runContext.context.userId;\n  },\n});\n```\n\n### Tool Input Capture\n\nThe SDK can capture tool input into the run context for debugging and logging:\n\n```typescript\nconst tool = Tool.from({\n  name: 'search',\n  description: 'Search the web',\n  parameters: { /* schema */ },\n  invoke: async (runContext, input, details) => {\n    // The SDK can capture input when shouldCaptureToolInput is enabled\n    const capturedInput = runContext.toolInput;\n    console.log(`Search called with: ${capturedInput}`);\n    return 'results';\n  },\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:200-280]()\n\n## Error Handling\n\n### Error Handlers\n\nThe SDK provides structured error handling through `RunErrorHandler` types:\n\n| Error Type | Description |\n|------------|-------------|\n| `MaxTurnsExceededError` | Maximum turns limit reached |\n| `ModelRefusalError` | Model refused to respond |\n\n```typescript\nimport { Agent, run, RunErrorHandlers } from '@openai/agents';\n\nconst errorHandlers: RunErrorHandlers = {\n  onMaxTurnsExceeded: async ({ error, context, runData }) => {\n    return {\n      finalOutput: 'The conversation reached its maximum length.',\n      includeInHistory: true,\n    };\n  },\n  onModelRefusal: async ({ error, context, runData }) => {\n    return {\n      finalOutput: 'I apologize, but I cannot help with that request.',\n      includeInHistory: false,\n    };\n  },\n  default: async ({ error }) => {\n    return {\n      finalOutput: 'An unexpected error occurred.',\n      includeInHistory: true,\n    };\n  },\n};\n\nconst result = await run(agent, input, { errorHandlers });\n```\n\n资料来源：[packages/agents-core/src/runner/errorHandlers.ts:1-80]()\n\n## Agent Factory Method\n\n### Static `create()` Method\n\nThe `Agent.create()` static method provides type-safe agent creation with automatic output type inference:\n\n```typescript\nimport { Agent } from '@openai/agents';\n\n// Create agent with handoffs - output type is inferred\nconst agent = Agent.create({\n  name: 'orchestrator',\n  instructions: 'Route requests appropriately.',\n  handoffs: [\n    salesAgent,           // outputs: TextOutput\n    billingAgent,         // outputs: JsonOutput\n  ],\n  // TOutput is automatically inferred as: TextOutput | JsonOutput\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:140-180]()\n\n## Complete Example\n\n```typescript\nimport { Agent, run, Tool } from '@openai/agents';\n\n// Define tools\nconst searchTool = Tool.from({\n  name: 'web_search',\n  description: 'Search the web for information',\n  parameters: {\n    type: 'object',\n    properties: {\n      query: { type: 'string' },\n    },\n    required: ['query'],\n  },\n  strict: true,\n  invoke: async (runContext, input) => {\n    const { query } = JSON.parse(input);\n    return `Results for: ${query}`;\n  },\n});\n\n// Define agents\nconst researchAgent = new Agent({\n  name: 'researcher',\n  instructions: 'Use web search to gather information.',\n  tools: [searchTool],\n});\n\nconst writerAgent = new Agent({\n  name: 'writer',\n  instructions: 'Write clear, concise summaries.',\n});\n\n// Orchestrator agent\nconst orchestrator = new Agent({\n  name: 'orchestrator',\n  instructions: 'Delegate research and writing tasks.',\n  handoffs: [researchAgent, writerAgent],\n});\n\n// Register lifecycle hooks\norchestrator.on('agent_start', (ctx, agent) => {\n  console.log(`Starting: ${agent.name}`);\n});\n\norchestrator.on('agent_handoff', (ctx, from, to) => {\n  console.log(`Handoff: ${from.name} → ${to.name}`);\n});\n\n// Run the agent\nconst result = await run(orchestrator, 'Research and write about AI');\nconsole.log(result.finalOutput);\n```\n\n## Summary\n\nThe OpenAI Agents SDK provides a flexible and extensible framework for creating and running AI agents:\n\n| Feature | Description |\n|---------|-------------|\n| **Agent Configuration** | Flexible configuration with instructions, tools, handoffs, and guardrails |\n| **Tool Integration** | Define custom tools with typed parameters and validation |\n| **Handoffs** | Transfer control between agents seamlessly |\n| **Lifecycle Events** | Monitor and debug agent execution |\n| **Context Management** | Share state across tools and handoffs |\n| **Error Handling** | Gracefully handle errors with custom handlers |\n| **Streaming** | Support for real-time streaming responses |\n\nAll agents are built on the core `Agent` class which implements the `AgentConfiguration` interface, providing consistency and predictability across the SDK.\n\n---\n\n<a id='tools'></a>\n\n## Tools and Tool Use\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/tool.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/tool.ts)\n- [packages/agents-core/src/mcp.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/mcp.ts)\n- [packages/agents-core/src/mcpUtil.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/mcpUtil.ts)\n- [packages/agents-core/src/runner/toolExecution.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/toolExecution.ts)\n- [packages/agents-core/src/runner/toolSearch.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/toolSearch.ts)\n</details>\n\n# Tools and Tool Use\n\n## Overview\n\nTools extend an agent's capabilities by allowing it to interact with external systems, execute code, search for information, and perform actions beyond text generation. In the OpenAI Agents SDK, tools are defined as first-class constructs that agents can invoke during their reasoning loops. When an agent decides to use a tool, the SDK handles the execution, processes the results, and feeds them back to the agent for continued decision-making.\n\nThe tool system supports multiple tool types including function tools, hosted tools, computer tools (for browser automation), shell tools, and MCP (Model Context Protocol) tools. Each tool type has specific use cases and integration patterns.\n\n资料来源：[packages/agents-core/src/tool.ts:1-50]()\n\n## Tool Types\n\nThe SDK defines several distinct tool types through a discriminated union. Understanding these types is essential for selecting the appropriate tool for a given task.\n\n| Tool Type | Description | Use Case |\n|-----------|-------------|----------|\n| `function` | Custom JavaScript functions exposed to the agent | Custom logic, API calls, data processing |\n| `hosted_tool` | Tools provided by external services (MCP, web search, etc.) | Third-party integrations |\n| `computer` | Browser automation via Playwright | Web interactions, UI testing |\n| `shell` | Command-line execution | System operations, script running |\n| `apply_patch` | Code modification operations | Automated code editing |\n\n资料来源：[packages/agents-core/src/tool.ts:60-120]()\n\n### Function Tools\n\nFunction tools are the most common tool type. They wrap JavaScript functions with metadata that allows the agent to understand when and how to call them.\n\n```typescript\ntype FunctionTool<\n  Context = UnknownContext,\n  TParameters extends ToolInputParameters = undefined,\n  Result = unknown,\n> = {\n  type: 'function';\n  name: string;\n  description: string;\n  parameters: JsonObjectSchema<any>;\n  strict: boolean;\n  deferLoading?: boolean;\n  invoke: (\n    runContext: RunContext<Context>,\n    input: string,\n    details?: ToolCallDetails,\n  ) => Promise<string | Result>;\n  needsApproval?: boolean | ToolApprovalFunction<TParameters>;\n};\n```\n\n资料来源：[packages/agents-core/src/tool.ts:60-85]()\n\n### Hosted Tools\n\nHosted tools represent external services that the agent can invoke. They include a `providerData` field for additional configuration and support for custom executors.\n\n```typescript\nexport type HostedTool = {\n  type: 'hosted_tool';\n  name: string;\n  providerData?: Record<string, any>;\n};\n```\n\n资料来源：[packages/agents-core/src/tool.ts:140-150]()\n\n## Tool Configuration Options\n\n### Basic Configuration\n\nWhen defining a tool, several configuration options control its behavior:\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `name` | `string` | (required) | Unique identifier for the tool |\n| `description` | `string` | (required) | Human-readable description for the agent |\n| `parameters` | `JsonObjectSchema` | `{ input: string }` | JSON Schema for input validation |\n| `strict` | `boolean` | `false` | Enforce strict schema following |\n| `deferLoading` | `boolean` | `false` | Defer tool loading until needed |\n| `needsApproval` | `boolean \\| Function` | `false` | Require human approval before execution |\n\n资料来源：[packages/agents-core/src/tool.ts:70-95]()\n\n### Namespace Support\n\nTools can be grouped into namespaces to organize related functionality:\n\n```typescript\nconst tool = FunctionTool.create({\n  name: 'search',\n  description: 'Search for information',\n  parameters: z.object({ query: z.string() }),\n  namespace: 'search_tools',\n  namespaceDescription: 'Tools for searching various sources',\n});\n```\n\nNamespaces are useful when you have many tools and want to help the agent understand logical groupings. All tools within a namespace must share the same description.\n\n资料来源：[packages/agents-openai/src/openaiResponsesModel.ts:30-60]()\n\n## Tool Registration with Agents\n\nTools are registered with agents through the agent configuration. The SDK provides flexible patterns for tool registration.\n\n### Using the `tools` Option\n\n```typescript\nimport { Agent, FunctionTool } from '@openai/agents-core';\n\nconst searchTool = FunctionTool.create({\n  name: 'web_search',\n  description: 'Search the web for information',\n  parameters: z.object({\n    query: z.string(),\n    maxResults: z.number().optional(),\n  }),\n  execute: async (context, args) => {\n    // Implementation\n    return await performSearch(args.query, args.maxResults);\n  },\n});\n\nconst agent = Agent.make({\n  name: 'Research Agent',\n  instructions: 'You are a research assistant.',\n  tools: [searchTool],\n});\n```\n\n### Using `Agent.asTool()`\n\nAgents can expose other agents as tools, enabling hierarchical agent architectures:\n\n```typescript\nconst translatorAgent = Agent.make({\n  name: 'Translator',\n  instructions: 'Translate text between languages.',\n});\n\nconst translatorTool = translatorAgent.asTool({\n  toolName: 'translate',\n  toolDescription: 'Translate text from one language to another',\n});\n\nconst orchestratorAgent = Agent.make({\n  name: 'Orchestrator',\n  instructions: 'Coordinate tasks using available tools.',\n  tools: [translatorTool],\n});\n```\n\n资料来源：[examples/agent-patterns/README.md:10-15]()\n\n## Tool Execution Flow\n\nThe following diagram illustrates the tool execution flow within the SDK:\n\n```mermaid\nsequenceDiagram\n    participant Agent as Agent\n    participant Runner as Runner\n    participant ToolSearch as Tool Search\n    participant Executor as Tool Executor\n    participant External as External System\n\n    Agent->>Runner: Request tool call\n    Runner->>ToolSearch: Check tool availability\n    alt Tool is deferred\n        ToolSearch->>ToolSearch: Load tool on demand\n    end\n    Runner->>Executor: Execute tool call\n    Executor->>External: Invoke tool\n    External-->>Executor: Return result\n    Executor-->>Runner: Process result\n    Runner-->>Agent: Feed back to agent\n```\n\n资料来源：[packages/agents-core/src/runner/toolExecution.ts:1-50]()\n\n## Deferred Tool Loading\n\nThe SDK supports deferred loading for tools that may not always be needed. This is particularly useful for:\n\n- Expensive tools that should only be loaded when actually called\n- Tools that depend on runtime configuration\n- Large tool sets where loading everything upfront is inefficient\n\n### Top-Level Deferred Tools\n\nTools can be marked with `deferLoading: true` at the top level:\n\n```typescript\nconst expensiveTool = FunctionTool.create({\n  name: 'expensive_operation',\n  description: 'Performs expensive computation',\n  deferLoading: true,  // Will not be loaded until called\n  parameters: z.object({ input: z.string() }),\n  execute: async (context, args) => {\n    return await runExpensiveOperation(args.input);\n  },\n});\n```\n\n资料来源：[packages/agents-core/src/runner/toolSearch.ts:40-80]()\n\n### Deferred Namespace Loading\n\nNamespaces can also be configured for deferred loading:\n\n```typescript\nconst tools = [\n  FunctionTool.create({\n    name: 'db_query',\n    description: 'Query the database',\n    namespace: 'database',\n    deferLoading: true,\n    parameters: z.object({ sql: z.string() }),\n  }),\n  FunctionTool.create({\n    name: 'db_insert',\n    description: 'Insert into database',\n    namespace: 'database',\n    deferLoading: true,\n    parameters: z.object({ table: z.string(), data: z.record(z.any()) }),\n  }),\n];\n\nconst agent = Agent.make({\n  name: 'Data Agent',\n  instructions: 'Manage data operations',\n  tools: tools,\n  toolNamespaces: {\n    database: {\n      description: 'Database operations',\n      deferLoading: true,\n    },\n  },\n});\n```\n\nThe SDK provides a built-in client tool search executor for handling deferred loading:\n\n```typescript\nexport type ClientToolSearchExecutor<Context = UnknownContext> = (\n  args: ClientToolSearchExecutorArgs<Context>,\n) => Tool<Context>[] | Tool<Context> | null | undefined | Promise<Tool<Context>[] | Tool<Context> | null | undefined>;\n```\n\n资料来源：[packages/agents-core/src/tool.ts:160-175]()\n\n## Tool Input Validation\n\nTools support JSON Schema-based input validation through the `parameters` option. The SDK uses Zod for schema definition but converts these to JSON Schema for API communication.\n\n### Schema Definition\n\n```typescript\nconst tool = FunctionTool.create({\n  name: 'calculate',\n  description: 'Perform calculations',\n  parameters: z.object({\n    expression: z.string().describe('Mathematical expression'),\n    precision: z.number().int().min(0).max(10).optional(),\n  }),\n  strict: true,  // Enforce strict schema following\n});\n```\n\nWhen `strict` is enabled, the model must try to strictly follow the schema, though this may result in slower response times.\n\n资料来源：[packages/agents-core/src/tool.ts:72-75]()\n\n## Human-in-the-Loop Approval\n\nTools can require human approval before execution. This is controlled via the `needsApproval` option:\n\n```typescript\nconst sensitiveTool = FunctionTool.create({\n  name: 'delete_data',\n  description: 'Delete data from the system',\n  needsApproval: true,  // Always require approval\n  parameters: z.object({\n    id: z.string(),\n    confirm: z.boolean(),\n  }),\n  execute: async (context, args) => {\n    if (!args.confirm) {\n      return 'Deletion cancelled';\n    }\n    return await deleteRecord(args.id);\n  },\n});\n```\n\nFor dynamic approval logic, pass a function:\n\n```typescript\nconst conditionalTool = FunctionTool.create({\n  name: 'process_payment',\n  description: 'Process payment transactions',\n  needsApproval: (args) => args.amount > 1000,  // Approve only large amounts\n  parameters: paymentSchema,\n});\n```\n\n资料来源：[packages/agents-core/src/tool.ts:80-85]()\n\n## Tool Serialization\n\nThe SDK supports serializing tools for transmission and storage. The `serializeTool` function handles different tool types:\n\n```typescript\nexport function serializeTool(tool: Tool<any>): SerializedTool {\n  if (tool.type === 'function') {\n    return {\n      type: 'function',\n      name: tool.name,\n      description: tool.description,\n      parameters: tool.parameters as JsonObjectSchema<any>,\n      strict: tool.strict,\n      deferLoading: tool.deferLoading,\n      ...(namespace ? { namespace } : {}),\n    };\n  }\n  // Handle other types...\n}\n```\n\n资料来源：[packages/agents-core/src/utils/serialize.ts:30-60]()\n\n### Computer Tool Serialization\n\nComputer tools have special serialization requirements since they require initialization:\n\n```typescript\nif (tool.type === 'computer') {\n  if (!isComputerInstance(tool.computer)) {\n    throw new UserError(\n      'Computer tool is not initialized for serialization. Call resolveComputer({ tool, runContext }) first.',\n    );\n  }\n  return {\n    type: 'computer',\n    name: tool.name,\n    environment: tool.computer.environment,\n    dimensions: tool.computer.dimensions,\n  };\n}\n```\n\n资料来源：[packages/agents-core/src/utils/serialize.ts:45-65]()\n\n## MCP Tool Integration\n\nThe SDK supports MCP (Model Context Protocol) tools through the `HostedMCPTool` type. MCP tools are hosted tools with special provider data:\n\n```typescript\nexport type HostedMCPTool<Context = UnknownContext> = HostedTool & {\n  providerData: {\n    type: 'mcp';\n    serverName: string;\n    toolName: string;\n    defer_loading?: boolean;\n  };\n};\n```\n\nMCP tools can also be deferred using the `defer_loading` flag in provider data:\n\n```typescript\nfunction isDeferredHostedMcpTool(tool: Tool<any>): tool is HostedMCPTool<any> {\n  return (\n    tool.type === 'hosted_tool' &&\n    tool.providerData?.type === 'mcp' &&\n    tool.providerData.defer_loading === true\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/mcp.ts:1-50]()\n\n## Best Practices\n\n### Tool Naming\n\n- Use clear, descriptive names that indicate the tool's purpose\n- Follow a consistent naming convention (e.g., `verb_noun` or `noun_verb`)\n- Avoid ambiguous abbreviations\n\n### Tool Descriptions\n\n- Write descriptions from the agent's perspective\n- Include examples of when to use the tool\n- Specify input requirements and constraints\n- Mention any limitations or side effects\n\n### Error Handling\n\nTools should handle errors gracefully and return meaningful error messages:\n\n```typescript\nconst robustTool = FunctionTool.create({\n  name: 'fetch_data',\n  description: 'Fetch data from the API',\n  parameters: z.object({ id: z.string() }),\n  execute: async (context, args) => {\n    try {\n      const result = await fetchData(args.id);\n      return JSON.stringify(result);\n    } catch (error) {\n      return JSON.stringify({\n        error: 'fetch_failed',\n        message: error instanceof Error ? error.message : 'Unknown error',\n      });\n    }\n  },\n});\n```\n\n### Tool Granularity\n\n- Prefer single-responsibility tools over monolithic tools\n- Compose complex operations from simpler tools\n- Avoid tools that do too many unrelated things\n\n## Summary\n\nThe OpenAI Agents SDK provides a flexible and extensible tool system that enables agents to interact with external systems and perform actions. Key concepts include:\n\n- **Multiple tool types**: Function tools, hosted tools, computer tools, shell tools, and MCP tools\n- **Rich configuration**: Namespaces, deferred loading, strict validation, and approval requirements\n- **Integration patterns**: Tools can be created directly, agents can be exposed as tools, and external services can be integrated via MCP\n- **Tool execution**: The SDK handles tool invocation, result processing, and agent feedback\n- **Serialization**: Tools can be serialized for transmission and storage\n\nBy following the patterns and practices outlined in this guide, you can effectively extend your agents' capabilities with custom tools tailored to your specific use cases.\n\n---\n\n<a id='guardrails'></a>\n\n## Guardrails and Input/Output Validation\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents), [Tools and Tool Use](#tools)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/guardrail.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/guardrail.ts)\n- [packages/agents-core/src/toolGuardrail.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/toolGuardrail.ts)\n- [packages/agents-core/src/runner/guardrails.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/guardrails.ts)\n- [docs/src/content/docs/guides/guardrails.mdx](https://github.com/openai/openai-agents-js/blob/main/docs/src/content/docs/guides/guardrails.mdx)\n</details>\n\n# Guardrails and Input/Output Validation\n\nGuardrails provide a security and validation layer in the Agents SDK, allowing developers to intercept and validate inputs before agent processing and outputs after generation. This mechanism ensures that agents operate within defined safety boundaries, reject malformed or harmful requests, and maintain controlled behavior throughout their execution lifecycle.\n\n## Architecture Overview\n\nThe guardrail system is organized into three distinct types, each serving a specific validation phase:\n\n| Guardrail Type | Trigger Point | Purpose |\n|----------------|---------------|---------|\n| **Input Guardrails** | Before agent processes user input | Reject or transform incoming requests |\n| **Output Guardrails** | After agent generates response | Validate and filter agent outputs |\n| **Tool Output Guardrails** | After tool execution | Validate tool results before agent sees them |\n\n资料来源：[packages/agents-core/src/guardrail.ts:1-50]()\n\n```mermaid\ngraph TD\n    A[User Input] --> B{Input Guardrails}\n    B -->|Pass| C[Agent Processing]\n    B -->|Fail| D[Reject Request]\n    C --> E[Tool Calls]\n    E --> F{Tool Output Guardrails}\n    F -->|Pass| G[Agent Receives Result]\n    F -->|Fail| H[Block Result]\n    G --> I[Agent Generates Output]\n    I --> J{Output Guardrails}\n    J -->|Pass| K[Final Response]\n    J -->|Fail| L[Block/Modify Output]\n    \n    style B fill:#e1f5fe\n    style F fill:#fff3e0\n    style J fill:#e8f5e9\n```\n\n## Input Guardrails\n\nInput guardrails intercept user requests before they reach the agent's processing logic. They are ideal for implementing rate limiting, content filtering, authentication checks, and request validation.\n\n### Interface Definition\n\n```typescript\nexport interface InputGuardrailFunctionArgs<TContext = UnknownContext> {\n  agent: Agent<any, any>;\n  input: string;\n  context: RunContext<TContext>;\n}\n\nexport type InputGuardrailFunction<TContext = UnknownContext> = (\n  args: InputGuardrailFunctionArgs<TContext>\n) => Promise<GuardrailFunctionOutput>;\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:1-30]()\n\n### Guardrail Function Output\n\nBoth input and output guardrails return a standardized result structure:\n\n```typescript\nexport interface GuardrailFunctionOutput {\n  decision: 'allow' | 'block';\n  message?: string;\n  metadata?: Record<string, unknown>;\n}\n```\n\nWhen `decision` is `'block'`, the run terminates and the optional `message` is returned to the user.\n\n### Input Guardrail Interface\n\n```typescript\nexport interface InputGuardrail<TContext = UnknownContext> {\n  name: string;\n  execute: InputGuardrailFunction<TContext>;\n}\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:35-50]()\n\n### Configuration in Agent\n\nInput guardrails are configured at the agent level:\n\n```typescript\nconst agent = Agent.make({\n  name: 'my-agent',\n  instructions: 'You are a helpful assistant.',\n  inputGuardrails: [\n    {\n      name: 'content-filter',\n      execute: async ({ input }) => {\n        if (containsProfanity(input)) {\n          return { decision: 'block', message: 'Inappropriate content detected' };\n        }\n        return { decision: 'allow' };\n      }\n    }\n  ]\n});\n```\n\n## Output Guardrails\n\nOutput guardrails validate the agent's generated response before it is returned to the user. They enable content safety checks, PII detection, quality filtering, and output format enforcement.\n\n### Interface Definition\n\n```typescript\nexport interface OutputGuardrailFunctionArgs<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> {\n  agent: Agent<any, TOutput>;\n  agentOutput: string;\n  context: RunContext<TContext>;\n  details: {\n    modelResponse: ModelResponse | undefined;\n    output: TurnInput;\n  };\n}\n\nexport type OutputGuardrailFunction<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> = (args: OutputGuardrailFunctionArgs<TContext, TOutput>) => Promise<GuardrailFunctionOutput>;\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:50-80]()\n\n### Output Guardrail Interface\n\n```typescript\nexport interface OutputGuardrail<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> {\n  name: string;\n  execute: OutputGuardrailFunction<TOutput, TContext>;\n}\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:80-100]()\n\n### Output Guardrail Definition\n\nThe SDK provides a builder function to create output guardrail definitions:\n\n```typescript\nexport interface DefineOutputGuardrailArgs<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> {\n  name: string;\n  execute: OutputGuardrailFunction<TOutput, TContext>;\n}\n\nexport function defineOutputGuardrail<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n>({ name, execute }: DefineOutputGuardrailArgs<TOutput, TContext>): OutputGuardrailDefinition<TOutput, TContext>\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:100-130]()\n\n## Tool Output Guardrails\n\nTool output guardrails validate the results returned by tool executions before the agent processes them. This is particularly useful for sanitizing tool responses, preventing sensitive data leakage, and enforcing output constraints.\n\n### Interface Definition\n\n```typescript\nexport interface ToolOutputGuardrailFunctionArgs<TContext = UnknownContext> {\n  toolCallId: string;\n  toolName: string;\n  toolOutput: string;\n  context: RunContext<TContext>;\n}\n\nexport type ToolOutputGuardrailFunction<TContext = UnknownContext> = (\n  args: ToolOutputGuardrailFunctionArgs<TContext>\n) => Promise<GuardrailFunctionOutput>;\n```\n\n资料来源：[packages/agents-core/src/toolGuardrail.ts:1-30]()\n\n### Definition Creation\n\nTool output guardrails can be created with or without explicit typing:\n\n```typescript\nexport function defineToolOutputGuardrail<TContext = UnknownContext>(\n  config: { name: string; run: ToolOutputGuardrailFunction<TContext> }\n): ToolOutputGuardrailDefinition<TContext>\n```\n\nWhen guardrails are passed to the runner, they are normalized to the definition format:\n\n```typescript\nexport function toToolOutputGuardrailDefinitions<TContext>(\n  guardrails?: ToolOutputGuardrailInit<TContext>[],\n): ToolOutputGuardrailDefinition<TContext>[] {\n  if (!guardrails) {\n    return [];\n  }\n  return guardrails.map((gr) =>\n    'type' in gr && gr.type === 'tool_output'\n      ? (gr as ToolOutputGuardrailDefinition<TContext>)\n      : defineToolOutputGuardrail(gr as { name: string; run: any }),\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/toolGuardrail.ts:30-60]()\n\n## Guardrail Execution in the Runner\n\nThe runner orchestrates guardrail execution at appropriate points in the agent lifecycle.\n\n### Input Guardrail Execution\n\n```typescript\nexport async function runInputGuardrails<TContext>(\n  state: RunState<TContext, Agent<any, any>>,\n  input: string,\n  inputGuardrailDefs: InputGuardrailDefinition[],\n) {\n  if (inputGuardrailDefs.length === 0) {\n    return;\n  }\n\n  for (const guardrail of inputGuardrailDefs) {\n    const result = await guardrail.run({\n      agent: state._currentAgent,\n      input,\n      context: state._context,\n    });\n\n    if (result.tripwireTriggered) {\n      throw new InputGuardrailTripwireTriggered(guardrail.name);\n    }\n  }\n}\n```\n\n资料来源：[packages/agents-core/src/runner/guardrails.ts:1-40]()\n\nOn failure, the current turn is rolled back to enable reruns:\n\n```typescript\nonError: (error) => {\n  state._currentTurn--;\n  throw new GuardrailExecutionError(\n    `Input guardrail failed to complete: ${error}`,\n    error as Error,\n    state,\n  );\n}\n```\n\n### Output Guardrail Execution\n\n```typescript\nexport async function runOutputGuardrails<\n  TContext,\n  TOutput extends AgentOutputType,\n  TAgent extends Agent<TContext, TOutput>,\n>(\n  state: RunState<TContext, TAgent>,\n  runnerOutputGuardrails: OutputGuardrailDefinition<...>[],\n  output: string,\n) {\n  const runnerGuardrails = runnerOutputGuardrails as OutputGuardrailDefinition<...>[];\n  const guardrails = runnerGuardrails.concat(\n    state._currentAgent.outputGuardrails.map(defineOutputGuardrail),\n  );\n  \n  if (guardrails.length === 0) {\n    return;\n  }\n  \n  const agentOutput = state._currentAgent.processFinalOutput(output);\n  const runOutput = getTurnInput([], state._generatedItems, ...);\n  \n  const guardrailArgs: OutputGuardrailFunctionArgs<TContext, TOutput> = {\n    agent: state._currentAgent,\n    agentOutput,\n    context: state._context,\n    details: { modelResponse: state._lastTurnResponse, output: runOutput },\n  };\n}\n```\n\n资料来源：[packages/agents-core/src/runner/guardrails.ts:50-100]()\n\n## Guardrail Types Comparison\n\n| Property | Input Guardrail | Output Guardrail | Tool Output Guardrail |\n|----------|-----------------|------------------|----------------------|\n| **Trigger** | Before agent processes input | After agent generates output | After tool execution |\n| **Input Access** | Raw user input | Processed agent output | Tool result string |\n| **Common Use Cases** | Content filtering, auth | Safety checks, PII removal | Data sanitization |\n| **Failure Action** | Block request | Block/modify output | Block tool result |\n| **Interface** | `InputGuardrailFunction` | `OutputGuardrailFunction` | `ToolOutputGuardrailFunction` |\n\n## Common Patterns\n\n### Content Safety Pattern\n\n```typescript\nconst contentSafetyGuardrail: OutputGuardrail = {\n  name: 'content-safety',\n  execute: async ({ agentOutput }) => {\n    const isSafe = await checkContentSafety(agentOutput);\n    if (!isSafe) {\n      return { \n        decision: 'block', \n        message: 'Output failed safety review' \n      };\n    }\n    return { decision: 'allow' };\n  }\n};\n```\n\n### Input Transformation Pattern\n\n```typescript\nconst sanitizationGuardrail: InputGuardrail = {\n  name: 'input-sanitizer',\n  execute: async ({ input }) => {\n    const sanitized = removeSensitiveData(input);\n    return { decision: 'allow' };\n  }\n};\n```\n\n### Tool Output Filtering Pattern\n\n```typescript\nconst toolOutputGuardrail = defineToolOutputGuardrail({\n  name: 'filter-database-results',\n  run: async ({ toolOutput }) => {\n    const filtered = filterPersonalInformation(toolOutput);\n    return { decision: 'allow' };\n  }\n});\n```\n\n## Integration with Agent Configuration\n\nGuardrails can be configured at multiple levels:\n\n| Level | Configuration Location | Scope |\n|-------|----------------------|-------|\n| **Agent** | `inputGuardrails`, `outputGuardrails` | Applies to all runs of this agent |\n| **Runner** | `outputGuardrails` parameter | Applies to all agents in the run |\n\n```typescript\nconst agent = Agent.make({\n  name: 'secure-agent',\n  instructions: '...',\n  inputGuardrails: [/* agent-level input guards */],\n  outputGuardrails: [/* agent-level output guards */],\n});\n\n// Runner-level guards apply to all agents\nconst result = await runAgent(agent, input, {\n  outputGuardrails: [/* runner-level output guards */]\n});\n```\n\n## Error Handling\n\nGuardrail failures generate specific error types:\n\n| Error Type | Cause | Recovery |\n|------------|-------|----------|\n| `InputGuardrailTripwireTriggered` | Input guardrail returned `block` | Request rejected |\n| `GuardrailExecutionError` | Guardrail threw exception | Rollback and retry possible |\n\nThe runner implements error handling that preserves state for potential reruns:\n\n```typescript\ntryOrThrow({\n  fn: async () => runInputGuardrails(...),\n  errorName: 'input guardrail',\n  onError: (error) => {\n    state._currentTurn--;  // Rollback for rerun\n    throw new GuardrailExecutionError(...);\n  }\n});\n```\n\n## Best Practices\n\n1. **Fail-safe defaults**: Return `decision: 'allow'` when guardrail cannot complete\n2. **Provide feedback**: Include meaningful `message` on block decisions\n3. **Order matters**: Place most restrictive guardrails first for early rejection\n4. **Avoid side effects**: Guardrails should be idempotent and not modify state\n5. **Performance**: Keep guardrail execution lightweight to avoid timeouts\n6. **Testing**: Test both allow and block paths for each guardrail\n\n## Source Files Summary\n\n| File | Role |\n|------|------|\n| `packages/agents-core/src/guardrail.ts` | Core interfaces and type definitions |\n| `packages/agents-core/src/toolGuardrail.ts` | Tool output guardrail utilities |\n| `packages/agents-core/src/runner/guardrails.ts` | Runner integration and execution logic |\n\n---\n\n<a id='handoffs'></a>\n\n## Handoffs and Multi-Agent Systems\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents), [Tools and Tool Use](#tools)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/runner/modelOutputs.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/modelOutputs.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n- [packages/agents-core/src/result.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/result.ts)\n- [packages/agents-core/src/runState.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runState.ts)\n- [packages/agents-realtime/src/realtimeSessionEvents.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeSessionEvents.ts)\n</details>\n\n# Handoffs and Multi-Agent Systems\n\n## Overview\n\nHandoffs enable one AI agent to transfer control to another agent within a conversation. This mechanism is fundamental to building multi-agent systems where different specialized agents collaborate to handle complex tasks. Unlike tools, which are called and return results to the calling agent, handoffs completely transfer conversational control to the new agent, which then continues the interaction with the user. 资料来源：[packages/agents-core/src/handoff.ts:1-50]()\n\n### Key Characteristics of Handoffs\n\n| Characteristic | Description |\n|----------------|-------------|\n| **Conversation Transfer** | The new agent receives the full conversation history and takes over the dialogue |\n| **Control Transfer** | The original agent stops execution; the new agent continues from where the previous left off |\n| **Bidirectional** | Agents can hand off to each other in any direction, enabling complex workflows |\n| **Typed Outputs** | Handoffs can carry structured output types from different agents |\n| **Feature Gating** | Handoffs can be conditionally enabled or disabled based on runtime context |\n\n资料来源：[packages/agents-core/src/agent.ts:1-30]()\n\n## Architecture\n\n### Handoff Flow\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Primary Agent]\n    B -->|Determines handoff needed| C[Handoff Tool Call]\n    C --> D{Handoff Enabled?}\n    D -->|Yes| E[Transfer to Target Agent]\n    D -->|No| F[Continue with Primary Agent]\n    E --> G[Target Agent Receives Full History]\n    G --> H[Target Agent Processes Request]\n    H --> I[Response to User]\n    I --> J[Optionally Handoff Back]\n    J -->|Yes| B\n```\n\n资料来源：[packages/agents-core/src/runner/modelOutputs.ts:1-50]()\n\n### Multi-Agent System Components\n\n| Component | Role | Location |\n|-----------|------|----------|\n| `Agent` | Base agent class with handoff capabilities | `packages/agents-core/src/agent.ts` |\n| `Handoff` | Wrapper class for agent-to-agent transfers | `packages/agents-core/src/handoff.ts` |\n| `HandoffConfig` | Configuration for handoff behavior | `packages/agents-core/src/handoff.ts` |\n| `RunResultData` | Results containing handoff information | `packages/agents-core/src/result.ts` |\n\n## Core Classes and Types\n\n### The Handoff Class\n\nThe `Handoff` class wraps an agent and provides the mechanism for transferring control:\n\n```typescript\nexport class Handoff<\n  TContext = UnknownContext,\n  TOutput extends AgentOutputType = TextOutput,\n> {\n  public agentName: string;\n  public toolName: string;\n  public toolDescription: string;\n  public inputParameters: JsonSchema;\n  public isEnabled: HandoffEnabledFunction<TContext> = async () => true;\n\n  constructor(\n    agent: Agent<TContext, TOutput>,\n    onInvokeHandoff: (context: RunContext<TContext>, args: string) => \n      Promise<Agent<TContext, TOutput>> | Agent<TContext, TOutput>,\n  ) { ... }\n}\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:50-80]()\n\n### Handoff Configuration\n\n```typescript\nexport type HandoffConfig<\n  TInputType extends ToolInputParameters,\n  TContext = UnknownContext,\n> = {\n  toolNameOverride?: string;\n  toolDescriptionOverride?: string;\n  onHandoff?: OnHandoffCallback<TInputType>;\n  inputType?: TInputType;\n  inputFilter?: HandoffInputFilterFunction<TContext>;\n};\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:100-130]()\n\n### Handoff Configuration Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `toolNameOverride` | `string` | Custom name for the handoff tool |\n| `toolDescriptionOverride` | `string` | Custom description shown to the model |\n| `onHandoff` | `OnHandoffCallback<TInputType>` | Callback function executed when handoff occurs |\n| `inputType` | `ToolInputParameters` | Zod schema for validating handoff input |\n| `inputFilter` | `HandoffInputFilterFunction` | Function to filter/modify conversation history |\n\n## Handoff Types and Output Union\n\n### Automatic Output Type Inference\n\nThe system automatically infers the union of output types from all handoff agents:\n\n```typescript\ntype ExtractAgentOutput<T> = T extends Agent<any, infer O> ? O : never;\ntype ExtractHandoffOutput<T> = T extends Handoff<any, infer O> ? O : never;\n\nexport type HandoffsOutputUnion<\n  Handoffs extends readonly (Agent<any, any> | Handoff<any, any>)[],\n> =\n  | ExtractAgentOutput<Handoffs[number]>\n  | ExtractHandoffOutput<Handoffs[number]>;\n```\n\n资料来源：[packages/agents-core/src/agent.ts:180-200]()\n\n### Creating Agents with Handoffs\n\n```typescript\nexport type AgentConfigWithHandoffs<\n  TOutput extends AgentOutputType,\n  Handoffs extends readonly (Agent<any, any> | Handoff<any, any>)[],\n> = {\n  name: string;\n  handoffs?: Handoffs;\n  outputType?: TOutput;\n} & Partial<Omit<AgentConfiguration<UnknownContext, TOutput | HandoffsOutputUnion<Handoffs>>, 'name' | 'handoffs' | 'outputType'>>;\n```\n\n资料来源：[packages/agents-core/src/agent.ts:15-30]()\n\n## Lifecycle Events\n\n### Agent Lifecycle Hooks\n\nHandoffs trigger specific lifecycle events that can be subscribed to:\n\n```typescript\nagent_handoff: [\n  context: RunContext<TContext>,\n  nextAgent: Agent<any, any>\n];\n```\n\n资料来源：[packages/agents-core/src/lifecycle.ts:1-30]()\n\n### Real-time Session Events\n\nFor real-time agents, additional handoff events are available:\n\n```typescript\nagent_handoff: [\n  context: RunContext<RealtimeContextData<TContext>>,\n  fromAgent: AgentWithOrWithoutHistory<TContext>,\n  toAgent: AgentWithOrWithoutHistory<TContext>,\n];\n```\n\n资料来源：[packages/agents-realtime/src/realtimeSessionEvents.ts:1-50]()\n\n### Available Lifecycle Events\n\n| Event | Parameters | Trigger |\n|-------|------------|---------|\n| `agent_start` | `context`, `agent`, `turnInput` | Agent begins processing |\n| `agent_end` | `context`, `agent`, `output` | Agent completes processing |\n| `agent_handoff` | `context`, `fromAgent`, `toAgent` | Control transfers to another agent |\n| `agent_tool_start` | `context`, `agent`, `tool`, `details` | Tool execution begins |\n| `agent_tool_end` | `context`, `agent`, `tool`, `result`, `details` | Tool execution completes |\n\n## Handoff Resolution\n\n### Tool Call Resolution\n\nWhen the model requests a handoff, the system resolves the tool call:\n\n```typescript\nfunction resolveHandoffOrTool(\n  toolCall: HandoffCallItem | FunctionCallItem,\n  handoffMap: Map<string, Handoff<any, any>>,\n  functionMap: Map<string, FunctionTool<any>>,\n  agent: Agent<any, any>,\n): | { type: 'handoff'; handoff: Handoff<any, any> }\n  | { type: 'function'; tool: FunctionTool<any> }\n```\n\n资料来源：[packages/agents-core/src/runner/modelOutputs.ts:1-50]()\n\n### Resolution Process\n\n1. The tool call name is resolved to handle namespaced tools\n2. Both function tools and handoffs are checked for matches\n3. Ambiguity is detected when a name matches both a function tool and a handoff\n4. The resolved tool or handoff is returned with its type\n\n### Error Handling\n\n| Error | Cause | Resolution |\n|-------|-------|------------|\n| `Tool not found` | Handoff name not registered | Register handoff in agent configuration |\n| `Ambiguous dotted tool call` | Name matches both function tool and handoff | Rename one or use explicit namespace |\n| `Handoff not enabled` | `isEnabled` returns false | Check feature flags or context conditions |\n\n## Using Agents as Tools\n\nAgents can be invoked as tools using the `asTool()` method:\n\n```typescript\nasTool<TAgent extends Agent<TContext, TOutput> = Agent<TContext, TOutput>>(\n  this: TAgent,\n  options: AgentToolOptions<TContext, TAgent, TParameters>,\n): AgentTool<TContext, TAgent, TParameters>\n```\n\n资料来源：[packages/agents-core/src/agent.ts:200-250]()\n\n### Agent as Tool Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `toolName` | `string` | Name of the tool (defaults to agent name) |\n| `toolDescription` | `string` | Description for model guidance |\n| `customOutputExtractor` | `function` | Extract output from agent result |\n| `needsApproval` | `boolean \\| ToolApprovalFunction` | Require human approval |\n| `parameters` | `TParameters` | JSON schema for tool input |\n| `inputBuilder` | `AgentToolInputBuilder` | Transform structured input to agent input |\n\n### Key Differences: Handoffs vs Agent-as-Tool\n\n| Aspect | Handoffs | Agent-as-Tool |\n|--------|----------|---------------|\n| **Conversation History** | Full history transferred | New agent receives generated input |\n| **Control Flow** | Original agent stops, new agent takes over | Original agent continues after tool returns |\n| **Use Case** | Complete task delegation | Subtask execution with return |\n\n资料来源：[packages/agents-core/src/agent.ts:150-180]()\n\n## Handoff Results\n\n### RunResultData Structure\n\nWhen a run includes handoffs, the result contains handoff information:\n\n```typescript\nexport interface RunResultData<\n  TAgent extends Agent<any, any>,\n  THandoffs extends (Agent<any, any> | Handoff<any>)[] = any[],\n> {\n  input: string | AgentInputItem[];\n  newItems: RunItem[];\n  rawResponses: ModelResponse[];\n  lastResponseId: string | undefined;\n  lastAgent: TAgent | undefined;\n  inputGuardrailResults: InputGuardrailResult[];\n  outputGuardrailResults: OutputGuardrailResult[];\n  // ... additional properties\n}\n```\n\n资料来源：[packages/agents-core/src/result.ts:1-50]()\n\n### Tracking Handoffs in State\n\n```typescript\nhandoffs: new Map(\n  currentAgent.handoffs.map((entry) => {\n    if (entry instanceof Agent) {\n      return [entry.name, handoff(entry)];\n    }\n    return [entry.toolName, entry];\n  }),\n);\n```\n\n资料来源：[packages/agents-core/src/runState.ts:1-50]()\n\n## Multi-Agent Patterns\n\n### Triage Pattern\n\nA primary agent analyzes user input and delegates to specialized agents:\n\n```mermaid\ngraph LR\n    A[User Request] --> B[Triage Agent]\n    B -->|Spanish Request| C[Spanish Agent]\n    B -->|Technical Issue| D[Support Agent]\n    B -->|Billing Question| E[Billing Agent]\n    C --> F[Response]\n    D --> F\n    E --> F\n```\n\n### Sequential Delegation\n\nAgents hand off in a chain for complex workflows:\n\n```mermaid\ngraph TD\n    A[Input] --> B[Data Collection Agent]\n    B --> C[Analysis Agent]\n    C --> D[Report Generation Agent]\n    D --> E[Review Agent]\n    E -->|Approved| F[Final Output]\n    E -->|Needs Revision| C\n```\n\n### Parallel Handoff with Selection\n\nMultiple agents work on the same problem, with selection based on quality:\n\n```mermaid\ngraph TD\n    A[Query] --> B[Agent 1]\n    A --> C[Agent 2]\n    A --> D[Agent 3]\n    B --> E[Evaluator]\n    C --> E\n    D --> E\n    E --> F[Best Response]\n```\n\n## Best Practices\n\n### Designing Agent Responsibilities\n\n| Guideline | Description |\n|-----------|-------------|\n| **Single Responsibility** | Each agent should have a clear, focused purpose |\n| **Clear Descriptions** | Use `handoffDescription` to help the triage agent decide |\n| **Typed Outputs** | Define output types for type-safe result handling |\n| **Feature Gates** | Use `isEnabled` for conditional handoff availability |\n\n### Error Handling\n\n- Always wrap handoff execution in try-catch blocks\n- Implement fallback handoffs for critical paths\n- Log handoff failures for debugging\n\n### Performance Considerations\n\n- Minimize the number of handoffs in a single conversation\n- Use `inputFilter` to reduce conversation history transfer size\n- Cache agent instances when possible\n\n## Real-time Agent Handoffs\n\nThe real-time agent system extends handoffs for voice applications:\n\n```typescript\nexport type RealtimeAgentConfiguration<TContext = UnknownContext> = Partial<\n  Omit<\n    AgentConfiguration<RealtimeContextData<TContext>, TextOutput>,\n    | 'model'\n    | 'handoffs'\n    | 'modelSettings'\n    | 'outputType'\n    | 'toolUseBehavior'\n    | 'resetToolChoice'\n    | 'outputGuardrails'\n    | 'inputGuardrails'\n  >\n> & {\n  name: string;\n  handoffs?: (RealtimeAgent<TContext> | Handoff<RealtimeContextData<TContext>, TextOutput>)[];\n  voice?: string;\n};\n```\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts:1-40]()\n\n### Voice Handoff Constraints\n\nWhen using handoffs in real-time sessions:\n- If another agent spoke during the session, changing the voice during a handoff will fail\n- All RealtimeAgents within a session share the same model\n- `modelSettings` is not supported for RealtimeAgents\n\n---\n\n<a id='sandbox-architecture'></a>\n\n## Sandbox Agents Architecture\n\n### 相关页面\n\n相关主题：[Sandbox Providers and Extensions](#sandbox-providers), [Creating and Running Agents](#agents)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/sandbox/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/agent.ts)\n- [packages/agents-core/src/sandbox/client.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/client.ts)\n- [packages/agents-core/src/sandbox/capabilities/index.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/capabilities/index.ts)\n- [packages/agents-core/src/sandbox/runtime/manager.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/runtime/manager.ts)\n- [packages/agents-core/src/sandbox/manifest.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/manifest.ts)\n- [docs/src/content/docs/guides/sandbox-agents.mdx](https://github.com/openai/openai-agents-js/blob/main/docs/src/content/docs/guides/sandbox-agents.mdx)\n</details>\n\n# Sandbox Agents Architecture\n\n## Overview\n\nThe Sandbox Agents Architecture provides a secure, isolated execution environment for AI agents to safely run code, execute shell commands, and interact with file systems. It extends the core `Agent` class with sandboxed capabilities that isolate agent operations from the host system while maintaining a controlled bridge for communication and data exchange.\n\nSandbox agents are designed to:\n\n- **Isolate Execution**: Run untrusted or potentially harmful code in a contained environment\n- **Secure File Operations**: Provide controlled access to file systems with manifest-based permission management\n- **Runtime Isolation**: Enforce capability-based security policies that limit what operations an agent can perform\n- **Preserve Sessions**: Maintain state across agent interactions while respecting security boundaries\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:1-50]()\n\n## Core Components\n\n### SandboxAgent Class\n\nThe `SandboxAgent` extends the core `Agent` class and adds sandbox-specific configuration and lifecycle management.\n\n```mermaid\nclassDiagram\n    class Agent {\n        +name: string\n        +instructions: string\n        +tools: Tool[]\n        +run(context, input)*\n    }\n    class SandboxAgent {\n        +defaultManifest?: Manifest\n        +baseInstructions?: SandboxBaseInstructions\n        +capabilities: Capability[]\n        +runAs?: string | SandboxUser\n        +runtimeManifest: Manifest\n        +clone(config): SandboxAgent\n    }\n    Agent <|-- SandboxAgent\n```\n\n**Configuration Options**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | Agent identifier |\n| `instructions` | `string \\| function` | System prompt or dynamic instruction generator |\n| `baseInstructions` | `SandboxBaseInstructions` | Base instructions appended to agent prompts |\n| `capabilities` | `Capability[]` | Runtime capabilities (file system, network, etc.) |\n| `runAs` | `string \\| SandboxUser` | User identity for sandbox execution |\n| `defaultManifest` | `Manifest` | Default file system permissions |\n| `tools` | `Tool[]` | Additional tools available to the agent |\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:35-80]()\n\n**Type Safety**\n\nThe `baseInstructions` property enforces strict type checking:\n\n```typescript\nif (\n  config.baseInstructions !== undefined &&\n  typeof config.baseInstructions !== 'string' &&\n  typeof config.baseInstructions !== 'function'\n) {\n  throw new TypeError(\n    'SandboxAgent baseInstructions must be a string or function.',\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:55-62]()\n\n### Manifest System\n\nThe `Manifest` class defines the file system permissions and access controls for a sandbox environment. Each manifest specifies which paths an agent can read, write, or execute within.\n\n**Key Manifest Operations**\n\n| Operation | Purpose |\n|-----------|---------|\n| `clone()` | Creates a deep copy of the manifest |\n| `addPermission()` | Adds a new path permission |\n| `removePermission()` | Removes an existing permission |\n| `checkAccess()` | Verifies if a path is permitted |\n\nThe manifest supports multiple manifest root levels, allowing fine-grained control over path translation and access boundaries.\n\n资料来源：[packages/agents-core/src/sandbox/manifest.ts:1-100]()\n\n### Capabilities\n\nCapabilities define what operations a sandbox agent can perform at runtime. The capability system follows a deny-by-default model.\n\n```mermaid\ngraph TD\n    A[SandboxAgent] --> B[Capability Manager]\n    B --> C[FileSystem Capability]\n    B --> D[Network Capability]\n    B --> E[Process Capability]\n    B --> F[Environment Capability]\n    \n    C --> G{Read}\n    C --> H{Write}\n    C --> I{Execute}\n    \n    D --> J[HTTP Allowed]\n    D --> K[WebSocket Allowed]\n```\n\n**Available Capability Types**\n\n| Capability | Description |\n|------------|-------------|\n| `FileSystemRead` | Read files from specified paths |\n| `FileSystemWrite` | Write or modify files |\n| `FileSystemExecute` | Execute binary files |\n| `NetworkHttp` | Make HTTP/HTTPS requests |\n| `NetworkWebSocket` | Establish WebSocket connections |\n| `ProcessSpawn` | Spawn child processes |\n\n资料来源：[packages/agents-core/src/sandbox/capabilities/index.ts:1-50]()\n\n## Sandbox Client\n\nThe `SandboxClient` manages the connection to the underlying sandbox runtime. It handles session lifecycle, authentication, and command routing.\n\n```mermaid\nsequenceDiagram\n    participant Host as Host Application\n    participant Client as SandboxClient\n    participant Runtime as Sandbox Runtime\n    participant Sandbox as Sandbox Environment\n    \n    Host->>Client: createSandbox(config)\n    Client->>Runtime: Initialize Session\n    Runtime->>Sandbox: Create Isolated Environment\n    Sandbox-->>Runtime: Session ID\n    Runtime-->>Client: Connected\n    Client-->>Host: SandboxHandle\n    \n    Host->>Client: executeCommand(cmd)\n    Client->>Sandbox: Run Command\n    Sandbox-->>Client: Output\n    Client-->>Host: Result\n```\n\n**Client Configuration**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `backendId` | `string` | Yes | Sandbox backend identifier |\n| `capabilities` | `Capability[]` | No | Override agent capabilities |\n| `manifest` | `Manifest` | No | File system permissions |\n| `environment` | `Record<string, string>` | No | Environment variables |\n\n资料来源：[packages/agents-core/src/sandbox/client.ts:1-100]()\n\n## Runtime Manager\n\nThe `RuntimeManager` orchestrates sandbox sessions, handles session preservation, and manages resource allocation across multiple concurrent sandbox environments.\n\n```mermaid\ngraph TB\n    subgraph RuntimeManager\n        A[Session Pool] --> B[Active Sessions]\n        A --> C[Preserved Sessions]\n        B --> D[Live Sessions]\n        C --> E[Serialized Sessions]\n    end\n    \n    F[Agent Request] --> G[Load Balancer]\n    G --> H{Route}\n    H -->|New| I[Create Session]\n    H -->|Preserved| J[Restore Session]\n    I --> D\n    J --> D\n```\n\n**Session Management Features**\n\n- **Live Sessions**: Active sandbox instances ready for immediate use\n- **Preserved Sessions**: Sessions that maintain state across turns\n- **Session Reuse**: Reuse live sessions within the same run state when appropriate\n- **Garbage Collection**: Clean up orphaned sessions when run state is destroyed\n\n资料来源：[packages/agents-core/src/sandbox/runtime/manager.ts:1-100]()\n\n## Path Translation\n\nSandbox environments use path translation to maintain security boundaries between the host file system and the sandbox workspace.\n\n```mermaid\ngraph LR\n    subgraph Host\n        A[/workspace/project]\n    end\n    \n    subgraph Sandbox\n        B[/]\n        C[/workspace/project]\n    end\n    \n    A -.->|Manifest Root| C\n    B -.->|Workspace Root| C\n```\n\n**Translation Functions**\n\n| Function | Purpose |\n|----------|---------|\n| `translateRootManifestCommandInput()` | Translates absolute paths in commands to workspace-relative paths |\n| `translateManifestRootCommandOutput()` | Translates output paths back to host paths |\n| `translateWorkspaceRootCommandOutput()` | Handles path prefix replacement in command output |\n\nThe translation system uses regex patterns to safely replace paths while preserving command structure:\n\n```typescript\nfunction translateRootManifestCommandInput(\n  command: string,\n  workspaceRootPath: string,\n): string {\n  return command.replace(\n    /(^|[\\s\"'=<>])\\/([^\\s\"'|&;<>(){}]*)/g,\n    (_match, prefix: string, pathSuffix: string) =>\n      `${prefix}${workspaceRootPath}/${pathSuffix}`,\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:20-35]()\n\n## Lifecycle\n\n### Session Initialization\n\n1. Agent receives task with sandbox configuration\n2. RuntimeManager checks for preserved sessions\n3. If no preserved session, create new sandbox instance\n4. Apply manifest and capabilities to sandbox\n5. Initialize runtime manifest with workspace bindings\n\n### Command Execution Flow\n\n```mermaid\ngraph TD\n    A[Agent Tool Call] --> B[SandboxClient]\n    B --> C{Path Translation}\n    C --> D[Translate Input Paths]\n    D --> E[Execute in Sandbox]\n    E --> F[Capture Output]\n    F --> G[Translate Output Paths]\n    G --> H[Return to Agent]\n```\n\n### Session Preservation\n\nSessions can be preserved across agent turns when:\n\n- `reuseLiveSession` is not explicitly set to `false`\n- The session's `backendId` matches the active client\n- The run state is still active\n\n```typescript\nexport function livePreservedOwnedSession<TContext>(args: {\n  runState: RunState<TContext, Agent<TContext, AgentOutputType>> | undefined;\n  client: SandboxClient;\n  agentKey: string;\n  serializedEntry: SerializedSandboxSessionEntry | undefined;\n}): LivePreservedOwnedSessionEntry | undefined {\n  if (!args.serializedEntry?.preservedOwnedSession || !args.runState) {\n    return undefined;\n  }\n  // ... validation and return\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/runtime/livePreservedSessions.ts:50-75]()\n\n## Security Model\n\n### Defense Layers\n\n```mermaid\ngraph TD\n    A[Host System] --> B[Manifest Permissions]\n    B --> C[Capability Checks]\n    C --> D[Path Translation]\n    D --> E[Sandbox Isolation]\n    E --> F[User Permission]\n    \n    F --> G{Allowed?}\n    G -->|No| H[Access Denied]\n    G -->|Yes| I[Execute]\n```\n\n### Permission Hierarchy\n\n| Layer | Check | Failure Action |\n|-------|-------|----------------|\n| Manifest | Path in allowed list | Reject before execution |\n| Capability | Operation permitted | Reject tool invocation |\n| Path Translation | Valid path transformation | Sanitize or reject |\n| User Permission | `runAs` identity | Fall back to default user |\n\n## Configuration Example\n\n```typescript\nimport { SandboxAgent, Manifest, Capability } from '@openai/agents-core';\n\nconst manifest = new Manifest({\n  roots: ['/workspace'],\n  permissions: [\n    { path: '/workspace/**', access: 'rw' },\n    { path: '/tmp/**', access: 'rw' },\n  ],\n});\n\nconst agent = new SandboxAgent({\n  name: 'code-executor',\n  instructions: 'You can execute code and manage files in /workspace',\n  capabilities: [\n    Capability.fileSystem(),\n    Capability.network({ http: true, webSocket: false }),\n    Capability.process(),\n  ],\n  manifest,\n  baseInstructions: 'Always verify paths are within allowed directories.',\n});\n```\n\n资料来源：[docs/src/content/docs/guides/sandbox-agents.mdx:1-100]()\n\n## Error Handling\n\nSandbox operations can fail for several reasons:\n\n| Error Type | Cause | Recovery |\n|------------|-------|----------|\n| `ManifestNotFoundError` | Manifest file missing | Provide default manifest |\n| `CapabilityDeniedError` | Operation not permitted | Add required capability |\n| `PathViolationError` | Access outside manifest | Translate or reject path |\n| `SessionExpiredError` | Preserved session invalid | Create new session |\n| `RuntimeConnectionError` | Cannot reach sandbox | Retry with backoff |\n\nError handlers should check `RunErrorKind` and provide appropriate fallbacks or user-facing error messages.\n\n资料来源：[packages/agents-core/src/runner/errorHandlers.ts:1-50]()\n\n## Best Practices\n\n### Session Management\n\n- **Preserve selectively**: Only preserve sessions when state needs to persist\n- **Clean up on completion**: Ensure sessions are released when no longer needed\n- **Monitor resource usage**: Track session creation to prevent leaks\n\n### Path Handling\n\n- **Always validate**: Check paths against manifest before operations\n- **Use translation utilities**: Never manually construct sandbox paths\n- **Log path operations**: Track path translations for debugging\n\n### Capability Assignment\n\n- **Principle of least privilege**: Grant only required capabilities\n- **Separate by trust level**: Use different agents with different capabilities\n- **Audit capability usage**: Log when sensitive capabilities are invoked\n\n---\n\n<a id='sandbox-providers'></a>\n\n## Sandbox Providers and Extensions\n\n### 相关页面\n\n相关主题：[Sandbox Agents Architecture](#sandbox-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-extensions/src/sandbox/cloudflare/sandbox.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/src/sandbox/cloudflare/sandbox.ts)\n- [packages/agents-extensions/src/sandbox/e2b/sandbox.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/src/sandbox/e2b/sandbox.ts)\n- [packages/agents-extensions/src/sandbox/daytona/sandbox.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/src/sandbox/daytona/sandbox.ts)\n- [packages/agents-core/src/sandbox/sandboxes/docker.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/sandboxes/docker.ts)\n- [packages/agents-core/src/sandbox/sandboxes/unixLocal.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/sandboxes/unixLocal.ts)\n</details>\n\n# Sandbox Providers and Extensions\n\nThe OpenAI Agents SDK provides a flexible sandbox architecture that enables AI agents to execute code and commands in isolated, secure environments. Sandboxes are essential for safely running untrusted or potentially harmful code generated by AI agents, ensuring system security while maintaining developer productivity.\n\n## Overview\n\nThe sandbox system consists of two primary layers:\n\n1. **Core Sandbox Infrastructure** (`agents-core`): Built-in sandbox implementations including Docker and Unix local execution\n2. **Extension Providers** (`agents-extensions`): Third-party sandbox provider integrations including Cloudflare, E2B, and Daytona\n\nSandboxes abstract away the complexity of secure code execution, providing agents with a virtual workspace where file operations, command execution, and environment management occur in isolation from the host system.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Agent] --> B[SandboxAgent]\n    B --> C[Sandbox Provider Interface]\n    C --> D[Core Providers]\n    C --> E[Extension Providers]\n    D --> D1[Docker Sandbox]\n    D --> D2[UnixLocal Sandbox]\n    E --> E1[Cloudflare Sandbox]\n    E --> E2[E2B Sandbox]\n    E --> E3[Daytona Sandbox]\n    F[Manifest] --> B\n    G[Capabilities] --> B\n    H[RunAs User] --> B\n```\n\n## Core Components\n\n### SandboxAgent Class\n\nThe `SandboxAgent` class extends the base `Agent` class and provides sandbox-specific configuration:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `defaultManifest` | `Manifest` | Default manifest for workspace structure |\n| `baseInstructions` | `SandboxBaseInstructions` | Base instructions for sandbox initialization |\n| `capabilities` | `Capability[]` | List of capabilities enabled for this sandbox |\n| `runAs` | `string \\| SandboxUser` | User or role to run sandbox commands as |\n| `runtimeManifest` | `Manifest` | Runtime manifest tracking workspace state |\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:1-50]()\n\n**Constructor Validation:**\n\n```typescript\nif (\n  config.baseInstructions !== undefined &&\n  typeof config.baseInstructions !== 'string' &&\n  typeof config.baseInstructions !== 'function'\n) {\n  throw new TypeError(\n    'SandboxAgent baseInstructions must be a string or function.',\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:20-28]()\n\n### Sandbox Agent Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `name` | `string` | Yes | Name identifier for the sandbox agent |\n| `instructions` | `string` | No | System prompt/instructions for the agent |\n| `defaultManifest` | `Manifest` | No | Initial workspace manifest |\n| `baseInstructions` | `string \\| function` | No | Base instructions for sandbox setup |\n| `capabilities` | `Capability[]` | No | Enabled capabilities (defaults to `Capabilities.default()`) |\n| `runAs` | `string \\| SandboxUser` | No | User identity for sandbox execution |\n\n## Path Translation System\n\nSandbox environments maintain an isolated filesystem. The SDK uses a **path translation system** to map between the host machine's paths and the sandbox's internal workspace paths.\n\n### Translation Strategy\n\n```mermaid\ngraph LR\n    A[Host Path] -->|translateRootManifestCommandInput| B[Sandbox Path]\n    B -->|execute| C[Command in Sandbox]\n    C -->|translateManifestRootCommandOutput| D[Host-Compatible Output]\n```\n\n### Translation Functions\n\nThe `unixLocal.ts` module provides path translation utilities:\n\n**Root Manifest Command Input Translation:**\n\n```typescript\nfunction translateRootManifestCommandInput(\n  command: string,\n  workspaceRootPath: string,\n): string {\n  return command.replace(\n    /(^|[\\s\"'=<>])\\/([^\\s\"'|&;<>(){}]*)/g,\n    (_match, prefix: string, pathSuffix: string) =>\n      `${prefix}${workspaceRootPath}/${pathSuffix}`,\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:30-40]()\n\n**Manifest Root Command Input Translation:**\n\n```typescript\nfunction translateManifestRootCommandInput(\n  command: string,\n  manifestRoot: string,\n  workspaceRootPath: string,\n): string {\n  const escapedManifestRoot = escapeRegExp(manifestRoot);\n  const pathPrefix = String.raw`(^|[\\s\"'=<>])`;\n  const pathSuffix = String.raw`(?=$|[\\/\\s\"'|&;<>(){}])`;\n  return command.replace(\n    new RegExp(`${pathPrefix}${escapedManifestRoot}${pathSuffix}`, 'g'),\n    (_match, prefix: string) => `${prefix}${workspaceRootPath}`,\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:42-55]()\n\n### Output Path Translation\n\nBoth root and manifest-level output translations use a shared helper:\n\n```typescript\nfunction translateWorkspaceRootCommandOutput(\n  output: string,\n  manifestRoot: string,\n  workspaceRootPath: string,\n): string {\n  // Core translation logic shared between input and output\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:67-75]()\n\n## Extension Providers\n\nThe `agents-extensions` package provides integrations with popular sandbox providers. Each provider implements a consistent interface while leveraging provider-specific features.\n\n### Provider Comparison\n\n| Provider | Package | Use Case | Key Features |\n|----------|---------|----------|--------------|\n| **Cloudflare** | `agents-extensions` | Edge computing, global distribution | Low latency execution, Workers integration |\n| **E2B** | `agents-extensions` | Code interpretation, AI debugging | Secure VM isolation, filesystem access |\n| **Daytona** | `agents-extensions` | Development environments | Full IDE capabilities, workspace management |\n\n### Daytona Sandbox Implementation\n\nDaytona provides a robust sandbox with advanced file operation capabilities.\n\n#### File Write Operations\n\nThe Daytona sandbox implements secure file writing with workspace escape prevention:\n\n```bash\nresolved_root=$(realpath -m -- \"$root\")\nparent=$(dirname -- \"$path\")\nbase=$(basename -- \"$path\")\nresolved_parent=$(realpath -m -- \"$parent\")\ncase \"$resolved_parent\" in \"$resolved_root\"|\"$resolved_root\"/*) ;; \n  *) printf \"workspace escape: %s\\\\n\" \"$resolved_parent\" >&2; exit 111 ;; \nesac\n```\n\n资料来源：[packages/agents-extensions/src/sandbox/daytona/sandbox.ts:50-60]()\n\n#### Security Measures\n\n| Check | Exit Code | Description |\n|-------|-----------|-------------|\n| Workspace Escape | 111 | Prevents writes outside allowed workspace |\n| Directory Target | 112 | Prevents overwriting directory with file |\n\n#### Write Operation Flow\n\n```mermaid\ngraph TD\n    A[Write Request] --> B{Validate Path}\n    B -->|Escape Detected| C[Exit 111]\n    B -->|Is Directory| D[Exit 112]\n    B -->|Valid| E[Create Temp File]\n    E --> F[base64 Decode Content]\n    F --> G[chmod 644]\n    G --> H[Atomic Move to Target]\n    H --> I[Cleanup Trap]\n```\n\n#### Temporary File Management\n\n```bash\ntmp=$(mktemp \"$resolved_parent/.openai-agents-write.XXXXXX\")\ncleanup() { rm -f -- \"$tmp\"; }\ntrap cleanup EXIT HUP INT TERM\nbase64 -d > \"$tmp\" <<'OPENAI_AGENTS_CONTENT'\n${encoded}\nOPENAI_AGENTS_CONTENT\nchmod 644 \"$tmp\"\nmv -f -- \"$tmp\" \"$target\"\ntrap - EXIT\n```\n\n资料来源：[packages/agents-extensions/src/sandbox/daytona/sandbox.ts:55-70]()\n\n### Environment Variables\n\nSandbox environments receive a standardized set of environment variables:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `HOME` | User home directory | `/home/user` |\n| `SHELL` | Default shell path | `/bin/bash` |\n| `TMPDIR` | Temporary directory | `/tmp` |\n| `PWD` | Current working directory | `/workspace` |\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:10-20]()\n\n## Docker Sandbox\n\nThe Docker sandbox provider enables containerized execution with full isolation:\n\n```mermaid\ngraph TD\n    A[Sandbox Request] --> B[Create Container]\n    B --> C[Mount Workspace Volume]\n    C --> D[Execute Commands]\n    D --> E[Translate Paths]\n    E --> F[Return Results]\n    F --> G[Cleanup Container]\n```\n\n### Docker Configuration\n\n| Option | Description |\n|--------|-------------|\n| `image` | Docker image to use |\n| `volumes` | Volume mounts for persistent storage |\n| `network` | Network configuration |\n| `memory` | Memory limits |\n| `cpus` | CPU allocation |\n\n## Manifest System\n\nThe Manifest system tracks workspace structure and enables consistent file operations across sandbox providers.\n\n### Manifest Structure\n\n```typescript\ninterface Manifest {\n  root: string;\n  files: FileEntry[];\n  directories: DirectoryEntry[];\n}\n```\n\n### Clone Behavior\n\nWhen creating a new `SandboxAgent` with modified configuration, manifests are cloned to prevent mutation:\n\n```typescript\nthis.defaultManifest = config.defaultManifest\n  ? cloneManifest(config.defaultManifest)\n  : undefined;\n```\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:29-32]()\n\n## Usage Patterns\n\n### Basic Sandbox Agent Creation\n\n```typescript\nimport { SandboxAgent } from '@openai/agents-core';\n\nconst sandboxAgent = SandboxAgent.create({\n  name: 'code-executor',\n  instructions: 'Execute code and return results',\n  baseInstructions: 'Initialize workspace at /workspace',\n  capabilities: [Capability.fileWrite, Capability.commandExecution],\n  runAs: 'sandbox-user',\n});\n```\n\n### Extension Provider Usage\n\n```typescript\nimport { createCloudflareSandbox } from '@openai/agents-extensions';\nimport { SandboxAgent } from '@openai/agents-core';\n\nconst cloudflareSandbox = createCloudflareSandbox({\n  name: 'edge-executor',\n  instructions: 'Execute at edge locations',\n});\n\nconst agent = SandboxAgent.create({\n  ...cloudflareSandbox,\n  capabilities: [Capability.fileWrite],\n});\n```\n\n## Best Practices\n\n### Security Considerations\n\n1. **Path Validation**: Always validate paths before execution to prevent workspace escapes\n2. **Resource Limits**: Configure memory and CPU limits for sandboxed operations\n3. **Cleanup**: Ensure proper trap handlers clean up temporary resources\n4. **User Isolation**: Run sandbox operations with minimal privileges\n\n### Performance Optimization\n\n1. **Connection Pooling**: Reuse sandbox instances when possible\n2. **Manifest Caching**: Cache manifest states to reduce initialization overhead\n3. **Path Translation Caching**: Memoize frequently used path translations\n\n## Error Handling\n\nSandbox operations may fail with specific error codes:\n\n| Error Type | Provider | Common Causes |\n|------------|----------|---------------|\n| Workspace Escape | Daytona | Path traversal attempt |\n| Resource Exhaustion | Docker/E2B | Memory/CPU limits exceeded |\n| Permission Denied | All | Insufficient sandbox user privileges |\n| Container Failure | Docker | Image not found, network issues |\n\n## Further Reading\n\n- [Agent Lifecycle Events](packages/agents-core/src/lifecycle.ts)\n- [Tool Configuration](packages/agents-core/src/tool.ts)\n- [Extension Packages](packages/agents-extensions/README.md)\n- [Agent Patterns Examples](examples/agent-patterns/README.md)\n\n---\n\n<a id='voice-realtime'></a>\n\n## Voice Agents and Realtime Communication\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-realtime/src/realtimeAgent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeAgent.ts)\n- [packages/agents-realtime/src/realtimeSession.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeSession.ts)\n- [packages/agents-realtime/src/openaiRealtimeBase.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/openaiRealtimeBase.ts)\n- [packages/agents-realtime/src/openaiRealtimeWebsocket.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/openaiRealtimeWebsocket.ts)\n- [packages/agents-realtime/src/realtimeSessionEvents.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeSessionEvents.ts)\n- [packages/agents-realtime/src/clientMessages.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/clientMessages.ts)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n</details>\n\n# Voice Agents and Realtime Communication\n\n## Overview\n\nThe OpenAI Agents SDK provides a comprehensive framework for building voice agents with realtime communication capabilities. This system enables developers to create interactive voice applications that leverage OpenAI's Realtime API for low-latency, bidirectional audio communication.\n\nThe voice agent system is built on two primary abstractions:\n\n1. **RealtimeAgent** - A specialized agent class designed for voice interactions\n2. **RealtimeSession** - A session manager that handles the connection lifecycle, event routing, and audio processing\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts:50-60]()\n\n## Architecture\n\n### High-Level Component Architecture\n\n```mermaid\ngraph TD\n    A[Client Application] --> B[RealtimeSession]\n    B --> C[Transport Layer]\n    C --> D[OpenAI Realtime API]\n    \n    B --> E[RealtimeAgent]\n    E --> F[System Prompt]\n    E --> G[Handoffs]\n    \n    B --> H[Event System]\n    H --> I[audio_start]\n    H --> J[audio_stopped]\n    H --> K[audio_interrupted]\n    H --> L[guardrail_tripped]\n    \n    C --> M[WebSocket Transport]\n    C --> N[WebRTC Transport]\n```\n\n### Session Configuration Flow\n\n```mermaid\nsequenceDiagram\n    participant App as Client App\n    participant Session as RealtimeSession\n    participant Transport as Transport Layer\n    participant API as OpenAI Realtime API\n    \n    App->>Session: create session with config\n    Session->>Transport: initialize transport\n    Transport->>API: establish connection\n    API-->>Transport: connection established\n    Transport-->>Session: emit ready\n    Session->>Session: updateSessionConfig()\n    Session->>App: emit session_started\n```\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:100-150]()\n\n## Core Components\n\n### RealtimeAgent\n\nThe `RealtimeAgent` class extends the base `Agent` class with voice-specific configuration:\n\n```typescript\nexport class RealtimeAgent<TContext = UnknownContext> extends Agent<\n  RealtimeContextData<TContext>,\n  TextOutput\n> {\n  readonly voice?: string;\n}\n```\n\n**Configuration Options:**\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `name` | `string` | The name of your realtime agent |\n| `instructions` | `string` | System prompt for the agent |\n| `handoffs` | `RealtimeAgent[] \\| Handoff[]` | Agents available for handoff |\n| `voice` | `string` | Voice identifier for audio output |\n\n**Unsupported Configuration Options:**\n\nDue to the nature of realtime sessions, the following `Agent` configuration options are not supported:\n\n- `model` - All RealtimeAgents use the same model within a session\n- `modelSettings` - Managed at the session level\n- `outputType` - Structured outputs are not supported\n- `toolUseBehavior` - Managed at the session level\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts:1-55]()\n\n### RealtimeSession\n\nThe `RealtimeSession` manages the complete lifecycle of a voice agent session:\n\n```typescript\nexport class RealtimeSession<TBaseContext = UnknownContext> extends EventEmitter<RealtimeSessionEvents<TBaseContext>>\n```\n\n**Transport Selection:**\n\nThe session automatically selects a transport based on configuration:\n\n| Transport Type | Condition | Use Case |\n|----------------|------------|----------|\n| `OpenAIRealtimeWebRTC` | `transport === 'webrtc'` or WebRTC supported | Browser-based applications |\n| `OpenAIRealtimeWebSocket` | `transport === 'websocket'` or undefined | Server-side, non-browser |\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:200-230]()\n\n## Transport Layer\n\n### WebSocket Transport\n\nThe WebSocket transport provides reliable, server-to-server connectivity:\n\n```typescript\nthis.#transport = new OpenAIRealtimeWebSocket();\n```\n\nKey methods:\n- `sendEvent(event)` - Send raw events to the API\n- `requestResponse(response?)` - Request a model response\n- `updateSessionConfig(config)` - Update session configuration\n\n资料来源：[packages/agents-realtime/src/openaiRealtimeWebsocket.ts:50-80]()\n\n### Turn Detection Configuration\n\nTurn detection can be configured with multiple parameters:\n\n```typescript\ninterface RealtimeTurnDetectionConfig {\n  type?: string;\n  createResponse?: boolean;\n  eagerness?: 'low' | 'medium' | 'high';\n  interruptResponse?: boolean;\n  prefixPaddingMs?: number;\n  silenceDurationMs?: number;\n  threshold?: number;\n  idleTimeoutMs?: number;\n  modelVersion?: string;\n}\n```\n\n**Config Normalization:**\n\nThe SDK automatically converts camelCase to snake_case for API compatibility:\n\n| camelCase | snake_case |\n|-----------|------------|\n| `createResponse` | `create_response` |\n| `interruptResponse` | `interrupt_response` |\n| `prefixPaddingMs` | `prefix_padding_ms` |\n| `silenceDurationMs` | `silence_duration_ms` |\n| `idleTimeoutMs` | `idle_timeout_ms` |\n| `modelVersion` | `model_version` |\n\n资料来源：[packages/agents-realtime/src/openaiRealtimeBase.ts:50-100]()\n\n## Session Configuration\n\n### Configuration Merging Strategy\n\nThe session configuration is built from multiple sources with the following priority:\n\n1. Session method parameters (highest priority)\n2. RealtimeSession constructor options\n3. Default values (lowest priority)\n\n```typescript\nasync #getSessionConfig(\n  additionalConfig: Partial<RealtimeSessionConfig> = {},\n): Promise<Partial<RealtimeSessionConfig>> {\n  const overridesConfig = additionalConfig ?? {};\n  const optionsConfig = this.options.config ?? {};\n  // Merge logic applies priority\n}\n```\n\n### Tracing Configuration\n\nTracing can be explicitly controlled:\n\n```typescript\nconst tracingConfig: RealtimeTracingConfig | null = this.options.tracingDisabled\n  ? null\n  : this.options.workflowName\n    ? { workflow_name: this.options.workflowName }\n    : 'auto';\n```\n\n**Tracing Options:**\n\n| Option | Behavior |\n|--------|----------|\n| `tracingDisabled: true` | Explicitly disable tracing |\n| `workflowName: string` | Enable tracing with workflow name |\n| `'auto'` | Automatic tracing configuration |\n| `groupId` | Group related traces (requires workflowName) |\n| `traceMetadata` | Custom metadata for traces (requires workflowName) |\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:300-350]()\n\n## Events System\n\n### Session Events\n\nThe `RealtimeSession` emits the following events:\n\n| Event | Payload | Description |\n|-------|---------|-------------|\n| `audio_start` | `context, agent` | Agent starts generating audio |\n| `audio_stopped` | `context, agent` | Agent stops generating audio |\n| `audio` | `TransportLayerAudio` | New audio data available |\n| `audio_interrupted` | `context, agent` | Audio generation was interrupted |\n| `guardrail_tripped` | `context, agent, error, details` | Output guardrail triggered |\n| `mcp_tool_call_completed` | `context, agent, toolCall` | MCP tool finished execution |\n| `tool_approval_requested` | `context, agent, approvalItem` | Human-in-the-loop approval needed |\n| `transport_event` | `event` | Raw transport event |\n| `error` | `error` | Error occurred |\n| `usage_update` | `usage` | Token usage update |\n| `mcp_tools_changed` | - | Available MCP tools updated |\n\n### Lifecycle Events\n\n```mermaid\nstateDiagram-v2\n    [*] --> Initializing\n    Initializing --> Connecting\n    Connecting --> Connected\n    Connected --> AudioActive\n    AudioActive --> AudioStopped\n    AudioActive --> Interrupted\n    Interrupted --> Connecting\n    AudioStopped --> Connected\n    Connected --> [*]\n```\n\n资料来源：[packages/agents-realtime/src/realtimeSessionEvents.ts:1-60]()\n\n## Handoffs in Voice Agents\n\nVoice agents support handoff functionality for seamless transitions between agents:\n\n```typescript\nexport type HandoffConfig<\n  TInputType extends ToolInputParameters,\n  TContext = UnknownContext,\n> = {\n  toolNameOverride?: string;\n  toolDescriptionOverride?: string;\n  onHandoff?: OnHandoffCallback<TInputType>;\n};\n```\n\n**Voice-Specific Handoff Behavior:**\n\n- Voice changes during handoff will fail if another agent already spoke during the session\n- The `voice` property can be set per agent but cannot be changed after the first agent speaks\n\n资料来源：[packages/agents-core/src/handoff.ts:50-80]()\n\n## Guardrails\n\n### Output Guardrails\n\nOutput guardrails can be configured at the session level:\n\n```typescript\nthis.#outputGuardrails = (options.outputGuardrails ?? []).map(\n  defineRealtimeOutputGuardrail,\n);\nthis.#outputGuardrailSettings = getRealtimeGuardrailSettings(\n  options.outputGuardrailSettings ?? {},\n);\n```\n\nWhen a guardrail is triggered, the `guardrail_tripped` event is emitted:\n\n```typescript\nthis.emit('guardrail_tripped', context, agent, error, { itemId });\n```\n\n## MCP Tool Integration\n\n### Tool Call Handling\n\nMCP (Model Context Protocol) tools are automatically integrated:\n\n```typescript\nthis.#transport.on('mcp_tool_call_completed', (toolCall) => {\n  this.emit('mcp_tool_call_completed', context, currentAgent, toolCall);\n\n  if (this.#automaticallyTriggerResponseForMcpToolCalls) {\n    if (this.#transport.requestResponse) {\n      this.#transport.requestResponse();\n    } else {\n      this.#transport.sendEvent({ type: 'response.create' });\n    }\n  }\n});\n```\n\n**Configuration Option:**\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `automaticallyTriggerResponseForMcpToolCalls` | `boolean` | `true` | Auto-trigger response after tool completion |\n\n## Usage Examples\n\n### Basic Voice Agent Setup\n\n```typescript\nimport { RealtimeAgent, RealtimeSession } from '@openai/agents-realtime';\n\nconst agent = new RealtimeAgent({\n  name: 'my-agent',\n  instructions: 'You are a helpful assistant that can answer questions and help with tasks.',\n});\n\nconst session = new RealtimeSession(agent);\n\nsession.on('audio', (event) => {\n  // Handle audio data\n  console.log('Audio received:', event);\n});\n\nsession.on('audio_interrupted', (context, agent) => {\n  // Stop audio playback\n  console.log('Audio interrupted');\n});\n\nawait session.start();\n```\n\n### Next.js Integration\n\nThe SDK provides examples for Next.js integration at `/examples/realtime-next`:\n\n```bash\npnpm examples:realtime-next\n```\n\nAvailable endpoints:\n- `/` - WebRTC voice demo\n- `/websocket` - WebSocket voice demo\n- `/raw-client` - Low-level WebRTC example using `OpenAIRealtimeWebRTC`\n\n资料来源：[examples/realtime-next/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/realtime-next/README.md)\n\n### Vite Demo Application\n\nA standalone demo is available at `/examples/realtime-demo`:\n\n```bash\npnpm -F realtime-demo generate-token\npnpm examples:realtime-demo\n```\n\n资料来源：[examples/realtime-demo/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/realtime-demo/README.md)\n\n## Type Definitions\n\n### Context Data Structure\n\n```typescript\ninterface RealtimeContextData<TContext = UnknownContext> {\n  history: Message[];\n  usage: UsageData;\n  // Additional user-defined context\n}\n```\n\n### Session Configuration\n\n```typescript\ninterface RealtimeSessionConfig {\n  model?: string;\n  modalities?: ('text' | 'audio')[];\n  instructions?: string;\n  voice?: string;\n  audio?: {\n    input?: {\n      format?: string;\n      noiseReduction?: boolean;\n      transcription?: TranscriptionConfig;\n      turnDetection?: RealtimeTurnDetectionConfig;\n    };\n    output?: {\n      format?: string;\n      voice?: string;\n    };\n  };\n  turnDetection?: RealtimeTurnDetectionConfig;\n}\n```\n\n## Best Practices\n\n### Connection Management\n\n1. **Always handle errors**: Subscribe to the `error` event to catch and handle connection issues\n2. **Implement reconnection logic**: The session should be recreated if the connection is lost\n3. **Monitor audio state**: Track `audio_start` and `audio_stopped` events for proper playback management\n\n### Voice Configuration\n\n1. **Set voice early**: Configure the voice in the agent or session configuration before the first agent speaks\n2. **Handle handoff failures**: Implement fallback logic when voice changes fail during handoffs\n3. **Test with different voices**: Use the `voice` property to find the best voice for your use case\n\n### Performance Considerations\n\n1. **Audio buffer management**: Handle `audio` events efficiently to prevent latency\n2. **Event cleanup**: Remove event listeners when the session is terminated\n3. **Use appropriate transport**: Choose WebRTC for browser applications, WebSocket for server-side\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:150-200]()\n\n## See Also\n\n- [Basic Examples](../examples/basic) - Simple script demonstrations\n- [AI SDK UI Integration](../examples/ai-sdk-ui) - Streaming text responses\n- [Agent Lifecycle](../packages/agents-core/src/lifecycle.ts) - Understanding agent lifecycle events\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：openai/openai-agents-js\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。\n\n## 1. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `openai-agents-js` 与安装入口 `@openai/agents` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @openai/agents`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:993521808 | https://github.com/openai/openai-agents-js | repo=openai-agents-js; install=@openai/agents\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:993521808 | https://github.com/openai/openai-agents-js | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | release_recency=unknown\n\n<!-- canonical_name: openai/openai-agents-js; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "openai-agents-js",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:993521808",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/openai/openai-agents-js"
        },
        {
          "evidence_id": "art_0e97ee656a1347e792406bb5b516f59f",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/openai/openai-agents-js#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "openai-agents-js 说明书",
      "toc": [
        "https://github.com/openai/openai-agents-js 项目说明书",
        "目录",
        "Introduction to OpenAI Agents SDK",
        "Overview",
        "Package Architecture",
        "Core Agent Class",
        "Tool System",
        "Agent Patterns",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "629d35af99e1ba80fc968b0d062c070caed0683d",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pnpm-lock.yaml",
      "package.json",
      "README.md",
      "docs/tsconfig.scripts.json",
      "docs/package.json",
      "docs/README.md",
      "docs/tsconfig.json",
      "docs/src/content.config.ts",
      "docs/src/plugins/typedoc-frontmatter.js",
      "docs/src/scripts/translate.ts",
      "docs/src/content/docs/index.mdx",
      "docs/src/content/docs/ja/index.mdx",
      "docs/src/content/docs/guides/multi-agent.md",
      "docs/src/content/docs/guides/config.mdx",
      "docs/src/content/docs/guides/troubleshooting.mdx",
      "docs/src/content/docs/guides/context.mdx",
      "docs/src/content/docs/guides/models.mdx",
      "docs/src/content/docs/guides/handoffs.mdx",
      "docs/src/content/docs/guides/sandbox-agents.mdx",
      "docs/src/content/docs/guides/human-in-the-loop.mdx",
      "docs/src/content/docs/guides/mcp.mdx",
      "docs/src/content/docs/guides/results.mdx",
      "docs/src/content/docs/guides/tracing.mdx",
      "docs/src/content/docs/guides/running-agents.mdx",
      "docs/src/content/docs/guides/quickstart.mdx",
      "docs/src/content/docs/guides/release.mdx",
      "docs/src/content/docs/guides/tools.mdx",
      "docs/src/content/docs/guides/agents.mdx",
      "docs/src/content/docs/guides/sessions.mdx",
      "docs/src/content/docs/guides/guardrails.mdx",
      "docs/src/content/docs/guides/streaming.mdx",
      "docs/src/content/docs/guides/voice-agents.mdx",
      "docs/src/content/docs/extensions/cloudflare.mdx",
      "docs/src/content/docs/extensions/ai-sdk.mdx",
      "docs/src/content/docs/extensions/twilio.mdx",
      "docs/src/content/docs/zh/index.mdx",
      "docs/src/content/docs/ko/index.mdx",
      "docs/src/content/docs/ja/guides/multi-agent.md",
      "docs/src/content/docs/ja/guides/config.mdx",
      "docs/src/content/docs/ja/guides/troubleshooting.mdx"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# openai-agents-js - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 openai-agents-js 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等 Claim：`clm_0003` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md`, `packages/agents-core/README.md`, `packages/agents-extensions/README.md` Claim：`clm_0002` supported 0.86\n\n## 怎么开始\n\n- `npm install @openai/agents zod` 证据：`README.md` Claim：`clm_0004` supported 0.86\n- `npm install @openai/agents` 证据：`packages/agents-core/README.md` Claim：`clm_0004` supported 0.86, `clm_0005` supported 0.86, `clm_0006` supported 0.86\n- `npm install @openai/agents @openai/agents-extensions` 证据：`packages/agents-extensions/README.md` Claim：`clm_0006` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做权限沙盒试用\n- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。\n\n### 30 秒判断\n\n- **现在怎么做**：先做权限沙盒试用\n- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等 Claim：`clm_0003` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md`, `packages/agents-core/README.md`, `packages/agents-extensions/README.md` Claim：`clm_0002` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0004` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`, `packages/agents-core/README.md`, `packages/agents-extensions/README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`, `packages/agents-core/README.md`, `packages/agents-extensions/README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0007` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md`, `packages/agents-core/README.md`, `packages/agents-extensions/README.md` Claim：`clm_0008` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`.agents/skills/changeset-validation/SKILL.md`, `.agents/skills/code-change-verification/SKILL.md`, `.agents/skills/docs-sync/SKILL.md`, `.agents/skills/examples-auto-run/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md`, `packages/agents-core/README.md`, `packages/agents-extensions/README.md` Claim：`clm_0002` supported 0.86\n\n### 上下文规模\n\n- 文件总数：1210\n- 重要文件覆盖：40/1210\n- 证据索引条目：86\n- 角色 / Skill 条目：15\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 openai-agents-js 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 openai-agents-js 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 openai-agents-js 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 15 个角色 / Skill / 项目文档条目。\n\n- **changeset-validation**（skill）：Validate changesets in openai-agents-js using LLM judgment against git diffs including uncommitted local changes . Use when packages/ or .changeset/ are modified, or when verifying PR changeset compliance and bump level. 激活提示：当用户任务与“changeset-validation”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/changeset-validation/SKILL.md`\n- **code-change-verification**（skill）：Run the mandatory verification stack when changes affect runtime code, tests, or build/test behavior in the OpenAI Agents JS monorepo. 激活提示：当用户任务与“code-change-verification”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/code-change-verification/SKILL.md`\n- **docs-sync**（skill）：Analyze main branch implementation and configuration to find missing, incorrect, or outdated documentation in docs/. Use when asked to audit doc coverage, sync docs with code, or propose doc updates/structure changes. Only update English docs docs/src/content/docs/ and never touch translated docs under docs/src/content/docs/ja, ko, or zh. Provide a report and ask for approval before editing docs. 激活提示：当用户任务与“docs-sync”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/docs-sync/SKILL.md`\n- **examples-auto-run**（skill）：Run examples:start-all in auto mode with parallel execution, per-script logs, and start/stop helpers. 激活提示：当用户任务与“examples-auto-run”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/examples-auto-run/SKILL.md`\n- **final-release-review**（skill）：Perform a release-readiness review by locating the previous release tag from remote tags and auditing the diff e.g., v1.2.3... for breaking changes, regressions, improvement opportunities, and risks before releasing openai-agents-js. 激活提示：当用户任务与“final-release-review”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/final-release-review/SKILL.md`\n- **implementation-strategy**（skill）：Decide how to implement runtime and API changes in openai-agents-js before editing code. Use when a task changes exported APIs, runtime behavior, schemas, tests, or docs and you need to choose the compatibility boundary, whether shims or migrations are warranted, and when unreleased interfaces can be rewritten directly. 激活提示：当用户任务与“implementation-strategy”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/implementation-strategy/SKILL.md`\n- **integration-tests**（skill）：Run the integration-tests pipeline that depends on a local npm registry Verdaccio . Use when asked to execute integration tests or local publish workflows in this repo. 激活提示：当用户任务与“integration-tests”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/integration-tests/SKILL.md`\n- **openai-knowledge**（skill）：Use when working with the OpenAI API Responses API or OpenAI platform features tools, streaming, Realtime API, auth, models, rate limits, MCP and you need authoritative, up-to-date documentation schemas, examples, limits, edge cases . Prefer the OpenAI Developer Documentation MCP server tools when available; otherwise guide the user to enable openaiDeveloperDocs . 激活提示：当用户任务与“openai-knowledge”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/openai-knowledge/SKILL.md`\n- **pnpm-upgrade**（skill）：Keep pnpm current: run pnpm self-update/corepack prepare, align packageManager in package.json, and bump pnpm/action-setup + pinned pnpm versions in .github/workflows to the latest release. Use this when refreshing the pnpm toolchain manually or in automation. 激活提示：当用户任务与“pnpm-upgrade”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/pnpm-upgrade/SKILL.md`\n- **pr-draft-summary**（skill）：Create the required PR-ready summary block, branch suggestion, title, and draft description for openai-agents-js. Use in the final handoff after moderate-or-larger changes to runtime code, tests, examples, build/test configuration, or docs with behavior impact; skip only for trivial or conversation-only tasks, repo-meta/doc-only tasks without behavior impact, or when the user explicitly says not to include the PR dr… 激活提示：当用户任务与“pr-draft-summary”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/pr-draft-summary/SKILL.md`\n- **runtime-behavior-probe**（skill）：Plan and execute runtime-behavior investigations with temporary TypeScript probe scripts, validation matrices, state controls, and findings-first reports. Use only when the user explicitly invokes this skill to verify actual runtime behavior beyond normal code-level checks, especially to uncover edge cases, undocumented behavior, or common failure modes in local or live integrations. A baseline smoke check is fine a… 激活提示：当用户任务与“runtime-behavior-probe”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/runtime-behavior-probe/SKILL.md`\n- **test-coverage-improver**（skill）：Improve test coverage in the OpenAI Agents JS monorepo: run pnpm test:coverage , inspect coverage artifacts, identify low-coverage files and branches, propose high-impact tests, and confirm with the user before writing tests. 激活提示：当用户任务与“test-coverage-improver”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/test-coverage-improver/SKILL.md`\n- **invoice-total-fixer**（skill）：Use when fixing invoice total calculations in the sandbox quickstart repository. 激活提示：当用户任务与“invoice-total-fixer”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`examples/docs/sandbox-agents/skills/invoice-total-fixer/SKILL.md`\n- **credit-note-fixer**（skill）：Fix the tiny credit-note formatting bug and rerun the exact targeted test command. 激活提示：当用户任务与“credit-note-fixer”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`examples/sandbox/data/coding-task/skills/credit-note-fixer/SKILL.md`\n- **csv-workbench**（skill）：Analyze CSV files in /mnt/data and return concise numeric summaries. 激活提示：当用户任务与“csv-workbench”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`examples/tools/skills/csv-workbench/SKILL.md`\n\n## 证据索引\n\n- 共索引 86 条证据。\n\n- **Docs**（documentation）：The documentation is generated using Astro Starlight. 证据：`docs/README.md`\n- **Documentation Snippets**（documentation）：This directory contains small scripts used throughout the documentation. Run them with pnpm using the commands shown below. 证据：`examples/docs/README.md`\n- **Invoice Total Fixer**（skill_instruction）：Inspect the implementation and test before editing. The total should apply tax as a percentage of the subtotal, so the expected formula is subtotal + subtotal taxRate . 证据：`examples/docs/sandbox-agents/skills/invoice-total-fixer/SKILL.md`\n- **Changesets**（documentation）：Hello and welcome! This folder has been automatically generated by @changesets/cli , a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it in our repository https://github.com/changesets/changesets 证据：`.changeset/README.md`\n- **Contributor Guide**（documentation）：This guide helps new contributors get started with the OpenAI Agents JS monorepo. It covers repo structure, how to test your work, available utilities, file locations, and guidelines for commits and PRs. 证据：`AGENTS.md`\n- **OpenAI Agents SDK JavaScript/TypeScript**（documentation）：OpenAI Agents SDK JavaScript/TypeScript 证据：`README.md`\n- **Integration tests**（documentation）：This project hosts packages to test the different environments that the Agents SDK works in. 证据：`integration-tests/README.md`\n- **Agent Pattern Examples**（documentation）：This directory contains small scripts that demonstrate different agent patterns. Run them with pnpm using the commands shown below. 证据：`examples/agent-patterns/README.md`\n- **AI SDK UI Stream Example**（documentation）：This example shows how to convert an Agents SDK streaming run into responses that are compatible with the AI SDK UI data stream and text stream protocols. 证据：`examples/ai-sdk-ui/README.md`\n- **AI SDK Example**（documentation）：This example shows how to run the Agents SDK with a model provided by the AI SDK https://www.npmjs.com/package/@ai-sdk/openai . 证据：`examples/ai-sdk-v1/README.md`\n- **AI SDK Examples**（documentation）：These examples show how to wrap models from the AI SDK https://www.npmjs.com/package/@ai-sdk/openai and compatible providers with the aisdk helper from @openai/agents-extensions/ai-sdk , then run them inside the Agents runtime. 证据：`examples/ai-sdk/README.md`\n- **Basic Examples**（documentation）：This directory contains small scripts that demonstrate features of the Agents SDK. Run them with pnpm using the commands shown below. 证据：`examples/basic/README.md`\n- **Customer Service Agent**（documentation）：This example demonstrates a multi-agent customer service workflow for an airline. The index.ts script sets up a triage agent that can delegate to specialized FAQ and seat booking agents. Tools are used to look up common questions and to update a passenger's seat. Interaction occurs through a simple CLI loop, showing how agents can hand off between each other and call tools. 证据：`examples/customer-service/README.md`\n- **Financial Research Agent**（documentation）：This example demonstrates a multi-agent workflow that produces a short financial analysis report. 证据：`examples/financial-research-agent/README.md`\n- **Agent Handoffs**（documentation）：This example shows how one agent can transfer control to another. The index.ts script sets up two English speaking assistants and a Spanish assistant. The second agent is configured with a handoff so that if the user requests Spanish replies it hands off to the Spanish agent. A message filter strips out tool messages and the first two history items before the handoff occurs. Run it with: 证据：`examples/handoffs/README.md`\n- **Model Context Protocol Example**（documentation）：This example demonstrates how to use the Model Context Protocol https://modelcontextprotocol.io/ with the OpenAI Agents SDK. 证据：`examples/mcp/README.md`\n- **Model Providers Examples**（documentation）：This directory contains small scripts showing how to integrate custom model providers. Run them with pnpm using the commands shown below. 证据：`examples/model-providers/README.md`\n- **Next.js Demo**（documentation）：This example shows a basic example of how to use human-in-the-loop in a Next.js application. 证据：`examples/nextjs/README.md`\n- **Realtime Demo**（documentation）：This example is a small Vite https://vitejs.dev/ application showcasing the realtime agent API. 证据：`examples/realtime-demo/README.md`\n- **Realtime Next.js Demo**（documentation）：This example shows how to combine Next.js with the OpenAI Agents SDK to create a realtime voice agent. 证据：`examples/realtime-next/README.md`\n- **Twilio SIP Realtime Example**（documentation）：This example shows how to handle OpenAI Realtime SIP calls with the Agents JS SDK. Incoming calls are accepted through the Realtime Calls API, a triage agent answers with a fixed greeting, and handoffs route the caller to specialist agents FAQ lookup and record updates similar to the realtime UI demo. 证据：`examples/realtime-twilio-sip/README.md`\n- **Realtime Twilio Integration**（documentation）：This example demonstrates how to connect the OpenAI Realtime API to a phone call using Twilio's Media Streams. The script in index.ts starts a Fastify server that serves TwiML for incoming calls and creates a WebSocket endpoint for streaming audio. When a call connects, the audio stream is forwarded through a TwilioRealtimeTransportLayer to a RealtimeSession so the RealtimeAgent can respond in real time. 证据：`examples/realtime-twilio/README.md`\n- **Research Bot**（documentation）：This example shows how to orchestrate several agents to produce a detailed research report. 证据：`examples/research-bot/README.md`\n- **Sandbox Examples**（documentation）：These examples show the JavaScript sandbox APIs that are implemented in this branch: Manifest , SandboxAgent , local and Docker sandbox clients, filesystem and shell capabilities, lazy skills, host tools, handoffs, local and remote snapshots, external memory stores, and SDK conversation sessions. 证据：`examples/sandbox/README.md`\n- **Credit Note Example Repo**（documentation）：This tiny repo exists to support examples/sandbox/coding-task.ts . 证据：`examples/sandbox/data/coding-task/repo/README.md`\n- **Cloud Sandbox Extension Examples**（documentation）：These examples mirror the Python sandbox extension runners and keep the same environment-variable names and flag shapes where that makes sense. 证据：`examples/sandbox/extensions/README.md`\n- **Tool Integrations**（documentation）：These examples demonstrate the hosted tools provided by the Agents SDK. 证据：`examples/tools/README.md`\n- **OpenAI Agents SDK**（documentation）：The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. 证据：`packages/agents-core/README.md`\n- **OpenAI Agents SDK Extensions**（documentation）：This package contains a collection of extension features for the OpenAI Agents SDK and is intended to be used alongside it. 证据：`packages/agents-extensions/README.md`\n- **OpenAI Agents SDK**（documentation）：The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. 证据：`packages/agents-openai/README.md`\n- **OpenAI Agents SDK**（documentation）：The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. 证据：`packages/agents-realtime/README.md`\n- **OpenAI Agents SDK JavaScript/TypeScript**（documentation）：OpenAI Agents SDK JavaScript/TypeScript 证据：`packages/agents/README.md`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"docs\", \"type\": \"module\", \"scripts\": { \"dev\": \"astro dev\", \"start\": \"astro dev\", \"build\": \"astro build\", \"preview\": \"astro preview\", \"astro\": \"astro\", \"translate\": \"tsx src/scripts/translate.ts\" }, \"dependencies\": { \"@astrojs/starlight\": \"^0.38.4\", \"@astrojs/starlight-tailwind\": \"^5.0.0\", \"@openai/agents\": \"workspace: \", \"@tailwindcss/vite\": \"^4.2.4\", \"astro\": \"^6.1.10\", \"sharp\": \"^0.34.5\", \"starlight-llms-txt\": \"^0.8.1\", \"starlight-typedoc\": \"^0.21.5\", \"typedoc\": \"^0.28.19\", \"typedoc-plugin-markdown\": \"^4.11.0\" }, \"devDependencies\": { \"tailwindcss\": \"^4.2.4\", \"tsx\": \"^4.21.0\", \"typedoc-plugin-frontmatter\": \"^1.3.1\", \"typedoc-plugin-zod\": \"^1.4.3\" } } 证据：`docs/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"openai-agents-js\", \"version\": \"0.0.1\", \"scripts\": { \"clean\": \"node scripts/clean-package-dists.mjs && tsc-multi --clean\", \"prebuild\": \"pnpm -F @openai/ -r prebuild\", \"build\": \"pnpm clean && tsc-multi\", \"build:ci\": \"pnpm run prebuild && pnpm clean && tsc-multi --maxWorkers 1 && pnpm run postbuild\", \"postbuild\": \"pnpm -r -F @openai/ bundle\", \"packages:dev\": \"tsc-multi --watch\", \"docs:dev\": \"pnpm -F docs dev\", \"docs:translate\": \"pnpm -F docs translate\", \"docs:build\": \"pnpm -F docs build\", \"docs:scripts:check\": \"pnpm exec tsc --pretty false --project docs/tsconfig.scripts.json\", \"test\": \"CI=1 NODE ENV=test vitest\", \"test:coverage\": \"NODE ENV=test vitest run --coverag… 证据：`package.json`\n- **Contributing to OpenAI Agents SDK**（documentation）：Thank you for your interest in contributing to the OpenAI Agents SDK. This document outlines the process for reporting issues, proposing changes, and submitting pull requests. 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"agent-patterns\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"chalk\": \"^5.4.1\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start:agents-as-tools\": \"tsx agents-as-tools.ts\", \"start:agents-as-tools-conditional\": \"tsx agents-as-tools-conditional.ts\", \"start:agents-as-tools-structured\": \"tsx agents-as-tools-structured.ts\", \"start:agents-as-tools-streaming\": \"tsx agents-as-tools-streaming.ts\", \"start:deterministic\": \"tsx deterministic.ts\", \"start:forcing-tool-use\": \"tsx forcing-tool-use.ts -t default\", \"start:human-in-the-loop-stream\": \"tsx human-in-the-loop-stream.ts\", \"start:human-in-the-loop\": \"tsx human-in-the-loop.ts\", \"start:input-gua… 证据：`examples/agent-patterns/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"ai-sdk-ui\", \"dependencies\": { \"@ai-sdk/react\": \"^3.0.44\", \"@openai/agents\": \"workspace: \", \"@openai/agents-extensions\": \"workspace: \", \"@openai/agents-openai\": \"workspace: \", \"ai\": \"^6.0.42\", \"next\": \"16.2.3\", \"react\": \"^19.2.3\", \"react-dom\": \"^19.2.3\", \"react-markdown\": \"^9.0.3\", \"rehype-sanitize\": \"^6.0.0\", \"remark-gfm\": \"^4.0.0\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"dev\": \"next dev --turbopack\", \"build\": \"next build\", \"start\": \"next start\", \"lint\": \"next lint\", \"start:script-simple\": \"tsx scripts/simple.ts\", \"start:script-ai-sdk\": \"tsx scripts/ai-sdk.ts\" }, \"devDependencies\": { \"@ai-sdk/openai\": \"^3.0.14\", \"@types/node\": \"^20\", \"@typ… 证据：`examples/ai-sdk-ui/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"ai-sdk-v1\", \"dependencies\": { \"@ai-sdk/openai\": \"1\", \"@ai-sdk/provider\": \"1.1.3\", \"@openai/agents\": \"0.3.9\", \"@openai/agents-extensions\": \"0.3.9\", \"hono\": \"^4.12.16\", \"zod\": \"^3.23.8\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\", \"start:stream\": \"tsx stream.ts\" } } 证据：`examples/ai-sdk-v1/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"ai-sdk\", \"dependencies\": { \"@ai-sdk/anthropic\": \"^3.0.9\", \"@ai-sdk/google\": \"^3.0.6\", \"@ai-sdk/openai\": \"^3.0.7\", \"@openai/agents\": \"workspace: \", \"@openai/agents-extensions\": \"workspace: \", \"@openrouter/ai-sdk-provider\": \"^2.9.0\", \"zod\": \"4.3.5\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\", \"start:gpt-5\": \"tsx gpt-5.ts\", \"start:retry\": \"tsx retry.ts\", \"start:stream\": \"tsx stream.ts\", \"start:image-tool-output\": \"tsx image-tool-output.ts\" }, \"devDependencies\": { \"ai\": \"^6.0.3\" } } 证据：`examples/ai-sdk/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"basic\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"openai\": \"^6.35.0\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\", \"start:agent-lifecycle-example\": \"tsx agent-lifecycle-example.ts\", \"start:chat\": \"tsx chat.ts\", \"start:dynamic-system-prompt\": \"tsx dynamic-system-prompt.ts\", \"start:hello-world\": \"tsx hello-world.ts\", \"start:hello-world-gpt-5\": \"tsx hello-world-gpt-5.ts\", \"start:hello-world-gpt-oss\": \"tsx hello-world-gpt-oss.ts\", \"start:lifecycle-example\": \"tsx lifecycle-example.ts\", \"start:local-image\": \"tsx local-image.ts\", \"start:image-tool-output\": \"tsx image-tool-output.ts\", \"start:file-tool-output\": \"tsx fil… 证据：`examples/basic/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"connectors\", \"dependencies\": { \"@openai/agents\": \"workspace: \" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\" } } 证据：`examples/connectors/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"customer-service\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@openai/agents-core\": \"workspace: \", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\" } } 证据：`examples/customer-service/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"docs-code\", \"dependencies\": { \"@ai-sdk/openai\": \"^2.0.15\", \"@modelcontextprotocol/server-filesystem\": \"^2026.1.14\", \"@openai/agents\": \"workspace: \", \"@openai/agents-core\": \"workspace: \", \"@openai/agents-extensions\": \"workspace: \", \"@openai/agents-realtime\": \"workspace: \", \"openai\": \"^6.35.0\", \"server-only\": \"^0.0.1\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\" }, \"devDependencies\": { \"typedoc-plugin-zod\": \"^1.4.1\" } } 证据：`examples/docs/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"type\": \"module\", \"scripts\": { \"test\": \"node --test\" } } 证据：`examples/docs/sandbox-agents/repo/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"financial-research-agent\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx main.ts\" } } 证据：`examples/financial-research-agent/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"handoffs\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@openai/agents-core\": \"workspace: \", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\", \"start:types\": \"tsx types.ts\", \"start:is-enabled\": \"tsx is-enabled.ts\" } } 证据：`examples/handoffs/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"mcp\", \"dependencies\": { \"@modelcontextprotocol/sdk\": \"^1.26.0\", \"@modelcontextprotocol/server-filesystem\": \"^2026.1.14\", \"@openai/agents\": \"workspace: \" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start:stdio\": \"tsx filesystem-example.ts\", \"start:streamable-http\": \"tsx streamable-http-example.ts\", \"start:hosted-mcp-on-approval\": \"tsx hosted-mcp-on-approval.ts\", \"start:hosted-mcp-human-in-the-loop\": \"tsx hosted-mcp-human-in-the-loop.ts\", \"start:hosted-mcp-simple\": \"tsx hosted-mcp-simple.ts\", \"start:tool-filter\": \"tsx tool-filter-example.ts\", \"start:sse\": \"tsx sse-example.ts\", \"start:get-all-tools\": \"tsx get-all-mcp-tools-example.ts\", \"start:mcp-servers\": \"tsx… 证据：`examples/mcp/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"memory\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@prisma/client\": \"^6.18.0\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start:memory\": \"tsx memory.ts\", \"start:memory-hitl\": \"tsx memory-hitl.ts\", \"start:hitl-session-scenario\": \"tsx hitl-session-scenario.ts\", \"start:oai\": \"tsx oai.ts\", \"start:oai-hitl\": \"tsx oai-hitl.ts\", \"start:oai-compact\": \"tsx oai-compact.ts\", \"start:oai-compact-stateless\": \"tsx oai-compact-stateless.ts\", \"start:file\": \"tsx file.ts\", \"start:file-hitl\": \"tsx file-hitl.ts\", \"start:prisma\": \"tsx start-prisma.ts\" }, \"devDependencies\": { \"prisma\": \"^6.18.0\" } } 证据：`examples/memory/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"model-providers\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"openai\": \"^6.35.0\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start:custom-example-agent\": \"tsx custom-example-agent.ts\", \"start:custom-example-global\": \"tsx custom-example-global.ts\", \"start:custom-example-provider\": \"tsx custom-example-provider.ts\" } } 证据：`examples/model-providers/package.json`\n- **Package**（package_manifest）：{ \"name\": \"nextjs\", \"private\": true, \"scripts\": { \"dev\": \"next dev --turbopack\", \"build\": \"next build\", \"start\": \"next start\", \"lint\": \"next lint\", \"build-check\": \"tsc --noEmit\" }, \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@radix-ui/react-dialog\": \"^1.1.14\", \"@radix-ui/react-slot\": \"^1.2.3\", \"@tanstack/react-query\": \"^5.80.7\", \"class-variance-authority\": \"^0.7.1\", \"clsx\": \"^2.1.1\", \"lucide-react\": \"^0.515.0\", \"next\": \"16.2.3\", \"react\": \"^19.0.0\", \"react-dom\": \"^19.0.0\", \"tailwind-merge\": \"^3.3.1\", \"wavtools\": \"^0.1.5\", \"zod\": \"^4.0.0\" }, \"devDependencies\": { \"@tailwindcss/postcss\": \"^4\", \"@types/node\": \"^20\", \"@types/react\": \"^19\", \"@types/react-dom\": \"^19\", \"tailwindcss\": \"^4\", \"… 证据：`examples/nextjs/package.json`\n- **Package**（package_manifest）：{ \"name\": \"realtime-demo\", \"private\": true, \"type\": \"module\", \"scripts\": { \"dev\": \"vite\", \"build-check\": \"tsc --noEmit\", \"build\": \"tsc && vite build\", \"preview\": \"vite preview\", \"generate-token\": \"tsx token.ts\" }, \"devDependencies\": { \"typescript\": \"~5.8.3\", \"vite\": \"^6.4.2\" }, \"dependencies\": { \"@openai/agents-realtime\": \"workspace: \", \"@tailwindcss/vite\": \"^4.1.7\", \"openai\": \"^6.35.0\", \"tailwindcss\": \"^4.1.7\", \"zod\": \"^4.0.0\" } } 证据：`examples/realtime-demo/package.json`\n- **Package**（package_manifest）：{ \"name\": \"realtime-next\", \"private\": true, \"scripts\": { \"dev\": \"next dev --turbopack\", \"build\": \"next build\", \"start\": \"next start\", \"lint\": \"next lint\", \"build-check\": \"tsc --noEmit\" }, \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@radix-ui/react-slot\": \"^1.2.3\", \"class-variance-authority\": \"^0.7.1\", \"clsx\": \"^2.1.1\", \"next\": \"16.2.3\", \"react\": \"^19.0.0\", \"react-dom\": \"^19.0.0\", \"tailwind-merge\": \"^3.3.0\", \"wavtools\": \"^0.1.5\", \"zod\": \"^4.0.0\" }, \"devDependencies\": { \"@tailwindcss/postcss\": \"^4\", \"@types/node\": \"^20\", \"@types/react\": \"^19\", \"@types/react-dom\": \"^19\", \"tailwindcss\": \"^4\", \"typescript\": \"^5\" } } 证据：`examples/realtime-next/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"realtime-twilio-sip\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@openai/agents-core\": \"workspace: \", \"@openai/agents-realtime\": \"workspace: \", \"dotenv\": \"^16.5.0\", \"fastify\": \"^5.8.5\", \"fastify-raw-body\": \"^5.0.0\", \"openai\": \"^6.35.0\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx server.ts\" } } 证据：`examples/realtime-twilio-sip/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"realtime-twilio\", \"dependencies\": { \"@fastify/formbody\": \"^8.0.2\", \"@fastify/websocket\": \"^11.1.0\", \"@openai/agents\": \"workspace: \", \"@openai/agents-extensions\": \"workspace: \", \"dotenv\": \"^16.5.0\", \"fastify\": \"^5.8.5\", \"ws\": \"^8.18.1\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx index.ts\" } } 证据：`examples/realtime-twilio/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"research-bot\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start\": \"tsx main.ts\" } } 证据：`examples/research-bot/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"sandbox\", \"type\": \"module\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@openai/agents-extensions\": \"workspace: \", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start:basic\": \"tsx basic.ts\", \"start:handoffs\": \"tsx handoffs.ts\", \"start:coding-task\": \"tsx coding-task.ts\", \"start:resume\": \"tsx resume.ts\", \"start:memory\": \"tsx memory.ts\", \"start:unix-local-pty\": \"tsx unix-local-pty.ts\", \"start:unix-local-runner\": \"tsx unix-local-runner.ts\", \"start:docker-runner\": \"tsx docker-runner.ts\", \"start:memory-generation\": \"tsx memory-generation.ts\", \"start:memory-multi-agent-multiturn\": \"tsx memory-multi-agent-multiturn.ts\", \"start:sandbox-agent-capa… 证据：`examples/sandbox/package.json`\n- **Package**（package_manifest）：{ \"private\": true, \"name\": \"tools\", \"type\": \"module\", \"dependencies\": { \"@openai/agents\": \"workspace: \", \"@openai/agents-core\": \"workspace: \", \"@openai/agents-extensions\": \"workspace: \", \"@openai/codex-sdk\": \"^0.86.0\", \"chalk\": \"^5.6.2\", \"openai\": \"^6.35.0\", \"playwright\": \"^1.55.1\", \"zod\": \"^4.0.0\" }, \"scripts\": { \"build-check\": \"tsc --noEmit\", \"start:codex\": \"tsx codex.ts\", \"start:codex-same-thread\": \"tsx codex-same-thread.ts\", \"start:computer-use\": \"tsx computer-use.ts\", \"start:computer-use-hitl\": \"tsx computer-use-hitl.ts\", \"start:file-search\": \"tsx file-search.ts\", \"start:tool-search\": \"tsx tool-search.ts\", \"start:web-search\": \"tsx web-search.ts\", \"start:web-search-filters\": \"tsx web-se… 证据：`examples/tools/package.json`\n- **Package**（package_manifest）：{ \"name\": \"bun\", \"module\": \"index.ts\", \"type\": \"module\", \"private\": true, \"scripts\": { \"start\": \"bun run index.ts\", \"start:aisdk\": \"bun run aisdk.ts\", \"start:zod\": \"bun run zod.ts\", \"start:sandbox:unix-local\": \"bun run sandbox-unix-local.ts\" }, \"devDependencies\": { \"@types/bun\": \"latest\" }, \"peerDependencies\": { \"typescript\": \"^5\" }, \"dependencies\": { \"@openai/agents\": \"latest\", \"@openai/agents-extensions\": \"latest\", \"zod\": \"^4\" } } 证据：`integration-tests/bun/package.json`\n- **Package**（package_manifest）：{ \"name\": \"worker\", \"version\": \"0.0.0\", \"private\": true, \"scripts\": { \"deploy\": \"wrangler deploy\", \"dev\": \"wrangler dev\", \"start\": \"wrangler dev\", \"test\": \"vitest\", \"cf-typegen\": \"wrangler types\", \"build\": \"wrangler deploy --dry-run --outdir dist\" }, \"dependencies\": { \"@openai/agents\": \"latest\", \"@openai/agents-extensions\": \"latest\" }, \"devDependencies\": { \"typescript\": \"^5.5.2\", \"wrangler\": \"^4.18.0\" } } 证据：`integration-tests/cloudflare-workers/worker/package.json`\n- **Package**（package_manifest）：{ \"name\": \"deno\", \"private\": true, \"scripts\": { \"start\": \"deno --allow-net --allow-env main.ts\" }, \"dependencies\": { \"@openai/agents\": \"latest\", \"@openai/agents-extensions\": \"latest\", \"zod\": \"^4\" } } 证据：`integration-tests/deno/package.json`\n- 其余 26 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/README.md`, `examples/docs/README.md`, `examples/docs/sandbox-agents/skills/invoice-total-fixer/SKILL.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/README.md`, `examples/docs/README.md`, `examples/docs/sandbox-agents/skills/invoice-total-fixer/SKILL.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Introduction to OpenAI Agents SDK**：importance `high`\n  - source_paths: README.md, packages/agents-core/src/index.ts, package.json\n- **Installation and Setup**：importance `high`\n  - source_paths: packages/agents-core/package.json, packages/agents/package.json, docs/src/content/docs/guides/quickstart.mdx\n- **Examples and Patterns**：importance `high`\n  - source_paths: examples/basic/hello-world.ts, examples/agent-patterns/agents-as-tools.ts, examples/mcp/hosted-mcp-simple.ts\n- **Creating and Running Agents**：importance `high`\n  - source_paths: packages/agents-core/src/agent.ts, packages/agents-core/src/run.ts, packages/agents-core/src/lifecycle.ts, docs/src/content/docs/guides/agents.mdx\n- **Tools and Tool Use**：importance `high`\n  - source_paths: packages/agents-core/src/tool.ts, packages/agents-core/src/mcp.ts, packages/agents-core/src/mcpUtil.ts, packages/agents-core/src/runner/toolExecution.ts, docs/src/content/docs/guides/tools.mdx\n- **Guardrails and Input/Output Validation**：importance `medium`\n  - source_paths: packages/agents-core/src/guardrail.ts, packages/agents-core/src/toolGuardrail.ts, packages/agents-core/src/runner/guardrails.ts, docs/src/content/docs/guides/guardrails.mdx\n- **Handoffs and Multi-Agent Systems**：importance `medium`\n  - source_paths: packages/agents-core/src/handoff.ts, packages/agents-core/src/extensions/handoffFilters.ts, packages/agents-core/src/extensions/handoffPrompt.ts, docs/src/content/docs/guides/handoffs.mdx\n- **Sandbox Agents Architecture**：importance `high`\n  - source_paths: packages/agents-core/src/sandbox/agent.ts, packages/agents-core/src/sandbox/client.ts, packages/agents-core/src/sandbox/capabilities/index.ts, packages/agents-core/src/sandbox/runtime/manager.ts, packages/agents-core/src/sandbox/manifest.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `629d35af99e1ba80fc968b0d062c070caed0683d`\n- inspected_files: `pnpm-lock.yaml`, `package.json`, `README.md`, `docs/tsconfig.scripts.json`, `docs/package.json`, `docs/README.md`, `docs/tsconfig.json`, `docs/src/content.config.ts`, `docs/src/plugins/typedoc-frontmatter.js`, `docs/src/scripts/translate.ts`, `docs/src/content/docs/index.mdx`, `docs/src/content/docs/ja/index.mdx`, `docs/src/content/docs/guides/multi-agent.md`, `docs/src/content/docs/guides/config.mdx`, `docs/src/content/docs/guides/troubleshooting.mdx`, `docs/src/content/docs/guides/context.mdx`, `docs/src/content/docs/guides/models.mdx`, `docs/src/content/docs/guides/handoffs.mdx`, `docs/src/content/docs/guides/sandbox-agents.mdx`, `docs/src/content/docs/guides/human-in-the-loop.mdx`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 仓库名和安装名不一致\n\n- Trigger: 仓库名 `openai-agents-js` 与安装入口 `@openai/agents` 不完全一致。\n- Host AI rule: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Why it matters: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Evidence: identity.distribution | github_repo:993521808 | https://github.com/openai/openai-agents-js | repo=openai-agents-js; install=@openai/agents\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:993521808 | https://github.com/openai/openai-agents-js | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | issue_or_pr_quality=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | release_recency=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：openai/openai-agents-js\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：chatgpt\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 仓库名和安装名不一致（medium）：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 维护活跃度未知（medium）：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项（medium）：下游已经要求复核，不能在页面中弱化。 建议检查：进入安全/权限治理复核队列。\n- 存在评分风险（medium）：风险会影响是否适合普通用户安装。 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/openai/openai-agents-js 项目说明书\n\n生成时间：2026-05-18 04:44:56 UTC\n\n## 目录\n\n- [Introduction to OpenAI Agents SDK](#introduction)\n- [Installation and Setup](#installation)\n- [Examples and Patterns](#examples-overview)\n- [Creating and Running Agents](#agents)\n- [Tools and Tool Use](#tools)\n- [Guardrails and Input/Output Validation](#guardrails)\n- [Handoffs and Multi-Agent Systems](#handoffs)\n- [Sandbox Agents Architecture](#sandbox-architecture)\n- [Sandbox Providers and Extensions](#sandbox-providers)\n- [Voice Agents and Realtime Communication](#voice-realtime)\n\n<a id='introduction'></a>\n\n## Introduction to OpenAI Agents SDK\n\n### 相关页面\n\n相关主题：[Installation and Setup](#installation), [Creating and Running Agents](#agents), [Examples and Patterns](#examples-overview)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/openai/openai-agents-js/blob/main/README.md)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/README.md)\n- [packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n- [packages/agents-extensions/package.json](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/package.json)\n- [packages/agents-realtime/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/README.md)\n- [examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n- [examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n</details>\n\n# Introduction to OpenAI Agents SDK\n\nThe OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows in JavaScript/TypeScript. It provides developers with primitives for creating AI agents that can use tools, handle complex conversations, manage handoffs between agents, and integrate with guardrails for input/output validation.\n\n## Overview\n\nThe SDK is designed to simplify the development of agentic applications by providing:\n\n- **Agent abstraction**: A core `Agent` class that encapsulates instructions, tools, and behaviors\n- **Tool system**: Built-in support for various tool types including function calling, web search, file search, and code execution\n- **Multi-agent orchestration**: Handoff mechanisms for routing conversations between specialized agents\n- **Guardrails**: Input and output validation to ensure safe and appropriate agent responses\n- **Tracing**: Comprehensive span-based telemetry for monitoring agent execution\n- **Streaming support**: Real-time response streaming for interactive applications\n\nThe framework is modular and extensible, allowing developers to pick and choose components based on their use case.\n\n## Package Architecture\n\nThe SDK is organized into multiple packages within a monorepo structure:\n\n```mermaid\ngraph TD\n    A[Application] --> B[@openai/agents]\n    A --> C[@openai/agents-core]\n    A --> D[@openai/agents-extensions]\n    A --> E[@openai/agents-realtime]\n    \n    B --> C\n    B --> D\n    \n    C --> F[agents-openai]\n    \n    D --> G[AI SDK Integration]\n    D --> H[Codex Tool]\n    D --> I[Daytona Sandbox]\n    \n    E --> C\n```\n\n### Package Matrix\n\n| Package | Purpose | Installation |\n|---------|---------|--------------|\n| `@openai/agents` | Main SDK bundle with all features | `npm install @openai/agents` |\n| `@openai/agents-core` | Core agent primitives and interfaces | `npm install @openai/agents` |\n| `@openai/agents-extensions` | Extension features (AI SDK UI, Codex, Sandbox) | `npm install @openai/agents-extensions` |\n| `@openai/agents-realtime` | Voice agent capabilities for realtime sessions | `npm install @openai/agents` |\n| `@openai/agents-openai` | OpenAI-specific implementations | `npm install @openai/agents` |\n\n资料来源：[packages/agents-core/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/README.md), [packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n\n## Core Agent Class\n\nThe `Agent` class is the fundamental building block of the SDK. It extends `AgentHooks` and implements `AgentConfiguration`, providing a comprehensive interface for agent configuration.\n\n资料来源：[packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n\n### Agent Configuration\n\nAgents are configured with the following key options:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | The agent's identifier |\n| `instructions` | `string \\| function` | System prompt or dynamic instruction generator |\n| `tools` | `Tool[]` | Collection of tools the agent can invoke |\n| `handoffs` | `Agent[] \\| Handoff[]` | Agents available for handoff |\n| `outputType` | `AgentOutputType` | Expected output format |\n| `model` | `string \\| Model` | The model to use for this agent |\n| `modelSettings` | `ModelSettings` | Model-specific configuration |\n| `inputGuardrails` | `Guardrail[]` | Validation for incoming messages |\n| `outputGuardrails` | `Guardrail[]` | Validation for agent responses |\n\n资料来源：[packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n\n### Creating an Agent\n\n```typescript\nimport { Agent } from '@openai/agents';\n\nconst agent = new Agent({\n  name: 'Assistant',\n  instructions: 'You are a helpful assistant that responds in concise sentences.',\n  tools: [/* your tools here */],\n});\n```\n\n## Tool System\n\nThe SDK provides a flexible tool system that allows agents to interact with external systems and perform actions.\n\n### Built-in Tool Categories\n\n| Category | Tools | Use Case |\n|----------|-------|----------|\n| **Web** | `webSearchTool`, `webSearchToolWithFilters` | General web queries and filtered searches |\n| **Files** | `fileSearchTool`, `fileSearchWithReferencesTool` | Vector-based file searching |\n| **Code** | `codeInterpreterTool`, `localShellTool`, `containerShellTool` | Code execution and shell commands |\n| **Images** | `imageGenerationTool` | AI image generation |\n| **Computer** | `computerTool` | Browser automation with Playwright |\n| **Codex** | `codexTool` | Code editing and task execution via Codex CLI |\n\n资料来源：[examples/tools/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/tools/README.md)\n\n### Tool Configuration Options\n\nWhen defining tools for an agent, the following options are available:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `toolName` | `string` | Custom name for the tool (defaults to agent name) |\n| `toolDescription` | `string` | Human-readable description of tool behavior |\n| `parameters` | `TParameters` | Zod schema for tool input validation |\n| `needsApproval` | `boolean \\| function` | Require human approval before execution |\n| `customOutputExtractor` | `function` | Custom logic to extract output from tool result |\n| `inputBuilder` | `AgentToolInputBuilder` | Build nested agent input from structured data |\n\n资料来源：[packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n\n## Agent Patterns\n\nThe SDK supports various agent orchestration patterns demonstrated in the examples directory.\n\n资料来源：[examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n\n### Common Patterns\n\n| Pattern | Example | Description |\n|---------|---------|-------------|\n| **Agents as Tools** | `agents-as-tools.ts` | Wrap agents as callable tools for orchestration |\n| **Structured Input** | `agents-as-tools-structured.ts` | Use `Agent.asTool()` with structured input schemas |\n| **Conditional Tools** | `agents-as-tools-conditional.ts` | Enable/disable tools based on context |\n| **Deterministic Flow** | `deterministic.ts` | Fixed agent flow with gating and quality checks |\n| **Human-in-the-Loop** | `human-in-the-loop.ts` | Manual approval for sensitive operations |\n| **Guardrails** | `input-guardrails.ts`, `output-guardrails.ts` | Validate inputs and block unsafe outputs |\n| **LLM as Judge** | `llm-as-a-judge.ts` | Use LLM to evaluate agent outputs |\n\n### Workflow Example\n\n```mermaid\ngraph LR\n    A[User Input] --> B[Input Guardrails]\n    B --> C[Agent Processing]\n    C --> D{Tool Call?}\n    D -->|Yes| E[Execute Tool]\n    E --> C\n    D -->|No| F[Output Guardrails]\n    F --> G[Response to User]\n```\n\n## Extensions Package\n\nThe `@openai/agents-extensions` package provides additional features beyond the core SDK.\n\n资料来源：[packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n\n### Available Exports\n\n| Export | Purpose |\n|--------|---------|\n| `./ai-sdk` | AI SDK integration utilities |\n| `./ai-sdk-ui` | UI framework adapters (Next.js, etc.) |\n| `./experimental/codex` | Experimental Codex CLI tool wrapper |\n\n资料来源：[packages/agents-extensions/package.json](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/package.json)\n\n### AI SDK UI Integration\n\nFor Next.js and similar frameworks, the SDK provides streaming response helpers:\n\n```typescript\nimport { Agent, run } from '@openai/agents';\nimport { createAiSdkTextStreamResponse } from '@openai/agents-extensions/ai-sdk-ui';\n\nexport async function POST() {\n  const agent = new Agent({\n    name: 'Assistant',\n    instructions: 'Reply with a short answer.',\n  });\n\n  const stream = await run(agent, 'Hello there.', { stream: true });\n  return createAiSdkTextStreamResponse(stream);\n}\n```\n\n资料来源：[examples/ai-sdk-ui/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/ai-sdk-ui/README.md)\n\n## Basic Examples\n\nThe SDK includes numerous example scripts demonstrating core functionality:\n\n资料来源：[examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n\n| Example | Command | Demonstrates |\n|---------|---------|--------------|\n| `hello-world.ts` | `pnpm -F basic start:hello-world` | Basic agent that responds in haiku |\n| `chat.ts` | `pnpm -F basic start:chat` | Interactive CLI chat with weather handoff |\n| `stream-text.ts` | `pnpm -F basic start:stream-text` | Plain text response streaming |\n| `stream-items.ts` | `pnpm -F basic start:stream-items` | Event streaming with tool usage |\n| `stream-ws.ts` | `pnpm -F basic start:stream-ws` | WebSocket streaming with HITL approval |\n| `dynamic-system-prompt.ts` | `pnpm -F basic start:dynamic-system-prompt` | Dynamic instructions per run |\n| `lifecycle-example.ts` | `pnpm -F basic start:lifecycle-example` | Detailed lifecycle events and usage |\n| `local-image.ts` | `pnpm -F basic start:local-image` | Sending local images to agents |\n| `image-tool-output.ts` | `pnpm -F basic start:image-tool-output` | Image return from tools |\n\n## Running Examples\n\nThe repository uses `pnpm` as its package manager with workspace-based organization.\n\n```bash\n# Install dependencies\npnpm install\n\n# Run a specific example\npnpm -F basic start:hello-world\npnpm -F basic start:chat\npnpm -F basic start:stream-text\n\n# Run agent pattern examples\npnpm examples:agents-as-tools\npnpm examples:human-in-the-loop\n\n# Run tool integration examples\npnpm examples:tools-web-search\npnpm examples:tools-file-search\npnpm examples:tools-codex\n```\n\n## Installation\n\nThe SDK can be installed via npm:\n\n```bash\n# Core package (includes agents-core, agents-openai)\nnpm install @openai/agents\n\n# Extensions package (requires agents-core)\nnpm install @openai/agents @openai/agents-extensions\n```\n\n资料来源：[README.md](https://github.com/openai/openai-agents-js/blob/main/README.md), [packages/agents-core/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/README.md)\n\n## Summary\n\nThe OpenAI Agents SDK provides a comprehensive framework for building agentic applications:\n\n- **Lightweight and modular**: Pick only the components you need\n- **Type-safe**: Full TypeScript support with generic types\n- **Extensible**: Create custom tools, guardrails, and hooks\n- **Observable**: Built-in tracing with customizable span types\n- **Production-ready**: MIT licensed with streaming and error handling support\n\n---\n\n<a id='installation'></a>\n\n## Installation and Setup\n\n### 相关页面\n\n相关主题：[Introduction to OpenAI Agents SDK](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/README.md)\n- [examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n- [examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n- [examples/sandbox/extensions/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/sandbox/extensions/README.md)\n- [examples/ai-sdk-ui/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/ai-sdk-ui/README.md)\n</details>\n\n# Installation and Setup\n\n## Overview\n\nThe OpenAI Agents SDK provides a modular JavaScript/TypeScript framework for building AI-powered agent applications. The SDK is organized into multiple packages that can be installed independently or together depending on your use case.\n\n资料来源：[packages/agents-extensions/README.md:1-8]()\n\n## Package Architecture\n\nThe SDK consists of several packages published to npm:\n\n| Package | Description | Core Dependency |\n|---------|-------------|-----------------|\n| `@openai/agents` | Main agent runtime and CLI | Yes |\n| `@openai/agents-core` | Core agent abstractions and types | Yes |\n| `@openai/agents-extensions` | Extension features and integrations | No |\n| `@openai/agents-openai` | OpenAI-specific model integrations | No |\n| `@openai/agents-realtime` | Realtime voice agent capabilities | No |\n\n资料来源：[packages/agents-extensions/README.md:1-12]()\n\n## Installation Methods\n\n### Standard Installation\n\nFor most use cases, install the core packages:\n\n```bash\nnpm install @openai/agents @openai/agents-extensions\n```\n\n资料来源：[packages/agents-extensions/README.md:6]()\n\n### With Extensions\n\nInstall additional extension packages based on your requirements:\n\n```bash\n# For AI SDK UI integration\nnpm install @openai/agents-extensions/ai-sdk-ui\n\n# For sandbox execution\nnpm install @openai/agents-extensions/sandbox\n```\n\n资料来源：[examples/ai-sdk-ui/README.md:1-15]()\n\n### Running Examples\n\nThe repository uses `pnpm` as the package manager for running example scripts:\n\n```bash\n# Run a basic example\npnpm -F basic start:hello-world\n\n# Run an agent pattern example\npnpm examples:agents-as-tools\n\n# Run with streaming\npnpm examples:streamed:human-in-the-loop\n```\n\n资料来源：[examples/basic/README.md:1-30]()\n资料来源：[examples/agent-patterns/README.md:1-20]()\n\n## Environment Configuration\n\n### Required Environment Variables\n\n#### OpenAI API Key\n\nSet your OpenAI API key before running any agent:\n\n```bash\nexport OPENAI_API_KEY=sk-...\n```\n\n#### Sandbox Extensions (Optional)\n\nFor sandbox execution features, additional environment variables are required:\n\n```bash\nexport BL_API_KEY=...\nexport BL_WORKSPACE=...\nexport BL_REGION=us-pdx-1\n```\n\n资料来源：[examples/sandbox/extensions/README.md:1-60]()\n\n### Environment File Setup\n\nCreate a `.env.local` file for local development:\n\n```bash\ncat > .env.local <<'EOF'\nOPENAI_API_KEY=your-api-key\nBL_WORKSPACE=your-workspace\nBL_API_KEY=your-api-key\nBL_REGION=us-pdx-1\nEOF\n\nset -a\nsource .env.local\nset +a\n```\n\n资料来源：[examples/sandbox/extensions/README.md:40-58]()\n\n## Project Structure\n\nWhen using the SDK in your project, the typical structure is:\n\n```mermaid\ngraph TD\n    A[Your Project] --> B[Install SDK]\n    B --> C[Configure Environment]\n    C --> D[Create Agent Instance]\n    D --> E[Add Tools & Guardrails]\n    E --> F[Run Agent]\n    \n    G[agents-core] --> H[Core Abstractions]\n    G --> I[Tool Definitions]\n    G --> J[Runner Logic]\n    \n    K[agents-extensions] --> L[Sandbox Integration]\n    K --> M[AI SDK UI]\n    K --> N[Daytona Support]\n```\n\n## Quick Start Workflow\n\n```mermaid\ngraph LR\n    A[Initialize Agent] --> B[Configure Model]\n    B --> C[Add Instructions]\n    C --> D[Register Tools]\n    D --> E[Execute Run]\n    E --> F[Process Output]\n    \n    A1[Agent Class] --> |config| B1\n    B1[Model Settings] --> |settings| C1\n    C1[Instructions] --> |prompt| D1\n    D1[Tools] --> |functions| E1\n    E1[Runner.run] --> |stream| F1\n```\n\n## TypeScript Configuration\n\nThe SDK is written in TypeScript and ships with type definitions. Ensure your `tsconfig.json` includes:\n\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"esModuleInterop\": true\n  }\n}\n```\n\n## Verifying Installation\n\nAfter installation, verify the setup by running a basic example:\n\n```bash\npnpm -F basic start:hello-world\n```\n\nExpected output: A response from the agent in haiku format.\n\n资料来源：[examples/basic/README.md:5-7]()\n\n## SDK Package Dependencies\n\n### Core Packages\n\nThe `agents` package depends on `agents-core`:\n\n```json\n{\n  \"dependencies\": {\n    \"@openai/agents-core\": \"workspace:*\"\n  }\n}\n```\n\n### Extension Packages\n\nExtensions are designed to be optional and do not require `agents-core` directly:\n\n```mermaid\ngraph TD\n    A[Your App] --> B[@openai/agents]\n    A --> C[@openai/agents-extensions]\n    B --> D[@openai/agents-core]\n    C --> D\n    C --> E[Optional: AI SDK]\n```\n\n## Next Steps\n\nAfter completing installation and setup:\n\n1. Review the [Agent Configuration](./agent-configuration.md) documentation\n2. Explore available [Tools](./tools.md)\n3. Implement [Guardrails](./guardrails.md) for input/output validation\n4. Set up [Handoffs](./handoffs.md) for multi-agent orchestration\n\n---\n\n<a id='examples-overview'></a>\n\n## Examples and Patterns\n\n### 相关页面\n\n相关主题：[Introduction to OpenAI Agents SDK](#introduction), [Creating and Running Agents](#agents), [Tools and Tool Use](#tools)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [examples/basic/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/basic/README.md)\n- [examples/agent-patterns/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/agent-patterns/README.md)\n- [examples/tools/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/tools/README.md)\n- [examples/research-bot/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/research-bot/README.md)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/tool.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/tool.ts)\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n- [packages/agents-realtime/src/realtimeAgent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeAgent.ts)\n</details>\n\n# Examples and Patterns\n\nThis page documents the example applications and architectural patterns demonstrated in the OpenAI Agents SDK for JavaScript/TypeScript. These examples serve as practical guides for building AI-powered applications using the `@openai/agents-core` package.\n\n## Overview\n\nThe repository organizes examples into distinct categories that demonstrate different aspects of agent development:\n\n| Category | Location | Purpose |\n|----------|----------|---------|\n| Basic Examples | `examples/basic/` | Core functionality and getting started |\n| Agent Patterns | `examples/agent-patterns/` | Common architectural patterns |\n| Tool Integrations | `examples/tools/` | Hosted tool usage |\n| Research Bot | `examples/research-bot/` | Multi-agent orchestration |\n| MCP Examples | `examples/mcp/` | Model Context Protocol integration |\n\n## Basic Examples\n\nThe Basic Examples directory provides foundational examples for understanding the Agents SDK core concepts.\n\n### Hello World\n\nA minimal agent that responds with a haiku, demonstrating the simplest possible agent setup.\n\n```bash\npnpm -F basic start:hello-world\n```\n\nThis example shows:\n- Creating an `Agent` instance with instructions\n- Running the agent with `run()` \n- Basic text output handling\n\n### Interactive Chat\n\nAn interactive CLI chat application that demonstrates:\n- Real-time user input handling\n- Streaming responses\n- Handoff integration with weather queries\n\n```bash\npnpm -F basic start:chat\n```\n\n### Streaming Examples\n\nThe SDK supports multiple streaming modes for different use cases:\n\n| Example | Command | Description |\n|---------|---------|-------------|\n| stream-text | `pnpm -F basic start:stream-text` | Plain text streaming |\n| stream-items | `pnpm -F basic start:stream-items` | Event streaming with tool usage |\n| stream-ws | `pnpm -F basic start:stream-ws` | WebSocket streaming with HITL approval |\n\n```bash\npnpm -F basic start:stream-text\npnpm -F basic start:stream-items\npnpm -F basic start:stream-ws\n```\n\n### Dynamic System Prompt\n\nDemonstrates runtime instruction modification using the `input_guardrails` pattern to pick instructions dynamically per run.\n\n```bash\npnpm -F basic start:dynamic-system-prompt\n```\n\n### Lifecycle Hooks\n\nTwo examples demonstrate the event hook system:\n\n- `lifecycle-example.ts` - Logs detailed lifecycle events and usage statistics\n- `agent-lifecycle-example.ts` - Minimal lifecycle hooks demonstration\n\n```bash\npnpm -F basic start:lifecycle-example\npnpm -F basic start:agent-lifecycle-example\n```\n\n### Image Handling\n\n| Example | Purpose |\n|---------|---------|\n| `local-image.ts` | Send local images to the agent |\n| `image-tool-output.ts` | Return images from tools for agent analysis |\n\n```bash\npnpm -F basic start:local-image\npnpm -F basic start:image-tool-output\n```\n\n## Agent Patterns\n\nThe Agent Patterns directory demonstrates common architectural patterns for building sophisticated AI applications.\n\n### Agents as Tools Pattern\n\nThe most important pattern - enabling agents to be used as tools by other agents. This enables hierarchical agent architectures.\n\n```bash\npnpm examples:agents-as-tools\n```\n\n#### Key Files\n\n- `agents-as-tools.ts` - Orchestrate translator agents using them as tools\n- `agents-as-tools-structured.ts` - Use structured tool input with `Agent.asTool()`\n- `agents-as-tools-conditional.ts` - Enable language tools based on user preference\n\n#### Implementation Pattern\n\n```typescript\n// From agents-as-tools.ts - Agents can be wrapped as tools\nconst translatorAgent = Agent.make({\n  name: 'translator',\n  instructions: 'Translate text between languages',\n});\n\nconst translatorTool = translatorAgent.asTool({\n  toolName: 'translate',\n  toolDescription: 'Translate text to a target language',\n});\n```\n\n资料来源：[examples/agent-patterns/agents-as-tools.ts]()\n\nThe `Agent.asTool()` method creates a `FunctionTool` that wraps the agent, allowing other agents to invoke it with typed parameters.\n\n### Deterministic Flow Pattern\n\nFixed agent flow with gating and quality checks for controlled execution paths.\n\n```bash\npnpm examples:deterministic\n```\n\n### Tool Forcing Pattern\n\nRequires specific tools to be called before final output is generated.\n\n```bash\npnpm -F agent-patterns start:forcing-tool-use\n```\n\n### Human-in-the-Loop (HITL) Pattern\n\nHuman approval integration for sensitive operations:\n\n| Example | Command | Use Case |\n|---------|---------|----------|\n| `human-in-the-loop.ts` | `pnpm examples:human-in-the-loop` | Manual approval |\n| `human-in-the-loop-stream.ts` | `pnpm examples:streamed:human-in-the-loop` | Streaming approval |\n\n```bash\npnpm examples:human-in-the-loop\npnpm examples:streamed:human-in-the-loop\n```\n\n### Guardrails Pattern\n\nInput and output validation to control agent behavior:\n\n| Example | Purpose |\n|---------|---------|\n| `input-guardrails.ts` | Reject unwanted requests before processing |\n| `output-guardrails.ts` | Block unsafe output |\n\n```bash\npnpm examples:input-guardrails\npnpm examples:output-guardrails\n```\n\n### LLM-as-Judge Pattern\n\nSelf-evaluation and iteration using a secondary LLM to judge outputs.\n\n```bash\npnpm -F agent-patterns start:llm-as-a-judge\n```\n\n## Tool Integrations\n\nThe Tools Examples directory demonstrates hosted tools provided by the SDK.\n\n### Computer Use Tool\n\nBrowser automation using Playwright for GUI interaction:\n\n```bash\npnpm examples:tools-computer-use\n```\n\n### File Search Tool\n\nVector search integration for document retrieval:\n\n```bash\npnpm examples:tools-file-search\n```\n\n### Tool Search (Deferred Loading)\n\nDemonstrates namespace loading and selective tool loading:\n\n```bash\npnpm examples:tools-tool-search\n```\n\nKey concepts:\n- `deferLoading: true` for lazy tool loading\n- Namespace-based tool organization\n- Selective tool loading per context\n\n### Codex Tool\n\nCode execution and analysis using the Codex CLI:\n\n| Example | Purpose |\n|---------|---------|\n| `codex.ts` | Streaming event logs and skill usage |\n| `codex-same-thread.ts` | Reuse Codex thread across turns |\n\n```bash\npnpm examples:tools-codex\npnpm examples:tools-codex-same-thread\n```\n\nEnvironment variables:\n- `CODEX_API_KEY` - Primary API key\n- `OPENAI_API_KEY` - Fallback API key\n- `CODEX_PATH` - Override Codex CLI path\n\n### Web Search Tool\n\nGeneral web queries using `webSearchTool`:\n\n```bash\npnpm examples:tools-web-search\n```\n\n### Code Interpreter\n\nSecure code execution environment:\n\n```bash\npnpm -F tools start:code-interpreter\n```\n\n### Image Generation\n\nDALL-E integration for image generation:\n\n```bash\npnpm examples:tools-image-generation\n```\n\n## Multi-Agent Orchestration\n\n### Research Bot Example\n\nA complete example demonstrating multi-agent coordination to produce research reports.\n\n#### Architecture\n\n```mermaid\ngraph TD\n    A[User Query] --> B[ResearchManager]\n    B --> C[Planner Agent]\n    C -->|Search Terms| D[Search Agent]\n    D --> E[Web Search Tool]\n    E --> D\n    D -->|Summaries| B\n    B --> F[Writer Agent]\n    F -->|Research Report| A\n```\n\n#### Components\n\n| File | Role |\n|------|------|\n| `main.ts` | CLI entrypoint |\n| `manager.ts` | Coordinates workflow stages |\n| `agents.ts` | Agent definitions |\n\n资料来源：[examples/research-bot/README.md]()\n\n#### Usage\n\n```bash\npnpm examples:research-bot\n```\n\n## Realtime Agents\n\nSpecialized agents for voice applications using the Realtime API.\n\n### Configuration Differences\n\nRealtime agents have limited configuration compared to standard agents:\n\n| Supported | Not Supported |\n|-----------|---------------|\n| `name` | `model` |\n| `handoffs` | `modelSettings` |\n| `voice` | `toolUseBehavior` |\n| | `outputGuardrails` |\n| | `inputGuardrails` |\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts]()\n\n## Lifecycle Events\n\nThe SDK provides comprehensive event hooks for monitoring agent execution:\n\n### Agent-Level Events\n\n| Event | Parameters | Description |\n|-------|------------|-------------|\n| `agent_start` | `context, agent, turnInput?` | Agent begins execution |\n| `agent_end` | `context, agent, output` | Agent completes |\n| `agent_handoff` | `context, fromAgent, toAgent` | Agent transfers control |\n| `agent_tool_start` | `context, agent, tool, details` | Tool invocation begins |\n| `agent_tool_end` | `context, agent, tool, result, details` | Tool invocation completes |\n\n资料来源：[packages/agents-core/src/lifecycle.ts]()\n\n### Event Handler Pattern\n\n```typescript\nagent.addHook('agent_start', async (context, agent) => {\n  console.log(`Starting agent: ${agent.name}`);\n});\n```\n\n## Common Patterns Summary\n\n### Pattern: Agent-as-Tool Hierarchy\n\n```mermaid\ngraph BT\n    A[Orchestrator Agent] -->|calls| B[Specialist Agent 1]\n    A -->|calls| C[Specialist Agent 2]\n    B -->|uses| D[Tool: Translation]\n    C -->|uses| E[Tool: Search]\n```\n\n### Pattern: Human-in-the-Loop\n\n```mermaid\ngraph LR\n    A[Agent] -->|tool call| B{Approval Gate}\n    B -->|approve| C[Execute Tool]\n    B -->|reject| D[Return Error]\n    C --> E[Continue Run]\n```\n\n### Pattern: Error Handling with Handlers\n\nThe SDK supports custom error handlers for:\n\n- `MaxTurnsExceededError` - Turn limit exceeded\n- `ModelRefusalError` - Model refused to respond\n\n```typescript\ntype RunErrorHandler<TContext, TAgent> = (input: {\n  error: MaxTurnsExceededError | ModelRefusalError;\n  context: RunContext<TContext>;\n  runData: RunErrorData<TContext, TAgent>;\n}) => RunErrorHandlerResult<TAgent> | void;\n```\n\n资料来源：[packages/agents-core/src/runner/errorHandlers.ts]()\n\n## Running Examples\n\nAll examples use `pnpm` for execution:\n\n```bash\n# From repository root\npnpm examples:<example-name>\n\n# Or with package-specific commands\npnpm -F <package-name> start:<script-name>\n```\n\n### Example Commands Reference\n\n| Category | Example | Command |\n|----------|---------|---------|\n| Basic | Hello World | `pnpm -F basic start:hello-world` |\n| Basic | Chat | `pnpm -F basic start:chat` |\n| Basic | Streaming | `pnpm -F basic start:stream-items` |\n| Patterns | Agents as Tools | `pnpm examples:agents-as-tools` |\n| Patterns | Human in Loop | `pnpm examples:human-in-the-loop` |\n| Patterns | Guardrails | `pnpm examples:input-guardrails` |\n| Tools | Web Search | `pnpm examples:tools-web-search` |\n| Tools | Code Interpreter | `pnpm -F tools start:code-interpreter` |\n| Research | Multi-Agent | `pnpm examples:research-bot` |\n\n## Key APIs Demonstrated\n\n### Agent Creation\n\n```typescript\nconst agent = Agent.make({\n  name: 'agent-name',\n  instructions: 'System prompt or instructions',\n  handoffs: [otherAgent],\n  tools: [someTool],\n  outputType: TextOutput,\n});\n```\n\n### Tool Creation\n\n```typescript\nconst tool = tool({\n  name: 'tool-name',\n  description: 'What this tool does',\n  parameters: z.object({ ... }),\n  strict: true,\n})(async (context, { param }) => {\n  return 'result';\n});\n```\n\n### Handoff Configuration\n\n```typescript\nconst handoff = new Handoff(agent, {\n  onHandoff: async (context, input) => {\n    // Custom handoff logic\n  },\n});\n```\n\n资料来源：[packages/agents-core/src/handoff.ts]()\n\n## See Also\n\n- [Agent SDK Documentation](https://github.com/openai/openai-agents-js)\n- [@openai/agents-core Package](packages/agents-core/)\n- [@openai/agents-realtime Package](packages/agents-realtime/)\n- [API Reference](packages/agents-core/src/)\n\n---\n\n<a id='agents'></a>\n\n## Creating and Running Agents\n\n### 相关页面\n\n相关主题：[Tools and Tool Use](#tools), [Guardrails and Input/Output Validation](#guardrails), [Handoffs and Multi-Agent Systems](#handoffs)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/run.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/run.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/tool.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/tool.ts)\n- [packages/agents-core/src/runner/errorHandlers.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/errorHandlers.ts)\n</details>\n\n# Creating and Running Agents\n\n## Overview\n\nAgents are the core building blocks of the OpenAI Agents SDK. An agent is an AI model configured with instructions (system prompt), tools, guardrails, handoffs, and other settings that determine its behavior during execution. The SDK provides a flexible `Agent` class that supports various configuration options for different use cases.\n\nAgents are designed to be composable — they can be chained together through handoffs, used as tools by other agents, and integrated into complex workflows. Each agent maintains its own configuration and can emit lifecycle events for monitoring and debugging.\n\n资料来源：[packages/agents-core/src/agent.ts:117-127]()\n\n## Agent Architecture\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Agent Runner]\n    B --> C[Model Execution]\n    C --> D{Tool Calls?}\n    D -->|Yes| E[Tool Executor]\n    E --> F[Tool Result]\n    F --> C\n    D -->|No| G[Output Generation]\n    G --> H[Final Output]\n    \n    subgraph \"Agent Components\"\n        I[Instructions/System Prompt]\n        J[Tools]\n        K[Handoffs]\n        L[Guardrails]\n        M[Output Type]\n    end\n    \n    B -.->|configures| I\n    B -.->|uses| J\n    B -.->|enables| K\n    B -.->|validates via| L\n    B -.->|produces| M\n```\n\n## Agent Configuration\n\n### Basic Configuration Parameters\n\nThe `Agent` class accepts a configuration object that defines its behavior. The main configuration interface is `AgentConfiguration<TContext, TOutput>`.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `name` | `string` | Yes | A unique identifier for the agent |\n| `instructions` | `string \\| function` | Recommended | The system prompt that guides agent behavior |\n| `handoffDescription` | `string` | No | Human-readable description for handoffs |\n| `tools` | `Tool[]` | No | Array of tools the agent can use |\n| `handoffs` | `Agent[] \\| Handoff[]` | No | Other agents the agent can transfer control to |\n| `outputType` | `AgentOutputType` | No | Expected output format |\n| `model` | `string` | No | The model to use (defaults to `gpt-4o`) |\n| `modelSettings` | `ModelSettings` | No | Additional model configuration |\n| `inputGuardrails` | `InputGuardrail[]` | No | Validation before agent execution |\n| `outputGuardrails` | `OutputGuardrail[]` | No | Validation after agent execution |\n\n资料来源：[packages/agents-core/src/agent.ts:1-150]()\n\n### Output Types\n\nAgents support different output types defined by the `AgentOutputType` union:\n\n| Output Type | Description |\n|-------------|-------------|\n| `TextOutput` | Plain text response (default) |\n| `JsonOutput` | Structured JSON response |\n| Custom types | User-defined output schemas |\n\n```typescript\nimport { Agent, TextOutput, JsonOutput } from '@openai/agents';\n\n// Text output agent (default)\nconst textAgent = new Agent({ name: 'text-agent', instructions: '...' });\n\n// JSON output agent\nconst jsonAgent = new Agent({\n  name: 'json-agent',\n  instructions: '...',\n  outputType: JsonOutput,\n});\n```\n\n## Creating an Agent\n\n### Basic Agent Creation\n\nThe simplest agent requires only a name and instructions:\n\n```typescript\nimport { Agent } from '@openai/agents';\n\nconst agent = new Agent({\n  name: 'my-agent',\n  instructions: 'You are a helpful assistant.',\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:128-150]()\n\n### Agent with Tools\n\nTools extend agent capabilities by allowing it to perform actions:\n\n```typescript\nimport { Agent, Tool } from '@openai/agents';\n\nconst myTool = Tool.from({\n  name: 'calculator',\n  description: 'Perform mathematical calculations',\n  parameters: {\n    type: 'object',\n    properties: {\n      expression: { type: 'string', description: 'Math expression' },\n    },\n    required: ['expression'],\n  },\n  invoke: async (runContext, input) => {\n    const { expression } = JSON.parse(input);\n    return eval(expression).toString();\n  },\n});\n\nconst agentWithTools = new Agent({\n  name: 'math-assistant',\n  instructions: 'Use the calculator for complex math.',\n  tools: [myTool],\n});\n```\n\n资料来源：[packages/agents-core/src/tool.ts:1-80]()\n\n### Agent with Handoffs\n\nHandoffs enable transfer of control between agents:\n\n```typescript\nimport { Agent, Handoff } from '@openai/agents';\n\nconst salesAgent = new Agent({\n  name: 'sales',\n  instructions: 'Handle sales inquiries.',\n});\n\nconst supportAgent = new Agent({\n  name: 'support',\n  instructions: 'Handle support requests.',\n});\n\nconst routerAgent = new Agent({\n  name: 'router',\n  instructions: 'Route to the appropriate department.',\n  handoffs: [salesAgent, supportAgent],\n});\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:1-80]()\n\n### Handoff Configuration\n\nThe `HandoffConfig` type provides additional options for handoff behavior:\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `toolNameOverride` | `string` | Custom name for the handoff tool |\n| `toolDescriptionOverride` | `string` | Custom description for the handoff |\n| `onHandoff` | `OnHandoffCallback` | Callback function executed during handoff |\n| `inputJsonSchema` | `JsonSchema` | Schema for handoff input validation |\n\n```typescript\nimport { Handoff } from '@openai/agents';\n\nconst configuredHandoff = new Handoff(supportAgent, async (context) => {\n  console.log(`Handing off to support for session ${context.threadId}`);\n  return supportAgent;\n});\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:80-120]()\n\n### Agents as Tools\n\nAgents can be used as tools by other agents using `Agent.asTool()`:\n\n```typescript\nconst translatorAgent = new Agent({\n  name: 'translator',\n  instructions: 'Translate text to the target language.',\n});\n\nconst mainAgent = new Agent({\n  name: 'main',\n  instructions: 'Use the translator for language tasks.',\n  tools: [\n    translatorAgent.asTool({\n      toolName: 'translate',\n      toolDescription: 'Translate text between languages',\n      parameters: {\n        type: 'object',\n        properties: {\n          text: { type: 'string' },\n          targetLanguage: { type: 'string' },\n        },\n      },\n    }),\n  ],\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:150-200]()\n\n## Running Agents\n\n### Basic Run\n\nExecute an agent using the `run()` function:\n\n```typescript\nimport { Agent, run } from '@openai/agents';\n\nconst agent = new Agent({\n  name: 'hello-agent',\n  instructions: 'Respond in haiku format.',\n});\n\nconst result = await run(agent, 'Tell me about dogs');\nconsole.log(result.finalOutput);\n```\n\n### Run with Options\n\nThe `run()` function accepts additional options:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `context` | `TContext` | Mutable context object passed to tools |\n| `stream` | `boolean` | Enable streaming response |\n| `maxTurns` | `number` | Maximum agent turns before stopping |\n| `model` | `string` | Override the agent's default model |\n| `modelSettings` | `ModelSettings` | Override model settings |\n| `tools` | `Tool[]` | Additional tools to include |\n| `outputType` | `AgentOutputType` | Override output type |\n\n```typescript\nconst result = await run(agent, 'Process this request', {\n  context: { userId: '123' },\n  maxTurns: 10,\n  modelSettings: { temperature: 0.7 },\n});\n```\n\n### Streaming Responses\n\nEnable streaming for real-time output:\n\n```typescript\nconst stream = await run(agent, 'Generate a long story', { stream: true });\n\nfor await (const event of stream) {\n  if (event.type === 'agent_update') {\n    console.log(event.data);\n  }\n}\n```\n\n## Agent Lifecycle\n\n### Lifecycle Events\n\nAgents emit events throughout their execution lifecycle. The `AgentHooks` class extends `EventEmitterDelegate` to provide event handling.\n\n```mermaid\nstateDiagram-v2\n    [*] --> start: agent_start\n    start --> tool_use: tool call required\n    start --> end: direct response\n    tool_use --> tool_execution: agent_tool_start\n    tool_execution --> tool_complete: agent_tool_end\n    tool_complete --> start: continue\n    tool_complete --> end: no more tools\n    end --> [*]: agent_end\n    \n    start --> handoff: handoff trigger\n    handoff --> [*]: agent_handoff\n```\n\n### Available Lifecycle Events\n\n| Event | Parameters | Description |\n|-------|------------|-------------|\n| `agent_start` | `context, agent, turnInput?` | Fired when agent execution begins |\n| `agent_end` | `context, agent, output` | Fired when agent execution completes |\n| `agent_handoff` | `context, fromAgent, toAgent` | Fired during agent transfer |\n| `agent_tool_start` | `context, tool, details` | Fired when a tool begins |\n| `agent_tool_end` | `context, tool, result, details` | Fired when a tool completes |\n\n```typescript\nconst agent = new Agent({\n  name: 'monitored-agent',\n  instructions: 'You are helpful.',\n});\n\nagent.on('agent_start', (context, agent) => {\n  console.log(`Starting agent: ${agent.name}`);\n});\n\nagent.on('agent_tool_start', (context, tool, details) => {\n  console.log(`Tool called: ${tool.name}`);\n});\n\nagent.on('agent_end', (context, agent, output) => {\n  console.log(`Agent finished with: ${output}`);\n});\n```\n\n资料来源：[packages/agents-core/src/lifecycle.ts:1-100]()\n\n### Run-Level Hooks\n\nIn addition to agent hooks, you can register hooks at the run level:\n\n```typescript\nimport { Agent, run, RunHookEvents } from '@openai/agents';\n\nconst hooks: RunHookEvents = {\n  onAgentStart: async (context, agent) => {\n    console.log(`Run starting with agent: ${agent.name}`);\n  },\n  onAgentEnd: async (context, agent, output) => {\n    console.log(`Run completed with output: ${output}`);\n  },\n};\n\nconst result = await run(agent, input, { hooks });\n```\n\n## Context Management\n\n### Run Context\n\nThe `RunContext` provides a mechanism to pass and share state across tools, guardrails, and handoffs:\n\n```typescript\nimport { Agent, run, RunContext } from '@openai/agents';\n\ninterface MyContext {\n  userId: string;\n  sessionData: Record<string, any>;\n}\n\nconst agent = new Agent<MyContext>({\n  name: 'context-agent',\n  instructions: 'You are a personalized assistant.',\n});\n\nconst result = await run(agent, 'Hello', {\n  context: {\n    userId: 'user-123',\n    sessionData: { lastVisit: Date.now() },\n  },\n});\n\n// Access context in tools\nconst myTool = Tool.from({\n  name: 'user-info',\n  description: 'Get user information',\n  invoke: async (runContext, input) => {\n    return runContext.context.userId;\n  },\n});\n```\n\n### Tool Input Capture\n\nThe SDK can capture tool input into the run context for debugging and logging:\n\n```typescript\nconst tool = Tool.from({\n  name: 'search',\n  description: 'Search the web',\n  parameters: { /* schema */ },\n  invoke: async (runContext, input, details) => {\n    // The SDK can capture input when shouldCaptureToolInput is enabled\n    const capturedInput = runContext.toolInput;\n    console.log(`Search called with: ${capturedInput}`);\n    return 'results';\n  },\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:200-280]()\n\n## Error Handling\n\n### Error Handlers\n\nThe SDK provides structured error handling through `RunErrorHandler` types:\n\n| Error Type | Description |\n|------------|-------------|\n| `MaxTurnsExceededError` | Maximum turns limit reached |\n| `ModelRefusalError` | Model refused to respond |\n\n```typescript\nimport { Agent, run, RunErrorHandlers } from '@openai/agents';\n\nconst errorHandlers: RunErrorHandlers = {\n  onMaxTurnsExceeded: async ({ error, context, runData }) => {\n    return {\n      finalOutput: 'The conversation reached its maximum length.',\n      includeInHistory: true,\n    };\n  },\n  onModelRefusal: async ({ error, context, runData }) => {\n    return {\n      finalOutput: 'I apologize, but I cannot help with that request.',\n      includeInHistory: false,\n    };\n  },\n  default: async ({ error }) => {\n    return {\n      finalOutput: 'An unexpected error occurred.',\n      includeInHistory: true,\n    };\n  },\n};\n\nconst result = await run(agent, input, { errorHandlers });\n```\n\n资料来源：[packages/agents-core/src/runner/errorHandlers.ts:1-80]()\n\n## Agent Factory Method\n\n### Static `create()` Method\n\nThe `Agent.create()` static method provides type-safe agent creation with automatic output type inference:\n\n```typescript\nimport { Agent } from '@openai/agents';\n\n// Create agent with handoffs - output type is inferred\nconst agent = Agent.create({\n  name: 'orchestrator',\n  instructions: 'Route requests appropriately.',\n  handoffs: [\n    salesAgent,           // outputs: TextOutput\n    billingAgent,         // outputs: JsonOutput\n  ],\n  // TOutput is automatically inferred as: TextOutput | JsonOutput\n});\n```\n\n资料来源：[packages/agents-core/src/agent.ts:140-180]()\n\n## Complete Example\n\n```typescript\nimport { Agent, run, Tool } from '@openai/agents';\n\n// Define tools\nconst searchTool = Tool.from({\n  name: 'web_search',\n  description: 'Search the web for information',\n  parameters: {\n    type: 'object',\n    properties: {\n      query: { type: 'string' },\n    },\n    required: ['query'],\n  },\n  strict: true,\n  invoke: async (runContext, input) => {\n    const { query } = JSON.parse(input);\n    return `Results for: ${query}`;\n  },\n});\n\n// Define agents\nconst researchAgent = new Agent({\n  name: 'researcher',\n  instructions: 'Use web search to gather information.',\n  tools: [searchTool],\n});\n\nconst writerAgent = new Agent({\n  name: 'writer',\n  instructions: 'Write clear, concise summaries.',\n});\n\n// Orchestrator agent\nconst orchestrator = new Agent({\n  name: 'orchestrator',\n  instructions: 'Delegate research and writing tasks.',\n  handoffs: [researchAgent, writerAgent],\n});\n\n// Register lifecycle hooks\norchestrator.on('agent_start', (ctx, agent) => {\n  console.log(`Starting: ${agent.name}`);\n});\n\norchestrator.on('agent_handoff', (ctx, from, to) => {\n  console.log(`Handoff: ${from.name} → ${to.name}`);\n});\n\n// Run the agent\nconst result = await run(orchestrator, 'Research and write about AI');\nconsole.log(result.finalOutput);\n```\n\n## Summary\n\nThe OpenAI Agents SDK provides a flexible and extensible framework for creating and running AI agents:\n\n| Feature | Description |\n|---------|-------------|\n| **Agent Configuration** | Flexible configuration with instructions, tools, handoffs, and guardrails |\n| **Tool Integration** | Define custom tools with typed parameters and validation |\n| **Handoffs** | Transfer control between agents seamlessly |\n| **Lifecycle Events** | Monitor and debug agent execution |\n| **Context Management** | Share state across tools and handoffs |\n| **Error Handling** | Gracefully handle errors with custom handlers |\n| **Streaming** | Support for real-time streaming responses |\n\nAll agents are built on the core `Agent` class which implements the `AgentConfiguration` interface, providing consistency and predictability across the SDK.\n\n---\n\n<a id='tools'></a>\n\n## Tools and Tool Use\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/tool.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/tool.ts)\n- [packages/agents-core/src/mcp.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/mcp.ts)\n- [packages/agents-core/src/mcpUtil.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/mcpUtil.ts)\n- [packages/agents-core/src/runner/toolExecution.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/toolExecution.ts)\n- [packages/agents-core/src/runner/toolSearch.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/toolSearch.ts)\n</details>\n\n# Tools and Tool Use\n\n## Overview\n\nTools extend an agent's capabilities by allowing it to interact with external systems, execute code, search for information, and perform actions beyond text generation. In the OpenAI Agents SDK, tools are defined as first-class constructs that agents can invoke during their reasoning loops. When an agent decides to use a tool, the SDK handles the execution, processes the results, and feeds them back to the agent for continued decision-making.\n\nThe tool system supports multiple tool types including function tools, hosted tools, computer tools (for browser automation), shell tools, and MCP (Model Context Protocol) tools. Each tool type has specific use cases and integration patterns.\n\n资料来源：[packages/agents-core/src/tool.ts:1-50]()\n\n## Tool Types\n\nThe SDK defines several distinct tool types through a discriminated union. Understanding these types is essential for selecting the appropriate tool for a given task.\n\n| Tool Type | Description | Use Case |\n|-----------|-------------|----------|\n| `function` | Custom JavaScript functions exposed to the agent | Custom logic, API calls, data processing |\n| `hosted_tool` | Tools provided by external services (MCP, web search, etc.) | Third-party integrations |\n| `computer` | Browser automation via Playwright | Web interactions, UI testing |\n| `shell` | Command-line execution | System operations, script running |\n| `apply_patch` | Code modification operations | Automated code editing |\n\n资料来源：[packages/agents-core/src/tool.ts:60-120]()\n\n### Function Tools\n\nFunction tools are the most common tool type. They wrap JavaScript functions with metadata that allows the agent to understand when and how to call them.\n\n```typescript\ntype FunctionTool<\n  Context = UnknownContext,\n  TParameters extends ToolInputParameters = undefined,\n  Result = unknown,\n> = {\n  type: 'function';\n  name: string;\n  description: string;\n  parameters: JsonObjectSchema<any>;\n  strict: boolean;\n  deferLoading?: boolean;\n  invoke: (\n    runContext: RunContext<Context>,\n    input: string,\n    details?: ToolCallDetails,\n  ) => Promise<string | Result>;\n  needsApproval?: boolean | ToolApprovalFunction<TParameters>;\n};\n```\n\n资料来源：[packages/agents-core/src/tool.ts:60-85]()\n\n### Hosted Tools\n\nHosted tools represent external services that the agent can invoke. They include a `providerData` field for additional configuration and support for custom executors.\n\n```typescript\nexport type HostedTool = {\n  type: 'hosted_tool';\n  name: string;\n  providerData?: Record<string, any>;\n};\n```\n\n资料来源：[packages/agents-core/src/tool.ts:140-150]()\n\n## Tool Configuration Options\n\n### Basic Configuration\n\nWhen defining a tool, several configuration options control its behavior:\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `name` | `string` | (required) | Unique identifier for the tool |\n| `description` | `string` | (required) | Human-readable description for the agent |\n| `parameters` | `JsonObjectSchema` | `{ input: string }` | JSON Schema for input validation |\n| `strict` | `boolean` | `false` | Enforce strict schema following |\n| `deferLoading` | `boolean` | `false` | Defer tool loading until needed |\n| `needsApproval` | `boolean \\| Function` | `false` | Require human approval before execution |\n\n资料来源：[packages/agents-core/src/tool.ts:70-95]()\n\n### Namespace Support\n\nTools can be grouped into namespaces to organize related functionality:\n\n```typescript\nconst tool = FunctionTool.create({\n  name: 'search',\n  description: 'Search for information',\n  parameters: z.object({ query: z.string() }),\n  namespace: 'search_tools',\n  namespaceDescription: 'Tools for searching various sources',\n});\n```\n\nNamespaces are useful when you have many tools and want to help the agent understand logical groupings. All tools within a namespace must share the same description.\n\n资料来源：[packages/agents-openai/src/openaiResponsesModel.ts:30-60]()\n\n## Tool Registration with Agents\n\nTools are registered with agents through the agent configuration. The SDK provides flexible patterns for tool registration.\n\n### Using the `tools` Option\n\n```typescript\nimport { Agent, FunctionTool } from '@openai/agents-core';\n\nconst searchTool = FunctionTool.create({\n  name: 'web_search',\n  description: 'Search the web for information',\n  parameters: z.object({\n    query: z.string(),\n    maxResults: z.number().optional(),\n  }),\n  execute: async (context, args) => {\n    // Implementation\n    return await performSearch(args.query, args.maxResults);\n  },\n});\n\nconst agent = Agent.make({\n  name: 'Research Agent',\n  instructions: 'You are a research assistant.',\n  tools: [searchTool],\n});\n```\n\n### Using `Agent.asTool()`\n\nAgents can expose other agents as tools, enabling hierarchical agent architectures:\n\n```typescript\nconst translatorAgent = Agent.make({\n  name: 'Translator',\n  instructions: 'Translate text between languages.',\n});\n\nconst translatorTool = translatorAgent.asTool({\n  toolName: 'translate',\n  toolDescription: 'Translate text from one language to another',\n});\n\nconst orchestratorAgent = Agent.make({\n  name: 'Orchestrator',\n  instructions: 'Coordinate tasks using available tools.',\n  tools: [translatorTool],\n});\n```\n\n资料来源：[examples/agent-patterns/README.md:10-15]()\n\n## Tool Execution Flow\n\nThe following diagram illustrates the tool execution flow within the SDK:\n\n```mermaid\nsequenceDiagram\n    participant Agent as Agent\n    participant Runner as Runner\n    participant ToolSearch as Tool Search\n    participant Executor as Tool Executor\n    participant External as External System\n\n    Agent->>Runner: Request tool call\n    Runner->>ToolSearch: Check tool availability\n    alt Tool is deferred\n        ToolSearch->>ToolSearch: Load tool on demand\n    end\n    Runner->>Executor: Execute tool call\n    Executor->>External: Invoke tool\n    External-->>Executor: Return result\n    Executor-->>Runner: Process result\n    Runner-->>Agent: Feed back to agent\n```\n\n资料来源：[packages/agents-core/src/runner/toolExecution.ts:1-50]()\n\n## Deferred Tool Loading\n\nThe SDK supports deferred loading for tools that may not always be needed. This is particularly useful for:\n\n- Expensive tools that should only be loaded when actually called\n- Tools that depend on runtime configuration\n- Large tool sets where loading everything upfront is inefficient\n\n### Top-Level Deferred Tools\n\nTools can be marked with `deferLoading: true` at the top level:\n\n```typescript\nconst expensiveTool = FunctionTool.create({\n  name: 'expensive_operation',\n  description: 'Performs expensive computation',\n  deferLoading: true,  // Will not be loaded until called\n  parameters: z.object({ input: z.string() }),\n  execute: async (context, args) => {\n    return await runExpensiveOperation(args.input);\n  },\n});\n```\n\n资料来源：[packages/agents-core/src/runner/toolSearch.ts:40-80]()\n\n### Deferred Namespace Loading\n\nNamespaces can also be configured for deferred loading:\n\n```typescript\nconst tools = [\n  FunctionTool.create({\n    name: 'db_query',\n    description: 'Query the database',\n    namespace: 'database',\n    deferLoading: true,\n    parameters: z.object({ sql: z.string() }),\n  }),\n  FunctionTool.create({\n    name: 'db_insert',\n    description: 'Insert into database',\n    namespace: 'database',\n    deferLoading: true,\n    parameters: z.object({ table: z.string(), data: z.record(z.any()) }),\n  }),\n];\n\nconst agent = Agent.make({\n  name: 'Data Agent',\n  instructions: 'Manage data operations',\n  tools: tools,\n  toolNamespaces: {\n    database: {\n      description: 'Database operations',\n      deferLoading: true,\n    },\n  },\n});\n```\n\nThe SDK provides a built-in client tool search executor for handling deferred loading:\n\n```typescript\nexport type ClientToolSearchExecutor<Context = UnknownContext> = (\n  args: ClientToolSearchExecutorArgs<Context>,\n) => Tool<Context>[] | Tool<Context> | null | undefined | Promise<Tool<Context>[] | Tool<Context> | null | undefined>;\n```\n\n资料来源：[packages/agents-core/src/tool.ts:160-175]()\n\n## Tool Input Validation\n\nTools support JSON Schema-based input validation through the `parameters` option. The SDK uses Zod for schema definition but converts these to JSON Schema for API communication.\n\n### Schema Definition\n\n```typescript\nconst tool = FunctionTool.create({\n  name: 'calculate',\n  description: 'Perform calculations',\n  parameters: z.object({\n    expression: z.string().describe('Mathematical expression'),\n    precision: z.number().int().min(0).max(10).optional(),\n  }),\n  strict: true,  // Enforce strict schema following\n});\n```\n\nWhen `strict` is enabled, the model must try to strictly follow the schema, though this may result in slower response times.\n\n资料来源：[packages/agents-core/src/tool.ts:72-75]()\n\n## Human-in-the-Loop Approval\n\nTools can require human approval before execution. This is controlled via the `needsApproval` option:\n\n```typescript\nconst sensitiveTool = FunctionTool.create({\n  name: 'delete_data',\n  description: 'Delete data from the system',\n  needsApproval: true,  // Always require approval\n  parameters: z.object({\n    id: z.string(),\n    confirm: z.boolean(),\n  }),\n  execute: async (context, args) => {\n    if (!args.confirm) {\n      return 'Deletion cancelled';\n    }\n    return await deleteRecord(args.id);\n  },\n});\n```\n\nFor dynamic approval logic, pass a function:\n\n```typescript\nconst conditionalTool = FunctionTool.create({\n  name: 'process_payment',\n  description: 'Process payment transactions',\n  needsApproval: (args) => args.amount > 1000,  // Approve only large amounts\n  parameters: paymentSchema,\n});\n```\n\n资料来源：[packages/agents-core/src/tool.ts:80-85]()\n\n## Tool Serialization\n\nThe SDK supports serializing tools for transmission and storage. The `serializeTool` function handles different tool types:\n\n```typescript\nexport function serializeTool(tool: Tool<any>): SerializedTool {\n  if (tool.type === 'function') {\n    return {\n      type: 'function',\n      name: tool.name,\n      description: tool.description,\n      parameters: tool.parameters as JsonObjectSchema<any>,\n      strict: tool.strict,\n      deferLoading: tool.deferLoading,\n      ...(namespace ? { namespace } : {}),\n    };\n  }\n  // Handle other types...\n}\n```\n\n资料来源：[packages/agents-core/src/utils/serialize.ts:30-60]()\n\n### Computer Tool Serialization\n\nComputer tools have special serialization requirements since they require initialization:\n\n```typescript\nif (tool.type === 'computer') {\n  if (!isComputerInstance(tool.computer)) {\n    throw new UserError(\n      'Computer tool is not initialized for serialization. Call resolveComputer({ tool, runContext }) first.',\n    );\n  }\n  return {\n    type: 'computer',\n    name: tool.name,\n    environment: tool.computer.environment,\n    dimensions: tool.computer.dimensions,\n  };\n}\n```\n\n资料来源：[packages/agents-core/src/utils/serialize.ts:45-65]()\n\n## MCP Tool Integration\n\nThe SDK supports MCP (Model Context Protocol) tools through the `HostedMCPTool` type. MCP tools are hosted tools with special provider data:\n\n```typescript\nexport type HostedMCPTool<Context = UnknownContext> = HostedTool & {\n  providerData: {\n    type: 'mcp';\n    serverName: string;\n    toolName: string;\n    defer_loading?: boolean;\n  };\n};\n```\n\nMCP tools can also be deferred using the `defer_loading` flag in provider data:\n\n```typescript\nfunction isDeferredHostedMcpTool(tool: Tool<any>): tool is HostedMCPTool<any> {\n  return (\n    tool.type === 'hosted_tool' &&\n    tool.providerData?.type === 'mcp' &&\n    tool.providerData.defer_loading === true\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/mcp.ts:1-50]()\n\n## Best Practices\n\n### Tool Naming\n\n- Use clear, descriptive names that indicate the tool's purpose\n- Follow a consistent naming convention (e.g., `verb_noun` or `noun_verb`)\n- Avoid ambiguous abbreviations\n\n### Tool Descriptions\n\n- Write descriptions from the agent's perspective\n- Include examples of when to use the tool\n- Specify input requirements and constraints\n- Mention any limitations or side effects\n\n### Error Handling\n\nTools should handle errors gracefully and return meaningful error messages:\n\n```typescript\nconst robustTool = FunctionTool.create({\n  name: 'fetch_data',\n  description: 'Fetch data from the API',\n  parameters: z.object({ id: z.string() }),\n  execute: async (context, args) => {\n    try {\n      const result = await fetchData(args.id);\n      return JSON.stringify(result);\n    } catch (error) {\n      return JSON.stringify({\n        error: 'fetch_failed',\n        message: error instanceof Error ? error.message : 'Unknown error',\n      });\n    }\n  },\n});\n```\n\n### Tool Granularity\n\n- Prefer single-responsibility tools over monolithic tools\n- Compose complex operations from simpler tools\n- Avoid tools that do too many unrelated things\n\n## Summary\n\nThe OpenAI Agents SDK provides a flexible and extensible tool system that enables agents to interact with external systems and perform actions. Key concepts include:\n\n- **Multiple tool types**: Function tools, hosted tools, computer tools, shell tools, and MCP tools\n- **Rich configuration**: Namespaces, deferred loading, strict validation, and approval requirements\n- **Integration patterns**: Tools can be created directly, agents can be exposed as tools, and external services can be integrated via MCP\n- **Tool execution**: The SDK handles tool invocation, result processing, and agent feedback\n- **Serialization**: Tools can be serialized for transmission and storage\n\nBy following the patterns and practices outlined in this guide, you can effectively extend your agents' capabilities with custom tools tailored to your specific use cases.\n\n---\n\n<a id='guardrails'></a>\n\n## Guardrails and Input/Output Validation\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents), [Tools and Tool Use](#tools)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/guardrail.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/guardrail.ts)\n- [packages/agents-core/src/toolGuardrail.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/toolGuardrail.ts)\n- [packages/agents-core/src/runner/guardrails.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/guardrails.ts)\n- [docs/src/content/docs/guides/guardrails.mdx](https://github.com/openai/openai-agents-js/blob/main/docs/src/content/docs/guides/guardrails.mdx)\n</details>\n\n# Guardrails and Input/Output Validation\n\nGuardrails provide a security and validation layer in the Agents SDK, allowing developers to intercept and validate inputs before agent processing and outputs after generation. This mechanism ensures that agents operate within defined safety boundaries, reject malformed or harmful requests, and maintain controlled behavior throughout their execution lifecycle.\n\n## Architecture Overview\n\nThe guardrail system is organized into three distinct types, each serving a specific validation phase:\n\n| Guardrail Type | Trigger Point | Purpose |\n|----------------|---------------|---------|\n| **Input Guardrails** | Before agent processes user input | Reject or transform incoming requests |\n| **Output Guardrails** | After agent generates response | Validate and filter agent outputs |\n| **Tool Output Guardrails** | After tool execution | Validate tool results before agent sees them |\n\n资料来源：[packages/agents-core/src/guardrail.ts:1-50]()\n\n```mermaid\ngraph TD\n    A[User Input] --> B{Input Guardrails}\n    B -->|Pass| C[Agent Processing]\n    B -->|Fail| D[Reject Request]\n    C --> E[Tool Calls]\n    E --> F{Tool Output Guardrails}\n    F -->|Pass| G[Agent Receives Result]\n    F -->|Fail| H[Block Result]\n    G --> I[Agent Generates Output]\n    I --> J{Output Guardrails}\n    J -->|Pass| K[Final Response]\n    J -->|Fail| L[Block/Modify Output]\n    \n    style B fill:#e1f5fe\n    style F fill:#fff3e0\n    style J fill:#e8f5e9\n```\n\n## Input Guardrails\n\nInput guardrails intercept user requests before they reach the agent's processing logic. They are ideal for implementing rate limiting, content filtering, authentication checks, and request validation.\n\n### Interface Definition\n\n```typescript\nexport interface InputGuardrailFunctionArgs<TContext = UnknownContext> {\n  agent: Agent<any, any>;\n  input: string;\n  context: RunContext<TContext>;\n}\n\nexport type InputGuardrailFunction<TContext = UnknownContext> = (\n  args: InputGuardrailFunctionArgs<TContext>\n) => Promise<GuardrailFunctionOutput>;\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:1-30]()\n\n### Guardrail Function Output\n\nBoth input and output guardrails return a standardized result structure:\n\n```typescript\nexport interface GuardrailFunctionOutput {\n  decision: 'allow' | 'block';\n  message?: string;\n  metadata?: Record<string, unknown>;\n}\n```\n\nWhen `decision` is `'block'`, the run terminates and the optional `message` is returned to the user.\n\n### Input Guardrail Interface\n\n```typescript\nexport interface InputGuardrail<TContext = UnknownContext> {\n  name: string;\n  execute: InputGuardrailFunction<TContext>;\n}\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:35-50]()\n\n### Configuration in Agent\n\nInput guardrails are configured at the agent level:\n\n```typescript\nconst agent = Agent.make({\n  name: 'my-agent',\n  instructions: 'You are a helpful assistant.',\n  inputGuardrails: [\n    {\n      name: 'content-filter',\n      execute: async ({ input }) => {\n        if (containsProfanity(input)) {\n          return { decision: 'block', message: 'Inappropriate content detected' };\n        }\n        return { decision: 'allow' };\n      }\n    }\n  ]\n});\n```\n\n## Output Guardrails\n\nOutput guardrails validate the agent's generated response before it is returned to the user. They enable content safety checks, PII detection, quality filtering, and output format enforcement.\n\n### Interface Definition\n\n```typescript\nexport interface OutputGuardrailFunctionArgs<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> {\n  agent: Agent<any, TOutput>;\n  agentOutput: string;\n  context: RunContext<TContext>;\n  details: {\n    modelResponse: ModelResponse | undefined;\n    output: TurnInput;\n  };\n}\n\nexport type OutputGuardrailFunction<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> = (args: OutputGuardrailFunctionArgs<TContext, TOutput>) => Promise<GuardrailFunctionOutput>;\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:50-80]()\n\n### Output Guardrail Interface\n\n```typescript\nexport interface OutputGuardrail<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> {\n  name: string;\n  execute: OutputGuardrailFunction<TOutput, TContext>;\n}\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:80-100]()\n\n### Output Guardrail Definition\n\nThe SDK provides a builder function to create output guardrail definitions:\n\n```typescript\nexport interface DefineOutputGuardrailArgs<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n> {\n  name: string;\n  execute: OutputGuardrailFunction<TOutput, TContext>;\n}\n\nexport function defineOutputGuardrail<\n  TOutput extends AgentOutputType = TextOutput,\n  TContext = UnknownContext,\n>({ name, execute }: DefineOutputGuardrailArgs<TOutput, TContext>): OutputGuardrailDefinition<TOutput, TContext>\n```\n\n资料来源：[packages/agents-core/src/guardrail.ts:100-130]()\n\n## Tool Output Guardrails\n\nTool output guardrails validate the results returned by tool executions before the agent processes them. This is particularly useful for sanitizing tool responses, preventing sensitive data leakage, and enforcing output constraints.\n\n### Interface Definition\n\n```typescript\nexport interface ToolOutputGuardrailFunctionArgs<TContext = UnknownContext> {\n  toolCallId: string;\n  toolName: string;\n  toolOutput: string;\n  context: RunContext<TContext>;\n}\n\nexport type ToolOutputGuardrailFunction<TContext = UnknownContext> = (\n  args: ToolOutputGuardrailFunctionArgs<TContext>\n) => Promise<GuardrailFunctionOutput>;\n```\n\n资料来源：[packages/agents-core/src/toolGuardrail.ts:1-30]()\n\n### Definition Creation\n\nTool output guardrails can be created with or without explicit typing:\n\n```typescript\nexport function defineToolOutputGuardrail<TContext = UnknownContext>(\n  config: { name: string; run: ToolOutputGuardrailFunction<TContext> }\n): ToolOutputGuardrailDefinition<TContext>\n```\n\nWhen guardrails are passed to the runner, they are normalized to the definition format:\n\n```typescript\nexport function toToolOutputGuardrailDefinitions<TContext>(\n  guardrails?: ToolOutputGuardrailInit<TContext>[],\n): ToolOutputGuardrailDefinition<TContext>[] {\n  if (!guardrails) {\n    return [];\n  }\n  return guardrails.map((gr) =>\n    'type' in gr && gr.type === 'tool_output'\n      ? (gr as ToolOutputGuardrailDefinition<TContext>)\n      : defineToolOutputGuardrail(gr as { name: string; run: any }),\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/toolGuardrail.ts:30-60]()\n\n## Guardrail Execution in the Runner\n\nThe runner orchestrates guardrail execution at appropriate points in the agent lifecycle.\n\n### Input Guardrail Execution\n\n```typescript\nexport async function runInputGuardrails<TContext>(\n  state: RunState<TContext, Agent<any, any>>,\n  input: string,\n  inputGuardrailDefs: InputGuardrailDefinition[],\n) {\n  if (inputGuardrailDefs.length === 0) {\n    return;\n  }\n\n  for (const guardrail of inputGuardrailDefs) {\n    const result = await guardrail.run({\n      agent: state._currentAgent,\n      input,\n      context: state._context,\n    });\n\n    if (result.tripwireTriggered) {\n      throw new InputGuardrailTripwireTriggered(guardrail.name);\n    }\n  }\n}\n```\n\n资料来源：[packages/agents-core/src/runner/guardrails.ts:1-40]()\n\nOn failure, the current turn is rolled back to enable reruns:\n\n```typescript\nonError: (error) => {\n  state._currentTurn--;\n  throw new GuardrailExecutionError(\n    `Input guardrail failed to complete: ${error}`,\n    error as Error,\n    state,\n  );\n}\n```\n\n### Output Guardrail Execution\n\n```typescript\nexport async function runOutputGuardrails<\n  TContext,\n  TOutput extends AgentOutputType,\n  TAgent extends Agent<TContext, TOutput>,\n>(\n  state: RunState<TContext, TAgent>,\n  runnerOutputGuardrails: OutputGuardrailDefinition<...>[],\n  output: string,\n) {\n  const runnerGuardrails = runnerOutputGuardrails as OutputGuardrailDefinition<...>[];\n  const guardrails = runnerGuardrails.concat(\n    state._currentAgent.outputGuardrails.map(defineOutputGuardrail),\n  );\n  \n  if (guardrails.length === 0) {\n    return;\n  }\n  \n  const agentOutput = state._currentAgent.processFinalOutput(output);\n  const runOutput = getTurnInput([], state._generatedItems, ...);\n  \n  const guardrailArgs: OutputGuardrailFunctionArgs<TContext, TOutput> = {\n    agent: state._currentAgent,\n    agentOutput,\n    context: state._context,\n    details: { modelResponse: state._lastTurnResponse, output: runOutput },\n  };\n}\n```\n\n资料来源：[packages/agents-core/src/runner/guardrails.ts:50-100]()\n\n## Guardrail Types Comparison\n\n| Property | Input Guardrail | Output Guardrail | Tool Output Guardrail |\n|----------|-----------------|------------------|----------------------|\n| **Trigger** | Before agent processes input | After agent generates output | After tool execution |\n| **Input Access** | Raw user input | Processed agent output | Tool result string |\n| **Common Use Cases** | Content filtering, auth | Safety checks, PII removal | Data sanitization |\n| **Failure Action** | Block request | Block/modify output | Block tool result |\n| **Interface** | `InputGuardrailFunction` | `OutputGuardrailFunction` | `ToolOutputGuardrailFunction` |\n\n## Common Patterns\n\n### Content Safety Pattern\n\n```typescript\nconst contentSafetyGuardrail: OutputGuardrail = {\n  name: 'content-safety',\n  execute: async ({ agentOutput }) => {\n    const isSafe = await checkContentSafety(agentOutput);\n    if (!isSafe) {\n      return { \n        decision: 'block', \n        message: 'Output failed safety review' \n      };\n    }\n    return { decision: 'allow' };\n  }\n};\n```\n\n### Input Transformation Pattern\n\n```typescript\nconst sanitizationGuardrail: InputGuardrail = {\n  name: 'input-sanitizer',\n  execute: async ({ input }) => {\n    const sanitized = removeSensitiveData(input);\n    return { decision: 'allow' };\n  }\n};\n```\n\n### Tool Output Filtering Pattern\n\n```typescript\nconst toolOutputGuardrail = defineToolOutputGuardrail({\n  name: 'filter-database-results',\n  run: async ({ toolOutput }) => {\n    const filtered = filterPersonalInformation(toolOutput);\n    return { decision: 'allow' };\n  }\n});\n```\n\n## Integration with Agent Configuration\n\nGuardrails can be configured at multiple levels:\n\n| Level | Configuration Location | Scope |\n|-------|----------------------|-------|\n| **Agent** | `inputGuardrails`, `outputGuardrails` | Applies to all runs of this agent |\n| **Runner** | `outputGuardrails` parameter | Applies to all agents in the run |\n\n```typescript\nconst agent = Agent.make({\n  name: 'secure-agent',\n  instructions: '...',\n  inputGuardrails: [/* agent-level input guards */],\n  outputGuardrails: [/* agent-level output guards */],\n});\n\n// Runner-level guards apply to all agents\nconst result = await runAgent(agent, input, {\n  outputGuardrails: [/* runner-level output guards */]\n});\n```\n\n## Error Handling\n\nGuardrail failures generate specific error types:\n\n| Error Type | Cause | Recovery |\n|------------|-------|----------|\n| `InputGuardrailTripwireTriggered` | Input guardrail returned `block` | Request rejected |\n| `GuardrailExecutionError` | Guardrail threw exception | Rollback and retry possible |\n\nThe runner implements error handling that preserves state for potential reruns:\n\n```typescript\ntryOrThrow({\n  fn: async () => runInputGuardrails(...),\n  errorName: 'input guardrail',\n  onError: (error) => {\n    state._currentTurn--;  // Rollback for rerun\n    throw new GuardrailExecutionError(...);\n  }\n});\n```\n\n## Best Practices\n\n1. **Fail-safe defaults**: Return `decision: 'allow'` when guardrail cannot complete\n2. **Provide feedback**: Include meaningful `message` on block decisions\n3. **Order matters**: Place most restrictive guardrails first for early rejection\n4. **Avoid side effects**: Guardrails should be idempotent and not modify state\n5. **Performance**: Keep guardrail execution lightweight to avoid timeouts\n6. **Testing**: Test both allow and block paths for each guardrail\n\n## Source Files Summary\n\n| File | Role |\n|------|------|\n| `packages/agents-core/src/guardrail.ts` | Core interfaces and type definitions |\n| `packages/agents-core/src/toolGuardrail.ts` | Tool output guardrail utilities |\n| `packages/agents-core/src/runner/guardrails.ts` | Runner integration and execution logic |\n\n---\n\n<a id='handoffs'></a>\n\n## Handoffs and Multi-Agent Systems\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents), [Tools and Tool Use](#tools)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/runner/modelOutputs.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runner/modelOutputs.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n- [packages/agents-core/src/result.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/result.ts)\n- [packages/agents-core/src/runState.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/runState.ts)\n- [packages/agents-realtime/src/realtimeSessionEvents.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeSessionEvents.ts)\n</details>\n\n# Handoffs and Multi-Agent Systems\n\n## Overview\n\nHandoffs enable one AI agent to transfer control to another agent within a conversation. This mechanism is fundamental to building multi-agent systems where different specialized agents collaborate to handle complex tasks. Unlike tools, which are called and return results to the calling agent, handoffs completely transfer conversational control to the new agent, which then continues the interaction with the user. 资料来源：[packages/agents-core/src/handoff.ts:1-50]()\n\n### Key Characteristics of Handoffs\n\n| Characteristic | Description |\n|----------------|-------------|\n| **Conversation Transfer** | The new agent receives the full conversation history and takes over the dialogue |\n| **Control Transfer** | The original agent stops execution; the new agent continues from where the previous left off |\n| **Bidirectional** | Agents can hand off to each other in any direction, enabling complex workflows |\n| **Typed Outputs** | Handoffs can carry structured output types from different agents |\n| **Feature Gating** | Handoffs can be conditionally enabled or disabled based on runtime context |\n\n资料来源：[packages/agents-core/src/agent.ts:1-30]()\n\n## Architecture\n\n### Handoff Flow\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Primary Agent]\n    B -->|Determines handoff needed| C[Handoff Tool Call]\n    C --> D{Handoff Enabled?}\n    D -->|Yes| E[Transfer to Target Agent]\n    D -->|No| F[Continue with Primary Agent]\n    E --> G[Target Agent Receives Full History]\n    G --> H[Target Agent Processes Request]\n    H --> I[Response to User]\n    I --> J[Optionally Handoff Back]\n    J -->|Yes| B\n```\n\n资料来源：[packages/agents-core/src/runner/modelOutputs.ts:1-50]()\n\n### Multi-Agent System Components\n\n| Component | Role | Location |\n|-----------|------|----------|\n| `Agent` | Base agent class with handoff capabilities | `packages/agents-core/src/agent.ts` |\n| `Handoff` | Wrapper class for agent-to-agent transfers | `packages/agents-core/src/handoff.ts` |\n| `HandoffConfig` | Configuration for handoff behavior | `packages/agents-core/src/handoff.ts` |\n| `RunResultData` | Results containing handoff information | `packages/agents-core/src/result.ts` |\n\n## Core Classes and Types\n\n### The Handoff Class\n\nThe `Handoff` class wraps an agent and provides the mechanism for transferring control:\n\n```typescript\nexport class Handoff<\n  TContext = UnknownContext,\n  TOutput extends AgentOutputType = TextOutput,\n> {\n  public agentName: string;\n  public toolName: string;\n  public toolDescription: string;\n  public inputParameters: JsonSchema;\n  public isEnabled: HandoffEnabledFunction<TContext> = async () => true;\n\n  constructor(\n    agent: Agent<TContext, TOutput>,\n    onInvokeHandoff: (context: RunContext<TContext>, args: string) => \n      Promise<Agent<TContext, TOutput>> | Agent<TContext, TOutput>,\n  ) { ... }\n}\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:50-80]()\n\n### Handoff Configuration\n\n```typescript\nexport type HandoffConfig<\n  TInputType extends ToolInputParameters,\n  TContext = UnknownContext,\n> = {\n  toolNameOverride?: string;\n  toolDescriptionOverride?: string;\n  onHandoff?: OnHandoffCallback<TInputType>;\n  inputType?: TInputType;\n  inputFilter?: HandoffInputFilterFunction<TContext>;\n};\n```\n\n资料来源：[packages/agents-core/src/handoff.ts:100-130]()\n\n### Handoff Configuration Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `toolNameOverride` | `string` | Custom name for the handoff tool |\n| `toolDescriptionOverride` | `string` | Custom description shown to the model |\n| `onHandoff` | `OnHandoffCallback<TInputType>` | Callback function executed when handoff occurs |\n| `inputType` | `ToolInputParameters` | Zod schema for validating handoff input |\n| `inputFilter` | `HandoffInputFilterFunction` | Function to filter/modify conversation history |\n\n## Handoff Types and Output Union\n\n### Automatic Output Type Inference\n\nThe system automatically infers the union of output types from all handoff agents:\n\n```typescript\ntype ExtractAgentOutput<T> = T extends Agent<any, infer O> ? O : never;\ntype ExtractHandoffOutput<T> = T extends Handoff<any, infer O> ? O : never;\n\nexport type HandoffsOutputUnion<\n  Handoffs extends readonly (Agent<any, any> | Handoff<any, any>)[],\n> =\n  | ExtractAgentOutput<Handoffs[number]>\n  | ExtractHandoffOutput<Handoffs[number]>;\n```\n\n资料来源：[packages/agents-core/src/agent.ts:180-200]()\n\n### Creating Agents with Handoffs\n\n```typescript\nexport type AgentConfigWithHandoffs<\n  TOutput extends AgentOutputType,\n  Handoffs extends readonly (Agent<any, any> | Handoff<any, any>)[],\n> = {\n  name: string;\n  handoffs?: Handoffs;\n  outputType?: TOutput;\n} & Partial<Omit<AgentConfiguration<UnknownContext, TOutput | HandoffsOutputUnion<Handoffs>>, 'name' | 'handoffs' | 'outputType'>>;\n```\n\n资料来源：[packages/agents-core/src/agent.ts:15-30]()\n\n## Lifecycle Events\n\n### Agent Lifecycle Hooks\n\nHandoffs trigger specific lifecycle events that can be subscribed to:\n\n```typescript\nagent_handoff: [\n  context: RunContext<TContext>,\n  nextAgent: Agent<any, any>\n];\n```\n\n资料来源：[packages/agents-core/src/lifecycle.ts:1-30]()\n\n### Real-time Session Events\n\nFor real-time agents, additional handoff events are available:\n\n```typescript\nagent_handoff: [\n  context: RunContext<RealtimeContextData<TContext>>,\n  fromAgent: AgentWithOrWithoutHistory<TContext>,\n  toAgent: AgentWithOrWithoutHistory<TContext>,\n];\n```\n\n资料来源：[packages/agents-realtime/src/realtimeSessionEvents.ts:1-50]()\n\n### Available Lifecycle Events\n\n| Event | Parameters | Trigger |\n|-------|------------|---------|\n| `agent_start` | `context`, `agent`, `turnInput` | Agent begins processing |\n| `agent_end` | `context`, `agent`, `output` | Agent completes processing |\n| `agent_handoff` | `context`, `fromAgent`, `toAgent` | Control transfers to another agent |\n| `agent_tool_start` | `context`, `agent`, `tool`, `details` | Tool execution begins |\n| `agent_tool_end` | `context`, `agent`, `tool`, `result`, `details` | Tool execution completes |\n\n## Handoff Resolution\n\n### Tool Call Resolution\n\nWhen the model requests a handoff, the system resolves the tool call:\n\n```typescript\nfunction resolveHandoffOrTool(\n  toolCall: HandoffCallItem | FunctionCallItem,\n  handoffMap: Map<string, Handoff<any, any>>,\n  functionMap: Map<string, FunctionTool<any>>,\n  agent: Agent<any, any>,\n): | { type: 'handoff'; handoff: Handoff<any, any> }\n  | { type: 'function'; tool: FunctionTool<any> }\n```\n\n资料来源：[packages/agents-core/src/runner/modelOutputs.ts:1-50]()\n\n### Resolution Process\n\n1. The tool call name is resolved to handle namespaced tools\n2. Both function tools and handoffs are checked for matches\n3. Ambiguity is detected when a name matches both a function tool and a handoff\n4. The resolved tool or handoff is returned with its type\n\n### Error Handling\n\n| Error | Cause | Resolution |\n|-------|-------|------------|\n| `Tool not found` | Handoff name not registered | Register handoff in agent configuration |\n| `Ambiguous dotted tool call` | Name matches both function tool and handoff | Rename one or use explicit namespace |\n| `Handoff not enabled` | `isEnabled` returns false | Check feature flags or context conditions |\n\n## Using Agents as Tools\n\nAgents can be invoked as tools using the `asTool()` method:\n\n```typescript\nasTool<TAgent extends Agent<TContext, TOutput> = Agent<TContext, TOutput>>(\n  this: TAgent,\n  options: AgentToolOptions<TContext, TAgent, TParameters>,\n): AgentTool<TContext, TAgent, TParameters>\n```\n\n资料来源：[packages/agents-core/src/agent.ts:200-250]()\n\n### Agent as Tool Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `toolName` | `string` | Name of the tool (defaults to agent name) |\n| `toolDescription` | `string` | Description for model guidance |\n| `customOutputExtractor` | `function` | Extract output from agent result |\n| `needsApproval` | `boolean \\| ToolApprovalFunction` | Require human approval |\n| `parameters` | `TParameters` | JSON schema for tool input |\n| `inputBuilder` | `AgentToolInputBuilder` | Transform structured input to agent input |\n\n### Key Differences: Handoffs vs Agent-as-Tool\n\n| Aspect | Handoffs | Agent-as-Tool |\n|--------|----------|---------------|\n| **Conversation History** | Full history transferred | New agent receives generated input |\n| **Control Flow** | Original agent stops, new agent takes over | Original agent continues after tool returns |\n| **Use Case** | Complete task delegation | Subtask execution with return |\n\n资料来源：[packages/agents-core/src/agent.ts:150-180]()\n\n## Handoff Results\n\n### RunResultData Structure\n\nWhen a run includes handoffs, the result contains handoff information:\n\n```typescript\nexport interface RunResultData<\n  TAgent extends Agent<any, any>,\n  THandoffs extends (Agent<any, any> | Handoff<any>)[] = any[],\n> {\n  input: string | AgentInputItem[];\n  newItems: RunItem[];\n  rawResponses: ModelResponse[];\n  lastResponseId: string | undefined;\n  lastAgent: TAgent | undefined;\n  inputGuardrailResults: InputGuardrailResult[];\n  outputGuardrailResults: OutputGuardrailResult[];\n  // ... additional properties\n}\n```\n\n资料来源：[packages/agents-core/src/result.ts:1-50]()\n\n### Tracking Handoffs in State\n\n```typescript\nhandoffs: new Map(\n  currentAgent.handoffs.map((entry) => {\n    if (entry instanceof Agent) {\n      return [entry.name, handoff(entry)];\n    }\n    return [entry.toolName, entry];\n  }),\n);\n```\n\n资料来源：[packages/agents-core/src/runState.ts:1-50]()\n\n## Multi-Agent Patterns\n\n### Triage Pattern\n\nA primary agent analyzes user input and delegates to specialized agents:\n\n```mermaid\ngraph LR\n    A[User Request] --> B[Triage Agent]\n    B -->|Spanish Request| C[Spanish Agent]\n    B -->|Technical Issue| D[Support Agent]\n    B -->|Billing Question| E[Billing Agent]\n    C --> F[Response]\n    D --> F\n    E --> F\n```\n\n### Sequential Delegation\n\nAgents hand off in a chain for complex workflows:\n\n```mermaid\ngraph TD\n    A[Input] --> B[Data Collection Agent]\n    B --> C[Analysis Agent]\n    C --> D[Report Generation Agent]\n    D --> E[Review Agent]\n    E -->|Approved| F[Final Output]\n    E -->|Needs Revision| C\n```\n\n### Parallel Handoff with Selection\n\nMultiple agents work on the same problem, with selection based on quality:\n\n```mermaid\ngraph TD\n    A[Query] --> B[Agent 1]\n    A --> C[Agent 2]\n    A --> D[Agent 3]\n    B --> E[Evaluator]\n    C --> E\n    D --> E\n    E --> F[Best Response]\n```\n\n## Best Practices\n\n### Designing Agent Responsibilities\n\n| Guideline | Description |\n|-----------|-------------|\n| **Single Responsibility** | Each agent should have a clear, focused purpose |\n| **Clear Descriptions** | Use `handoffDescription` to help the triage agent decide |\n| **Typed Outputs** | Define output types for type-safe result handling |\n| **Feature Gates** | Use `isEnabled` for conditional handoff availability |\n\n### Error Handling\n\n- Always wrap handoff execution in try-catch blocks\n- Implement fallback handoffs for critical paths\n- Log handoff failures for debugging\n\n### Performance Considerations\n\n- Minimize the number of handoffs in a single conversation\n- Use `inputFilter` to reduce conversation history transfer size\n- Cache agent instances when possible\n\n## Real-time Agent Handoffs\n\nThe real-time agent system extends handoffs for voice applications:\n\n```typescript\nexport type RealtimeAgentConfiguration<TContext = UnknownContext> = Partial<\n  Omit<\n    AgentConfiguration<RealtimeContextData<TContext>, TextOutput>,\n    | 'model'\n    | 'handoffs'\n    | 'modelSettings'\n    | 'outputType'\n    | 'toolUseBehavior'\n    | 'resetToolChoice'\n    | 'outputGuardrails'\n    | 'inputGuardrails'\n  >\n> & {\n  name: string;\n  handoffs?: (RealtimeAgent<TContext> | Handoff<RealtimeContextData<TContext>, TextOutput>)[];\n  voice?: string;\n};\n```\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts:1-40]()\n\n### Voice Handoff Constraints\n\nWhen using handoffs in real-time sessions:\n- If another agent spoke during the session, changing the voice during a handoff will fail\n- All RealtimeAgents within a session share the same model\n- `modelSettings` is not supported for RealtimeAgents\n\n---\n\n<a id='sandbox-architecture'></a>\n\n## Sandbox Agents Architecture\n\n### 相关页面\n\n相关主题：[Sandbox Providers and Extensions](#sandbox-providers), [Creating and Running Agents](#agents)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-core/src/sandbox/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/agent.ts)\n- [packages/agents-core/src/sandbox/client.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/client.ts)\n- [packages/agents-core/src/sandbox/capabilities/index.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/capabilities/index.ts)\n- [packages/agents-core/src/sandbox/runtime/manager.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/runtime/manager.ts)\n- [packages/agents-core/src/sandbox/manifest.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/manifest.ts)\n- [docs/src/content/docs/guides/sandbox-agents.mdx](https://github.com/openai/openai-agents-js/blob/main/docs/src/content/docs/guides/sandbox-agents.mdx)\n</details>\n\n# Sandbox Agents Architecture\n\n## Overview\n\nThe Sandbox Agents Architecture provides a secure, isolated execution environment for AI agents to safely run code, execute shell commands, and interact with file systems. It extends the core `Agent` class with sandboxed capabilities that isolate agent operations from the host system while maintaining a controlled bridge for communication and data exchange.\n\nSandbox agents are designed to:\n\n- **Isolate Execution**: Run untrusted or potentially harmful code in a contained environment\n- **Secure File Operations**: Provide controlled access to file systems with manifest-based permission management\n- **Runtime Isolation**: Enforce capability-based security policies that limit what operations an agent can perform\n- **Preserve Sessions**: Maintain state across agent interactions while respecting security boundaries\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:1-50]()\n\n## Core Components\n\n### SandboxAgent Class\n\nThe `SandboxAgent` extends the core `Agent` class and adds sandbox-specific configuration and lifecycle management.\n\n```mermaid\nclassDiagram\n    class Agent {\n        +name: string\n        +instructions: string\n        +tools: Tool[]\n        +run(context, input)*\n    }\n    class SandboxAgent {\n        +defaultManifest?: Manifest\n        +baseInstructions?: SandboxBaseInstructions\n        +capabilities: Capability[]\n        +runAs?: string | SandboxUser\n        +runtimeManifest: Manifest\n        +clone(config): SandboxAgent\n    }\n    Agent <|-- SandboxAgent\n```\n\n**Configuration Options**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `name` | `string` | Agent identifier |\n| `instructions` | `string \\| function` | System prompt or dynamic instruction generator |\n| `baseInstructions` | `SandboxBaseInstructions` | Base instructions appended to agent prompts |\n| `capabilities` | `Capability[]` | Runtime capabilities (file system, network, etc.) |\n| `runAs` | `string \\| SandboxUser` | User identity for sandbox execution |\n| `defaultManifest` | `Manifest` | Default file system permissions |\n| `tools` | `Tool[]` | Additional tools available to the agent |\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:35-80]()\n\n**Type Safety**\n\nThe `baseInstructions` property enforces strict type checking:\n\n```typescript\nif (\n  config.baseInstructions !== undefined &&\n  typeof config.baseInstructions !== 'string' &&\n  typeof config.baseInstructions !== 'function'\n) {\n  throw new TypeError(\n    'SandboxAgent baseInstructions must be a string or function.',\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:55-62]()\n\n### Manifest System\n\nThe `Manifest` class defines the file system permissions and access controls for a sandbox environment. Each manifest specifies which paths an agent can read, write, or execute within.\n\n**Key Manifest Operations**\n\n| Operation | Purpose |\n|-----------|---------|\n| `clone()` | Creates a deep copy of the manifest |\n| `addPermission()` | Adds a new path permission |\n| `removePermission()` | Removes an existing permission |\n| `checkAccess()` | Verifies if a path is permitted |\n\nThe manifest supports multiple manifest root levels, allowing fine-grained control over path translation and access boundaries.\n\n资料来源：[packages/agents-core/src/sandbox/manifest.ts:1-100]()\n\n### Capabilities\n\nCapabilities define what operations a sandbox agent can perform at runtime. The capability system follows a deny-by-default model.\n\n```mermaid\ngraph TD\n    A[SandboxAgent] --> B[Capability Manager]\n    B --> C[FileSystem Capability]\n    B --> D[Network Capability]\n    B --> E[Process Capability]\n    B --> F[Environment Capability]\n    \n    C --> G{Read}\n    C --> H{Write}\n    C --> I{Execute}\n    \n    D --> J[HTTP Allowed]\n    D --> K[WebSocket Allowed]\n```\n\n**Available Capability Types**\n\n| Capability | Description |\n|------------|-------------|\n| `FileSystemRead` | Read files from specified paths |\n| `FileSystemWrite` | Write or modify files |\n| `FileSystemExecute` | Execute binary files |\n| `NetworkHttp` | Make HTTP/HTTPS requests |\n| `NetworkWebSocket` | Establish WebSocket connections |\n| `ProcessSpawn` | Spawn child processes |\n\n资料来源：[packages/agents-core/src/sandbox/capabilities/index.ts:1-50]()\n\n## Sandbox Client\n\nThe `SandboxClient` manages the connection to the underlying sandbox runtime. It handles session lifecycle, authentication, and command routing.\n\n```mermaid\nsequenceDiagram\n    participant Host as Host Application\n    participant Client as SandboxClient\n    participant Runtime as Sandbox Runtime\n    participant Sandbox as Sandbox Environment\n    \n    Host->>Client: createSandbox(config)\n    Client->>Runtime: Initialize Session\n    Runtime->>Sandbox: Create Isolated Environment\n    Sandbox-->>Runtime: Session ID\n    Runtime-->>Client: Connected\n    Client-->>Host: SandboxHandle\n    \n    Host->>Client: executeCommand(cmd)\n    Client->>Sandbox: Run Command\n    Sandbox-->>Client: Output\n    Client-->>Host: Result\n```\n\n**Client Configuration**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `backendId` | `string` | Yes | Sandbox backend identifier |\n| `capabilities` | `Capability[]` | No | Override agent capabilities |\n| `manifest` | `Manifest` | No | File system permissions |\n| `environment` | `Record<string, string>` | No | Environment variables |\n\n资料来源：[packages/agents-core/src/sandbox/client.ts:1-100]()\n\n## Runtime Manager\n\nThe `RuntimeManager` orchestrates sandbox sessions, handles session preservation, and manages resource allocation across multiple concurrent sandbox environments.\n\n```mermaid\ngraph TB\n    subgraph RuntimeManager\n        A[Session Pool] --> B[Active Sessions]\n        A --> C[Preserved Sessions]\n        B --> D[Live Sessions]\n        C --> E[Serialized Sessions]\n    end\n    \n    F[Agent Request] --> G[Load Balancer]\n    G --> H{Route}\n    H -->|New| I[Create Session]\n    H -->|Preserved| J[Restore Session]\n    I --> D\n    J --> D\n```\n\n**Session Management Features**\n\n- **Live Sessions**: Active sandbox instances ready for immediate use\n- **Preserved Sessions**: Sessions that maintain state across turns\n- **Session Reuse**: Reuse live sessions within the same run state when appropriate\n- **Garbage Collection**: Clean up orphaned sessions when run state is destroyed\n\n资料来源：[packages/agents-core/src/sandbox/runtime/manager.ts:1-100]()\n\n## Path Translation\n\nSandbox environments use path translation to maintain security boundaries between the host file system and the sandbox workspace.\n\n```mermaid\ngraph LR\n    subgraph Host\n        A[/workspace/project]\n    end\n    \n    subgraph Sandbox\n        B[/]\n        C[/workspace/project]\n    end\n    \n    A -.->|Manifest Root| C\n    B -.->|Workspace Root| C\n```\n\n**Translation Functions**\n\n| Function | Purpose |\n|----------|---------|\n| `translateRootManifestCommandInput()` | Translates absolute paths in commands to workspace-relative paths |\n| `translateManifestRootCommandOutput()` | Translates output paths back to host paths |\n| `translateWorkspaceRootCommandOutput()` | Handles path prefix replacement in command output |\n\nThe translation system uses regex patterns to safely replace paths while preserving command structure:\n\n```typescript\nfunction translateRootManifestCommandInput(\n  command: string,\n  workspaceRootPath: string,\n): string {\n  return command.replace(\n    /(^|[\\s\"'=<>])\\/([^\\s\"'|&;<>(){}]*)/g,\n    (_match, prefix: string, pathSuffix: string) =>\n      `${prefix}${workspaceRootPath}/${pathSuffix}`,\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:20-35]()\n\n## Lifecycle\n\n### Session Initialization\n\n1. Agent receives task with sandbox configuration\n2. RuntimeManager checks for preserved sessions\n3. If no preserved session, create new sandbox instance\n4. Apply manifest and capabilities to sandbox\n5. Initialize runtime manifest with workspace bindings\n\n### Command Execution Flow\n\n```mermaid\ngraph TD\n    A[Agent Tool Call] --> B[SandboxClient]\n    B --> C{Path Translation}\n    C --> D[Translate Input Paths]\n    D --> E[Execute in Sandbox]\n    E --> F[Capture Output]\n    F --> G[Translate Output Paths]\n    G --> H[Return to Agent]\n```\n\n### Session Preservation\n\nSessions can be preserved across agent turns when:\n\n- `reuseLiveSession` is not explicitly set to `false`\n- The session's `backendId` matches the active client\n- The run state is still active\n\n```typescript\nexport function livePreservedOwnedSession<TContext>(args: {\n  runState: RunState<TContext, Agent<TContext, AgentOutputType>> | undefined;\n  client: SandboxClient;\n  agentKey: string;\n  serializedEntry: SerializedSandboxSessionEntry | undefined;\n}): LivePreservedOwnedSessionEntry | undefined {\n  if (!args.serializedEntry?.preservedOwnedSession || !args.runState) {\n    return undefined;\n  }\n  // ... validation and return\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/runtime/livePreservedSessions.ts:50-75]()\n\n## Security Model\n\n### Defense Layers\n\n```mermaid\ngraph TD\n    A[Host System] --> B[Manifest Permissions]\n    B --> C[Capability Checks]\n    C --> D[Path Translation]\n    D --> E[Sandbox Isolation]\n    E --> F[User Permission]\n    \n    F --> G{Allowed?}\n    G -->|No| H[Access Denied]\n    G -->|Yes| I[Execute]\n```\n\n### Permission Hierarchy\n\n| Layer | Check | Failure Action |\n|-------|-------|----------------|\n| Manifest | Path in allowed list | Reject before execution |\n| Capability | Operation permitted | Reject tool invocation |\n| Path Translation | Valid path transformation | Sanitize or reject |\n| User Permission | `runAs` identity | Fall back to default user |\n\n## Configuration Example\n\n```typescript\nimport { SandboxAgent, Manifest, Capability } from '@openai/agents-core';\n\nconst manifest = new Manifest({\n  roots: ['/workspace'],\n  permissions: [\n    { path: '/workspace/**', access: 'rw' },\n    { path: '/tmp/**', access: 'rw' },\n  ],\n});\n\nconst agent = new SandboxAgent({\n  name: 'code-executor',\n  instructions: 'You can execute code and manage files in /workspace',\n  capabilities: [\n    Capability.fileSystem(),\n    Capability.network({ http: true, webSocket: false }),\n    Capability.process(),\n  ],\n  manifest,\n  baseInstructions: 'Always verify paths are within allowed directories.',\n});\n```\n\n资料来源：[docs/src/content/docs/guides/sandbox-agents.mdx:1-100]()\n\n## Error Handling\n\nSandbox operations can fail for several reasons:\n\n| Error Type | Cause | Recovery |\n|------------|-------|----------|\n| `ManifestNotFoundError` | Manifest file missing | Provide default manifest |\n| `CapabilityDeniedError` | Operation not permitted | Add required capability |\n| `PathViolationError` | Access outside manifest | Translate or reject path |\n| `SessionExpiredError` | Preserved session invalid | Create new session |\n| `RuntimeConnectionError` | Cannot reach sandbox | Retry with backoff |\n\nError handlers should check `RunErrorKind` and provide appropriate fallbacks or user-facing error messages.\n\n资料来源：[packages/agents-core/src/runner/errorHandlers.ts:1-50]()\n\n## Best Practices\n\n### Session Management\n\n- **Preserve selectively**: Only preserve sessions when state needs to persist\n- **Clean up on completion**: Ensure sessions are released when no longer needed\n- **Monitor resource usage**: Track session creation to prevent leaks\n\n### Path Handling\n\n- **Always validate**: Check paths against manifest before operations\n- **Use translation utilities**: Never manually construct sandbox paths\n- **Log path operations**: Track path translations for debugging\n\n### Capability Assignment\n\n- **Principle of least privilege**: Grant only required capabilities\n- **Separate by trust level**: Use different agents with different capabilities\n- **Audit capability usage**: Log when sensitive capabilities are invoked\n\n---\n\n<a id='sandbox-providers'></a>\n\n## Sandbox Providers and Extensions\n\n### 相关页面\n\n相关主题：[Sandbox Agents Architecture](#sandbox-architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-extensions/src/sandbox/cloudflare/sandbox.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/src/sandbox/cloudflare/sandbox.ts)\n- [packages/agents-extensions/src/sandbox/e2b/sandbox.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/src/sandbox/e2b/sandbox.ts)\n- [packages/agents-extensions/src/sandbox/daytona/sandbox.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-extensions/src/sandbox/daytona/sandbox.ts)\n- [packages/agents-core/src/sandbox/sandboxes/docker.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/sandboxes/docker.ts)\n- [packages/agents-core/src/sandbox/sandboxes/unixLocal.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/sandbox/sandboxes/unixLocal.ts)\n</details>\n\n# Sandbox Providers and Extensions\n\nThe OpenAI Agents SDK provides a flexible sandbox architecture that enables AI agents to execute code and commands in isolated, secure environments. Sandboxes are essential for safely running untrusted or potentially harmful code generated by AI agents, ensuring system security while maintaining developer productivity.\n\n## Overview\n\nThe sandbox system consists of two primary layers:\n\n1. **Core Sandbox Infrastructure** (`agents-core`): Built-in sandbox implementations including Docker and Unix local execution\n2. **Extension Providers** (`agents-extensions`): Third-party sandbox provider integrations including Cloudflare, E2B, and Daytona\n\nSandboxes abstract away the complexity of secure code execution, providing agents with a virtual workspace where file operations, command execution, and environment management occur in isolation from the host system.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Agent] --> B[SandboxAgent]\n    B --> C[Sandbox Provider Interface]\n    C --> D[Core Providers]\n    C --> E[Extension Providers]\n    D --> D1[Docker Sandbox]\n    D --> D2[UnixLocal Sandbox]\n    E --> E1[Cloudflare Sandbox]\n    E --> E2[E2B Sandbox]\n    E --> E3[Daytona Sandbox]\n    F[Manifest] --> B\n    G[Capabilities] --> B\n    H[RunAs User] --> B\n```\n\n## Core Components\n\n### SandboxAgent Class\n\nThe `SandboxAgent` class extends the base `Agent` class and provides sandbox-specific configuration:\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `defaultManifest` | `Manifest` | Default manifest for workspace structure |\n| `baseInstructions` | `SandboxBaseInstructions` | Base instructions for sandbox initialization |\n| `capabilities` | `Capability[]` | List of capabilities enabled for this sandbox |\n| `runAs` | `string \\| SandboxUser` | User or role to run sandbox commands as |\n| `runtimeManifest` | `Manifest` | Runtime manifest tracking workspace state |\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:1-50]()\n\n**Constructor Validation:**\n\n```typescript\nif (\n  config.baseInstructions !== undefined &&\n  typeof config.baseInstructions !== 'string' &&\n  typeof config.baseInstructions !== 'function'\n) {\n  throw new TypeError(\n    'SandboxAgent baseInstructions must be a string or function.',\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:20-28]()\n\n### Sandbox Agent Options\n\n| Option | Type | Required | Description |\n|--------|------|----------|-------------|\n| `name` | `string` | Yes | Name identifier for the sandbox agent |\n| `instructions` | `string` | No | System prompt/instructions for the agent |\n| `defaultManifest` | `Manifest` | No | Initial workspace manifest |\n| `baseInstructions` | `string \\| function` | No | Base instructions for sandbox setup |\n| `capabilities` | `Capability[]` | No | Enabled capabilities (defaults to `Capabilities.default()`) |\n| `runAs` | `string \\| SandboxUser` | No | User identity for sandbox execution |\n\n## Path Translation System\n\nSandbox environments maintain an isolated filesystem. The SDK uses a **path translation system** to map between the host machine's paths and the sandbox's internal workspace paths.\n\n### Translation Strategy\n\n```mermaid\ngraph LR\n    A[Host Path] -->|translateRootManifestCommandInput| B[Sandbox Path]\n    B -->|execute| C[Command in Sandbox]\n    C -->|translateManifestRootCommandOutput| D[Host-Compatible Output]\n```\n\n### Translation Functions\n\nThe `unixLocal.ts` module provides path translation utilities:\n\n**Root Manifest Command Input Translation:**\n\n```typescript\nfunction translateRootManifestCommandInput(\n  command: string,\n  workspaceRootPath: string,\n): string {\n  return command.replace(\n    /(^|[\\s\"'=<>])\\/([^\\s\"'|&;<>(){}]*)/g,\n    (_match, prefix: string, pathSuffix: string) =>\n      `${prefix}${workspaceRootPath}/${pathSuffix}`,\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:30-40]()\n\n**Manifest Root Command Input Translation:**\n\n```typescript\nfunction translateManifestRootCommandInput(\n  command: string,\n  manifestRoot: string,\n  workspaceRootPath: string,\n): string {\n  const escapedManifestRoot = escapeRegExp(manifestRoot);\n  const pathPrefix = String.raw`(^|[\\s\"'=<>])`;\n  const pathSuffix = String.raw`(?=$|[\\/\\s\"'|&;<>(){}])`;\n  return command.replace(\n    new RegExp(`${pathPrefix}${escapedManifestRoot}${pathSuffix}`, 'g'),\n    (_match, prefix: string) => `${prefix}${workspaceRootPath}`,\n  );\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:42-55]()\n\n### Output Path Translation\n\nBoth root and manifest-level output translations use a shared helper:\n\n```typescript\nfunction translateWorkspaceRootCommandOutput(\n  output: string,\n  manifestRoot: string,\n  workspaceRootPath: string,\n): string {\n  // Core translation logic shared between input and output\n}\n```\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:67-75]()\n\n## Extension Providers\n\nThe `agents-extensions` package provides integrations with popular sandbox providers. Each provider implements a consistent interface while leveraging provider-specific features.\n\n### Provider Comparison\n\n| Provider | Package | Use Case | Key Features |\n|----------|---------|----------|--------------|\n| **Cloudflare** | `agents-extensions` | Edge computing, global distribution | Low latency execution, Workers integration |\n| **E2B** | `agents-extensions` | Code interpretation, AI debugging | Secure VM isolation, filesystem access |\n| **Daytona** | `agents-extensions` | Development environments | Full IDE capabilities, workspace management |\n\n### Daytona Sandbox Implementation\n\nDaytona provides a robust sandbox with advanced file operation capabilities.\n\n#### File Write Operations\n\nThe Daytona sandbox implements secure file writing with workspace escape prevention:\n\n```bash\nresolved_root=$(realpath -m -- \"$root\")\nparent=$(dirname -- \"$path\")\nbase=$(basename -- \"$path\")\nresolved_parent=$(realpath -m -- \"$parent\")\ncase \"$resolved_parent\" in \"$resolved_root\"|\"$resolved_root\"/*) ;; \n  *) printf \"workspace escape: %s\\\\n\" \"$resolved_parent\" >&2; exit 111 ;; \nesac\n```\n\n资料来源：[packages/agents-extensions/src/sandbox/daytona/sandbox.ts:50-60]()\n\n#### Security Measures\n\n| Check | Exit Code | Description |\n|-------|-----------|-------------|\n| Workspace Escape | 111 | Prevents writes outside allowed workspace |\n| Directory Target | 112 | Prevents overwriting directory with file |\n\n#### Write Operation Flow\n\n```mermaid\ngraph TD\n    A[Write Request] --> B{Validate Path}\n    B -->|Escape Detected| C[Exit 111]\n    B -->|Is Directory| D[Exit 112]\n    B -->|Valid| E[Create Temp File]\n    E --> F[base64 Decode Content]\n    F --> G[chmod 644]\n    G --> H[Atomic Move to Target]\n    H --> I[Cleanup Trap]\n```\n\n#### Temporary File Management\n\n```bash\ntmp=$(mktemp \"$resolved_parent/.openai-agents-write.XXXXXX\")\ncleanup() { rm -f -- \"$tmp\"; }\ntrap cleanup EXIT HUP INT TERM\nbase64 -d > \"$tmp\" <<'OPENAI_AGENTS_CONTENT'\n${encoded}\nOPENAI_AGENTS_CONTENT\nchmod 644 \"$tmp\"\nmv -f -- \"$tmp\" \"$target\"\ntrap - EXIT\n```\n\n资料来源：[packages/agents-extensions/src/sandbox/daytona/sandbox.ts:55-70]()\n\n### Environment Variables\n\nSandbox environments receive a standardized set of environment variables:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `HOME` | User home directory | `/home/user` |\n| `SHELL` | Default shell path | `/bin/bash` |\n| `TMPDIR` | Temporary directory | `/tmp` |\n| `PWD` | Current working directory | `/workspace` |\n\n资料来源：[packages/agents-core/src/sandbox/sandboxes/unixLocal.ts:10-20]()\n\n## Docker Sandbox\n\nThe Docker sandbox provider enables containerized execution with full isolation:\n\n```mermaid\ngraph TD\n    A[Sandbox Request] --> B[Create Container]\n    B --> C[Mount Workspace Volume]\n    C --> D[Execute Commands]\n    D --> E[Translate Paths]\n    E --> F[Return Results]\n    F --> G[Cleanup Container]\n```\n\n### Docker Configuration\n\n| Option | Description |\n|--------|-------------|\n| `image` | Docker image to use |\n| `volumes` | Volume mounts for persistent storage |\n| `network` | Network configuration |\n| `memory` | Memory limits |\n| `cpus` | CPU allocation |\n\n## Manifest System\n\nThe Manifest system tracks workspace structure and enables consistent file operations across sandbox providers.\n\n### Manifest Structure\n\n```typescript\ninterface Manifest {\n  root: string;\n  files: FileEntry[];\n  directories: DirectoryEntry[];\n}\n```\n\n### Clone Behavior\n\nWhen creating a new `SandboxAgent` with modified configuration, manifests are cloned to prevent mutation:\n\n```typescript\nthis.defaultManifest = config.defaultManifest\n  ? cloneManifest(config.defaultManifest)\n  : undefined;\n```\n\n资料来源：[packages/agents-core/src/sandbox/agent.ts:29-32]()\n\n## Usage Patterns\n\n### Basic Sandbox Agent Creation\n\n```typescript\nimport { SandboxAgent } from '@openai/agents-core';\n\nconst sandboxAgent = SandboxAgent.create({\n  name: 'code-executor',\n  instructions: 'Execute code and return results',\n  baseInstructions: 'Initialize workspace at /workspace',\n  capabilities: [Capability.fileWrite, Capability.commandExecution],\n  runAs: 'sandbox-user',\n});\n```\n\n### Extension Provider Usage\n\n```typescript\nimport { createCloudflareSandbox } from '@openai/agents-extensions';\nimport { SandboxAgent } from '@openai/agents-core';\n\nconst cloudflareSandbox = createCloudflareSandbox({\n  name: 'edge-executor',\n  instructions: 'Execute at edge locations',\n});\n\nconst agent = SandboxAgent.create({\n  ...cloudflareSandbox,\n  capabilities: [Capability.fileWrite],\n});\n```\n\n## Best Practices\n\n### Security Considerations\n\n1. **Path Validation**: Always validate paths before execution to prevent workspace escapes\n2. **Resource Limits**: Configure memory and CPU limits for sandboxed operations\n3. **Cleanup**: Ensure proper trap handlers clean up temporary resources\n4. **User Isolation**: Run sandbox operations with minimal privileges\n\n### Performance Optimization\n\n1. **Connection Pooling**: Reuse sandbox instances when possible\n2. **Manifest Caching**: Cache manifest states to reduce initialization overhead\n3. **Path Translation Caching**: Memoize frequently used path translations\n\n## Error Handling\n\nSandbox operations may fail with specific error codes:\n\n| Error Type | Provider | Common Causes |\n|------------|----------|---------------|\n| Workspace Escape | Daytona | Path traversal attempt |\n| Resource Exhaustion | Docker/E2B | Memory/CPU limits exceeded |\n| Permission Denied | All | Insufficient sandbox user privileges |\n| Container Failure | Docker | Image not found, network issues |\n\n## Further Reading\n\n- [Agent Lifecycle Events](packages/agents-core/src/lifecycle.ts)\n- [Tool Configuration](packages/agents-core/src/tool.ts)\n- [Extension Packages](packages/agents-extensions/README.md)\n- [Agent Patterns Examples](examples/agent-patterns/README.md)\n\n---\n\n<a id='voice-realtime'></a>\n\n## Voice Agents and Realtime Communication\n\n### 相关页面\n\n相关主题：[Creating and Running Agents](#agents)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [packages/agents-realtime/src/realtimeAgent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeAgent.ts)\n- [packages/agents-realtime/src/realtimeSession.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeSession.ts)\n- [packages/agents-realtime/src/openaiRealtimeBase.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/openaiRealtimeBase.ts)\n- [packages/agents-realtime/src/openaiRealtimeWebsocket.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/openaiRealtimeWebsocket.ts)\n- [packages/agents-realtime/src/realtimeSessionEvents.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/realtimeSessionEvents.ts)\n- [packages/agents-realtime/src/clientMessages.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-realtime/src/clientMessages.ts)\n- [packages/agents-core/src/agent.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/agent.ts)\n- [packages/agents-core/src/handoff.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/handoff.ts)\n- [packages/agents-core/src/lifecycle.ts](https://github.com/openai/openai-agents-js/blob/main/packages/agents-core/src/lifecycle.ts)\n</details>\n\n# Voice Agents and Realtime Communication\n\n## Overview\n\nThe OpenAI Agents SDK provides a comprehensive framework for building voice agents with realtime communication capabilities. This system enables developers to create interactive voice applications that leverage OpenAI's Realtime API for low-latency, bidirectional audio communication.\n\nThe voice agent system is built on two primary abstractions:\n\n1. **RealtimeAgent** - A specialized agent class designed for voice interactions\n2. **RealtimeSession** - A session manager that handles the connection lifecycle, event routing, and audio processing\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts:50-60]()\n\n## Architecture\n\n### High-Level Component Architecture\n\n```mermaid\ngraph TD\n    A[Client Application] --> B[RealtimeSession]\n    B --> C[Transport Layer]\n    C --> D[OpenAI Realtime API]\n    \n    B --> E[RealtimeAgent]\n    E --> F[System Prompt]\n    E --> G[Handoffs]\n    \n    B --> H[Event System]\n    H --> I[audio_start]\n    H --> J[audio_stopped]\n    H --> K[audio_interrupted]\n    H --> L[guardrail_tripped]\n    \n    C --> M[WebSocket Transport]\n    C --> N[WebRTC Transport]\n```\n\n### Session Configuration Flow\n\n```mermaid\nsequenceDiagram\n    participant App as Client App\n    participant Session as RealtimeSession\n    participant Transport as Transport Layer\n    participant API as OpenAI Realtime API\n    \n    App->>Session: create session with config\n    Session->>Transport: initialize transport\n    Transport->>API: establish connection\n    API-->>Transport: connection established\n    Transport-->>Session: emit ready\n    Session->>Session: updateSessionConfig()\n    Session->>App: emit session_started\n```\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:100-150]()\n\n## Core Components\n\n### RealtimeAgent\n\nThe `RealtimeAgent` class extends the base `Agent` class with voice-specific configuration:\n\n```typescript\nexport class RealtimeAgent<TContext = UnknownContext> extends Agent<\n  RealtimeContextData<TContext>,\n  TextOutput\n> {\n  readonly voice?: string;\n}\n```\n\n**Configuration Options:**\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `name` | `string` | The name of your realtime agent |\n| `instructions` | `string` | System prompt for the agent |\n| `handoffs` | `RealtimeAgent[] \\| Handoff[]` | Agents available for handoff |\n| `voice` | `string` | Voice identifier for audio output |\n\n**Unsupported Configuration Options:**\n\nDue to the nature of realtime sessions, the following `Agent` configuration options are not supported:\n\n- `model` - All RealtimeAgents use the same model within a session\n- `modelSettings` - Managed at the session level\n- `outputType` - Structured outputs are not supported\n- `toolUseBehavior` - Managed at the session level\n\n资料来源：[packages/agents-realtime/src/realtimeAgent.ts:1-55]()\n\n### RealtimeSession\n\nThe `RealtimeSession` manages the complete lifecycle of a voice agent session:\n\n```typescript\nexport class RealtimeSession<TBaseContext = UnknownContext> extends EventEmitter<RealtimeSessionEvents<TBaseContext>>\n```\n\n**Transport Selection:**\n\nThe session automatically selects a transport based on configuration:\n\n| Transport Type | Condition | Use Case |\n|----------------|------------|----------|\n| `OpenAIRealtimeWebRTC` | `transport === 'webrtc'` or WebRTC supported | Browser-based applications |\n| `OpenAIRealtimeWebSocket` | `transport === 'websocket'` or undefined | Server-side, non-browser |\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:200-230]()\n\n## Transport Layer\n\n### WebSocket Transport\n\nThe WebSocket transport provides reliable, server-to-server connectivity:\n\n```typescript\nthis.#transport = new OpenAIRealtimeWebSocket();\n```\n\nKey methods:\n- `sendEvent(event)` - Send raw events to the API\n- `requestResponse(response?)` - Request a model response\n- `updateSessionConfig(config)` - Update session configuration\n\n资料来源：[packages/agents-realtime/src/openaiRealtimeWebsocket.ts:50-80]()\n\n### Turn Detection Configuration\n\nTurn detection can be configured with multiple parameters:\n\n```typescript\ninterface RealtimeTurnDetectionConfig {\n  type?: string;\n  createResponse?: boolean;\n  eagerness?: 'low' | 'medium' | 'high';\n  interruptResponse?: boolean;\n  prefixPaddingMs?: number;\n  silenceDurationMs?: number;\n  threshold?: number;\n  idleTimeoutMs?: number;\n  modelVersion?: string;\n}\n```\n\n**Config Normalization:**\n\nThe SDK automatically converts camelCase to snake_case for API compatibility:\n\n| camelCase | snake_case |\n|-----------|------------|\n| `createResponse` | `create_response` |\n| `interruptResponse` | `interrupt_response` |\n| `prefixPaddingMs` | `prefix_padding_ms` |\n| `silenceDurationMs` | `silence_duration_ms` |\n| `idleTimeoutMs` | `idle_timeout_ms` |\n| `modelVersion` | `model_version` |\n\n资料来源：[packages/agents-realtime/src/openaiRealtimeBase.ts:50-100]()\n\n## Session Configuration\n\n### Configuration Merging Strategy\n\nThe session configuration is built from multiple sources with the following priority:\n\n1. Session method parameters (highest priority)\n2. RealtimeSession constructor options\n3. Default values (lowest priority)\n\n```typescript\nasync #getSessionConfig(\n  additionalConfig: Partial<RealtimeSessionConfig> = {},\n): Promise<Partial<RealtimeSessionConfig>> {\n  const overridesConfig = additionalConfig ?? {};\n  const optionsConfig = this.options.config ?? {};\n  // Merge logic applies priority\n}\n```\n\n### Tracing Configuration\n\nTracing can be explicitly controlled:\n\n```typescript\nconst tracingConfig: RealtimeTracingConfig | null = this.options.tracingDisabled\n  ? null\n  : this.options.workflowName\n    ? { workflow_name: this.options.workflowName }\n    : 'auto';\n```\n\n**Tracing Options:**\n\n| Option | Behavior |\n|--------|----------|\n| `tracingDisabled: true` | Explicitly disable tracing |\n| `workflowName: string` | Enable tracing with workflow name |\n| `'auto'` | Automatic tracing configuration |\n| `groupId` | Group related traces (requires workflowName) |\n| `traceMetadata` | Custom metadata for traces (requires workflowName) |\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:300-350]()\n\n## Events System\n\n### Session Events\n\nThe `RealtimeSession` emits the following events:\n\n| Event | Payload | Description |\n|-------|---------|-------------|\n| `audio_start` | `context, agent` | Agent starts generating audio |\n| `audio_stopped` | `context, agent` | Agent stops generating audio |\n| `audio` | `TransportLayerAudio` | New audio data available |\n| `audio_interrupted` | `context, agent` | Audio generation was interrupted |\n| `guardrail_tripped` | `context, agent, error, details` | Output guardrail triggered |\n| `mcp_tool_call_completed` | `context, agent, toolCall` | MCP tool finished execution |\n| `tool_approval_requested` | `context, agent, approvalItem` | Human-in-the-loop approval needed |\n| `transport_event` | `event` | Raw transport event |\n| `error` | `error` | Error occurred |\n| `usage_update` | `usage` | Token usage update |\n| `mcp_tools_changed` | - | Available MCP tools updated |\n\n### Lifecycle Events\n\n```mermaid\nstateDiagram-v2\n    [*] --> Initializing\n    Initializing --> Connecting\n    Connecting --> Connected\n    Connected --> AudioActive\n    AudioActive --> AudioStopped\n    AudioActive --> Interrupted\n    Interrupted --> Connecting\n    AudioStopped --> Connected\n    Connected --> [*]\n```\n\n资料来源：[packages/agents-realtime/src/realtimeSessionEvents.ts:1-60]()\n\n## Handoffs in Voice Agents\n\nVoice agents support handoff functionality for seamless transitions between agents:\n\n```typescript\nexport type HandoffConfig<\n  TInputType extends ToolInputParameters,\n  TContext = UnknownContext,\n> = {\n  toolNameOverride?: string;\n  toolDescriptionOverride?: string;\n  onHandoff?: OnHandoffCallback<TInputType>;\n};\n```\n\n**Voice-Specific Handoff Behavior:**\n\n- Voice changes during handoff will fail if another agent already spoke during the session\n- The `voice` property can be set per agent but cannot be changed after the first agent speaks\n\n资料来源：[packages/agents-core/src/handoff.ts:50-80]()\n\n## Guardrails\n\n### Output Guardrails\n\nOutput guardrails can be configured at the session level:\n\n```typescript\nthis.#outputGuardrails = (options.outputGuardrails ?? []).map(\n  defineRealtimeOutputGuardrail,\n);\nthis.#outputGuardrailSettings = getRealtimeGuardrailSettings(\n  options.outputGuardrailSettings ?? {},\n);\n```\n\nWhen a guardrail is triggered, the `guardrail_tripped` event is emitted:\n\n```typescript\nthis.emit('guardrail_tripped', context, agent, error, { itemId });\n```\n\n## MCP Tool Integration\n\n### Tool Call Handling\n\nMCP (Model Context Protocol) tools are automatically integrated:\n\n```typescript\nthis.#transport.on('mcp_tool_call_completed', (toolCall) => {\n  this.emit('mcp_tool_call_completed', context, currentAgent, toolCall);\n\n  if (this.#automaticallyTriggerResponseForMcpToolCalls) {\n    if (this.#transport.requestResponse) {\n      this.#transport.requestResponse();\n    } else {\n      this.#transport.sendEvent({ type: 'response.create' });\n    }\n  }\n});\n```\n\n**Configuration Option:**\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `automaticallyTriggerResponseForMcpToolCalls` | `boolean` | `true` | Auto-trigger response after tool completion |\n\n## Usage Examples\n\n### Basic Voice Agent Setup\n\n```typescript\nimport { RealtimeAgent, RealtimeSession } from '@openai/agents-realtime';\n\nconst agent = new RealtimeAgent({\n  name: 'my-agent',\n  instructions: 'You are a helpful assistant that can answer questions and help with tasks.',\n});\n\nconst session = new RealtimeSession(agent);\n\nsession.on('audio', (event) => {\n  // Handle audio data\n  console.log('Audio received:', event);\n});\n\nsession.on('audio_interrupted', (context, agent) => {\n  // Stop audio playback\n  console.log('Audio interrupted');\n});\n\nawait session.start();\n```\n\n### Next.js Integration\n\nThe SDK provides examples for Next.js integration at `/examples/realtime-next`:\n\n```bash\npnpm examples:realtime-next\n```\n\nAvailable endpoints:\n- `/` - WebRTC voice demo\n- `/websocket` - WebSocket voice demo\n- `/raw-client` - Low-level WebRTC example using `OpenAIRealtimeWebRTC`\n\n资料来源：[examples/realtime-next/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/realtime-next/README.md)\n\n### Vite Demo Application\n\nA standalone demo is available at `/examples/realtime-demo`:\n\n```bash\npnpm -F realtime-demo generate-token\npnpm examples:realtime-demo\n```\n\n资料来源：[examples/realtime-demo/README.md](https://github.com/openai/openai-agents-js/blob/main/examples/realtime-demo/README.md)\n\n## Type Definitions\n\n### Context Data Structure\n\n```typescript\ninterface RealtimeContextData<TContext = UnknownContext> {\n  history: Message[];\n  usage: UsageData;\n  // Additional user-defined context\n}\n```\n\n### Session Configuration\n\n```typescript\ninterface RealtimeSessionConfig {\n  model?: string;\n  modalities?: ('text' | 'audio')[];\n  instructions?: string;\n  voice?: string;\n  audio?: {\n    input?: {\n      format?: string;\n      noiseReduction?: boolean;\n      transcription?: TranscriptionConfig;\n      turnDetection?: RealtimeTurnDetectionConfig;\n    };\n    output?: {\n      format?: string;\n      voice?: string;\n    };\n  };\n  turnDetection?: RealtimeTurnDetectionConfig;\n}\n```\n\n## Best Practices\n\n### Connection Management\n\n1. **Always handle errors**: Subscribe to the `error` event to catch and handle connection issues\n2. **Implement reconnection logic**: The session should be recreated if the connection is lost\n3. **Monitor audio state**: Track `audio_start` and `audio_stopped` events for proper playback management\n\n### Voice Configuration\n\n1. **Set voice early**: Configure the voice in the agent or session configuration before the first agent speaks\n2. **Handle handoff failures**: Implement fallback logic when voice changes fail during handoffs\n3. **Test with different voices**: Use the `voice` property to find the best voice for your use case\n\n### Performance Considerations\n\n1. **Audio buffer management**: Handle `audio` events efficiently to prevent latency\n2. **Event cleanup**: Remove event listeners when the session is terminated\n3. **Use appropriate transport**: Choose WebRTC for browser applications, WebSocket for server-side\n\n资料来源：[packages/agents-realtime/src/realtimeSession.ts:150-200]()\n\n## See Also\n\n- [Basic Examples](../examples/basic) - Simple script demonstrations\n- [AI SDK UI Integration](../examples/ai-sdk-ui) - Streaming text responses\n- [Agent Lifecycle](../packages/agents-core/src/lifecycle.ts) - Understanding agent lifecycle events\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：openai/openai-agents-js\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。\n\n## 1. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `openai-agents-js` 与安装入口 `@openai/agents` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @openai/agents`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:993521808 | https://github.com/openai/openai-agents-js | repo=openai-agents-js; install=@openai/agents\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:993521808 | https://github.com/openai/openai-agents-js | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | release_recency=unknown\n\n<!-- canonical_name: openai/openai-agents-js; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：openai/openai-agents-js\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。\n\n## 1. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `openai-agents-js` 与安装入口 `@openai/agents` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @openai/agents`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:993521808 | https://github.com/openai/openai-agents-js | repo=openai-agents-js; install=@openai/agents\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:993521808 | https://github.com/openai/openai-agents-js | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:993521808 | https://github.com/openai/openai-agents-js | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:993521808 | https://github.com/openai/openai-agents-js | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# openai-agents-js - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for openai/openai-agents-js.\n\nProject:\n- Name: openai-agents-js\n- Repository: https://github.com/openai/openai-agents-js\n- Summary: A lightweight, powerful framework for multi-agent workflows and voice agents\n- Host target: chatgpt\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: A lightweight, powerful framework for multi-agent workflows and voice agents\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to OpenAI Agents SDK. Produce one small intermediate artifact and wait for confirmation.\n2. examples-overview: Examples and Patterns. Produce one small intermediate artifact and wait for confirmation.\n3. agents: Creating and Running Agents. Produce one small intermediate artifact and wait for confirmation.\n4. tools: Tools and Tool Use. Produce one small intermediate artifact and wait for confirmation.\n5. sandbox-architecture: Sandbox Agents Architecture. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/openai/openai-agents-js\n- https://github.com/openai/openai-agents-js#readme\n- .agents/skills/changeset-validation/SKILL.md\n- .agents/skills/code-change-verification/SKILL.md\n- .agents/skills/docs-sync/SKILL.md\n- .agents/skills/examples-auto-run/SKILL.md\n- .agents/skills/final-release-review/SKILL.md\n- .agents/skills/implementation-strategy/SKILL.md\n- .agents/skills/integration-tests/SKILL.md\n- .agents/skills/openai-knowledge/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：openai/openai-agents-js\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install @openai/agents\n```\n\n来源：https://github.com/openai/openai-agents-js#readme\n\n## 来源\n\n- repo: https://github.com/openai/openai-agents-js\n- docs: https://github.com/openai/openai-agents-js#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_536af9c378e94ca28f7c1cd57210eead"
}
