mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
b000a2cf51
* Adding AgentFileStore and FileAccessProvider to support file ased operations for agents. * Address PR review feedback on FileAccessProvider - Probe symlinks on the unresolved candidate path so in-root symlinks cannot silently pass and out-of-root symlinks surface the correct error message. - Validate matching_lines elements in FileSearchResult.from_dict and raise a clean ValueError for non-mapping entries. - Cap search regex pattern length (256 chars) via a new _compile_search_regex helper to mitigate ReDoS, and surface the cap in the file_access_search_files tool description. - Skip non-UTF-8 files during filesystem search instead of aborting the entire directory walk. - Replace the module-scope trailing string in the data-processing sample with comments to avoid Ruff B018. - Remove the checked-in working/region_totals.md sample artifact so the save flow works from a clean checkout. - Expand the Windows stdout reconfiguration comment in task_runner.py for clarity. - Add tests for invalid/oversize regex, non-UTF-8 file search, and in-root symlink rejection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix mypy redundant-cast in FileSearchResult.from_dict Use cast(list[object], ...) instead of cast(list[Any], ...) so the cast represents a real type change (lists are invariant) and is no longer flagged by mypy as redundant, while still satisfying pyright's reportUnknownVariableType. Matches the existing pattern in _memory.py. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Tighten path normalization and directory resolution in FileAccess - _normalize_relative_path now strips surrounding whitespace up front so leading/trailing spaces never leak into file segments, and rejects trailing path separators for file paths so 'foo/' is no longer silently coerced to 'foo'. - FileSystemAgentFileStore._resolve_safe_directory_path normalizes with is_directory=True and maps an empty normalized result to the root. This matches InMemoryAgentFileStore so whitespace-only directory inputs resolve to the root instead of raising. - Added tests for whitespace stripping, trailing-separator rejection, and whitespace-only directory listing on the filesystem store. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Harden FileAccess search and atomic save in store API - Add wall-clock timeout (10s) around regex scans so a pathological pattern (e.g. `(a+)+`) below the length cap cannot stall the event loop. - Offload the InMemoryAgentFileStore regex scan to a worker thread, matching the filesystem store. - Fail closed when `Path.is_symlink` raises during the safe-path probe so a permission error cannot silently bypass the symlink/reparse-point rejection. - Add `overwrite: bool = True` to `AgentFileStore.write_file`; the in-memory store performs the check under the existing lock and the filesystem store uses `open(mode='x')` so concurrent callers cannot race past `overwrite=False`. - `file_access_save_file` now relies on the atomic store call instead of a separate `file_exists` round-trip. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fix Python 3.10 timeout handling and add directory arg to list/search tools - Catch asyncio.TimeoutError in _run_search_with_timeout. In Python 3.10 asyncio.wait_for raises asyncio.exceptions.TimeoutError, which is distinct from the builtin TimeoutError (the two were unified in 3.11). Catching the asyncio alias works on every supported version. - Add an optional directory parameter to file_access_list_files and file_access_search_files so agents can enumerate / scope searches to nested folders, not just the store root. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address FileAccess review feedback: case, errors, signal, TOCTOU - InMemoryAgentFileStore now stores (display_name, content) so list_files and search_files return the original-case names callers wrote, matching the behaviour of FileSystemAgentFileStore on case-preserving filesystems and removing the silent in-memory vs. on-disk contract divergence. - FileSystemAgentFileStore.read_file raises ValueError instead of letting UnicodeDecodeError bubble for binary / non-UTF-8 input, restoring symmetry with search_files (which still skips) and giving the tool layer a recoverable type to translate. - Tool wrappers now catch ValueError and OSError around every operation and surface them as readable strings, so 'you used ..' and 'the file already exists' are both reported to the model the same way instead of the former crashing out as an unhandled exception. - _search_files_sync logs per skipped non-UTF-8 file at WARNING and an aggregate INFO summary so operators can distinguish 'no matches' from 'half the corpus was unreadable'. - FileSystemAgentFileStore softens its docstrings to acknowledge the inherent probe-then-open TOCTOU window. On POSIX both read and write now pass O_NOFOLLOW so the kernel refuses if the leaf segment becomes a symlink between the probe and the open. Windows has no equivalent flag; the limitation is documented. - Tests cover: case preservation on list/search, ValueError on non-UTF-8 read at the store and tool layer, tool-layer string responses for path-traversal and oversized-regex inputs, search-skip log output, symlink rejection on delete/search/list, and symlinked intermediate directory rejection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address FileAccess nit comments: docstrings, enumerate, opt-in delete approval - Expand FileSearchMatch/FileSearchResult.to_dict docstrings to explain why the override is needed (__slots__ defeats the mixin's __dict__ iteration) and why exclude/exclude_none are accepted-but-ignored (mixin signature compatibility for callers like to_json). - Use enumerate(lines, start=1) in _search_file_content so the +1 below is no longer needed; rename loop variable to line_number for clarity. - Add opt-in require_delete_approval: bool = False on FileAccessProvider. When True, file_access_delete_file is registered with approval_mode 'always_require' so the host must approve every delete. Default False preserves current behaviour and matches the .NET reference, but deployments that want a safer-by-default posture can enable it. - Add tests covering both delete approval modes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * FileAccess: require delete approval by default Flip the default for FileAccessProvider(require_delete_approval=...) from False to True so destructive deletes are gated by host approval out of the box. Callers that want the previous autonomous behaviour (which matches the .NET reference) can pass require_delete_approval=False. Tests updated accordingly. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fixing linkinspector by installing Chrome for puppeteer first. --------- Co-authored-by: Ben Thomas <25218250+alliscode@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
229 lines
8.2 KiB
Python
229 lines
8.2 KiB
Python
# Copyright (c) Microsoft. All rights reserved.
|
|
|
|
"""Shared utilities for running Poe tasks across workspace packages.
|
|
|
|
These helpers centralize workspace discovery, selector matching, and execution
|
|
mode so the root task dispatcher and dependency tooling interpret package
|
|
filters the same way.
|
|
"""
|
|
|
|
import concurrent.futures
|
|
import contextlib
|
|
import glob
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from collections.abc import Sequence
|
|
from fnmatch import fnmatch
|
|
from pathlib import Path
|
|
|
|
# On Windows, stdout defaults to cp1252 under non-interactive callers (e.g.
|
|
# prek / pre-commit hooks). Reconfigure to UTF-8 before importing rich so
|
|
# unicode glyphs like ``\u2713`` don't raise ``UnicodeEncodeError``.
|
|
if sys.platform == "win32":
|
|
for _stream in (sys.stdout, sys.stderr):
|
|
reconfigure = getattr(_stream, "reconfigure", None)
|
|
if callable(reconfigure):
|
|
with contextlib.suppress(OSError, ValueError):
|
|
reconfigure(encoding="utf-8")
|
|
|
|
import tomli
|
|
from rich import print
|
|
|
|
|
|
def discover_projects(workspace_pyproject_file: Path) -> list[Path]:
|
|
"""Discover all workspace projects from pyproject.toml."""
|
|
with workspace_pyproject_file.open("rb") as f:
|
|
data = tomli.load(f)
|
|
|
|
projects = data["tool"]["uv"]["workspace"]["members"]
|
|
exclude = data["tool"]["uv"]["workspace"].get("exclude", [])
|
|
|
|
all_projects: list[Path] = []
|
|
for project in projects:
|
|
if "*" in project:
|
|
globbed = glob.glob(str(project), root_dir=workspace_pyproject_file.parent)
|
|
globbed_paths = [Path(p) for p in globbed]
|
|
all_projects.extend(globbed_paths)
|
|
else:
|
|
all_projects.append(Path(project))
|
|
|
|
for project in exclude:
|
|
if "*" in project:
|
|
globbed = glob.glob(str(project), root_dir=workspace_pyproject_file.parent)
|
|
globbed_paths = [Path(p) for p in globbed]
|
|
all_projects = [p for p in all_projects if p not in globbed_paths]
|
|
else:
|
|
all_projects = [p for p in all_projects if p != Path(project)]
|
|
|
|
return all_projects
|
|
|
|
|
|
def extract_poe_tasks(file: Path) -> set[str]:
|
|
"""Extract poe task names from a pyproject.toml file."""
|
|
with file.open("rb") as f:
|
|
data = tomli.load(f)
|
|
|
|
tasks = set(data.get("tool", {}).get("poe", {}).get("tasks", {}).keys())
|
|
|
|
# Check if there is an include too
|
|
include: str | None = data.get("tool", {}).get("poe", {}).get("include", None)
|
|
if include:
|
|
include_file = file.parent / include
|
|
if include_file.exists():
|
|
tasks = tasks.union(extract_poe_tasks(include_file))
|
|
|
|
return tasks
|
|
|
|
|
|
def build_work_items(projects: list[Path], task_names: list[str]) -> list[tuple[Path, str]]:
|
|
"""Build cross-product of (package, task) for packages that define the task."""
|
|
work_items: list[tuple[Path, str]] = []
|
|
for project in projects:
|
|
available_tasks = extract_poe_tasks(project / "pyproject.toml")
|
|
for task in task_names:
|
|
if task in available_tasks:
|
|
work_items.append((project, task))
|
|
return work_items
|
|
|
|
|
|
def normalize_project_filter(value: str) -> str:
|
|
"""Normalize a user-supplied workspace selector.
|
|
|
|
Strip presentation differences so short names, relative paths, and globs can
|
|
be compared with one matcher.
|
|
"""
|
|
normalized = value.strip().strip("/").replace("\\", "/")
|
|
return normalized or "."
|
|
|
|
|
|
def build_project_filter_candidates(project: Path | str, aliases: Sequence[str] = ()) -> set[str]:
|
|
"""Return accepted selector values for one workspace project.
|
|
|
|
We accept the workspace path, short package name, and any supplied aliases
|
|
so user-facing ``--package core`` stays stable even when underlying tools
|
|
still need paths or distribution names.
|
|
"""
|
|
normalized_path = normalize_project_filter(str(project))
|
|
candidates = {normalized_path}
|
|
if normalized_path == ".":
|
|
candidates.update({"./", "root"})
|
|
else:
|
|
# Accept bare short names like ``core`` alongside ``packages/core`` and
|
|
# ``./packages/core`` so callers do not have to care which form a
|
|
# downstream script prefers.
|
|
path = Path(normalized_path)
|
|
candidates.add(path.name)
|
|
candidates.add(f"./{normalized_path}")
|
|
|
|
for alias in aliases:
|
|
normalized_alias = normalize_project_filter(alias)
|
|
if normalized_alias and normalized_alias != ".":
|
|
candidates.add(normalized_alias)
|
|
|
|
return {candidate.lower() for candidate in candidates}
|
|
|
|
|
|
def project_filter_matches(project: Path | str, pattern: str, aliases: Sequence[str] = ()) -> bool:
|
|
"""Return whether a project matches a user-supplied selector or glob.
|
|
|
|
Matching happens against the normalized candidate set so CLI callers can use
|
|
the same selector vocabulary everywhere.
|
|
"""
|
|
normalized_pattern = normalize_project_filter(pattern).lower()
|
|
return any(
|
|
fnmatch(candidate, normalized_pattern) for candidate in build_project_filter_candidates(project, aliases)
|
|
)
|
|
|
|
|
|
def _run_task_subprocess(
|
|
project: Path,
|
|
task: str,
|
|
workspace_root: Path,
|
|
task_args: Sequence[str] = (),
|
|
) -> tuple[Path, str, int, str, str, float]:
|
|
"""Run a single poe task in a project directory via subprocess."""
|
|
start = time.monotonic()
|
|
cwd = workspace_root / project
|
|
result = subprocess.run(
|
|
["uv", "run", "poe", task, *task_args],
|
|
cwd=cwd,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
elapsed = time.monotonic() - start
|
|
return (project, task, result.returncode, result.stdout, result.stderr, elapsed)
|
|
|
|
|
|
def _run_sequential(work_items: list[tuple[Path, str]], task_args: Sequence[str] = ()) -> None:
|
|
"""Run tasks sequentially using in-process PoeThePoet (streaming output)."""
|
|
from poethepoet.app import PoeThePoet
|
|
|
|
for project, task in work_items:
|
|
print(f"Running task {task} in {project}")
|
|
app = PoeThePoet(cwd=project)
|
|
result = app(cli_args=[task, *task_args])
|
|
if result:
|
|
sys.exit(result)
|
|
|
|
|
|
def _run_parallel(work_items: list[tuple[Path, str]], workspace_root: Path, task_args: Sequence[str] = ()) -> None:
|
|
"""Run all (package x task) combinations in parallel via subprocesses."""
|
|
max_workers = min(len(work_items), os.cpu_count() or 4)
|
|
failures: list[tuple[Path, str, str, str]] = []
|
|
completed = 0
|
|
total = len(work_items)
|
|
|
|
print(f"[cyan]Running {total} task(s) in parallel (max {max_workers} workers)...[/cyan]")
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
futures = {
|
|
executor.submit(_run_task_subprocess, project, task, workspace_root, task_args): (project, task)
|
|
for project, task in work_items
|
|
}
|
|
for future in concurrent.futures.as_completed(futures):
|
|
project, task, returncode, stdout, stderr, elapsed = future.result()
|
|
completed += 1
|
|
progress = f"[{completed}/{total}]"
|
|
if returncode == 0:
|
|
print(f" [green]✓[/green] {progress} {task} in {project} ({elapsed:.1f}s)")
|
|
else:
|
|
print(f" [red]✗[/red] {progress} {task} in {project} ({elapsed:.1f}s)")
|
|
failures.append((project, task, stdout, stderr))
|
|
|
|
if failures:
|
|
print(f"\n[red]{len(failures)} task(s) failed:[/red]")
|
|
for project, task, stdout, stderr in failures:
|
|
print(f"\n[red]{'=' * 60}[/red]")
|
|
print(f"[red]FAILED: {task} in {project}[/red]")
|
|
if stdout.strip():
|
|
print(stdout)
|
|
if stderr.strip():
|
|
sys.stderr.write(stderr)
|
|
sys.exit(1)
|
|
|
|
print(f"\n[green]All {total} task(s) passed ✓[/green]")
|
|
|
|
|
|
def run_tasks(
|
|
work_items: list[tuple[Path, str]],
|
|
workspace_root: Path,
|
|
*,
|
|
sequential: bool = False,
|
|
task_args: Sequence[str] = (),
|
|
) -> None:
|
|
"""Run work items either in parallel or sequentially.
|
|
|
|
Single items use in-process PoeThePoet for streaming output.
|
|
Multiple items use parallel subprocesses by default.
|
|
"""
|
|
if not work_items:
|
|
print("[yellow]No matching tasks found in any package[/yellow]")
|
|
return
|
|
|
|
if sequential or len(work_items) == 1:
|
|
_run_sequential(work_items, task_args)
|
|
else:
|
|
_run_parallel(work_items, workspace_root, task_args)
|