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
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:
@@ -0,0 +1,131 @@
|
||||
"""Pi coding-task tool: hand a coding task to the Pi agent so it implements the change.
|
||||
|
||||
Package layout (separation of concerns):
|
||||
|
||||
- ``errors.py`` — :class:`PiCodingError` + stable ``error_kind`` constants.
|
||||
- ``validation.py`` — argument validators + :class:`ResolvedRequest` resolution.
|
||||
- ``runner.py`` — lifecycle/execution stages (enable gate, CLI readiness,
|
||||
run the polled Pi process, shape the result dict).
|
||||
- ``__init__.py`` — this file: the agent-facing :class:`BaseTool` contract whose
|
||||
``run`` orchestrates those stages. The class lives here (rather than a sister
|
||||
module) because the tool registry discovers instances by ``__class__.__module__``
|
||||
and does not recurse into sub-modules.
|
||||
|
||||
This is the first **mutating** agent-callable tool, so it is deliberately gated,
|
||||
mirroring how ``execute_python_code`` is gated by availability:
|
||||
|
||||
- ``side_effect_level = "mutating"``.
|
||||
- ``is_available`` returns True only when ``PI_CODING_ENABLED`` is set, so it is
|
||||
never offered to the agent unless the operator opts in.
|
||||
- ``surfaces = ("investigation",)`` — the surface the REPL assistant tool loop and
|
||||
the investigation pipeline actually consume (the ``chat`` surface has no live
|
||||
consumer). Reachability is gated by ``PI_CODING_ENABLED``, not by the surface.
|
||||
|
||||
Expected failures return a structured ``{"success": False, "error_kind": ...}`` dict;
|
||||
any *unexpected* exception propagates to ``BaseTool.__call__``, which reports it to
|
||||
Sentry. It edits the working tree and returns a summary + git diff; it never commits,
|
||||
pushes, or opens a PR (see ``integrations/pi``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from core.tool_framework.base import BaseTool
|
||||
from integrations.pi import is_pi_coding_enabled
|
||||
from tools.pi_coding_tool.errors import PiCodingError
|
||||
from tools.pi_coding_tool.runner import (
|
||||
SOURCE,
|
||||
ensure_cli_ready,
|
||||
ensure_enabled,
|
||||
error_output,
|
||||
execute,
|
||||
to_output,
|
||||
)
|
||||
from tools.pi_coding_tool.validation import resolve_request
|
||||
|
||||
|
||||
class PiCodingTool(BaseTool):
|
||||
"""Submit a coding task to the Pi agent; it edits the workspace and returns a diff."""
|
||||
|
||||
name = "pi_coding_task"
|
||||
display_name = "Pi coding task"
|
||||
source = SOURCE
|
||||
side_effect_level = "mutating"
|
||||
surfaces = ("investigation",)
|
||||
description = (
|
||||
"Submit a coding task to the Pi agent (pi.dev). Pi edits files in the workspace to "
|
||||
"implement the change and returns a summary plus the git diff. It does not commit, "
|
||||
"push, or open a PR. Disabled unless PI_CODING_ENABLED=1 and the Pi CLI is installed "
|
||||
"and authenticated."
|
||||
)
|
||||
use_cases = [
|
||||
"Apply a small, well-scoped fix identified during an investigation",
|
||||
"Make a targeted code change in the current repository and return the diff for review",
|
||||
]
|
||||
anti_examples = [
|
||||
"Reading logs, metrics, or traces (use a read-only evidence tool instead)",
|
||||
"Large multi-file refactors that should be reviewed interactively",
|
||||
]
|
||||
input_schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task": {
|
||||
"type": "string",
|
||||
"description": "Natural-language description of the coding change Pi should make.",
|
||||
},
|
||||
"workspace": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"Absolute path to the repository to edit. "
|
||||
"Defaults to PI_CODING_WORKSPACE or the current directory."
|
||||
),
|
||||
"nullable": True,
|
||||
},
|
||||
"model": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"Optional Pi model override in provider/model form "
|
||||
"(e.g. anthropic/claude-haiku-4-5). Defaults to PI_CODING_MODEL."
|
||||
),
|
||||
"nullable": True,
|
||||
},
|
||||
},
|
||||
"required": ["task"],
|
||||
}
|
||||
outputs = {
|
||||
"success": "True when Pi completed and exited cleanly",
|
||||
"error_kind": "Stable failure category (disabled, invalid_input, cli_unavailable, "
|
||||
"timeout, execution_error) or None on success",
|
||||
"summary": "Pi's final message summarizing what it changed",
|
||||
"changed_files": "Files modified in the working tree (status porcelain)",
|
||||
"diff": "git diff of the changes vs HEAD (truncated if large)",
|
||||
"diff_truncated": "True when the diff was truncated",
|
||||
"error": "Human-readable error detail when the task failed",
|
||||
}
|
||||
|
||||
def is_available(self, _sources: dict[str, dict]) -> bool:
|
||||
"""Only available when explicitly opted in (cheap flag check)."""
|
||||
return is_pi_coding_enabled()
|
||||
|
||||
def run(
|
||||
self,
|
||||
task: str,
|
||||
workspace: str | None = None,
|
||||
model: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
ensure_enabled()
|
||||
request = resolve_request(task, workspace, model)
|
||||
ensure_cli_ready()
|
||||
except PiCodingError as exc:
|
||||
return error_output(exc.kind, exc.message)
|
||||
|
||||
# Expected execution failures (timeout, provider limit, no-op) come back as a
|
||||
# populated PiCodingResult; any *unexpected* exception propagates to
|
||||
# BaseTool.__call__, which reports it to Sentry (the global tool wrapper).
|
||||
return to_output(execute(request))
|
||||
|
||||
|
||||
# Module-level instance so the tool registry auto-discovers it (see tools/registry.py).
|
||||
pi_coding_task = PiCodingTool()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Error model for the Pi coding tool.
|
||||
|
||||
A single typed exception (:class:`PiCodingError`) carries a stable ``kind`` that is
|
||||
surfaced to callers as the tool's ``error_kind`` output field, so failures are
|
||||
machine-classifiable instead of free-text-only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Stable failure categories surfaced in the tool's ``error_kind`` output field.
|
||||
ERR_DISABLED = "disabled"
|
||||
ERR_INVALID_INPUT = "invalid_input"
|
||||
ERR_CLI_UNAVAILABLE = "cli_unavailable"
|
||||
ERR_TIMEOUT = "timeout"
|
||||
ERR_EXECUTION = "execution_error"
|
||||
|
||||
|
||||
class PiCodingError(Exception):
|
||||
"""An expected, user-actionable failure with a stable ``kind``."""
|
||||
|
||||
def __init__(self, kind: str, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
self.message = message
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Lifecycle and execution orchestration for the Pi coding tool.
|
||||
|
||||
These are the stages ``PiCodingTool.run`` drives, kept as small free functions so
|
||||
the tool class stays a thin agent-facing contract:
|
||||
|
||||
- :func:`ensure_enabled` — opt-in gate (``PI_CODING_ENABLED``).
|
||||
- :func:`ensure_cli_ready` — Pi binary installed and authenticated.
|
||||
- :func:`execute` — run the polled Pi process (``integrations/pi`` client).
|
||||
- :func:`to_output` — shape a stable result dict (with ``error_kind``).
|
||||
- :func:`error_output` — the same dict shape for an early/expected failure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Final
|
||||
|
||||
from integrations.pi import (
|
||||
PiCodingResult,
|
||||
is_pi_coding_enabled,
|
||||
run_pi_coding_task,
|
||||
verify_pi_coding,
|
||||
)
|
||||
from tools.pi_coding_tool.errors import (
|
||||
ERR_CLI_UNAVAILABLE,
|
||||
ERR_DISABLED,
|
||||
ERR_EXECUTION,
|
||||
ERR_TIMEOUT,
|
||||
PiCodingError,
|
||||
)
|
||||
from tools.pi_coding_tool.validation import ResolvedRequest
|
||||
|
||||
#: Evidence source tag stamped on every result dict.
|
||||
SOURCE: Final = "knowledge"
|
||||
|
||||
_DISABLED_MESSAGE = (
|
||||
"Pi coding tool is disabled. Set PI_CODING_ENABLED=1 (and install/authenticate "
|
||||
"the Pi CLI) to enable it."
|
||||
)
|
||||
|
||||
|
||||
def ensure_enabled() -> None:
|
||||
if not is_pi_coding_enabled():
|
||||
raise PiCodingError(ERR_DISABLED, _DISABLED_MESSAGE)
|
||||
|
||||
|
||||
def ensure_cli_ready() -> None:
|
||||
available, detail = verify_pi_coding()
|
||||
if not available:
|
||||
raise PiCodingError(ERR_CLI_UNAVAILABLE, f"Pi CLI is not ready: {detail}")
|
||||
|
||||
|
||||
def execute(request: ResolvedRequest) -> PiCodingResult:
|
||||
return run_pi_coding_task(
|
||||
request.task,
|
||||
workspace=request.workspace,
|
||||
model=request.model,
|
||||
timeout_sec=request.timeout_sec,
|
||||
)
|
||||
|
||||
|
||||
def to_output(result: PiCodingResult) -> dict[str, Any]:
|
||||
error_kind: str | None = None
|
||||
if not result.success:
|
||||
error_kind = ERR_TIMEOUT if result.timed_out else ERR_EXECUTION
|
||||
return {
|
||||
"source": SOURCE,
|
||||
"success": result.success,
|
||||
"error_kind": error_kind,
|
||||
"summary": result.summary,
|
||||
"changed_files": result.changed_files,
|
||||
"diff": result.diff,
|
||||
"diff_truncated": result.diff_truncated,
|
||||
"returncode": result.returncode,
|
||||
"timed_out": result.timed_out,
|
||||
"error": result.error,
|
||||
}
|
||||
|
||||
|
||||
def error_output(kind: str, message: str) -> dict[str, Any]:
|
||||
return {"source": SOURCE, "success": False, "error_kind": kind, "error": message}
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Input validation and request resolution for the Pi coding tool.
|
||||
|
||||
Turns the loose tool arguments (``task`` / ``workspace`` / ``model``) into a
|
||||
validated, fully-resolved :class:`ResolvedRequest`, applying config defaults
|
||||
(``PI_CODING_WORKSPACE`` / ``PI_CODING_MODEL`` / ``PI_CODING_TIMEOUT_SECONDS``).
|
||||
Each validator raises :class:`PiCodingError` with ``kind="invalid_input"`` on a
|
||||
bad value.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from integrations.pi import pi_coding_model, pi_coding_timeout_seconds, pi_coding_workspace
|
||||
from tools.pi_coding_tool.errors import ERR_INVALID_INPUT, PiCodingError
|
||||
|
||||
_MAX_TASK_CHARS = 4000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedRequest:
|
||||
"""A validated, fully-resolved coding request ready to execute."""
|
||||
|
||||
task: str
|
||||
workspace: str
|
||||
model: str | None
|
||||
timeout_sec: float
|
||||
|
||||
|
||||
def validate_task(task: str | None) -> str:
|
||||
cleaned = (task or "").strip()
|
||||
if not cleaned:
|
||||
raise PiCodingError(ERR_INVALID_INPUT, "task is required and must be non-empty.")
|
||||
if len(cleaned) > _MAX_TASK_CHARS:
|
||||
raise PiCodingError(
|
||||
ERR_INVALID_INPUT,
|
||||
f"task is too long ({len(cleaned)} chars); keep it under {_MAX_TASK_CHARS}.",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
def validate_workspace(workspace: str | None) -> str:
|
||||
resolved = (workspace or "").strip() or pi_coding_workspace()
|
||||
path = Path(resolved).expanduser()
|
||||
if not path.exists():
|
||||
raise PiCodingError(ERR_INVALID_INPUT, f"workspace does not exist: {path}")
|
||||
if not path.is_dir():
|
||||
raise PiCodingError(ERR_INVALID_INPUT, f"workspace is not a directory: {path}")
|
||||
return str(path)
|
||||
|
||||
|
||||
def validate_model(model: str | None) -> str | None:
|
||||
resolved = (model or "").strip() or pi_coding_model()
|
||||
if resolved is None:
|
||||
return None
|
||||
# Pi accepts "provider/model" and shorthands (e.g. "sonnet:high"); only reject
|
||||
# obviously malformed values (whitespace inside the token).
|
||||
if any(ch.isspace() for ch in resolved):
|
||||
raise PiCodingError(
|
||||
ERR_INVALID_INPUT,
|
||||
f"model must not contain whitespace; got {resolved!r}.",
|
||||
)
|
||||
return resolved
|
||||
|
||||
|
||||
def resolve_request(task: str | None, workspace: str | None, model: str | None) -> ResolvedRequest:
|
||||
"""Validate + normalize the tool arguments into a :class:`ResolvedRequest`."""
|
||||
return ResolvedRequest(
|
||||
task=validate_task(task),
|
||||
workspace=validate_workspace(workspace),
|
||||
model=validate_model(model),
|
||||
timeout_sec=pi_coding_timeout_seconds(),
|
||||
)
|
||||
Reference in New Issue
Block a user