refactor: убрать дубли, развести слои, разбить тесты

- Support/FileWalker: один обход каталога вместо двух копий
- Support/Bytes: форматирование размера вместо трёх копий
- Support/UrlGuard: SSRF-проверки вынесены из HttpRequestTool
- Support/AtomicWriter: запись вынесена из FileSandbox
- HttpRequest: normalizeUrl/resolveRedirect — одна реализация URL-логики
- AiClient поверх HttpTransport::request: один транспорт, одна TLS-логика
  (было две копии cURL-настроек), подсказка про AI_CAINFO переехала в HttpTransport
- Http переименован в HttpTransport: транспорт/значение/инструмент больше
  не называются одинаково
- Agent: удалён мёртвый withDefaults — ядро больше не зависит от tools
- tests: раннер + support + cases по темам (agent, files, http, shell,
  logging, tools, architecture)
- архитектурные тесты: src не импортирует Tools, tools не создают AiClient
  и не вызывают cURL напрямую
- 100 тестов
This commit is contained in:
rsgrinko committed 2026-11-12 23:13:45 +03:00
1 parent 74bb23c159
commit 76b3be7115
28 files changed
+2022 -1749

No files matched your search

-30
View File
@@ -121,36 +121,6 @@ final class FileSandbox
* Атомарная запись: сначала во временный файл рядом, потом rename.
* Так при сбое не остаётся полузаписанный файл.
*/
public function writeAtomic(string $absolute, string $content): void
{
$directory = dirname($absolute);
$temporary = @tempnam($directory, '.aisdk_');
if ($temporary === false) {
throw new \RuntimeException('Не удалось создать временный файл в ' . $directory);
}
$written = @file_put_contents($temporary, $content);
if ($written === false) {
@unlink($temporary);
throw new \RuntimeException('Не удалось записать файл.');
}
@chmod($temporary, 0644);
// На Windows rename не перезаписывает существующий файл.
if (is_file($absolute) && DIRECTORY_SEPARATOR === '\\') {
@unlink($absolute);
}
if (!@rename($temporary, $absolute)) {
@unlink($temporary);
throw new \RuntimeException('Не удалось переименовать временный файл.');
}
}
/**
* Путь для показа пользователю (относительно корня, если внутри него).
+4 -41
View File
@@ -5,13 +5,14 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
use AiSdk\Tools\Support\Bytes;
use AiSdk\Tools\Support\FileWalker;
/**
* Поиск файлов по маске имени внутри песочницы.
*/
final class FindFilesTool implements Tool
{
private const IGNORED = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var'];
public function __construct(
private readonly FileSandbox $sandbox,
@@ -78,7 +79,7 @@ final class FindFilesTool implements Tool
$truncated = false;
try {
$this->eachEntry($start, function (string $path) use (&$found, $pattern, $limit): void {
FileWalker::walk($start, function (string $path) use (&$found, $pattern, $limit): void {
$relative = $this->sandbox->relative($path);
if (!fnmatch($pattern, $relative) && !fnmatch($pattern, basename($path))) {
@@ -86,7 +87,7 @@ final class FindFilesTool implements Tool
}
$size = @filesize($path);
$found[] = $relative . ' (' . $this->human($size === false ? 0 : $size) . ')';
$found[] = $relative . ' (' . Bytes::human($size === false ? 0 : $size) . ')';
if (count($found) >= $limit) {
throw new \RuntimeException('__limit__');
@@ -111,43 +112,5 @@ final class FindFilesTool implements Tool
/**
* @param callable(string): void $onFile
*/
private function eachEntry(string $directory, callable $onFile): void
{
$entries = @scandir($directory);
if ($entries === false) {
return;
}
foreach ($entries as $name) {
if ($name === '.' || $name === '..' || in_array($name, self::IGNORED, true)) {
continue;
}
$path = $directory . DIRECTORY_SEPARATOR . $name;
if (is_dir($path)) {
$this->eachEntry($path, $onFile);
continue;
}
if (is_file($path)) {
$onFile($path);
}
}
}
private function human(int $bytes): string
{
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' МБ';
}
if ($bytes >= 1024) {
return round($bytes / 1024, 1) . ' КБ';
}
return $bytes . ' Б';
}
}
+8 -103
View File
@@ -4,8 +4,9 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Http;
use AiSdk\HttpTransport;
use AiSdk\HttpRequest;
use AiSdk\Tools\Support\UrlGuard;
use AiSdk\Tool;
/**
@@ -28,6 +29,7 @@ final class HttpRequestTool implements Tool
/** @var array<string, array<string, string>> креды по хосту (в нижнем регистре) */
private readonly array $auth;
private readonly UrlGuard $guard;
/**
* @param array<string, array<string, string>> $auth креды по хосту:
@@ -46,6 +48,7 @@ final class HttpRequestTool implements Tool
}
$this->auth = $normalized;
$this->guard = new UrlGuard($allowPrivate);
}
public function name(): string
@@ -143,9 +146,9 @@ final class HttpRequestTool implements Tool
$response = null;
for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) {
$this->assertAllowed($url);
$this->guard->assertAllowed($url);
$response = Http::request(
$response = HttpTransport::request(
$url,
self::TIMEOUT,
false,
@@ -167,7 +170,7 @@ final class HttpRequestTool implements Tool
. '. Повтори запрос по этому адресу, если он нужен.';
}
$url = $this->normalize($this->absolute($url, $response['location']));
$url = HttpRequest::normalizeUrl(HttpRequest::resolveRedirect($url, $response['location']));
}
} catch (\Throwable $e) {
return 'Ошибка: ' . $e->getMessage();
@@ -219,106 +222,8 @@ final class HttpRequestTool implements Tool
return $this->auth[$host] ?? null;
}
private function assertAllowed(string $url): void
{
$parts = parse_url($url);
if ($parts === false || !isset($parts['scheme'], $parts['host'])) {
throw new \RuntimeException('некорректный URL');
}
$scheme = strtolower((string) $parts['scheme']);
if (!in_array($scheme, ['http', 'https'], true)) {
throw new \RuntimeException('разрешены только http и https');
}
if ($this->allowPrivate) {
return;
}
$host = strtolower((string) $parts['host']);
if ($host === 'localhost' || str_ends_with($host, '.local') || str_contains($host, 'metadata')) {
throw new \RuntimeException('запрос к локальному адресу запрещён');
}
$ips = [];
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
$ips[] = $host;
} else {
$resolved = @gethostbynamel($host);
if ($resolved === false || $resolved === []) {
throw new \RuntimeException('не удалось разрешить хост: ' . $host);
}
$ips = $resolved;
}
foreach ($ips as $ip) {
if (!$this->isPublicIp($ip)) {
throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host);
}
}
}
private function isPublicIp(string $ip): bool
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return false;
}
// 100.64.0.0/10 (CGNAT) не покрывается флагами PHP.
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
$long = ip2long($ip);
$cgnat = ip2long('100.64.0.0');
if ($long !== false && $cgnat !== false && ($long & 0xFFC00000) === ($cgnat & 0xFFC00000)) {
return false;
}
}
return true;
}
private function normalize(string $url): string
{
$url = trim($url);
if (preg_match('#^[a-z][a-z0-9+.-]*://#i', $url) === 1) {
return $url;
}
return 'https://' . ltrim($url, '/');
}
private function absolute(string $base, string $location): string
{
if (preg_match('#^https?://#i', $location) === 1) {
return $location;
}
$parts = parse_url($base);
if ($parts === false || !isset($parts['scheme'], $parts['host'])) {
throw new \RuntimeException('некорректный адрес редиректа');
}
$origin = $parts['scheme'] . '://' . $parts['host']
. (isset($parts['port']) ? ':' . $parts['port'] : '');
if (str_starts_with($location, '//')) {
return $parts['scheme'] . ':' . $location;
}
if (str_starts_with($location, '/')) {
return $origin . $location;
}
$dir = rtrim(dirname($parts['path'] ?? '/'), '/');
return $origin . $dir . '/' . $location;
}
}
+3 -13
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
use AiSdk\Tools\Support\Bytes;
/**
* Список файлов и каталогов внутри заданного корня.
@@ -83,7 +84,7 @@ final class ListDirTool implements Tool
}
$size = @filesize($full);
$files[] = $name . ' (' . $this->human($size === false ? 0 : $size) . ')';
$files[] = $name . ' (' . Bytes::human($size === false ? 0 : $size) . ')';
}
$all = array_merge($dirs, $files);
@@ -99,16 +100,5 @@ final class ListDirTool implements Tool
return $text;
}
private function human(int $bytes): string
{
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' МБ';
}
if ($bytes >= 1024) {
return round($bytes / 1024, 1) . ' КБ';
}
return $bytes . ' Б';
}
}
+4 -14
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
use AiSdk\Tools\Support\Bytes;
/**
* Чтение текстового файла внутри заданного корня.
@@ -84,7 +85,7 @@ final class ReadFileTool implements Tool
}
if ($size > 10 * 1024 * 1024) {
return 'Файл слишком большой (' . $this->human($size) . '). Читай частями через offset и limit.';
return 'Файл слишком большой (' . Bytes::human($size) . '). Читай частями через offset и limit.';
}
$handle = fopen($file, 'rb');
@@ -101,7 +102,7 @@ final class ReadFileTool implements Tool
}
if ($first !== '' && !mb_check_encoding($first, 'UTF-8')) {
return 'Файл бинарный (' . $this->human($size) . '), не читаю.';
return 'Файл бинарный (' . Bytes::human($size) . '), не читаю.';
}
$lines = file($file, FILE_IGNORE_NEW_LINES);
@@ -129,16 +130,5 @@ final class ReadFileTool implements Tool
return 'Файл ' . $path . ', строки ' . $from . '–' . $to . ' из ' . $total . ":\n" . $text;
}
private function human(int $bytes): string
{
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' МБ';
}
if ($bytes >= 1024) {
return round($bytes / 1024, 1) . ' КБ';
}
return $bytes . ' Б';
}
}
+3 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
use AiSdk\Tools\Support\AtomicWriter;
/**
* Точечная замена в файле: старый фрагмент -> новый.
@@ -94,7 +95,7 @@ final class ReplaceInFileTool implements Tool
: $this->replaceOnce($content, $search, $replace);
try {
$this->sandbox->writeAtomic($file, $updated);
AtomicWriter::write($file, $updated);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
@@ -118,3 +119,4 @@ final class ReplaceInFileTool implements Tool
return substr_replace($content, $replace, $position, strlen($search));
}
}
+3 -28
View File
@@ -5,6 +5,8 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
use AiSdk\Tools\Support\Bytes;
use AiSdk\Tools\Support\FileWalker;
/**
* Поиск по содержимому файлов внутри песочницы (аналог grep).
@@ -14,7 +16,6 @@ use AiSdk\Tool;
*/
final class SearchFilesTool implements Tool
{
private const IGNORED = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var'];
private const MAX_FILE = 1048576;
private const MAX_LINE = 200;
@@ -100,7 +101,7 @@ final class SearchFilesTool implements Tool
$truncated = false;
try {
$this->eachFile($start, function (string $file) use (&$results, $regex, $glob, $limit): void {
FileWalker::walk($start, function (string $file) use (&$results, $regex, $glob, $limit): void {
$relative = $this->sandbox->relative($file);
if (!fnmatch($glob, $relative) && !fnmatch($glob, basename($file))) {
@@ -192,30 +193,4 @@ final class SearchFilesTool implements Tool
/**
* @param callable(string): void $onFile
*/
private function eachFile(string $directory, callable $onFile): void
{
$entries = @scandir($directory);
if ($entries === false) {
return;
}
foreach ($entries as $name) {
if ($name === '.' || $name === '..' || in_array($name, self::IGNORED, true)) {
continue;
}
$path = $directory . DIRECTORY_SEPARATOR . $name;
if (is_dir($path)) {
$this->eachFile($path, $onFile);
continue;
}
if (is_file($path)) {
$onFile($path);
}
}
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Атомарная запись файла: сначала во временный файл рядом, потом rename.
*
* Так при сбое не остаётся полузаписанный файл, а на Windows
* существующий файл удаляется перед переименованием.
*/
final class AtomicWriter
{
/**
* @throws \RuntimeException если записать не удалось
*/
public static function write(string $absolute, string $content): void
{
$directory = dirname($absolute);
$temporary = @tempnam($directory, '.aisdk_');
if ($temporary === false) {
throw new \RuntimeException('Не удалось создать временный файл в ' . $directory);
}
if (@file_put_contents($temporary, $content) === false) {
@unlink($temporary);
throw new \RuntimeException('Не удалось записать файл.');
}
@chmod($temporary, 0644);
// На Windows rename не перезаписывает существующий файл.
if (is_file($absolute) && DIRECTORY_SEPARATOR === '\\') {
@unlink($absolute);
}
if (!@rename($temporary, $absolute)) {
@unlink($temporary);
throw new \RuntimeException('Не удалось переименовать временный файл.');
}
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Человекочитаемый размер в байтах.
*/
final class Bytes
{
public static function human(int $bytes): string
{
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' МБ';
}
if ($bytes >= 1024) {
return round($bytes / 1024, 1) . ' КБ';
}
return $bytes . ' Б';
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Рекурсивный обход каталога с единым списком игнорируемых папок.
*
* Исключения из колбэка пробрасываются наружу — так инструменты
* останавливают обход по достижении лимита.
*/
final class FileWalker
{
public const DEFAULT_IGNORE = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var'];
/**
* @param callable(string): void $onFile
* @param list<string> $ignore
*/
public static function walk(string $directory, callable $onFile, array $ignore = self::DEFAULT_IGNORE): void
{
$entries = @scandir($directory);
if ($entries === false) {
return;
}
foreach ($entries as $name) {
if ($name === '.' || $name === '..' || in_array($name, $ignore, true)) {
continue;
}
$path = $directory . DIRECTORY_SEPARATOR . $name;
if (is_dir($path)) {
self::walk($path, $onFile, $ignore);
continue;
}
if (is_file($path)) {
$onFile($path);
}
}
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools\Support;
/**
* Защита от SSRF: пропускает только публичные http/https-адреса.
*
* Проверяются схема, имя хоста и все A-записи. `localhost`, `.local`,
* `metadata`, приватные диапазоны и CGNAT запрещены. Флаг allowPrivate
* снимает проверку адреса (оставляя проверку схемы) — для внутренних API.
*/
final class UrlGuard
{
public function __construct(private readonly bool $allowPrivate = false)
{
}
/**
* @throws \RuntimeException если адрес недопустим
*/
public function assertAllowed(string $url): void
{
$parts = parse_url($url);
if ($parts === false || !isset($parts['scheme'], $parts['host'])) {
throw new \RuntimeException('некорректный URL');
}
$scheme = strtolower((string) $parts['scheme']);
if (!in_array($scheme, ['http', 'https'], true)) {
throw new \RuntimeException('разрешены только http и https');
}
if ($this->allowPrivate) {
return;
}
$host = strtolower((string) $parts['host']);
if ($host === 'localhost' || str_ends_with($host, '.local') || str_contains($host, 'metadata')) {
throw new \RuntimeException('запрос к локальному адресу запрещён');
}
$ips = [];
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
$ips[] = $host;
} else {
$resolved = @gethostbynamel($host);
if ($resolved === false || $resolved === []) {
throw new \RuntimeException('не удалось разрешить хост: ' . $host);
}
$ips = $resolved;
}
foreach ($ips as $ip) {
if (!$this->isPublicIp($ip)) {
throw new \RuntimeException('запрос к приватному адресу запрещён: ' . $host);
}
}
}
private function isPublicIp(string $ip): bool
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return false;
}
// 100.64.0.0/10 (CGNAT) не покрывается флагами PHP.
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
$long = ip2long($ip);
$cgnat = ip2long('100.64.0.0');
if ($long !== false && $cgnat !== false && ($long & 0xFFC00000) === ($cgnat & 0xFFC00000)) {
return false;
}
}
return true;
}
}
+4 -3
View File
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Http;
use AiSdk\HttpTransport;
use AiSdk\Tool;
/**
@@ -90,7 +90,7 @@ final class WeatherTool implements Tool
'timezone' => 'auto',
]);
[$status, $body] = Http::get('https://api.open-meteo.com/v1/forecast?' . $query);
[$status, $body] = HttpTransport::get('https://api.open-meteo.com/v1/forecast?' . $query);
$data = json_decode($body, true);
$current = $data['current'] ?? null;
@@ -124,7 +124,7 @@ final class WeatherTool implements Tool
'format' => 'json',
]);
[$status, $body] = Http::get('https://geocoding-api.open-meteo.com/v1/search?' . $query);
[$status, $body] = HttpTransport::get('https://geocoding-api.open-meteo.com/v1/search?' . $query);
if ($status >= 400) {
return null;
@@ -150,3 +150,4 @@ final class WeatherTool implements Tool
];
}
}
+3 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
use AiSdk\Tools\Support\AtomicWriter;
/**
* Создание и перезапись файла внутри песочницы.
@@ -76,7 +77,7 @@ final class WriteFileTool implements Tool
}
$existed = is_file($target);
$this->sandbox->writeAtomic($target, $content);
AtomicWriter::write($target, $content);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
@@ -86,3 +87,4 @@ final class WriteFileTool implements Tool
. ': ' . strlen($content) . ' Б.';
}
}