diff --git a/README.md b/README.md index ecde467..d502f6f 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ src/ LoggingClient.php декоратор: логи запросов и ответов Tool.php интерфейс инструмента ToolRegistry.php набор инструментов - Http.php низкоуровневый HTTP: методы, тело, лимит размера + HttpTransport.php низкоуровневый HTTP: методы, тело, лимит размера HttpRequest.php сборка запроса: query, body, заголовки, Basic/Bearer Env.php .env без зависимостей AiException.php ошибки @@ -108,6 +108,7 @@ tools/ DateCalcTool.php разница дат и прибавление интервала UuidTool.php UUID v4 HashTool.php sha256/sha1/md5 + Support/ общие помощники: Bytes, FileWalker, UrlGuard, AtomicWriter examples/ 01-chat.php простой вопрос 02-tools.php агент с тремя инструментами @@ -121,7 +122,9 @@ examples/ 10-http.php HTTP: запрос, SSRF, allowPrivate 11-json.php инструменты без модели 12-logging.php логирование запросов к модели -tests/run.php тесты без сети +tests/run.php раннер тестов +tests/support.php помощники, заглушки, FakeClient +tests/cases/ тесты по темам (agent, files, http, shell, ...) ``` ## Как это работает @@ -530,7 +533,7 @@ curl http://10.10.10.77:8080/v1/models php tests/run.php ``` -97 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, +100 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, настройки (tool_choice, подтверждение вызовов, история), finish, файлы (чтение, запись, замена, поиск, побег из песочницы, свободный режим), CSV, единицы, даты, uuid/хеши, сборка HTTP-запроса (методы, тело, заголовки, @@ -639,10 +642,12 @@ $tools->add(new FinishTool()); Если хочется проверить весь цикл, не тратя токены: ```php -$agent = new Agent($fakeClient, $tools); // ChatClient из tests/run.php +$agent = new Agent($fakeClient, $tools); // ChatClient из tests/support.php $agent->ask('вопрос'); ``` --- Лицензия: делайте что хотите. + + diff --git a/src/Agent.php b/src/Agent.php index 733f0e2..6b0a021 100644 --- a/src/Agent.php +++ b/src/Agent.php @@ -4,8 +4,6 @@ declare(strict_types=1); namespace AiSdk; -use AiSdk\Tools\CalculatorTool; -use AiSdk\Tools\TimeTool; /** * Диалог с моделью и цикл вызова инструментов. @@ -410,11 +408,4 @@ final class Agent /** * Быстрый старт: агент с инструментами по умолчанию. */ - public static function withDefaults(ChatClient $client): self - { - return new self( - $client, - (new ToolRegistry())->add(new TimeTool(), new CalculatorTool()), - ); - } } diff --git a/src/AiClient.php b/src/AiClient.php index 55f52a4..059dc0c 100644 --- a/src/AiClient.php +++ b/src/AiClient.php @@ -83,12 +83,22 @@ final class AiClient implements ChatClient $body = array_merge($body, $this->extraBody); - [$raw, $status, $error] = $this->post($body); - - if ($raw === null) { - throw new AiException('Ошибка сети: ' . $error . $this->tlsHint($error)); - } + // Транспорт живёт в Http: TLS, CAINFO, таймауты и ошибки — в одном месте. + $response = HttpTransport::request( + url: rtrim($this->baseUrl, '/') . '/chat/completions', + timeout: $this->timeout, + follow: false, + maxBytes: 1048576, + method: 'POST', + headers: $this->requestHeaders(), + body: (string) json_encode( + $body, + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE + ), + ); + $status = $response['status']; + $raw = $response['body']; $data = json_decode($raw, true); if (!is_array($data)) { @@ -125,6 +135,24 @@ final class AiClient implements ChatClient ); } + /** + * @return array + */ + private function requestHeaders(): array + { + $headers = [ + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + 'Expect' => '', + ]; + + if ($this->apiKey !== '') { + $headers['Authorization'] = 'Bearer ' . $this->apiKey; + } + + return $headers; + } + /** * Разобрать tool_calls в удобный вид. Аргументы приходят строкой JSON. * @@ -186,86 +214,6 @@ final class AiClient implements ChatClient // Имя конкретного инструмента -> объект. return ['type' => 'function', 'function' => ['name' => $choice]]; } - - /** - * Подсказка при типовой ошибке TLS на Windows. - */ - private function tlsHint(string $error): string - { - if (!$this->verifySsl) { - return ''; - } - - if (!str_contains($error, 'certificate') && !str_contains($error, 'SSL')) { - return ''; - } - - return ' Подсказка: укажите путь к корневым сертификатам в AI_CAINFO ' - . 'или временно поставьте AI_VERIFY_SSL=false (только локально).'; - } - - /** - * @param array $body - * @return array{0: string|null, 1: int, 2: string|null} тело, HTTP-код, ошибка - */ - private function post(array $body): array - { - $url = rtrim($this->baseUrl, '/') . '/chat/completions'; - - $headers = [ - 'Content-Type: application/json', - 'Accept: application/json', - 'Expect:', - ]; - - if ($this->apiKey !== '') { - $headers[] = 'Authorization: Bearer ' . $this->apiKey; - } - - $payload = json_encode( - $body, - JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE - ); - - if ($payload === false) { - return [null, 0, 'не удалось сериализовать запрос в JSON']; - } - - $ch = curl_init($url); - - if ($ch === false) { - return [null, 0, 'не удалось создать cURL-дескриптор']; - } - - $options = [ - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => $payload, - CURLOPT_HTTPHEADER => $headers, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_TIMEOUT_MS => (int) round($this->timeout * 1000), - CURLOPT_CONNECTTIMEOUT_MS => 5000, - // AI_VERIFY_SSL=false отключает проверку цепочки и имени хоста. - CURLOPT_SSL_VERIFYPEER => $this->verifySsl, - CURLOPT_SSL_VERIFYHOST => $this->verifySsl ? 2 : 0, - CURLOPT_FOLLOWLOCATION => false, - ]; - - // Свой CA-бандл: актуально для Windows, где у PHP нет системных корней. - if ($this->caInfo !== '') { - $options[CURLOPT_CAINFO] = $this->caInfo; - } - - curl_setopt_array($ch, $options); - - $raw = curl_exec($ch); - $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); - $error = curl_error($ch); - curl_close($ch); - - if ($raw === false) { - return [null, $status, $error !== '' ? $error : 'неизвестная ошибка cURL']; - } - - return [(string) $raw, $status, null]; - } } + + diff --git a/src/ChatResult.php b/src/ChatResult.php index ab24ac6..e5eb50c 100644 --- a/src/ChatResult.php +++ b/src/ChatResult.php @@ -16,7 +16,7 @@ final class ChatResult * @param list}> $toolCalls * @param array $assistantMessage * @param array $usage - * @param array $raw + * @param array $raw полный ответ провайдера (для отладки) */ public function __construct( public readonly string $text, @@ -32,3 +32,4 @@ final class ChatResult return $this->toolCalls !== []; } } + diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 5392d50..af9b8fc 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -97,7 +97,7 @@ final class HttpRequest return new self($method, $url, $normalized, $encoded); } - private static function normalizeUrl(string $url): string + public static function normalizeUrl(string $url): string { $url = trim($url); @@ -112,6 +112,39 @@ final class HttpRequest return 'https://' . ltrim($url, '/'); } + /** + * Абсолютный адрес редиректа относительно текущего URL. + * + * @throws \RuntimeException если базовый адрес некорректен + */ + public static function resolveRedirect(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; + } + + $directory = rtrim(dirname($parts['path'] ?? '/'), '/'); + + return $origin . $directory . '/' . $location; + } + /** * @param array $query */ @@ -212,3 +245,4 @@ final class HttpRequest return 'Basic ' . base64_encode($user . ':' . $pass); } } + diff --git a/src/Http.php b/src/HttpTransport.php similarity index 86% rename from src/Http.php rename to src/HttpTransport.php index 76cba95..18b5faa 100644 --- a/src/Http.php +++ b/src/HttpTransport.php @@ -11,7 +11,7 @@ namespace AiSdk; * request() — низкоуровневый вызов: метод, заголовки, тело, лимит размера. * На нём построен http_request, включая защиту от SSRF. */ -final class Http +final class HttpTransport { /** * @return array{0: int, 1: string} HTTP-код и тело ответа @@ -23,6 +23,23 @@ final class Http return [$response['status'], $response['body']]; } + /** + * Подсказка при типовой ошибке TLS на Windows. + */ + private static function tlsHint(string $error, bool $verify): string + { + if (!$verify) { + return ''; + } + + if (!str_contains($error, 'certificate') && !str_contains($error, 'SSL')) { + return ''; + } + + return ' Подсказка: укажите путь к корневым сертификатам в AI_CAINFO ' + . 'или временно поставьте AI_VERIFY_SSL=false (только локально).'; + } + /** * Привести заголовки к формату cURL: список строк "Имя: значение". * @@ -139,7 +156,10 @@ final class Http // 23 = CURLE_WRITE_ERROR: это мы сами оборвали слишком большой ответ. if ($errno !== 0 && !($truncated && $errno === 23)) { - throw new AiException('HTTP-ошибка: ' . ($error !== '' ? $error : 'код ' . $errno)); + throw new AiException( + 'HTTP-ошибка: ' . ($error !== '' ? $error : 'код ' . $errno) + . self::tlsHint($error, $verify) + ); } return [ @@ -151,3 +171,4 @@ final class Http ]; } } + diff --git a/tests/cases/agent.php b/tests/cases/agent.php new file mode 100644 index 0000000..9687ec3 --- /dev/null +++ b/tests/cases/agent.php @@ -0,0 +1,409 @@ + '2+2'], 'call_42'), + textResult('Получилось 4.'), + ]); + + $agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'ты тестовый', 3); + + $answer = $agent->ask('Сколько будет 2+2?'); + + assertSame('Получилось 4.', $answer); + assertSame(2, count($client->requests), 'должно быть два запроса к модели'); + + // Второй запрос обязан содержать результат инструмента. + $messages = $client->requests[1]['messages']; + $last = $messages[count($messages) - 1]; + + assertSame('tool', $last['role']); + assertSame('call_42', $last['tool_call_id']); + assertSame('2+2 = 4', $last['content']); + + // И сами схемы инструментов ушли модели. + assertTrue($client->requests[0]['tools'] !== [], 'схемы инструментов не отправлены'); + + // Трассировка для отладки. + assertSame(1, count($agent->trace())); + assertSame('calculator', $agent->trace()[0]['name']); +}); + +test('агент: ошибка инструмента уходит модели, а не в exception', function (): void { + $client = new FakeClient([ + toolCall('nope', []), + textResult('Не смог посчитать.'), + ]); + + $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3); + $answer = $agent->ask('вопрос'); + + assertSame('Не смог посчитать.', $answer); + + $messages = $client->requests[1]['messages']; + $last = $messages[count($messages) - 1]; + + assertContains('неизвестный инструмент', $last['content']); +}); + +test('агент: после лимита раундов просит ответ без инструментов', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '1+1'], 'c1'), + toolCall('calculator', ['expression' => '1+1'], 'c2'), + toolCall('calculator', ['expression' => '1+1'], 'c3'), + textResult('Два.'), + ]); + + $agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'ты тестовый', 2); + + assertSame('Два.', $agent->ask('сколько?')); + + // 1 стартовый + 2 раунда + 1 финальный. + assertSame(4, count($client->requests)); + + $lastRequest = $client->requests[3]; + assertSame([], $lastRequest['tools'], 'финальный запрос должен идти без инструментов'); +}); + +test('агент: помнит историю между вопросами', function (): void { + $client = new FakeClient([ + textResult('Первый ответ.'), + textResult('Второй ответ.'), + ]); + + $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3); + + $agent->ask('первый вопрос'); + $agent->ask('второй вопрос'); + + $messages = $client->requests[1]['messages']; + $roles = array_column($messages, 'role'); + + assertSame(['system', 'user', 'assistant', 'user'], $roles); + assertSame('Первый ответ.', $messages[2]['content']); +}); + +test('агент: системный промпт можно сменить на ходу', function (): void { + $client = new FakeClient([textResult('первый'), textResult('второй')]); + $agent = new Agent($client, new ToolRegistry(), 'промпт №1', 3); + + $agent->ask('вопрос'); + $agent->setSystemPrompt('промпт №2'); + $agent->ask('ещё вопрос'); + + assertSame('промпт №2', $agent->systemPrompt()); + + // System-сообщение остаётся первым и в истории, и в запросе к модели. + $messages = $client->requests[1]['messages']; + assertSame('system', $messages[0]['role']); + assertSame('промпт №2', $messages[0]['content']); + + // История диалога при этом не потерялась. + assertSame(4, count($messages), 'system + 2 user + assistant'); +}); + +test('агент: без явного промпта берётся встроенный', function (): void { + $agent = new Agent(new FakeClient([textResult('ок')]), new ToolRegistry()); + + assertTrue($agent->systemPrompt() !== '', 'промпт по умолчанию пустой'); +}); + +test('агент: tool_choice не навязывается на повторных раундах', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('4'), + ]); + + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool()), + 'тест', + 3, + 'required', + ); + + $agent->ask('посчитай'); + + assertSame('required', $client->requests[0]['options']['tool_choice'] ?? null); + assertTrue( + !isset($client->requests[1]['options']['tool_choice']), + 'во втором раунде tool_choice должен вернуться к auto, иначе модель зациклится' + ); +}); + + +// --------------------------------------------------------------------------- +// Настройки агента +// --------------------------------------------------------------------------- + +test('настройки: tool_choice уходит в клиент', function (): void { + $client = new FakeClient([textResult('ок')]); + $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'required'); + + $agent->ask('вопрос'); + + assertSame('required', $client->requests[0]['options']['tool_choice'] ?? null); +}); + +test('настройки: tool_choice по умолчанию не навязывается', function (): void { + $client = new FakeClient([textResult('ок')]); + $agent = new Agent($client, new ToolRegistry(), 'тест', 3); + + $agent->ask('вопрос'); + + assertTrue(!isset($client->requests[0]['options']['tool_choice']), 'auto не должен уходить явно'); +}); + +test('настройки: parallel_tool_calls=false отправляется только когда выключено', function (): void { + $off = new FakeClient([textResult('ок')]); + (new Agent($off, new ToolRegistry(), 'тест', 3, 'auto', false))->ask('вопрос'); + + assertSame(false, $off->requests[0]['options']['parallel_tool_calls']); + + $on = new FakeClient([textResult('ок')]); + (new Agent($on, new ToolRegistry(), 'тест', 3, 'auto', true))->ask('вопрос'); + + assertTrue(!isset($on->requests[0]['options']['parallel_tool_calls']), 'true — это значение по умолчанию'); +}); + +test('настройки: хук может запретить вызов инструмента', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('Не смог: действие запрещено.'), + ]); + + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool()), + 'тест', + 3, + 'auto', + true, + 40, + static fn (string $name, array $args): bool => false, + ); + + $agent->ask('посчитай'); + + assertTrue($agent->trace()[0]['blocked'], 'вызов должен быть помечен как отклонённый'); + assertContains('отклонён оператором', $agent->trace()[0]['output']); + + $messages = $client->requests[1]['messages']; + $last = $messages[count($messages) - 1]; + assertContains('отклонён оператором', $last['content']); +}); + +test('настройки: хук пропускает разрешённый вызов', function (): void { + $client = new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('4'), + ]); + + $seen = null; + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool()), + 'тест', + 3, + 'auto', + true, + 40, + static function (string $name, array $args) use (&$seen): bool { + $seen = [$name, $args]; + + return true; + }, + ); + + $agent->ask('посчитай'); + + assertSame('calculator', $seen[0]); + assertSame('2+2', $seen[1]['expression']); + assertSame(false, $agent->trace()[0]['blocked']); + assertSame('2+2 = 4', $agent->trace()[0]['output']); +}); + +test('настройки: historyLimit обрезает историю целыми ходами', function (): void { + $client = new FakeClient([ + textResult('a1'), + textResult('a2'), + textResult('a3'), + textResult('a4'), + ]); + + $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'auto', true, 4); + + $agent->ask('вопрос 1'); + $agent->ask('вопрос 2'); + $agent->ask('вопрос 3'); + $agent->ask('вопрос 4'); + + $messages = $agent->messages(); + + assertSame('system', $messages[0]['role'], 'system должен оставаться первым'); + assertTrue(($messages[1]['role'] ?? '') !== 'tool', 'история не должна начинаться с tool'); + + // Обрезка идёт Перед запросом: лимит 4 + system + финальный ответ. + assertSame(6, count($messages), 'без лимита было бы 9'); + + $last = $messages[count($messages) - 1]; + $question = $messages[count($messages) - 2]; + + assertSame('user', $question['role']); + assertSame('вопрос 4', $question['content'], 'текущий вопрос должен сохраниться'); + assertSame('assistant', $last['role']); +}); + +test('настройки: historyLimit=0 отключает обрезку', function (): void { + $client = new FakeClient([textResult('a'), textResult('b')]); + $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'auto', true, 0); + + $agent->ask('раз'); + $agent->ask('два'); + + assertSame(5, count($agent->messages()), 'system + 2 вопроса + 2 ответа'); +}); + +test('агент: reset очищает историю и трассировку', function (): void { + $client = new FakeClient([textResult('ответ')]); + $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3); + + $agent->ask('вопрос'); + $agent->reset(); + + assertSame([], $agent->messages()); + assertSame([], $agent->trace()); +}); + + +// --------------------------------------------------------------------------- +// Завершение через finish +// --------------------------------------------------------------------------- + +test('finish: возвращает result и не делает лишний запрос', function (): void { + $client = new FakeClient([ + toolCalls([['name' => 'finish', 'arguments' => ['result' => 'готово'], 'id' => 'f1']]), + ]); + + $agent = new Agent( + $client, + (new ToolRegistry())->add(new FinishTool()), + 'ты тестовый', + 3, + ); + + assertSame('готово', $agent->ask('сделай')); + assertSame(1, count($client->requests), 'после finish второго запроса быть не должно'); + assertSame('finish', $agent->trace()[0]['name']); + + $last = $agent->messages()[count($agent->messages()) - 1]; + assertSame('assistant', $last['role']); + assertSame('готово', $last['content']); +}); + +test('finish: остальные вызовы из того же ответа получают ответ', function (): void { + $client = new FakeClient([ + toolCalls([ + ['name' => 'calculator', 'arguments' => ['expression' => '2+2'], 'id' => 'c1'], + ['name' => 'finish', 'arguments' => ['result' => '4'], 'id' => 'f1'], + ]), + ]); + + $agent = new Agent( + $client, + (new ToolRegistry())->add(new CalculatorTool(), new FinishTool()), + 'ты тестовый', + 3, + ); + + assertSame('4', $agent->ask('посчитай')); + + // История должна остаться валидной: у каждого tool_call_id есть tool-ответ. + $messages = $agent->messages(); + $answered = []; + + foreach ($messages as $message) { + if (($message['role'] ?? '') === 'tool') { + $answered[] = $message['tool_call_id']; + } + } + + assertSame(['c1', 'f1'], $answered); + assertSame('2+2 = 4', $messages[3]['content'], 'калькулятор должен выполниться до finish'); +}); + +test('finish: без result возвращает понятную заглушку', function (): void { + $client = new FakeClient([ + toolCalls([['name' => 'finish', 'arguments' => [], 'id' => 'f1']]), + ]); + + $agent = new Agent($client, (new ToolRegistry())->add(new FinishTool()), 'тест', 3); + + assertContains('без результата', $agent->ask('сделай')); +}); + +test('finish: незарегистрированный инструмент не перехватывается', function (): void { + $client = new FakeClient([ + toolCall('finish', ['result' => 'x'], 'f1'), + textResult('продолжил'), + ]); + + $agent = new Agent($client, new ToolRegistry(), 'тест', 3); + + assertSame('продолжил', $agent->ask('сделай')); + assertContains('неизвестный инструмент', $agent->trace()[0]['output']); +}); + +test('finish: можно отключить перехват через finishTool', function (): void { + $client = new FakeClient([ + toolCall('finish', ['result' => 'x'], 'f1'), + textResult('обычный ответ'), + ]); + + $agent = new Agent( + client: $client, + tools: (new ToolRegistry())->add(new FinishTool()), + systemPrompt: 'тест', + maxRounds: 3, + finishTool: '', + ); + + assertSame('обычный ответ', $agent->ask('сделай')); +}); + + diff --git a/tests/cases/architecture.php b/tests/cases/architecture.php new file mode 100644 index 0000000..cdf9b06 --- /dev/null +++ b/tests/cases/architecture.php @@ -0,0 +1,38 @@ +handle(['path' => 'note.txt']); + + assertContains('строки 1–3 из 3', $result); + assertContains('вторая', $result); +}); + +test('read_file: offset и limit в строках', function (): void { + $dir = testDir(); + file_put_contents($dir . '/note.txt', "1\n2\n3\n4\n5"); + + $result = (new ReadFileTool(new FileSandbox($dir))) + ->handle(['path' => 'note.txt', 'offset' => 1, 'limit' => 2]); + + assertContains('строки 2–3 из 5', $result); + assertContains("2\n3", $result); +}); + +test('read_file: побег через .. запрещён', function (): void { + $dir = testDir(); + file_put_contents(dirname($dir) . '/outside.txt', 'секрет'); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../outside.txt']); + + assertContains('не должен содержать', $result); +}); + +test('read_file: абсолютный путь запрещён', function (): void { + $dir = testDir(); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '/etc/passwd']); + + assertContains('Абсолютные пути запрещены', $result); +}); + +test('read_file: бинарный файл не читается', function (): void { + $dir = testDir(); + file_put_contents($dir . '/bin.dat', "\x00\x01\x02\xFF"); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => 'bin.dat']); + + assertContains('бинарный', $result); +}); + +test('list_dir: показывает каталоги и файлы', function (): void { + $dir = testDir(); + mkdir($dir . '/sub'); + file_put_contents($dir . '/a.txt', 'hello'); + + $result = (new ListDirTool(new FileSandbox($dir)))->handle([]); + + assertContains('sub/', $result); + assertContains('a.txt', $result); +}); + +test('list_dir: выход за корень запрещён', function (): void { + $dir = testDir(); + + $result = (new ListDirTool(new FileSandbox($dir)))->handle(['path' => '..']); + + assertContains('не должен содержать', $result); +}); + + +// --------------------------------------------------------------------------- +// CSV +// --------------------------------------------------------------------------- + +test('csv_query: фильтр по колонке', function (): void { + $dir = testDir(); + file_put_contents( + $dir . '/people.csv', + "name,city,age\nИван,Тула,30\nМария,Москва,25\nПётр,Тула,41\n" + ); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ + 'path' => 'people.csv', + 'where' => 'city=Тула', + ]); + + assertContains('Иван', $result); + assertContains('Пётр', $result); + assertTrue(!str_contains($result, 'Мария'), 'строка из другого города попала в выборку'); + assertContains('2 из 3 строк', $result); +}); + +test('csv_query: вхождение подстроки и лимит', function (): void { + $dir = testDir(); + file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\nИгорь,Тула\nПётр,Тула\n"); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ + 'path' => 'people.csv', + 'where' => 'name~и', + 'columns' => 'name', + 'limit' => 2, + ]); + + assertContains('2 из 3 строк', $result); + assertTrue(!str_contains($result, 'city'), 'лишняя колонка в выборке'); +}); + +test('csv_query: неизвестная колонка — понятная ошибка', function (): void { + $dir = testDir(); + file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\n"); + + $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ + 'path' => 'people.csv', + 'where' => 'город=Тула', + ]); + + assertContains('Нет колонки', $result); + assertContains('name, city', $result); +}); + + +// --------------------------------------------------------------------------- +// Запись и правка файлов +// --------------------------------------------------------------------------- + +test('write_file: создаёт файл', function (): void { + $dir = testDir(); + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'note.txt', + 'content' => 'привет', + ]); + + assertContains('Создан', $result); + assertSame('привет', file_get_contents($dir . '/note.txt')); +}); + +test('write_file: перезаписывает файл', function (): void { + $dir = testDir(); + file_put_contents($dir . '/note.txt', 'старое'); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'note.txt', + 'content' => 'новое', + ]); + + assertContains('Перезаписан', $result); + assertSame('новое', file_get_contents($dir . '/note.txt')); +}); + +test('write_file: создаёт каталоги с create_dirs', function (): void { + $dir = testDir(); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'a/b/c.txt', + 'content' => 'x', + 'create_dirs' => true, + ]); + + assertContains('Создан', $result); + assertTrue(is_file($dir . '/a/b/c.txt'), 'файл не создан'); +}); + +test('write_file: без create_dirs каталог обязателен', function (): void { + $dir = testDir(); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'nope/x.txt', + 'content' => 'x', + ]); + + assertContains('Каталог не существует', $result); +}); + +test('write_file: запись вне песочницы запрещена', function (): void { + $dir = testDir(); + + $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ + 'path' => '../evil.txt', + 'content' => 'x', + ]); + + assertContains('не должен содержать', $result); +}); + +test('replace_in_file: заменяет единственное совпадение', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', "class A\nclass B\n"); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'class A', + 'replace' => 'final class A', + ]); + + assertContains('Заменено вхождений: 1', $result); + + $content = (string) file_get_contents($dir . '/code.txt'); + + assertContains('final class A', $content); + assertContains('class B', $content); +}); + +test('replace_in_file: несколько совпадений требуют all', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', "x\nx\n"); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'x', + 'replace' => 'y', + ]); + + assertContains('Найдено совпадений: 2', $result); +}); + +test('replace_in_file: не найдено — понятная ошибка', function (): void { + $dir = testDir(); + file_put_contents($dir . '/code.txt', 'abc'); + + $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ + 'path' => 'code.txt', + 'search' => 'zzz', + 'replace' => 'y', + ]); + + assertContains('не найден', $result); +}); + + +// --------------------------------------------------------------------------- +// Поиск по файлам +// --------------------------------------------------------------------------- + +test('search_files: находит строки с номерами', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.php', "handle(['pattern' => 'class \w+']); + + assertContains('a.php:2:', $result); + assertContains('b.txt:1:', $result); +}); + +test('search_files: glob ограничивает файлы', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.php', "class Foo\n"); + file_put_contents($dir . '/b.txt', "class Bar\n"); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle([ + 'pattern' => 'class', + 'glob' => '*.php', + ]); + + assertContains('a.php', $result); + assertTrue(!str_contains($result, 'b.txt'), 'лишний файл в выдаче'); +}); + +test('search_files: служебные каталоги пропускаются', function (): void { + $dir = testDir(); + mkdir($dir . '/vendor', 0777, true); + file_put_contents($dir . '/vendor/lib.php', "class Vendor\n"); + file_put_contents($dir . '/app.php', "class App\n"); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle(['pattern' => 'class']); + + assertContains('app.php', $result); + assertTrue(!str_contains($result, 'vendor'), 'vendor не должен сканироваться'); +}); + +test('search_files: некорректная регулярка', function (): void { + $dir = testDir(); + + $result = (new SearchFilesTool(new FileSandbox($dir)))->handle(['pattern' => '([']); + + assertContains('Некорректное регулярное выражение', $result); +}); + +test('find_files: поиск по маске', function (): void { + $dir = testDir(); + file_put_contents($dir . '/a.php', 'x'); + file_put_contents($dir . '/b.txt', 'x'); + + $result = (new FindFilesTool(new FileSandbox($dir)))->handle(['pattern' => '*.php']); + + assertContains('a.php', $result); + assertTrue(!str_contains($result, 'b.txt'), 'лишний файл в выдаче'); +}); + + +// --------------------------------------------------------------------------- +// Песочница: ограниченный и свободный режимы +// --------------------------------------------------------------------------- + +test('sandbox: по умолчанию ограничена', function (): void { + $dir = testDir(); + + assertTrue((new FileSandbox($dir))->isRestricted()); + assertTrue(!FileSandbox::unrestricted($dir)->isRestricted()); +}); + +test('sandbox: свободный режим читает вне корня', function (): void { + $dir = testDir(); + $outside = str_replace('\\', '/', dirname($dir) . '/outside.txt'); + file_put_contents($outside, 'снаружи'); + + $result = (new ReadFileTool(FileSandbox::unrestricted($dir)))->handle(['path' => $outside]); + + assertContains('снаружи', $result); +}); + +test('sandbox: свободный режим пишет вне корня', function (): void { + $dir = testDir(); + $outside = str_replace('\\', '/', dirname($dir) . '/written.txt'); + + $result = (new WriteFileTool(FileSandbox::unrestricted($dir)))->handle([ + 'path' => $outside, + 'content' => 'записано', + ]); + + assertContains('Создан', $result); + assertSame('записано', file_get_contents($outside)); +}); + +test('sandbox: политика задаётся для каждого инструмента отдельно', function (): void { + $dir = testDir(); + $outside = str_replace('\\', '/', dirname($dir) . '/mixed.txt'); + file_put_contents($outside, 'данные'); + + // Читать можно везде... + $read = new ReadFileTool(FileSandbox::unrestricted($dir)); + assertContains('данные', $read->handle(['path' => $outside])); + + // ...а писать — только в корень. + $write = new WriteFileTool(new FileSandbox($dir)); + assertContains('запрещены', $write->handle(['path' => $outside, 'content' => 'x'])); +}); + +test('sandbox: ограниченный режим по-прежнему блокирует выход', function (): void { + $dir = testDir(); + $outside = dirname($dir) . '/blocked.txt'; + file_put_contents($outside, 'секрет'); + + $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../blocked.txt']); + + assertContains('не должен содержать', $result); +}); + + diff --git a/tests/cases/http.php b/tests/cases/http.php new file mode 100644 index 0000000..db8e7bc --- /dev/null +++ b/tests/cases/http.php @@ -0,0 +1,144 @@ + 'кот', 'page' => 2]); + + assertSame('GET', $request->method); + assertContains('q=%D0%BA%D0%BE%D1%82', $request->url); + assertContains('page=2', $request->url); +}); + +test('http_request: JSON-тело и Content-Type', function (): void { + $request = HttpRequest::build('POST', 'https://example.com/orders', body: ['sku' => 'A-1']); + + assertSame('{"sku":"A-1"}', $request->body); + assertSame('application/json', $request->headers['Content-Type']); + assertSame('POST', $request->method); +}); + +test('http_request: form-тело', function (): void { + $request = HttpRequest::build( + 'POST', + 'https://example.com/login', + body: ['u' => 'a', 'p' => 'b'], + contentType: 'form', + ); + + assertSame('u=a&p=b', $request->body); + assertSame('application/x-www-form-urlencoded', $request->headers['Content-Type']); +}); + +test('http_request: Basic-авторизация', function (): void { + $request = HttpRequest::build( + 'GET', + 'https://example.com/me', + auth: ['user' => 'bot', 'pass' => 'secret'], + ); + + assertSame('Basic ' . base64_encode('bot:secret'), $request->headers['Authorization']); +}); + +test('http_request: Bearer-авторизация', function (): void { + $request = HttpRequest::build( + 'GET', + 'https://example.com/me', + auth: ['type' => 'bearer', 'token' => 'abc'], + ); + + assertSame('Bearer abc', $request->headers['Authorization']); +}); + +test('http_request: запрещённые заголовки отбрасываются', function (): void { + $request = HttpRequest::build( + 'GET', + 'https://example.com', + headers: ['Host' => 'evil', 'X-Ok' => '1'], + ); + + assertTrue(!isset($request->headers['Host']), 'Host должен отбрасываться'); + assertSame('1', $request->headers['X-Ok']); +}); + +test('http_request: неизвестный метод отвергается', function (): void { + assertThrows(static fn () => HttpRequest::build('TRACE', 'https://example.com')); +}); + +test('http_request: без схемы подставляется https', function (): void { + assertSame('https://example.com/x', HttpRequest::build('GET', 'example.com/x')->url); +}); + +test('http: заголовки превращаются в строки cURL', function (): void { + // Регрессия: ассоциативный массив, отданный в cURL напрямую, + // молча терял и Content-Type, и Authorization. + assertSame(['X-Ok: 1'], HttpTransport::headerLines(['X-Ok' => '1'])); + assertSame(['Accept: */*'], HttpTransport::headerLines([])); + assertSame(['Accept: */*'], HttpTransport::headerLines(['Accept: */*'])); +}); + + +// --------------------------------------------------------------------------- +// http_request: защита от SSRF (без сети) +// --------------------------------------------------------------------------- + +test('http_request: localhost запрещён', function (): void { + assertContains('локальному адресу', (new HttpRequestTool())->handle(['url' => 'http://localhost/x'])); +}); + +test('http_request: приватные адреса запрещены', function (): void { + $tool = new HttpRequestTool(); + + assertContains('приватному адресу', $tool->handle(['url' => 'http://127.0.0.1/x'])); + assertContains('приватному адресу', $tool->handle(['url' => 'http://10.0.0.5/x'])); + assertContains('приватному адресу', $tool->handle(['url' => 'http://192.168.1.10/x'])); +}); + +test('http_request: только http и https', function (): void { + assertContains('только http и https', (new HttpRequestTool())->handle(['url' => 'ftp://example.com/x'])); +}); + +test('http_request: allowPrivate снимает блокировку внутренней сети', function (): void { + // Порт закрыт: проверяем именно то, что SSRF-отказ больше не выдаётся. + $result = (new HttpRequestTool(allowPrivate: true))->handle(['url' => 'http://127.0.0.1:9/x']); + + assertTrue( + !str_contains($result, 'приватному адресу'), + 'с allowPrivate адрес не должен блокироваться: ' . $result + ); +}); + + diff --git a/tests/cases/logging.php b/tests/cases/logging.php new file mode 100644 index 0000000..96e9f0e --- /dev/null +++ b/tests/cases/logging.php @@ -0,0 +1,119 @@ +chat([['role' => 'user', 'content' => 'вопрос']]); + + assertSame('привет', $result->text); + assertSame(2, count($lines), 'ожидались две строки: запрос и ответ'); + assertContains('LLM →', $lines[0]); + assertContains('LLM ←', $lines[1]); + assertContains('текст 6 симв.', $lines[1]); +}); + +test('logging: ошибка пишется и пробрасывается', function (): void { + $broken = new class implements ChatClient { + public function chat(array $messages, array $tools = [], array $options = []): ChatResult + { + throw new RuntimeException('сеть упала'); + } + }; + + $lines = []; + $client = new LoggingClient($broken, sink: static function (string $line) use (&$lines): void { + $lines[] = $line; + }); + + assertThrows(static fn () => $client->chat([['role' => 'user', 'content' => 'x']])); + + $log = implode("\n", $lines); + + assertContains('LLM ✗', $log); + assertContains('сеть упала', $log); +}); + +test('logging: verbose печатает сообщения и инструменты', function (): void { + $lines = []; + $client = new LoggingClient( + new FakeClient([textResult('ок')]), + sink: static function (string $line) use (&$lines): void { + $lines[] = $line; + }, + verbose: true, + ); + + $tools = (new ToolRegistry())->add(new TimeTool())->definitions(); + $client->chat([['role' => 'user', 'content' => 'который час']], $tools); + + $log = implode("\n", $lines); + + assertContains('[0] user: который час', $log); + assertContains('инструменты: get_time', $log); + assertContains('ответ: ок', $log); +}); + +test('logging: в агенте логирует каждый раунд', function (): void { + $lines = []; + $client = new LoggingClient( + new FakeClient([ + toolCall('calculator', ['expression' => '2+2'], 'c1'), + textResult('4'), + ]), + sink: static function (string $line) use (&$lines): void { + $lines[] = $line; + }, + ); + + $agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'тест', 3); + + assertSame('4', $agent->ask('посчитай')); + + $log = implode("\n", $lines); + + assertContains('tool_calls: calculator', $log); + assertSame(4, count($lines), 'два раунда — по две строки'); +}); + + diff --git a/tests/cases/shell.php b/tests/cases/shell.php new file mode 100644 index 0000000..3951b90 --- /dev/null +++ b/tests/cases/shell.php @@ -0,0 +1,82 @@ +handle(['command' => 'echo hello']); + + assertContains('hello', $result); + assertContains('exit: 0', $result); +}); + +test('shell: возвращает ненулевой код выхода', function (): void { + assertContains('exit: 3', (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'exit 3'])); +}); + +test('shell: таймаут прерывает команду', function (): void { + $command = DIRECTORY_SEPARATOR === '\\' ? 'ping -n 5 127.0.0.1 >NUL' : 'sleep 5'; + + $started = microtime(true); + $result = (new ShellTool(timeout: 0.5, tmpDir: __DIR__ . '/tmp'))->handle(['command' => $command]); + $elapsed = microtime(true) - $started; + + assertContains('таймаут', $result); + assertTrue($elapsed < 3.0, 'таймаут не сработал: ' . round($elapsed, 2) . ' с'); +}); + +test('shell: allowlist запрещает лишнее', function (): void { + $result = (new ShellTool(allow: ['echo'], tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'whoami']); + + assertContains('не разрешена', $result); +}); + +test('shell: allowlist пропускает разрешённое', function (): void { + $result = (new ShellTool(allow: ['echo'], tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'echo ok']); + + assertContains('ok', $result); +}); + +test('shell: длинный вывод обрезается', function (): void { + $result = (new ShellTool(maxOutput: 100, tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'echo ' . str_repeat('x', 500)]); + + assertContains('обрезано', $result); +}); + +test('shell: пустая команда не запускается', function (): void { + assertContains('Пустая команда', (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => ' '])); +}); + + diff --git a/tests/cases/tools.php b/tests/cases/tools.php new file mode 100644 index 0000000..fc4f1a8 --- /dev/null +++ b/tests/cases/tools.php @@ -0,0 +1,264 @@ +handle(['expression' => '2+2*2'])); +}); + +test('calculator: скобки и степень', function (): void { + assertSame('(1+2)^2 = 9', (new CalculatorTool())->handle(['expression' => '(1+2)^2'])); +}); + +test('calculator: деление даёт дробь', function (): void { + assertSame('10/4 = 2.5', (new CalculatorTool())->handle(['expression' => '10/4'])); +}); + +test('calculator: деление на ноль — понятная ошибка', function (): void { + assertContains('деление на ноль', (new CalculatorTool())->handle(['expression' => '1/0'])); +}); + +test('calculator: буквы не пропускаются', function (): void { + assertContains('Разрешены только', (new CalculatorTool())->handle(['expression' => '2+a'])); +}); + +test('time: возвращает дату в нужном поясе', function (): void { + $result = (new TimeTool())->handle(['timezone' => 'Europe/Moscow']); + + assertTrue( + preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \S+ \((\p{L}{2})\)$/u', $result) === 1, + 'неожиданный формат: ' . $result + ); +}); + +test('time: неизвестный пояс — понятная ошибка', function (): void { + assertContains('Неизвестный часовой пояс', (new TimeTool())->handle(['timezone' => 'Mars/Olympus'])); +}); + + +// --------------------------------------------------------------------------- +// Реестр инструментов +// --------------------------------------------------------------------------- + +test('реестр: схемы в формате OpenAI tools', function (): void { + $definitions = (new ToolRegistry())->add(new TimeTool(), new CalculatorTool())->definitions(); + + assertSame(2, count($definitions)); + assertSame('function', $definitions[0]['type']); + assertSame('get_time', $definitions[0]['function']['name']); + assertSame('object', $definitions[0]['function']['parameters']['type']); +}); + +test('реестр: неизвестный инструмент не бросает исключение', function (): void { + $result = (new ToolRegistry())->execute('nope', []); + + assertContains('неизвестный инструмент', $result); +}); + +test('реестр: исключение инструмента превращается в текст', function (): void { + $broken = new class implements Tool { + public function name(): string + { + return 'broken'; + } + + public function description(): string + { + return 'всегда падает'; + } + + public function parameters(): array + { + return ['type' => 'object', 'properties' => []]; + } + + public function handle(array $args): string + { + throw new RuntimeException('сломалось'); + } + }; + + $result = (new ToolRegistry())->add($broken)->execute('broken', []); + + assertContains('Ошибка инструмента "broken"', $result); + assertContains('сломалось', $result); +}); + +test('реестр: длинный результат обрезается', function (): void { + $verbose = new class implements Tool { + public function name(): string + { + return 'verbose'; + } + + public function description(): string + { + return 'много текста'; + } + + public function parameters(): array + { + return ['type' => 'object', 'properties' => []]; + } + + public function handle(array $args): string + { + return str_repeat('x', 100); + } + }; + + $result = (new ToolRegistry(10))->add($verbose)->execute('verbose', []); + + assertSame(11, mb_strlen($result), 'ожидалось 10 символов и многоточие'); +}); + + +// --------------------------------------------------------------------------- +// Единицы и даты +// --------------------------------------------------------------------------- + +test('convert_units: километры в мили', function (): void { + assertSame('100 km = 62.137119 mi', (new ConvertUnitsTool())->handle([ + 'value' => 100, + 'from' => 'km', + 'to' => 'mi', + ])); +}); + +test('convert_units: температура', function (): void { + $tool = new ConvertUnitsTool(); + + assertSame('0 c = 32 f', $tool->handle(['value' => 0, 'from' => 'c', 'to' => 'f'])); + assertSame('100 c = 373.15 k', $tool->handle(['value' => 100, 'from' => 'c', 'to' => 'k'])); +}); + +test('convert_units: русские названия единиц', function (): void { + // Ответ приходит в канонических кодах, независимо от ввода. + assertSame('5 km = 5000 m', (new ConvertUnitsTool())->handle([ + 'value' => 5, + 'from' => 'км', + 'to' => 'м', + ])); +}); + +test('convert_units: неизвестная единица', function (): void { + $result = (new ConvertUnitsTool())->handle(['value' => 1, 'from' => 'parsec', 'to' => 'm']); + + assertContains('Не знаю единицы', $result); +}); + +test('date_calc: разница между датами', function (): void { + $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'to' => '2026-02-01']); + + assertContains('31 день', $result); +}); + +test('date_calc: дата без времени — это полночь, а не «сейчас»', function (): void { + $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'modifier' => '+1 day']); + + assertContains('2026-01-01 00:00:00', $result); + assertContains('2026-01-02 00:00:00', $result); +}); + +test('date_calc: прибавить интервал', function (): void { + $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'modifier' => '+30 days']); + + assertContains('2026-01-31', $result); +}); + +test('date_calc: без параметров — подсказка', function (): void { + assertContains('Нужен либо to', (new DateCalcTool())->handle([])); +}); + +test('date_calc: плохой часовой пояс', function (): void { + assertContains('Неизвестный часовой пояс', (new DateCalcTool())->handle([ + 'from' => 'now', + 'timezone' => 'Mars/Olympus', + ])); +}); + + +// --------------------------------------------------------------------------- +// UUID и хеши +// --------------------------------------------------------------------------- + +test('uuid: формат v4 и уникальность', function (): void { + $tool = new UuidTool(); + $first = $tool->handle([]); + $second = $tool->handle([]); + + assertTrue( + preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $first) === 1, + 'не UUID v4: ' . $first + ); + assertTrue($first !== $second, 'два вызова вернули одинаковый UUID'); +}); + +test('hash_text: известные значения', function (): void { + $tool = new HashTool(); + + assertSame('sha256: ' . hash('sha256', 'привет'), $tool->handle(['text' => 'привет'])); + assertSame('md5: ' . md5('x'), $tool->handle(['text' => 'x', 'algo' => 'md5'])); + assertContains('Неизвестный алгоритм', $tool->handle(['text' => 'x', 'algo' => 'crc32'])); +}); + + +// --------------------------------------------------------------------------- +// JSON +// --------------------------------------------------------------------------- + +test('json_query: вложенный путь', function (): void { + $result = (new JsonQueryTool())->handle([ + 'json' => '{"data":{"items":[{"id":42,"name":"x"}]}}', + 'path' => 'data.items[0].id', + ]); + + assertContains('42', $result); +}); + +test('json_query: нет ключа — сообщение', function (): void { + $result = (new JsonQueryTool())->handle(['json' => '{"a":1}', 'path' => 'b']); + + assertContains('не найден', $result); +}); + +test('json_query: битый JSON', function (): void { + $result = (new JsonQueryTool())->handle(['json' => '{oops', 'path' => 'a']); + + assertContains('Некорректный JSON', $result); +}); + + diff --git a/tests/run.php b/tests/run.php index 88d2ade..d80eb7a 100644 --- a/tests/run.php +++ b/tests/run.php @@ -3,1428 +3,23 @@ declare(strict_types=1); /** - * Тесты SDK: без сети, без модели и без API-ключа. - * - * Модель подменяется FakeClient — он отдаёт заранее заготовленные ответы. - * Именно так удобно тестировать агентов в своих проектах. + * Раннер тестов: подключает кейсы из tests/cases и печатает итог. * * Запуск: * php tests/run.php */ -require dirname(__DIR__) . '/bootstrap.php'; +require __DIR__ . '/support.php'; -use AiSdk\Agent; -use AiSdk\ChatClient; -use AiSdk\ChatResult; -use AiSdk\Http; -use AiSdk\HttpRequest; -use AiSdk\LoggingClient; -use AiSdk\Tool; -use AiSdk\ToolRegistry; -use AiSdk\Tools\CalculatorTool; -use AiSdk\Tools\ConvertUnitsTool; -use AiSdk\Tools\CsvQueryTool; -use AiSdk\Tools\DateCalcTool; -use AiSdk\Tools\FileSandbox; -use AiSdk\Tools\FindFilesTool; -use AiSdk\Tools\JsonQueryTool; -use AiSdk\Tools\FinishTool; -use AiSdk\Tools\HashTool; -use AiSdk\Tools\HttpRequestTool; -use AiSdk\Tools\ListDirTool; -use AiSdk\Tools\ReadFileTool; -use AiSdk\Tools\ReplaceInFileTool; -use AiSdk\Tools\SearchFilesTool; -use AiSdk\Tools\ShellTool; -use AiSdk\Tools\TimeTool; -use AiSdk\Tools\WriteFileTool; -use AiSdk\Tools\UuidTool; +$cases = glob(__DIR__ . '/cases/*.php') ?: []; +sort($cases); -mb_internal_encoding('UTF-8'); - -$passed = 0; -$failed = 0; - -function test(string $name, callable $fn): void -{ - global $passed, $failed; - - try { - $fn(); - $passed++; - echo 'ok ' . $name . PHP_EOL; - } catch (Throwable $e) { - $failed++; - echo 'FAIL ' . $name . PHP_EOL . ' ' . $e->getMessage() . PHP_EOL; - } +foreach ($cases as $case) { + require $case; } -function assertSame(mixed $expected, mixed $actual, string $message = ''): void -{ - if ($expected !== $actual) { - throw new RuntimeException( - ($message !== '' ? $message . ': ' : '') - . 'ожидалось ' . var_export($expected, true) - . ', получено ' . var_export($actual, true) - ); - } -} - -function assertTrue(bool $value, string $message = ''): void -{ - if (!$value) { - throw new RuntimeException($message !== '' ? $message : 'ожидалось true'); - } -} - -function assertContains(string $needle, string $haystack, string $message = ''): void -{ - if (!str_contains($haystack, $needle)) { - throw new RuntimeException( - ($message !== '' ? $message . ': ' : '') - . 'нет "' . $needle . '" в "' . $haystack . '"' - ); - } -} - -function assertThrows(callable $fn, string $message = ''): void -{ - try { - $fn(); - } catch (Throwable) { - return; - } - - throw new RuntimeException($message !== '' ? $message : 'ожидалось исключение'); -} - -/** - * Модель-заглушка: отдаёт ответы по очереди и запоминает все запросы. - */ -final class FakeClient implements ChatClient -{ - /** @var list, tools: array, options: array}> */ - public array $requests = []; - - /** - * @param list $results - */ - public function __construct(private array $results) - { - } - - public function chat(array $messages, array $tools = [], array $options = []): ChatResult - { - $this->requests[] = ['messages' => $messages, 'tools' => $tools, 'options' => $options]; - - $result = array_shift($this->results); - - if ($result === null) { - throw new RuntimeException('FakeClient: закончились заготовленные ответы'); - } - - return $result; - } -} - -/** - * Ответ «вызови инструмент». - * - * @param array $arguments - */ -function toolCall(string $name, array $arguments, string $id = 'call_1'): ChatResult -{ - $message = [ - 'role' => 'assistant', - 'content' => '', - 'tool_calls' => [[ - 'id' => $id, - 'type' => 'function', - 'function' => [ - 'name' => $name, - 'arguments' => json_encode($arguments, JSON_UNESCAPED_UNICODE), - ], - ]], - ]; - - return new ChatResult('', [['id' => $id, 'name' => $name, 'arguments' => $arguments]], $message); -} - -function textResult(string $text): ChatResult -{ - return new ChatResult($text, [], ['role' => 'assistant', 'content' => $text]); -} - -/** - * Временный каталог для файловых инструментов. - */ -function testDir(): string -{ - $base = __DIR__ . '/tmp'; - - if (!is_dir($base) && !mkdir($base, 0777, true) && !is_dir($base)) { - throw new RuntimeException('не удалось создать tests/tmp'); - } - - $dir = $base . '/sandbox-' . bin2hex(random_bytes(3)); - - if (!mkdir($dir, 0777, true)) { - throw new RuntimeException('не удалось создать ' . $dir); - } - - return $dir; -} - -function removeDir(string $dir): void -{ - if (!is_dir($dir)) { - return; - } - - $items = scandir($dir) ?: []; - - foreach ($items as $item) { - if ($item === '.' || $item === '..') { - continue; - } - - $path = $dir . '/' . $item; - - if (is_dir($path)) { - removeDir($path); - } else { - @unlink($path); - } - } - - @rmdir($dir); -} - -/** - * Ответ модели с несколькими вызовами сразу. - * - * @param list, id: string}> $calls - */ -function toolCalls(array $calls): ChatResult -{ - $message = ['role' => 'assistant', 'content' => '', 'tool_calls' => []]; - $parsed = []; - - foreach ($calls as $call) { - $message['tool_calls'][] = [ - 'id' => $call['id'], - 'type' => 'function', - 'function' => [ - 'name' => $call['name'], - 'arguments' => json_encode($call['arguments'], JSON_UNESCAPED_UNICODE), - ], - ]; - - $parsed[] = [ - 'id' => $call['id'], - 'name' => $call['name'], - 'arguments' => $call['arguments'], - ]; - } - - return new ChatResult('', $parsed, $message); -} - -// --------------------------------------------------------------------------- -// Инструменты -// --------------------------------------------------------------------------- - -test('calculator: приоритет операций', function (): void { - assertSame('2+2*2 = 6', (new CalculatorTool())->handle(['expression' => '2+2*2'])); -}); - -test('calculator: скобки и степень', function (): void { - assertSame('(1+2)^2 = 9', (new CalculatorTool())->handle(['expression' => '(1+2)^2'])); -}); - -test('calculator: деление даёт дробь', function (): void { - assertSame('10/4 = 2.5', (new CalculatorTool())->handle(['expression' => '10/4'])); -}); - -test('calculator: деление на ноль — понятная ошибка', function (): void { - assertContains('деление на ноль', (new CalculatorTool())->handle(['expression' => '1/0'])); -}); - -test('calculator: буквы не пропускаются', function (): void { - assertContains('Разрешены только', (new CalculatorTool())->handle(['expression' => '2+a'])); -}); - -test('time: возвращает дату в нужном поясе', function (): void { - $result = (new TimeTool())->handle(['timezone' => 'Europe/Moscow']); - - assertTrue( - preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \S+ \((\p{L}{2})\)$/u', $result) === 1, - 'неожиданный формат: ' . $result - ); -}); - -test('time: неизвестный пояс — понятная ошибка', function (): void { - assertContains('Неизвестный часовой пояс', (new TimeTool())->handle(['timezone' => 'Mars/Olympus'])); -}); - -// --------------------------------------------------------------------------- -// Реестр инструментов -// --------------------------------------------------------------------------- - -test('реестр: схемы в формате OpenAI tools', function (): void { - $definitions = (new ToolRegistry())->add(new TimeTool(), new CalculatorTool())->definitions(); - - assertSame(2, count($definitions)); - assertSame('function', $definitions[0]['type']); - assertSame('get_time', $definitions[0]['function']['name']); - assertSame('object', $definitions[0]['function']['parameters']['type']); -}); - -test('реестр: неизвестный инструмент не бросает исключение', function (): void { - $result = (new ToolRegistry())->execute('nope', []); - - assertContains('неизвестный инструмент', $result); -}); - -test('реестр: исключение инструмента превращается в текст', function (): void { - $broken = new class implements Tool { - public function name(): string - { - return 'broken'; - } - - public function description(): string - { - return 'всегда падает'; - } - - public function parameters(): array - { - return ['type' => 'object', 'properties' => []]; - } - - public function handle(array $args): string - { - throw new RuntimeException('сломалось'); - } - }; - - $result = (new ToolRegistry())->add($broken)->execute('broken', []); - - assertContains('Ошибка инструмента "broken"', $result); - assertContains('сломалось', $result); -}); - -test('реестр: длинный результат обрезается', function (): void { - $verbose = new class implements Tool { - public function name(): string - { - return 'verbose'; - } - - public function description(): string - { - return 'много текста'; - } - - public function parameters(): array - { - return ['type' => 'object', 'properties' => []]; - } - - public function handle(array $args): string - { - return str_repeat('x', 100); - } - }; - - $result = (new ToolRegistry(10))->add($verbose)->execute('verbose', []); - - assertSame(11, mb_strlen($result), 'ожидалось 10 символов и многоточие'); -}); - -// --------------------------------------------------------------------------- -// Агент -// --------------------------------------------------------------------------- - -test('агент: вызывает инструмент и отдаёт финальный ответ', function (): void { - $client = new FakeClient([ - toolCall('calculator', ['expression' => '2+2'], 'call_42'), - textResult('Получилось 4.'), - ]); - - $agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'ты тестовый', 3); - - $answer = $agent->ask('Сколько будет 2+2?'); - - assertSame('Получилось 4.', $answer); - assertSame(2, count($client->requests), 'должно быть два запроса к модели'); - - // Второй запрос обязан содержать результат инструмента. - $messages = $client->requests[1]['messages']; - $last = $messages[count($messages) - 1]; - - assertSame('tool', $last['role']); - assertSame('call_42', $last['tool_call_id']); - assertSame('2+2 = 4', $last['content']); - - // И сами схемы инструментов ушли модели. - assertTrue($client->requests[0]['tools'] !== [], 'схемы инструментов не отправлены'); - - // Трассировка для отладки. - assertSame(1, count($agent->trace())); - assertSame('calculator', $agent->trace()[0]['name']); -}); - -test('агент: ошибка инструмента уходит модели, а не в exception', function (): void { - $client = new FakeClient([ - toolCall('nope', []), - textResult('Не смог посчитать.'), - ]); - - $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3); - $answer = $agent->ask('вопрос'); - - assertSame('Не смог посчитать.', $answer); - - $messages = $client->requests[1]['messages']; - $last = $messages[count($messages) - 1]; - - assertContains('неизвестный инструмент', $last['content']); -}); - -test('агент: после лимита раундов просит ответ без инструментов', function (): void { - $client = new FakeClient([ - toolCall('calculator', ['expression' => '1+1'], 'c1'), - toolCall('calculator', ['expression' => '1+1'], 'c2'), - toolCall('calculator', ['expression' => '1+1'], 'c3'), - textResult('Два.'), - ]); - - $agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'ты тестовый', 2); - - assertSame('Два.', $agent->ask('сколько?')); - - // 1 стартовый + 2 раунда + 1 финальный. - assertSame(4, count($client->requests)); - - $lastRequest = $client->requests[3]; - assertSame([], $lastRequest['tools'], 'финальный запрос должен идти без инструментов'); -}); - -test('агент: помнит историю между вопросами', function (): void { - $client = new FakeClient([ - textResult('Первый ответ.'), - textResult('Второй ответ.'), - ]); - - $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3); - - $agent->ask('первый вопрос'); - $agent->ask('второй вопрос'); - - $messages = $client->requests[1]['messages']; - $roles = array_column($messages, 'role'); - - assertSame(['system', 'user', 'assistant', 'user'], $roles); - assertSame('Первый ответ.', $messages[2]['content']); -}); - -test('агент: системный промпт можно сменить на ходу', function (): void { - $client = new FakeClient([textResult('первый'), textResult('второй')]); - $agent = new Agent($client, new ToolRegistry(), 'промпт №1', 3); - - $agent->ask('вопрос'); - $agent->setSystemPrompt('промпт №2'); - $agent->ask('ещё вопрос'); - - assertSame('промпт №2', $agent->systemPrompt()); - - // System-сообщение остаётся первым и в истории, и в запросе к модели. - $messages = $client->requests[1]['messages']; - assertSame('system', $messages[0]['role']); - assertSame('промпт №2', $messages[0]['content']); - - // История диалога при этом не потерялась. - assertSame(4, count($messages), 'system + 2 user + assistant'); -}); - -test('агент: без явного промпта берётся встроенный', function (): void { - $agent = new Agent(new FakeClient([textResult('ок')]), new ToolRegistry()); - - assertTrue($agent->systemPrompt() !== '', 'промпт по умолчанию пустой'); -}); - -test('агент: tool_choice не навязывается на повторных раундах', function (): void { - $client = new FakeClient([ - toolCall('calculator', ['expression' => '2+2'], 'c1'), - textResult('4'), - ]); - - $agent = new Agent( - $client, - (new ToolRegistry())->add(new CalculatorTool()), - 'тест', - 3, - 'required', - ); - - $agent->ask('посчитай'); - - assertSame('required', $client->requests[0]['options']['tool_choice'] ?? null); - assertTrue( - !isset($client->requests[1]['options']['tool_choice']), - 'во втором раунде tool_choice должен вернуться к auto, иначе модель зациклится' - ); -}); - -// --------------------------------------------------------------------------- -// Настройки агента -// --------------------------------------------------------------------------- - -test('настройки: tool_choice уходит в клиент', function (): void { - $client = new FakeClient([textResult('ок')]); - $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'required'); - - $agent->ask('вопрос'); - - assertSame('required', $client->requests[0]['options']['tool_choice'] ?? null); -}); - -test('настройки: tool_choice по умолчанию не навязывается', function (): void { - $client = new FakeClient([textResult('ок')]); - $agent = new Agent($client, new ToolRegistry(), 'тест', 3); - - $agent->ask('вопрос'); - - assertTrue(!isset($client->requests[0]['options']['tool_choice']), 'auto не должен уходить явно'); -}); - -test('настройки: parallel_tool_calls=false отправляется только когда выключено', function (): void { - $off = new FakeClient([textResult('ок')]); - (new Agent($off, new ToolRegistry(), 'тест', 3, 'auto', false))->ask('вопрос'); - - assertSame(false, $off->requests[0]['options']['parallel_tool_calls']); - - $on = new FakeClient([textResult('ок')]); - (new Agent($on, new ToolRegistry(), 'тест', 3, 'auto', true))->ask('вопрос'); - - assertTrue(!isset($on->requests[0]['options']['parallel_tool_calls']), 'true — это значение по умолчанию'); -}); - -test('настройки: хук может запретить вызов инструмента', function (): void { - $client = new FakeClient([ - toolCall('calculator', ['expression' => '2+2'], 'c1'), - textResult('Не смог: действие запрещено.'), - ]); - - $agent = new Agent( - $client, - (new ToolRegistry())->add(new CalculatorTool()), - 'тест', - 3, - 'auto', - true, - 40, - static fn (string $name, array $args): bool => false, - ); - - $agent->ask('посчитай'); - - assertTrue($agent->trace()[0]['blocked'], 'вызов должен быть помечен как отклонённый'); - assertContains('отклонён оператором', $agent->trace()[0]['output']); - - $messages = $client->requests[1]['messages']; - $last = $messages[count($messages) - 1]; - assertContains('отклонён оператором', $last['content']); -}); - -test('настройки: хук пропускает разрешённый вызов', function (): void { - $client = new FakeClient([ - toolCall('calculator', ['expression' => '2+2'], 'c1'), - textResult('4'), - ]); - - $seen = null; - $agent = new Agent( - $client, - (new ToolRegistry())->add(new CalculatorTool()), - 'тест', - 3, - 'auto', - true, - 40, - static function (string $name, array $args) use (&$seen): bool { - $seen = [$name, $args]; - - return true; - }, - ); - - $agent->ask('посчитай'); - - assertSame('calculator', $seen[0]); - assertSame('2+2', $seen[1]['expression']); - assertSame(false, $agent->trace()[0]['blocked']); - assertSame('2+2 = 4', $agent->trace()[0]['output']); -}); - -test('настройки: historyLimit обрезает историю целыми ходами', function (): void { - $client = new FakeClient([ - textResult('a1'), - textResult('a2'), - textResult('a3'), - textResult('a4'), - ]); - - $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'auto', true, 4); - - $agent->ask('вопрос 1'); - $agent->ask('вопрос 2'); - $agent->ask('вопрос 3'); - $agent->ask('вопрос 4'); - - $messages = $agent->messages(); - - assertSame('system', $messages[0]['role'], 'system должен оставаться первым'); - assertTrue(($messages[1]['role'] ?? '') !== 'tool', 'история не должна начинаться с tool'); - - // Обрезка идёт Перед запросом: лимит 4 + system + финальный ответ. - assertSame(6, count($messages), 'без лимита было бы 9'); - - $last = $messages[count($messages) - 1]; - $question = $messages[count($messages) - 2]; - - assertSame('user', $question['role']); - assertSame('вопрос 4', $question['content'], 'текущий вопрос должен сохраниться'); - assertSame('assistant', $last['role']); -}); - -test('настройки: historyLimit=0 отключает обрезку', function (): void { - $client = new FakeClient([textResult('a'), textResult('b')]); - $agent = new Agent($client, new ToolRegistry(), 'тест', 3, 'auto', true, 0); - - $agent->ask('раз'); - $agent->ask('два'); - - assertSame(5, count($agent->messages()), 'system + 2 вопроса + 2 ответа'); -}); - -test('агент: reset очищает историю и трассировку', function (): void { - $client = new FakeClient([textResult('ответ')]); - $agent = new Agent($client, new ToolRegistry(), 'ты тестовый', 3); - - $agent->ask('вопрос'); - $agent->reset(); - - assertSame([], $agent->messages()); - assertSame([], $agent->trace()); -}); - -// --------------------------------------------------------------------------- -// Завершение через finish -// --------------------------------------------------------------------------- - -test('finish: возвращает result и не делает лишний запрос', function (): void { - $client = new FakeClient([ - toolCalls([['name' => 'finish', 'arguments' => ['result' => 'готово'], 'id' => 'f1']]), - ]); - - $agent = new Agent( - $client, - (new ToolRegistry())->add(new FinishTool()), - 'ты тестовый', - 3, - ); - - assertSame('готово', $agent->ask('сделай')); - assertSame(1, count($client->requests), 'после finish второго запроса быть не должно'); - assertSame('finish', $agent->trace()[0]['name']); - - $last = $agent->messages()[count($agent->messages()) - 1]; - assertSame('assistant', $last['role']); - assertSame('готово', $last['content']); -}); - -test('finish: остальные вызовы из того же ответа получают ответ', function (): void { - $client = new FakeClient([ - toolCalls([ - ['name' => 'calculator', 'arguments' => ['expression' => '2+2'], 'id' => 'c1'], - ['name' => 'finish', 'arguments' => ['result' => '4'], 'id' => 'f1'], - ]), - ]); - - $agent = new Agent( - $client, - (new ToolRegistry())->add(new CalculatorTool(), new FinishTool()), - 'ты тестовый', - 3, - ); - - assertSame('4', $agent->ask('посчитай')); - - // История должна остаться валидной: у каждого tool_call_id есть tool-ответ. - $messages = $agent->messages(); - $answered = []; - - foreach ($messages as $message) { - if (($message['role'] ?? '') === 'tool') { - $answered[] = $message['tool_call_id']; - } - } - - assertSame(['c1', 'f1'], $answered); - assertSame('2+2 = 4', $messages[3]['content'], 'калькулятор должен выполниться до finish'); -}); - -test('finish: без result возвращает понятную заглушку', function (): void { - $client = new FakeClient([ - toolCalls([['name' => 'finish', 'arguments' => [], 'id' => 'f1']]), - ]); - - $agent = new Agent($client, (new ToolRegistry())->add(new FinishTool()), 'тест', 3); - - assertContains('без результата', $agent->ask('сделай')); -}); - -test('finish: незарегистрированный инструмент не перехватывается', function (): void { - $client = new FakeClient([ - toolCall('finish', ['result' => 'x'], 'f1'), - textResult('продолжил'), - ]); - - $agent = new Agent($client, new ToolRegistry(), 'тест', 3); - - assertSame('продолжил', $agent->ask('сделай')); - assertContains('неизвестный инструмент', $agent->trace()[0]['output']); -}); - -test('finish: можно отключить перехват через finishTool', function (): void { - $client = new FakeClient([ - toolCall('finish', ['result' => 'x'], 'f1'), - textResult('обычный ответ'), - ]); - - $agent = new Agent( - client: $client, - tools: (new ToolRegistry())->add(new FinishTool()), - systemPrompt: 'тест', - maxRounds: 3, - finishTool: '', - ); - - assertSame('обычный ответ', $agent->ask('сделай')); -}); - -// --------------------------------------------------------------------------- -// Файлы -// --------------------------------------------------------------------------- - -test('read_file: читает файл внутри корня', function (): void { - $dir = testDir(); - file_put_contents($dir . '/note.txt', "первая\nвторая\nтретья"); - - $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => 'note.txt']); - - assertContains('строки 1–3 из 3', $result); - assertContains('вторая', $result); -}); - -test('read_file: offset и limit в строках', function (): void { - $dir = testDir(); - file_put_contents($dir . '/note.txt', "1\n2\n3\n4\n5"); - - $result = (new ReadFileTool(new FileSandbox($dir))) - ->handle(['path' => 'note.txt', 'offset' => 1, 'limit' => 2]); - - assertContains('строки 2–3 из 5', $result); - assertContains("2\n3", $result); -}); - -test('read_file: побег через .. запрещён', function (): void { - $dir = testDir(); - file_put_contents(dirname($dir) . '/outside.txt', 'секрет'); - - $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../outside.txt']); - - assertContains('не должен содержать', $result); -}); - -test('read_file: абсолютный путь запрещён', function (): void { - $dir = testDir(); - - $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '/etc/passwd']); - - assertContains('Абсолютные пути запрещены', $result); -}); - -test('read_file: бинарный файл не читается', function (): void { - $dir = testDir(); - file_put_contents($dir . '/bin.dat', "\x00\x01\x02\xFF"); - - $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => 'bin.dat']); - - assertContains('бинарный', $result); -}); - -test('list_dir: показывает каталоги и файлы', function (): void { - $dir = testDir(); - mkdir($dir . '/sub'); - file_put_contents($dir . '/a.txt', 'hello'); - - $result = (new ListDirTool(new FileSandbox($dir)))->handle([]); - - assertContains('sub/', $result); - assertContains('a.txt', $result); -}); - -test('list_dir: выход за корень запрещён', function (): void { - $dir = testDir(); - - $result = (new ListDirTool(new FileSandbox($dir)))->handle(['path' => '..']); - - assertContains('не должен содержать', $result); -}); - -// --------------------------------------------------------------------------- -// CSV -// --------------------------------------------------------------------------- - -test('csv_query: фильтр по колонке', function (): void { - $dir = testDir(); - file_put_contents( - $dir . '/people.csv', - "name,city,age\nИван,Тула,30\nМария,Москва,25\nПётр,Тула,41\n" - ); - - $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ - 'path' => 'people.csv', - 'where' => 'city=Тула', - ]); - - assertContains('Иван', $result); - assertContains('Пётр', $result); - assertTrue(!str_contains($result, 'Мария'), 'строка из другого города попала в выборку'); - assertContains('2 из 3 строк', $result); -}); - -test('csv_query: вхождение подстроки и лимит', function (): void { - $dir = testDir(); - file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\nИгорь,Тула\nПётр,Тула\n"); - - $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ - 'path' => 'people.csv', - 'where' => 'name~и', - 'columns' => 'name', - 'limit' => 2, - ]); - - assertContains('2 из 3 строк', $result); - assertTrue(!str_contains($result, 'city'), 'лишняя колонка в выборке'); -}); - -test('csv_query: неизвестная колонка — понятная ошибка', function (): void { - $dir = testDir(); - file_put_contents($dir . '/people.csv', "name,city\nИван,Тула\n"); - - $result = (new CsvQueryTool(new FileSandbox($dir)))->handle([ - 'path' => 'people.csv', - 'where' => 'город=Тула', - ]); - - assertContains('Нет колонки', $result); - assertContains('name, city', $result); -}); - -// --------------------------------------------------------------------------- -// Единицы и даты -// --------------------------------------------------------------------------- - -test('convert_units: километры в мили', function (): void { - assertSame('100 km = 62.137119 mi', (new ConvertUnitsTool())->handle([ - 'value' => 100, - 'from' => 'km', - 'to' => 'mi', - ])); -}); - -test('convert_units: температура', function (): void { - $tool = new ConvertUnitsTool(); - - assertSame('0 c = 32 f', $tool->handle(['value' => 0, 'from' => 'c', 'to' => 'f'])); - assertSame('100 c = 373.15 k', $tool->handle(['value' => 100, 'from' => 'c', 'to' => 'k'])); -}); - -test('convert_units: русские названия единиц', function (): void { - // Ответ приходит в канонических кодах, независимо от ввода. - assertSame('5 km = 5000 m', (new ConvertUnitsTool())->handle([ - 'value' => 5, - 'from' => 'км', - 'to' => 'м', - ])); -}); - -test('convert_units: неизвестная единица', function (): void { - $result = (new ConvertUnitsTool())->handle(['value' => 1, 'from' => 'parsec', 'to' => 'm']); - - assertContains('Не знаю единицы', $result); -}); - -test('date_calc: разница между датами', function (): void { - $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'to' => '2026-02-01']); - - assertContains('31 день', $result); -}); - -test('date_calc: дата без времени — это полночь, а не «сейчас»', function (): void { - $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'modifier' => '+1 day']); - - assertContains('2026-01-01 00:00:00', $result); - assertContains('2026-01-02 00:00:00', $result); -}); - -test('date_calc: прибавить интервал', function (): void { - $result = (new DateCalcTool())->handle(['from' => '2026-01-01', 'modifier' => '+30 days']); - - assertContains('2026-01-31', $result); -}); - -test('date_calc: без параметров — подсказка', function (): void { - assertContains('Нужен либо to', (new DateCalcTool())->handle([])); -}); - -test('date_calc: плохой часовой пояс', function (): void { - assertContains('Неизвестный часовой пояс', (new DateCalcTool())->handle([ - 'from' => 'now', - 'timezone' => 'Mars/Olympus', - ])); -}); - -// --------------------------------------------------------------------------- -// UUID и хеши -// --------------------------------------------------------------------------- - -test('uuid: формат v4 и уникальность', function (): void { - $tool = new UuidTool(); - $first = $tool->handle([]); - $second = $tool->handle([]); - - assertTrue( - preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $first) === 1, - 'не UUID v4: ' . $first - ); - assertTrue($first !== $second, 'два вызова вернули одинаковый UUID'); -}); - -test('hash_text: известные значения', function (): void { - $tool = new HashTool(); - - assertSame('sha256: ' . hash('sha256', 'привет'), $tool->handle(['text' => 'привет'])); - assertSame('md5: ' . md5('x'), $tool->handle(['text' => 'x', 'algo' => 'md5'])); - assertContains('Неизвестный алгоритм', $tool->handle(['text' => 'x', 'algo' => 'crc32'])); -}); - -// --------------------------------------------------------------------------- -// http_request: сборка запроса (без сети) -// --------------------------------------------------------------------------- - -test('http_request: query добавляется к URL', function (): void { - $request = HttpRequest::build('get', 'https://example.com/search', ['q' => 'кот', 'page' => 2]); - - assertSame('GET', $request->method); - assertContains('q=%D0%BA%D0%BE%D1%82', $request->url); - assertContains('page=2', $request->url); -}); - -test('http_request: JSON-тело и Content-Type', function (): void { - $request = HttpRequest::build('POST', 'https://example.com/orders', body: ['sku' => 'A-1']); - - assertSame('{"sku":"A-1"}', $request->body); - assertSame('application/json', $request->headers['Content-Type']); - assertSame('POST', $request->method); -}); - -test('http_request: form-тело', function (): void { - $request = HttpRequest::build( - 'POST', - 'https://example.com/login', - body: ['u' => 'a', 'p' => 'b'], - contentType: 'form', - ); - - assertSame('u=a&p=b', $request->body); - assertSame('application/x-www-form-urlencoded', $request->headers['Content-Type']); -}); - -test('http_request: Basic-авторизация', function (): void { - $request = HttpRequest::build( - 'GET', - 'https://example.com/me', - auth: ['user' => 'bot', 'pass' => 'secret'], - ); - - assertSame('Basic ' . base64_encode('bot:secret'), $request->headers['Authorization']); -}); - -test('http_request: Bearer-авторизация', function (): void { - $request = HttpRequest::build( - 'GET', - 'https://example.com/me', - auth: ['type' => 'bearer', 'token' => 'abc'], - ); - - assertSame('Bearer abc', $request->headers['Authorization']); -}); - -test('http_request: запрещённые заголовки отбрасываются', function (): void { - $request = HttpRequest::build( - 'GET', - 'https://example.com', - headers: ['Host' => 'evil', 'X-Ok' => '1'], - ); - - assertTrue(!isset($request->headers['Host']), 'Host должен отбрасываться'); - assertSame('1', $request->headers['X-Ok']); -}); - -test('http_request: неизвестный метод отвергается', function (): void { - assertThrows(static fn () => HttpRequest::build('TRACE', 'https://example.com')); -}); - -test('http_request: без схемы подставляется https', function (): void { - assertSame('https://example.com/x', HttpRequest::build('GET', 'example.com/x')->url); -}); - -test('http: заголовки превращаются в строки cURL', function (): void { - // Регрессия: ассоциативный массив, отданный в cURL напрямую, - // молча терял и Content-Type, и Authorization. - assertSame(['X-Ok: 1'], Http::headerLines(['X-Ok' => '1'])); - assertSame(['Accept: */*'], Http::headerLines([])); - assertSame(['Accept: */*'], Http::headerLines(['Accept: */*'])); -}); - -// --------------------------------------------------------------------------- -// http_request: защита от SSRF (без сети) -// --------------------------------------------------------------------------- - -test('http_request: localhost запрещён', function (): void { - assertContains('локальному адресу', (new HttpRequestTool())->handle(['url' => 'http://localhost/x'])); -}); - -test('http_request: приватные адреса запрещены', function (): void { - $tool = new HttpRequestTool(); - - assertContains('приватному адресу', $tool->handle(['url' => 'http://127.0.0.1/x'])); - assertContains('приватному адресу', $tool->handle(['url' => 'http://10.0.0.5/x'])); - assertContains('приватному адресу', $tool->handle(['url' => 'http://192.168.1.10/x'])); -}); - -test('http_request: только http и https', function (): void { - assertContains('только http и https', (new HttpRequestTool())->handle(['url' => 'ftp://example.com/x'])); -}); - -test('http_request: allowPrivate снимает блокировку внутренней сети', function (): void { - // Порт закрыт: проверяем именно то, что SSRF-отказ больше не выдаётся. - $result = (new HttpRequestTool(allowPrivate: true))->handle(['url' => 'http://127.0.0.1:9/x']); - - assertTrue( - !str_contains($result, 'приватному адресу'), - 'с allowPrivate адрес не должен блокироваться: ' . $result - ); -}); - -// --------------------------------------------------------------------------- -// Запись и правка файлов -// --------------------------------------------------------------------------- - -test('write_file: создаёт файл', function (): void { - $dir = testDir(); - $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'note.txt', - 'content' => 'привет', - ]); - - assertContains('Создан', $result); - assertSame('привет', file_get_contents($dir . '/note.txt')); -}); - -test('write_file: перезаписывает файл', function (): void { - $dir = testDir(); - file_put_contents($dir . '/note.txt', 'старое'); - - $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'note.txt', - 'content' => 'новое', - ]); - - assertContains('Перезаписан', $result); - assertSame('новое', file_get_contents($dir . '/note.txt')); -}); - -test('write_file: создаёт каталоги с create_dirs', function (): void { - $dir = testDir(); - - $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'a/b/c.txt', - 'content' => 'x', - 'create_dirs' => true, - ]); - - assertContains('Создан', $result); - assertTrue(is_file($dir . '/a/b/c.txt'), 'файл не создан'); -}); - -test('write_file: без create_dirs каталог обязателен', function (): void { - $dir = testDir(); - - $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'nope/x.txt', - 'content' => 'x', - ]); - - assertContains('Каталог не существует', $result); -}); - -test('write_file: запись вне песочницы запрещена', function (): void { - $dir = testDir(); - - $result = (new WriteFileTool(new FileSandbox($dir)))->handle([ - 'path' => '../evil.txt', - 'content' => 'x', - ]); - - assertContains('не должен содержать', $result); -}); - -test('replace_in_file: заменяет единственное совпадение', function (): void { - $dir = testDir(); - file_put_contents($dir . '/code.txt', "class A\nclass B\n"); - - $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'code.txt', - 'search' => 'class A', - 'replace' => 'final class A', - ]); - - assertContains('Заменено вхождений: 1', $result); - - $content = (string) file_get_contents($dir . '/code.txt'); - - assertContains('final class A', $content); - assertContains('class B', $content); -}); - -test('replace_in_file: несколько совпадений требуют all', function (): void { - $dir = testDir(); - file_put_contents($dir . '/code.txt', "x\nx\n"); - - $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'code.txt', - 'search' => 'x', - 'replace' => 'y', - ]); - - assertContains('Найдено совпадений: 2', $result); -}); - -test('replace_in_file: не найдено — понятная ошибка', function (): void { - $dir = testDir(); - file_put_contents($dir . '/code.txt', 'abc'); - - $result = (new ReplaceInFileTool(new FileSandbox($dir)))->handle([ - 'path' => 'code.txt', - 'search' => 'zzz', - 'replace' => 'y', - ]); - - assertContains('не найден', $result); -}); - -// --------------------------------------------------------------------------- -// Поиск по файлам -// --------------------------------------------------------------------------- - -test('search_files: находит строки с номерами', function (): void { - $dir = testDir(); - file_put_contents($dir . '/a.php', "handle(['pattern' => 'class \w+']); - - assertContains('a.php:2:', $result); - assertContains('b.txt:1:', $result); -}); - -test('search_files: glob ограничивает файлы', function (): void { - $dir = testDir(); - file_put_contents($dir . '/a.php', "class Foo\n"); - file_put_contents($dir . '/b.txt', "class Bar\n"); - - $result = (new SearchFilesTool(new FileSandbox($dir)))->handle([ - 'pattern' => 'class', - 'glob' => '*.php', - ]); - - assertContains('a.php', $result); - assertTrue(!str_contains($result, 'b.txt'), 'лишний файл в выдаче'); -}); - -test('search_files: служебные каталоги пропускаются', function (): void { - $dir = testDir(); - mkdir($dir . '/vendor', 0777, true); - file_put_contents($dir . '/vendor/lib.php', "class Vendor\n"); - file_put_contents($dir . '/app.php', "class App\n"); - - $result = (new SearchFilesTool(new FileSandbox($dir)))->handle(['pattern' => 'class']); - - assertContains('app.php', $result); - assertTrue(!str_contains($result, 'vendor'), 'vendor не должен сканироваться'); -}); - -test('search_files: некорректная регулярка', function (): void { - $dir = testDir(); - - $result = (new SearchFilesTool(new FileSandbox($dir)))->handle(['pattern' => '([']); - - assertContains('Некорректное регулярное выражение', $result); -}); - -test('find_files: поиск по маске', function (): void { - $dir = testDir(); - file_put_contents($dir . '/a.php', 'x'); - file_put_contents($dir . '/b.txt', 'x'); - - $result = (new FindFilesTool(new FileSandbox($dir)))->handle(['pattern' => '*.php']); - - assertContains('a.php', $result); - assertTrue(!str_contains($result, 'b.txt'), 'лишний файл в выдаче'); -}); - -// --------------------------------------------------------------------------- -// JSON -// --------------------------------------------------------------------------- - -test('json_query: вложенный путь', function (): void { - $result = (new JsonQueryTool())->handle([ - 'json' => '{"data":{"items":[{"id":42,"name":"x"}]}}', - 'path' => 'data.items[0].id', - ]); - - assertContains('42', $result); -}); - -test('json_query: нет ключа — сообщение', function (): void { - $result = (new JsonQueryTool())->handle(['json' => '{"a":1}', 'path' => 'b']); - - assertContains('не найден', $result); -}); - -test('json_query: битый JSON', function (): void { - $result = (new JsonQueryTool())->handle(['json' => '{oops', 'path' => 'a']); - - assertContains('Некорректный JSON', $result); -}); - -// --------------------------------------------------------------------------- -// Песочница: ограниченный и свободный режимы -// --------------------------------------------------------------------------- - -test('sandbox: по умолчанию ограничена', function (): void { - $dir = testDir(); - - assertTrue((new FileSandbox($dir))->isRestricted()); - assertTrue(!FileSandbox::unrestricted($dir)->isRestricted()); -}); - -test('sandbox: свободный режим читает вне корня', function (): void { - $dir = testDir(); - $outside = str_replace('\\', '/', dirname($dir) . '/outside.txt'); - file_put_contents($outside, 'снаружи'); - - $result = (new ReadFileTool(FileSandbox::unrestricted($dir)))->handle(['path' => $outside]); - - assertContains('снаружи', $result); -}); - -test('sandbox: свободный режим пишет вне корня', function (): void { - $dir = testDir(); - $outside = str_replace('\\', '/', dirname($dir) . '/written.txt'); - - $result = (new WriteFileTool(FileSandbox::unrestricted($dir)))->handle([ - 'path' => $outside, - 'content' => 'записано', - ]); - - assertContains('Создан', $result); - assertSame('записано', file_get_contents($outside)); -}); - -test('sandbox: политика задаётся для каждого инструмента отдельно', function (): void { - $dir = testDir(); - $outside = str_replace('\\', '/', dirname($dir) . '/mixed.txt'); - file_put_contents($outside, 'данные'); - - // Читать можно везде... - $read = new ReadFileTool(FileSandbox::unrestricted($dir)); - assertContains('данные', $read->handle(['path' => $outside])); - - // ...а писать — только в корень. - $write = new WriteFileTool(new FileSandbox($dir)); - assertContains('запрещены', $write->handle(['path' => $outside, 'content' => 'x'])); -}); - -test('sandbox: ограниченный режим по-прежнему блокирует выход', function (): void { - $dir = testDir(); - $outside = dirname($dir) . '/blocked.txt'; - file_put_contents($outside, 'секрет'); - - $result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../blocked.txt']); - - assertContains('не должен содержать', $result); -}); - -// --------------------------------------------------------------------------- -// Логирование -// --------------------------------------------------------------------------- - -test('logging: прокидывает ответ и пишет строки', function (): void { - $lines = []; - $client = new LoggingClient( - new FakeClient([textResult('привет')]), - sink: static function (string $line) use (&$lines): void { - $lines[] = $line; - }, - ); - - $result = $client->chat([['role' => 'user', 'content' => 'вопрос']]); - - assertSame('привет', $result->text); - assertSame(2, count($lines), 'ожидались две строки: запрос и ответ'); - assertContains('LLM →', $lines[0]); - assertContains('LLM ←', $lines[1]); - assertContains('текст 6 симв.', $lines[1]); -}); - -test('logging: ошибка пишется и пробрасывается', function (): void { - $broken = new class implements ChatClient { - public function chat(array $messages, array $tools = [], array $options = []): ChatResult - { - throw new RuntimeException('сеть упала'); - } - }; - - $lines = []; - $client = new LoggingClient($broken, sink: static function (string $line) use (&$lines): void { - $lines[] = $line; - }); - - assertThrows(static fn () => $client->chat([['role' => 'user', 'content' => 'x']])); - - $log = implode("\n", $lines); - - assertContains('LLM ✗', $log); - assertContains('сеть упала', $log); -}); - -test('logging: verbose печатает сообщения и инструменты', function (): void { - $lines = []; - $client = new LoggingClient( - new FakeClient([textResult('ок')]), - sink: static function (string $line) use (&$lines): void { - $lines[] = $line; - }, - verbose: true, - ); - - $tools = (new ToolRegistry())->add(new TimeTool())->definitions(); - $client->chat([['role' => 'user', 'content' => 'который час']], $tools); - - $log = implode("\n", $lines); - - assertContains('[0] user: который час', $log); - assertContains('инструменты: get_time', $log); - assertContains('ответ: ок', $log); -}); - -test('logging: в агенте логирует каждый раунд', function (): void { - $lines = []; - $client = new LoggingClient( - new FakeClient([ - toolCall('calculator', ['expression' => '2+2'], 'c1'), - textResult('4'), - ]), - sink: static function (string $line) use (&$lines): void { - $lines[] = $line; - }, - ); - - $agent = new Agent($client, (new ToolRegistry())->add(new CalculatorTool()), 'тест', 3); - - assertSame('4', $agent->ask('посчитай')); - - $log = implode("\n", $lines); - - assertContains('tool_calls: calculator', $log); - assertSame(4, count($lines), 'два раунда — по две строки'); -}); - -// --------------------------------------------------------------------------- -// run_command: оболочка -// --------------------------------------------------------------------------- - -test('shell: выполняет команду и возвращает код', function (): void { - $result = (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'echo hello']); - - assertContains('hello', $result); - assertContains('exit: 0', $result); -}); - -test('shell: возвращает ненулевой код выхода', function (): void { - assertContains('exit: 3', (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'exit 3'])); -}); - -test('shell: таймаут прерывает команду', function (): void { - $command = DIRECTORY_SEPARATOR === '\\' ? 'ping -n 5 127.0.0.1 >NUL' : 'sleep 5'; - - $started = microtime(true); - $result = (new ShellTool(timeout: 0.5, tmpDir: __DIR__ . '/tmp'))->handle(['command' => $command]); - $elapsed = microtime(true) - $started; - - assertContains('таймаут', $result); - assertTrue($elapsed < 3.0, 'таймаут не сработал: ' . round($elapsed, 2) . ' с'); -}); - -test('shell: allowlist запрещает лишнее', function (): void { - $result = (new ShellTool(allow: ['echo'], tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'whoami']); - - assertContains('не разрешена', $result); -}); - -test('shell: allowlist пропускает разрешённое', function (): void { - $result = (new ShellTool(allow: ['echo'], tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'echo ok']); - - assertContains('ok', $result); -}); - -test('shell: длинный вывод обрезается', function (): void { - $result = (new ShellTool(maxOutput: 100, tmpDir: __DIR__ . '/tmp'))->handle(['command' => 'echo ' . str_repeat('x', 500)]); - - assertContains('обрезано', $result); -}); - -test('shell: пустая команда не запускается', function (): void { - assertContains('Пустая команда', (new ShellTool(tmpDir: __DIR__ . '/tmp'))->handle(['command' => ' '])); -}); - -// --------------------------------------------------------------------------- - removeDir(__DIR__ . '/tmp'); echo PHP_EOL . 'пройдено: ' . $passed . ', провалено: ' . $failed . PHP_EOL; exit($failed === 0 ? 0 : 1); - - - - diff --git a/tests/support.php b/tests/support.php new file mode 100644 index 0000000..d1bae3d --- /dev/null +++ b/tests/support.php @@ -0,0 +1,238 @@ +getMessage() . PHP_EOL; + } +} + +function assertSame(mixed $expected, mixed $actual, string $message = ''): void +{ + if ($expected !== $actual) { + throw new RuntimeException( + ($message !== '' ? $message . ': ' : '') + . 'ожидалось ' . var_export($expected, true) + . ', получено ' . var_export($actual, true) + ); + } +} + +function assertTrue(bool $value, string $message = ''): void +{ + if (!$value) { + throw new RuntimeException($message !== '' ? $message : 'ожидалось true'); + } +} + +function assertContains(string $needle, string $haystack, string $message = ''): void +{ + if (!str_contains($haystack, $needle)) { + throw new RuntimeException( + ($message !== '' ? $message . ': ' : '') + . 'нет "' . $needle . '" в "' . $haystack . '"' + ); + } +} + +function assertThrows(callable $fn, string $message = ''): void +{ + try { + $fn(); + } catch (Throwable) { + return; + } + + throw new RuntimeException($message !== '' ? $message : 'ожидалось исключение'); +} + +/** + * Модель-заглушка: отдаёт ответы по очереди и запоминает все запросы. + */ +final class FakeClient implements ChatClient +{ + /** @var list, tools: array, options: array}> */ + public array $requests = []; + + /** + * @param list $results + */ + public function __construct(private array $results) + { + } + + public function chat(array $messages, array $tools = [], array $options = []): ChatResult + { + $this->requests[] = ['messages' => $messages, 'tools' => $tools, 'options' => $options]; + + $result = array_shift($this->results); + + if ($result === null) { + throw new RuntimeException('FakeClient: закончились заготовленные ответы'); + } + + return $result; + } +} + +/** + * Ответ «вызови инструмент». + * + * @param array $arguments + */ +function toolCall(string $name, array $arguments, string $id = 'call_1'): ChatResult +{ + $message = [ + 'role' => 'assistant', + 'content' => '', + 'tool_calls' => [[ + 'id' => $id, + 'type' => 'function', + 'function' => [ + 'name' => $name, + 'arguments' => json_encode($arguments, JSON_UNESCAPED_UNICODE), + ], + ]], + ]; + + return new ChatResult('', [['id' => $id, 'name' => $name, 'arguments' => $arguments]], $message); +} + +function textResult(string $text): ChatResult +{ + return new ChatResult($text, [], ['role' => 'assistant', 'content' => $text]); +} + +/** + * Временный каталог для файловых инструментов. + */ +function testDir(): string +{ + $base = __DIR__ . '/tmp'; + + if (!is_dir($base) && !mkdir($base, 0777, true) && !is_dir($base)) { + throw new RuntimeException('не удалось создать tests/tmp'); + } + + $dir = $base . '/sandbox-' . bin2hex(random_bytes(3)); + + if (!mkdir($dir, 0777, true)) { + throw new RuntimeException('не удалось создать ' . $dir); + } + + return $dir; +} + +function removeDir(string $dir): void +{ + if (!is_dir($dir)) { + return; + } + + $items = scandir($dir) ?: []; + + foreach ($items as $item) { + if ($item === '.' || $item === '..') { + continue; + } + + $path = $dir . '/' . $item; + + if (is_dir($path)) { + removeDir($path); + } else { + @unlink($path); + } + } + + @rmdir($dir); +} + +/** + * Ответ модели с несколькими вызовами сразу. + * + * @param list, id: string}> $calls + */ +function toolCalls(array $calls): ChatResult +{ + $message = ['role' => 'assistant', 'content' => '', 'tool_calls' => []]; + $parsed = []; + + foreach ($calls as $call) { + $message['tool_calls'][] = [ + 'id' => $call['id'], + 'type' => 'function', + 'function' => [ + 'name' => $call['name'], + 'arguments' => json_encode($call['arguments'], JSON_UNESCAPED_UNICODE), + ], + ]; + + $parsed[] = [ + 'id' => $call['id'], + 'name' => $call['name'], + 'arguments' => $call['arguments'], + ]; + } + + return new ChatResult('', $parsed, $message); +} + diff --git a/tools/FileSandbox.php b/tools/FileSandbox.php index 9775d0c..634865c 100644 --- a/tools/FileSandbox.php +++ b/tools/FileSandbox.php @@ -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('Не удалось переименовать временный файл.'); - } - } /** * Путь для показа пользователю (относительно корня, если внутри него). diff --git a/tools/FindFilesTool.php b/tools/FindFilesTool.php index ac431a7..845496d 100644 --- a/tools/FindFilesTool.php +++ b/tools/FindFilesTool.php @@ -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 . ' Б'; - } } diff --git a/tools/HttpRequestTool.php b/tools/HttpRequestTool.php index 0d7aeec..84045cb 100644 --- a/tools/HttpRequestTool.php +++ b/tools/HttpRequestTool.php @@ -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> креды по хосту (в нижнем регистре) */ private readonly array $auth; + private readonly UrlGuard $guard; /** * @param array> $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; - } } + diff --git a/tools/ListDirTool.php b/tools/ListDirTool.php index be30d52..7aaf764 100644 --- a/tools/ListDirTool.php +++ b/tools/ListDirTool.php @@ -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 . ' Б'; - } } + diff --git a/tools/ReadFileTool.php b/tools/ReadFileTool.php index e21c363..7ff2b11 100644 --- a/tools/ReadFileTool.php +++ b/tools/ReadFileTool.php @@ -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 . ' Б'; - } } + diff --git a/tools/ReplaceInFileTool.php b/tools/ReplaceInFileTool.php index 0bcdac9..693c4b3 100644 --- a/tools/ReplaceInFileTool.php +++ b/tools/ReplaceInFileTool.php @@ -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)); } } + diff --git a/tools/SearchFilesTool.php b/tools/SearchFilesTool.php index 232df47..f9d41fe 100644 --- a/tools/SearchFilesTool.php +++ b/tools/SearchFilesTool.php @@ -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); - } - } - } } diff --git a/tools/Support/AtomicWriter.php b/tools/Support/AtomicWriter.php new file mode 100644 index 0000000..566b736 --- /dev/null +++ b/tools/Support/AtomicWriter.php @@ -0,0 +1,46 @@ += 1048576) { + return round($bytes / 1048576, 1) . ' МБ'; + } + + if ($bytes >= 1024) { + return round($bytes / 1024, 1) . ' КБ'; + } + + return $bytes . ' Б'; + } +} diff --git a/tools/Support/FileWalker.php b/tools/Support/FileWalker.php new file mode 100644 index 0000000..d51d8e8 --- /dev/null +++ b/tools/Support/FileWalker.php @@ -0,0 +1,47 @@ + $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); + } + } + } +} diff --git a/tools/Support/UrlGuard.php b/tools/Support/UrlGuard.php new file mode 100644 index 0000000..f6ba829 --- /dev/null +++ b/tools/Support/UrlGuard.php @@ -0,0 +1,86 @@ +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; + } +} diff --git a/tools/WeatherTool.php b/tools/WeatherTool.php index 80ea83b..3d55e9e 100644 --- a/tools/WeatherTool.php +++ b/tools/WeatherTool.php @@ -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 ]; } } + diff --git a/tools/WriteFileTool.php b/tools/WriteFileTool.php index 173663a..38b5a16 100644 --- a/tools/WriteFileTool.php +++ b/tools/WriteFileTool.php @@ -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) . ' Б.'; } } +