chore: import upstream snapshot with attribution
CI (OpenClaw E2E) / openclaw test (push) Has been cancelled
CI / coverage-report (push) Has been cancelled
CI / test-kubernetes (push) Has been cancelled
CI / should-run-thorough (push) Has been cancelled
CI / test-thorough (cloudwatch-demo) (push) Has been cancelled
CI / test-thorough (flink-ecs) (push) Has been cancelled
CI / test-thorough (upstream-lambda) (push) Has been cancelled
CI / test-thorough (prefect-ecs-fargate) (push) Has been cancelled
Release / build-binaries (zip, opensre.exe, onefile, windows-latest, windows-x64) (push) Has been cancelled
Benchmark image — build + push to ECR (any adapter) / build + push (push) Has been cancelled
CI / quality (ubuntu-latest) (push) Has been cancelled
CI / test (tools-runtime) (push) Has been cancelled
CI / test (e2e-general) (push) Has been cancelled
CI / test (cli-runtime) (push) Has been cancelled
CI / test (e2e-provider-and-openclaw) (push) Has been cancelled
CI / test (integrations-and-misc) (push) Has been cancelled
Release / verify (push) Has been cancelled
Release / build-python-dist (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, macos-15-intel, darwin-x64) (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, macos-latest, darwin-arm64) (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, ubuntu-22.04, linux-x64) (push) Has been cancelled
Release / publish-release (push) Has been cancelled
Release / publish-main-release (push) Has been cancelled
Interactive Shell Live (PR + post-merge) / turn-checks (no-LLM) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
Interactive Shell Live (PR + post-merge) / turn-live shard ${{ matrix.shard_index }} (push) Has been cancelled
Release / prepare (push) Has been cancelled
Release / build-binaries (tar.gz, opensre, onedir, ubuntu-22.04-arm, linux-arm64) (push) Has been cancelled
Synthetic Deterministic Tests / Synthetic offline (deterministic) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:10:45 +08:00
commit 4b6817381b
3933 changed files with 525247 additions and 0 deletions
@@ -0,0 +1,133 @@
"""Agent-facing Python execution tool."""
from __future__ import annotations
from typing import Any
from core.tool_framework.base import BaseTool
from platform.observability.trace.spans import component_span
from tools.system.python_execution_tool.credentials import execution_env, github_extract_params
from tools.system.python_execution_tool.runner import run_python_execution
class PythonExecutionTool(BaseTool):
"""Run generated Python code with structured inputs and approved credentials."""
name = "execute_python_code"
display_name = "Python execution"
source = "knowledge"
side_effect_level = "read_only"
surfaces = ("investigation", "chat")
injected_params = ["github_token"]
description = (
"Execute generated Python code in a restricted subprocess, capture stdout, stderr, "
"exceptions, and timeout state, and return the result to the agent. Network access is "
"blocked by default; opt in only for approved API-backed analysis. Subprocess spawning "
"is always blocked — for OpenSRE version/runtime facts use "
"`inputs['opensre_runtime']` (injected automatically) or "
"`importlib.metadata.version('opensre')`, never `opensre --version` or "
"`subprocess`. When workflow guidance lists skills, read each skill description and "
"follow the one that matches the user's request."
)
use_cases = [
"Compute metrics or summaries from structured evidence already in context",
"Run a small API-backed calculation with approved credentials",
"Parse logs or JSON payloads when a direct tool result needs post-processing",
"Read OpenSRE version via inputs['opensre_runtime'] or importlib.metadata",
]
anti_examples = [
"Changing local files or shelling out to other processes",
"Calling opensre --version / subprocess / os.system (blocked by sandbox)",
"Long-running jobs, crawlers, or broad external scans",
"Accessing credentials not explicitly provided by configured integrations or env vars",
]
input_schema = {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Python source code to execute.",
},
"inputs": {
"type": "object",
"description": (
"Optional JSON-serializable values injected into the script as the "
"`inputs` global. OpenSRE always merges `opensre_runtime` "
"(version, runtime_env, feature_flags) unless you already set that key."
),
"nullable": True,
},
"timeout": {
"type": "integer",
"description": "Maximum execution time in seconds. Defaults to 30 and caps at 60.",
"nullable": True,
},
"allow_network": {
"type": "boolean",
"description": (
"Allow outbound network calls for approved API-backed analysis. Defaults to "
"false; subprocess execution and filesystem write restrictions still apply."
),
"nullable": True,
},
"github_token": {
"type": "string",
"description": "Injected GitHub token. Hidden from the model-facing schema.",
},
},
"required": ["code"],
}
outputs = {
"success": "True when execution completed with exit code 0 and did not time out",
"stdout": "Captured standard output",
"stderr": "Captured standard error",
"exit_code": "Process exit code, or -1 for timeout/runner failures",
"timed_out": "True when execution exceeded the timeout",
"error": "Human-readable runner error when available",
"credentials_available": "Credential labels made available to the subprocess",
}
def is_available(self, _sources: dict[str, dict]) -> bool:
"""The sandbox itself is local and always available."""
return True
def extract_params(self, sources: dict[str, dict]) -> dict[str, Any]:
"""Inject approved credentials from resolved integration sources."""
return github_extract_params(sources)
def run(
self,
code: str,
inputs: dict[str, Any] | None = None,
timeout: int | None = None,
allow_network: bool | None = None,
github_token: str | None = None,
runtime_metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Execute ``code`` in the sandbox with runtime metadata injected.
``runtime_metadata`` — when the caller has a session with a pre-built
``runtime_metadata`` dict (e.g. ``SessionCore.runtime_metadata``),
passing it here avoids re-running ``build_runtime_metadata()`` per tool
call. When ``None`` (default) the merge helper builds a fresh dict —
preserving the pre-#3946 behavior. Callers that thread session down
(T-2c follow-up) can pass ``session.runtime_metadata`` directly.
"""
from config.runtime_metadata import merge_runtime_into_inputs
with component_span("runtime_metadata:sandbox"):
env, credentials_available = execution_env(github_token=github_token)
return run_python_execution(
code=code,
inputs=merge_runtime_into_inputs(inputs, metadata=runtime_metadata),
timeout=timeout,
env=env,
allow_network=bool(allow_network),
credentials_available=credentials_available,
)
execute_python_code = PythonExecutionTool()
__all__ = ["PythonExecutionTool", "execute_python_code"]
@@ -0,0 +1,33 @@
"""Credential/environment resolution for the Python execution tool."""
from __future__ import annotations
from typing import Any
from integrations.github.client import resolve_github_token
from integrations.github.helpers import github_creds
GITHUB_TOKEN_ENV = "GITHUB_TOKEN"
def github_extract_params(sources: dict[str, dict]) -> dict[str, Any]:
"""Extract GitHub credentials from resolved integration sources."""
gh = sources.get("github", {})
token = github_creds(gh).get("github_token") if gh else None
return {"github_token": token} if token else {}
def execution_env(*, github_token: str | None = None) -> tuple[dict[str, str], list[str]]:
"""Return approved env vars for generated Python code plus credential labels."""
env: dict[str, str] = {}
available: list[str] = []
token = resolve_github_token(github_token)
if token:
env[GITHUB_TOKEN_ENV] = token
available.append("github")
return env, available
__all__ = ["GITHUB_TOKEN_ENV", "execution_env", "github_extract_params"]
@@ -0,0 +1,54 @@
"""Execution helpers for the Python execution tool."""
from __future__ import annotations
from typing import Any
from platform.sandbox.runner import DEFAULT_TIMEOUT, MAX_TIMEOUT, run_python_sandbox
def run_python_execution(
*,
code: str,
inputs: dict[str, Any] | None,
timeout: int | None,
env: dict[str, str],
allow_network: bool,
credentials_available: list[str],
) -> dict[str, Any]:
"""Run generated Python and return a stable, planner-friendly result."""
effective_timeout = min(timeout or DEFAULT_TIMEOUT, MAX_TIMEOUT)
secret_values = tuple(value for value in env.values() if value)
result = run_python_sandbox(
code=code,
inputs=inputs,
timeout=effective_timeout,
env=env,
allow_network=allow_network,
)
output: dict[str, Any] = {
"source": "knowledge",
"code": result.code,
"inputs": result.inputs,
"stdout": _redact(result.stdout, secret_values),
"stderr": _redact(result.stderr, secret_values),
"exit_code": result.exit_code,
"timed_out": result.timed_out,
"success": result.success,
"credentials_available": credentials_available,
"network_allowed": allow_network,
}
if result.error:
output["error"] = _redact(result.error, secret_values)
return output
def _redact(text: str, secret_values: tuple[str, ...]) -> str:
redacted = text
for secret in secret_values:
redacted = redacted.replace(secret, "[redacted]")
return redacted
__all__ = ["run_python_execution"]
@@ -0,0 +1,61 @@
---
name: github-star-velocity
description: Compute GitHub repository star velocity over a rolling time window using the stargazers API.
tools:
- execute_python_code
---
# GitHub Star Velocity
Use this skill when the user asks for GitHub star velocity, stars gained in the
last N hours, star growth rate, or similar metrics for a repository.
## Prerequisites
1. Set `allow_network: true` on `execute_python_code`.
2. Read `GITHUB_TOKEN` from the subprocess environment (injected when GitHub
credentials are configured). Never print the token.
3. Parse `owner/repo` from the repository URL or user input.
## API approach
1. Fetch current `stargazers_count` from `GET /repos/{owner}/{repo}`.
2. Fetch stargazers with timestamps from
`GET /repos/{owner}/{repo}/stargazers?per_page=100` using
`Accept: application/vnd.github.v3.star+json`.
3. Each entry includes `starred_at`. Count stars where `starred_at` is within
the requested window (for example, the last 24 hours).
## Critical pagination trap
Stargazers are returned **oldest first**, not newest first. Do **not** stop
after the first page when the newest entries on that page fall outside the
window — that produces a false zero.
Instead, paginate through **all** pages (follow the `Link` response header
until there is no `rel="next"`) and count every `starred_at` inside the window.
## Sanity check before reporting
Treat these results as suspicious and rerun with a full paginated scan before
answering:
- `0` stars in the last 24 hours for a repo with thousands of stars and recent
activity
- Velocity that implies losing stars without an explicit unstar request
- Counts that disagree sharply with `stargazers_count` deltas when you have a
recent baseline
When a result looks wrong, widen the scan (all pages), print the most recent
`starred_at` observed, and only then return the velocity.
## Output shape
Return:
- Total current stars
- Stars gained in the window
- Velocity (stars per hour and stars per day)
- Window start timestamp (UTC)
- Most recent `starred_at` in the window
- Optional hourly breakdown for the last 24 hours