refactor: убрать мёртвый API и сентинель-исключение

- удалены неиспользуемые ToolRegistry::all(), FileSandbox::root(),
  ChatResult::\ (вместе с параметром конструктора)
- HttpRequestTool: allowPrivate больше не свойство, только параметр
- FileWalker возвращает bool: колбэк возвращает false, чтобы остановить
  обход; из search_files и find_files убраны throw/catch '__limit__'
- добавлены тесты лимита для search_files и find_files
- 102 теста
This commit is contained in:
rsgrinko committed 2026-11-12 23:29:51 +03:00
1 parent 27c0fc2477
commit 6734ca5289
9 files changed
+72 -66

No files matched your search

+1 -1
View File
@@ -131,7 +131,6 @@ final class AiClient implements ChatClient
toolCalls: self::parseToolCalls($message), toolCalls: self::parseToolCalls($message),
assistantMessage: $assistant, assistantMessage: $assistant,
usage: is_array($data['usage'] ?? null) ? $data['usage'] : [], usage: is_array($data['usage'] ?? null) ? $data['usage'] : [],
raw: $data,
); );
} }
@@ -217,3 +216,4 @@ final class AiClient implements ChatClient
} }
-2
View File
@@ -16,14 +16,12 @@ final class ChatResult
* @param list<array{id: string, name: string, arguments: array<string, mixed>}> $toolCalls * @param list<array{id: string, name: string, arguments: array<string, mixed>}> $toolCalls
* @param array<string, mixed> $assistantMessage * @param array<string, mixed> $assistantMessage
* @param array<string, int> $usage * @param array<string, int> $usage
* @param array<string, mixed> $raw полный ответ провайдера (для отладки)
*/ */
public function __construct( public function __construct(
public readonly string $text, public readonly string $text,
public readonly array $toolCalls, public readonly array $toolCalls,
public readonly array $assistantMessage, public readonly array $assistantMessage,
public readonly array $usage = [], public readonly array $usage = [],
public readonly array $raw = [],
) { ) {
} }
-8
View File
@@ -33,14 +33,6 @@ final class ToolRegistry
return isset($this->tools[$name]); return isset($this->tools[$name]);
} }
/**
* @return list<Tool>
*/
public function all(): array
{
return array_values($this->tools);
}
/** /**
* Схемы для поля "tools" запроса к модели. * Схемы для поля "tools" запроса к модели.
* *
+29
View File
@@ -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);
});
-5
View File
@@ -47,11 +47,6 @@ final class FileSandbox
return new self($base, false); return new self($base, false);
} }
public function root(): string
{
return $this->root;
}
public function isRestricted(): bool public function isRestricted(): bool
{ {
return $this->restricted; return $this->restricted;
+11 -20
View File
@@ -76,35 +76,26 @@ final class FindFilesTool implements Tool
} }
$found = []; $found = [];
$truncated = false;
try { FileWalker::walk($start, function (string $path) use (&$found, $pattern, $limit): bool {
FileWalker::walk($start, function (string $path) use (&$found, $pattern, $limit): void { $relative = $this->sandbox->relative($path);
$relative = $this->sandbox->relative($path);
if (!fnmatch($pattern, $relative) && !fnmatch($pattern, basename($path))) { if (!fnmatch($pattern, $relative) && !fnmatch($pattern, basename($path))) {
return; return true;
}
$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();
} }
$truncated = true; $size = @filesize($path);
} $found[] = $relative . ' (' . Bytes::human($size === false ? 0 : $size) . ')';
return count($found) < $limit;
});
if ($found === []) { if ($found === []) {
return 'Файлы не найдены по маске "' . $pattern . '".'; return 'Файлы не найдены по маске "' . $pattern . '".';
} }
$truncated = count($found) >= $limit;
return 'Найдено ' . count($found) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n" return 'Найдено ' . count($found) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n"
. implode("\n", $found); . implode("\n", $found);
} }
+2 -1
View File
@@ -38,7 +38,7 @@ final class HttpRequestTool implements Tool
*/ */
public function __construct( public function __construct(
array $auth = [], array $auth = [],
private readonly bool $allowPrivate = false, bool $allowPrivate = false,
private readonly int $defaultChars = 4000, private readonly int $defaultChars = 4000,
) { ) {
$normalized = []; $normalized = [];
@@ -227,3 +227,4 @@ final class HttpRequestTool implements Tool
} }
+16 -21
View File
@@ -98,36 +98,31 @@ final class SearchFilesTool implements Tool
} }
$results = []; $results = [];
$truncated = false;
try { FileWalker::walk($start, function (string $file) use (&$results, $regex, $glob, $limit): bool {
FileWalker::walk($start, function (string $file) use (&$results, $regex, $glob, $limit): void { $relative = $this->sandbox->relative($file);
$relative = $this->sandbox->relative($file);
if (!fnmatch($glob, $relative) && !fnmatch($glob, basename($file))) { if (!fnmatch($glob, $relative) && !fnmatch($glob, basename($file))) {
return; return true;
}
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();
} }
$truncated = true; foreach ($this->matchLines($file, $regex) as $line) {
} $results[] = $relative . ':' . $line;
if (count($results) >= $limit) {
return false; // лимит: останавливаем обход
}
}
return true;
});
if ($results === []) { if ($results === []) {
return 'Ничего не найдено по "' . $pattern . '".'; return 'Ничего не найдено по "' . $pattern . '".';
} }
$truncated = count($results) >= $limit;
return 'Найдено ' . count($results) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n" return 'Найдено ' . count($results) . ($truncated ? ' (обрезано по лимиту ' . $limit . ')' : '') . ":\n"
. implode("\n", $results); . implode("\n", $results);
} }
+13 -8
View File
@@ -7,23 +7,24 @@ namespace AiSdk\Tools\Support;
/** /**
* Рекурсивный обход каталога с единым списком игнорируемых папок. * Рекурсивный обход каталога с единым списком игнорируемых папок.
* *
* Исключения из колбэка пробрасываются наружу — так инструменты * Колбэк возвращает false, чтобы остановить обход: это нужно инструментам
* останавливают обход по достижении лимита. * с лимитом результатов.
*/ */
final class FileWalker final class FileWalker
{ {
public const DEFAULT_IGNORE = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var']; public const DEFAULT_IGNORE = ['.git', '.idea', '.vscode', 'vendor', 'node_modules', 'var'];
/** /**
* @param callable(string): void $onFile * @param callable(string): bool $onFile вернуть false — остановить обход
* @param list<string> $ignore * @param list<string> $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); $entries = @scandir($directory);
if ($entries === false) { if ($entries === false) {
return; return true;
} }
foreach ($entries as $name) { foreach ($entries as $name) {
@@ -34,14 +35,18 @@ final class FileWalker
$path = $directory . DIRECTORY_SEPARATOR . $name; $path = $directory . DIRECTORY_SEPARATOR . $name;
if (is_dir($path)) { if (is_dir($path)) {
self::walk($path, $onFile, $ignore); if (!self::walk($path, $onFile, $ignore)) {
return false;
}
continue; continue;
} }
if (is_file($path)) { if (is_file($path) && $onFile($path) === false) {
$onFile($path); return false;
} }
} }
return true;
} }
} }