From 6734ca5289176c60209e073fa5d1c242921ae146 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Thu, 12 Nov 2026 23:29:51 +0300 Subject: [PATCH] =?UTF-8?q?refactor:=20=D1=83=D0=B1=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BC=D1=91=D1=80=D1=82=D0=B2=D1=8B=D0=B9=20API=20?= =?UTF-8?q?=D0=B8=20=D1=81=D0=B5=D0=BD=D1=82=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?-=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - удалены неиспользуемые ToolRegistry::all(), FileSandbox::root(), ChatResult::\ (вместе с параметром конструктора) - HttpRequestTool: allowPrivate больше не свойство, только параметр - FileWalker возвращает bool: колбэк возвращает false, чтобы остановить обход; из search_files и find_files убраны throw/catch '__limit__' - добавлены тесты лимита для search_files и find_files - 102 теста --- src/AiClient.php | 2 +- src/ChatResult.php | 2 -- src/ToolRegistry.php | 8 -------- tests/cases/files.php | 29 ++++++++++++++++++++++++++++ tools/FileSandbox.php | 5 ----- tools/FindFilesTool.php | 31 +++++++++++------------------- tools/HttpRequestTool.php | 3 ++- tools/SearchFilesTool.php | 37 ++++++++++++++++-------------------- tools/Support/FileWalker.php | 21 ++++++++++++-------- 9 files changed, 72 insertions(+), 66 deletions(-) diff --git a/src/AiClient.php b/src/AiClient.php index 059dc0c..b59db31 100644 --- a/src/AiClient.php +++ b/src/AiClient.php @@ -131,7 +131,6 @@ final class AiClient implements ChatClient toolCalls: self::parseToolCalls($message), assistantMessage: $assistant, usage: is_array($data['usage'] ?? null) ? $data['usage'] : [], - raw: $data, ); } @@ -217,3 +216,4 @@ final class AiClient implements ChatClient } + diff --git a/src/ChatResult.php b/src/ChatResult.php index e5eb50c..cebe22e 100644 --- a/src/ChatResult.php +++ b/src/ChatResult.php @@ -16,14 +16,12 @@ final class ChatResult * @param list}> $toolCalls * @param array $assistantMessage * @param array $usage - * @param array $raw полный ответ провайдера (для отладки) */ public function __construct( public readonly string $text, public readonly array $toolCalls, public readonly array $assistantMessage, public readonly array $usage = [], - public readonly array $raw = [], ) { } diff --git a/src/ToolRegistry.php b/src/ToolRegistry.php index f9349b3..80bf8d6 100644 --- a/src/ToolRegistry.php +++ b/src/ToolRegistry.php @@ -33,14 +33,6 @@ final class ToolRegistry return isset($this->tools[$name]); } - /** - * @return list - */ - public function all(): array - { - return array_values($this->tools); - } - /** * Схемы для поля "tools" запроса к модели. * diff --git a/tests/cases/files.php b/tests/cases/files.php index 833acd4..c3e8a1a 100644 --- a/tests/cases/files.php +++ b/tests/cases/files.php @@ -359,3 +359,32 @@ test('sandbox: ограниченный режим по-прежнему бло }); + +test('search_files: лимит останавливает обход', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.txt', "one\ntwo\nthree\n"); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle([ + 'pattern' => '\w+', + 'limit' => 2, + ]); + + assertContains('обрезано по лимиту 2', $result); + assertContains('Найдено 2', $result); +}); + +test('find_files: лимит останавливает обход', function (): void { + $dir = testDir(); + + for ($i = 1; $i <= 5; $i++) { + file_put_contents($dir . '/f' . $i . '.php', 'x'); + } + + $result = (new FindFilesTool(new FileSandbox($dir)))->handle([ + 'pattern' => '*.php', + 'limit' => 2, + ]); + + assertContains('обрезано по лимиту 2', $result); + assertContains('Найдено 2', $result); +}); diff --git a/tools/FileSandbox.php b/tools/FileSandbox.php index 634865c..d940153 100644 --- a/tools/FileSandbox.php +++ b/tools/FileSandbox.php @@ -47,11 +47,6 @@ final class FileSandbox return new self($base, false); } - public function root(): string - { - return $this->root; - } - public function isRestricted(): bool { return $this->restricted; diff --git a/tools/FindFilesTool.php b/tools/FindFilesTool.php index 845496d..0f1b969 100644 --- a/tools/FindFilesTool.php +++ b/tools/FindFilesTool.php @@ -76,35 +76,26 @@ final class FindFilesTool implements Tool } $found = []; - $truncated = false; - try { - FileWalker::walk($start, function (string $path) use (&$found, $pattern, $limit): void { - $relative = $this->sandbox->relative($path); + FileWalker::walk($start, function (string $path) use (&$found, $pattern, $limit): bool { + $relative = $this->sandbox->relative($path); - if (!fnmatch($pattern, $relative) && !fnmatch($pattern, basename($path))) { - return; - } - - $size = @filesize($path); - $found[] = $relative . ' (' . Bytes::human($size === false ? 0 : $size) . ')'; - - if (count($found) >= $limit) { - throw new \RuntimeException('__limit__'); - } - }); - } catch (\RuntimeException $e) { - if ($e->getMessage() !== '__limit__') { - return 'Ошибка поиска: ' . $e->getMessage(); + if (!fnmatch($pattern, $relative) && !fnmatch($pattern, basename($path))) { + return true; } - $truncated = true; - } + $size = @filesize($path); + $found[] = $relative . ' (' . Bytes::human($size === false ? 0 : $size) . ')'; + + return count($found) < $limit; + }); if ($found === []) { return 'Файлы не найдены по маске "' . $pattern . '".'; } + $truncated = count($found) >= $limit; + return 'Найдено ' . count($found) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n" . implode("\n", $found); } diff --git a/tools/HttpRequestTool.php b/tools/HttpRequestTool.php index 84045cb..0d6ae1f 100644 --- a/tools/HttpRequestTool.php +++ b/tools/HttpRequestTool.php @@ -38,7 +38,7 @@ final class HttpRequestTool implements Tool */ public function __construct( array $auth = [], - private readonly bool $allowPrivate = false, + bool $allowPrivate = false, private readonly int $defaultChars = 4000, ) { $normalized = []; @@ -227,3 +227,4 @@ final class HttpRequestTool implements Tool } + diff --git a/tools/SearchFilesTool.php b/tools/SearchFilesTool.php index f9d41fe..27d59ef 100644 --- a/tools/SearchFilesTool.php +++ b/tools/SearchFilesTool.php @@ -98,36 +98,31 @@ final class SearchFilesTool implements Tool } $results = []; - $truncated = false; - try { - FileWalker::walk($start, function (string $file) use (&$results, $regex, $glob, $limit): void { - $relative = $this->sandbox->relative($file); + FileWalker::walk($start, function (string $file) use (&$results, $regex, $glob, $limit): bool { + $relative = $this->sandbox->relative($file); - if (!fnmatch($glob, $relative) && !fnmatch($glob, basename($file))) { - return; - } - - foreach ($this->matchLines($file, $regex) as $line) { - $results[] = $relative . ':' . $line; - - if (count($results) >= $limit) { - throw new \RuntimeException('__limit__'); - } - } - }); - } catch (\RuntimeException $e) { - if ($e->getMessage() !== '__limit__') { - return 'Ошибка поиска: ' . $e->getMessage(); + if (!fnmatch($glob, $relative) && !fnmatch($glob, basename($file))) { + return true; } - $truncated = true; - } + foreach ($this->matchLines($file, $regex) as $line) { + $results[] = $relative . ':' . $line; + + if (count($results) >= $limit) { + return false; // лимит: останавливаем обход + } + } + + return true; + }); if ($results === []) { return 'Ничего не найдено по "' . $pattern . '".'; } + $truncated = count($results) >= $limit; + return 'Найдено ' . count($results) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n" . implode("\n", $results); } diff --git a/tools/Support/FileWalker.php b/tools/Support/FileWalker.php index d51d8e8..975d9cf 100644 --- a/tools/Support/FileWalker.php +++ b/tools/Support/FileWalker.php @@ -7,23 +7,24 @@ namespace AiSdk\Tools\Support; /** * Рекурсивный обход каталога с единым списком игнорируемых папок. * - * Исключения из колбэка пробрасываются наружу — так инструменты - * останавливают обход по достижении лимита. + * Колбэк возвращает false, чтобы остановить обход: это нужно инструментам + * с лимитом результатов. */ final class FileWalker { public const DEFAULT_IGNORE = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var']; /** - * @param callable(string): void $onFile + * @param callable(string): bool $onFile вернуть false — остановить обход * @param list $ignore + * @return bool true — обошли всё; false — остановились по просьбе колбэка */ - public static function walk(string $directory, callable $onFile, array $ignore = self::DEFAULT_IGNORE): void + public static function walk(string $directory, callable $onFile, array $ignore = self::DEFAULT_IGNORE): bool { $entries = @scandir($directory); if ($entries === false) { - return; + return true; } foreach ($entries as $name) { @@ -34,14 +35,18 @@ final class FileWalker $path = $directory . DIRECTORY_SEPARATOR . $name; if (is_dir($path)) { - self::walk($path, $onFile, $ignore); + if (!self::walk($path, $onFile, $ignore)) { + return false; + } continue; } - if (is_file($path)) { - $onFile($path); + if (is_file($path) && $onFile($path) === false) { + return false; } } + + return true; } }