chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:39:17 +08:00
commit 4ed4e9ff99
1368 changed files with 334957 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
# Shared support code for sandbox examples.
+33
View File
@@ -0,0 +1,33 @@
from __future__ import annotations
from collections.abc import Mapping
from agents.sandbox import Manifest
from agents.sandbox.entries import File
def text_manifest(files: Mapping[str, str]) -> Manifest:
"""Build a manifest from in-memory UTF-8 text files."""
return Manifest(
entries={path: File(content=contents.encode("utf-8")) for path, contents in files.items()}
)
def tool_call_name(raw_item: object) -> str:
"""Return a readable name for a raw tool call item."""
if isinstance(raw_item, dict):
name = raw_item.get("name")
item_type = raw_item.get("type")
else:
name = getattr(raw_item, "name", None)
item_type = getattr(raw_item, "type", None)
if isinstance(name, str) and name:
return name
if item_type == "shell_call":
return "shell"
if isinstance(item_type, str):
return item_type
return ""
@@ -0,0 +1,25 @@
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Reference Policy Server")
@mcp.tool()
def get_policy_reference(topic: str) -> str:
"""Return short internal policy guidance for a supported topic."""
normalized = topic.strip().lower()
if "discount" in normalized:
return (
"Discount policy: discounts from 11 to 15 percent require regional sales director "
"approval. Discounts above 15 percent require both finance and the regional sales "
"director."
)
if "security" in normalized or "review" in normalized:
return (
"Security review policy: any new data export workflow must finish security review "
"before kickoff or production access."
)
return "No policy reference is available for that topic in this demo."
if __name__ == "__main__":
mcp.run()
@@ -0,0 +1,78 @@
from __future__ import annotations
import io
from pathlib import Path
from agents import ApplyPatchTool, apply_diff
from agents.editor import ApplyPatchOperation, ApplyPatchResult
from agents.sandbox import Capability, Manifest
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
from agents.tool import Tool
def _read_text(handle: io.IOBase) -> str:
payload = handle.read()
if isinstance(payload, str):
return payload
if isinstance(payload, bytes | bytearray):
return bytes(payload).decode("utf-8", errors="replace")
return str(payload)
class _SandboxWorkspaceEditor:
def __init__(self, session: BaseSandboxSession) -> None:
self._session = session
async def create_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
target = self._resolve_path(operation.path)
content = apply_diff("", operation.diff or "", mode="create")
await self._session.mkdir(target.parent, parents=True)
await self._session.write(target, io.BytesIO(content.encode("utf-8")))
return ApplyPatchResult(output=f"Created {self._display_path(target)}")
async def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
target = self._resolve_path(operation.path)
handle = await self._session.read(target)
try:
original = _read_text(handle)
finally:
handle.close()
updated = apply_diff(original, operation.diff or "")
await self._session.write(target, io.BytesIO(updated.encode("utf-8")))
return ApplyPatchResult(output=f"Updated {self._display_path(target)}")
async def delete_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
target = self._resolve_path(operation.path)
await self._session.rm(target)
return ApplyPatchResult(output=f"Deleted {self._display_path(target)}")
def _resolve_path(self, raw_path: str) -> Path:
return self._session.normalize_path(raw_path)
def _display_path(self, path: Path) -> str:
root = Path(self._session.state.manifest.root)
return path.relative_to(root).as_posix()
class WorkspaceApplyPatchCapability(Capability):
"""Expose the hosted apply_patch tool against the active sandbox workspace."""
def __init__(self) -> None:
super().__init__(type="workspace_apply_patch")
self._session: BaseSandboxSession | None = None
def bind(self, session: BaseSandboxSession) -> None:
self._session = session
def tools(self) -> list[Tool]:
if self._session is None:
return []
return [ApplyPatchTool(editor=_SandboxWorkspaceEditor(self._session))]
async def instructions(self, manifest: Manifest) -> str | None:
_ = manifest
return (
"Use the `apply_patch` tool for workspace text edits when you need to create or "
"update files inside the sandbox. Prefer saving final outputs in the requested "
"workspace directories instead of describing edits without writing them."
)
+56
View File
@@ -0,0 +1,56 @@
from __future__ import annotations
from agents.sandbox import Capability, Manifest
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
from agents.tool import (
ShellCallOutcome,
ShellCommandOutput,
ShellCommandRequest,
ShellResult,
ShellTool,
Tool,
)
class WorkspaceShellCapability(Capability):
"""Expose one shell tool for inspecting the active sandbox workspace."""
def __init__(self) -> None:
super().__init__(type="workspace_shell")
self._session: BaseSandboxSession | None = None
def bind(self, session: BaseSandboxSession) -> None:
self._session = session
def tools(self) -> list[Tool]:
return [ShellTool(executor=self._execute_shell)]
async def instructions(self, manifest: Manifest) -> str | None:
_ = manifest
return (
"Use the `shell` tool to inspect the sandbox workspace before answering. "
"The workspace root is the current working directory, so prefer relative paths "
"with commands like `pwd`, `find .`, and `cat`. Only cite files you actually read."
)
async def _execute_shell(self, request: ShellCommandRequest) -> ShellResult:
if self._session is None:
raise RuntimeError("Workspace shell is not bound to a sandbox session.")
timeout_s = (
request.data.action.timeout_ms / 1000
if request.data.action.timeout_ms is not None
else None
)
outputs: list[ShellCommandOutput] = []
for command in request.data.action.commands:
result = await self._session.exec(command, timeout=timeout_s, shell=True)
outputs.append(
ShellCommandOutput(
command=command,
stdout=result.stdout.decode("utf-8", errors="replace"),
stderr=result.stderr.decode("utf-8", errors="replace"),
outcome=ShellCallOutcome(type="exit", exit_code=result.exit_code),
)
)
return ShellResult(output=outputs)