feat: файловые, сетевые и прикладные инструменты

- FileSandbox + read_file/list_dir: доступ только внутри заданного корня,
  отказ на .., абсолютные пути и симлинки наружу; бинарные файлы не читаются
- csv_query: фильтр =/~ по колонке, выбор колонок, лимит строк
- http_get: защита от SSRF (только публичные IP), проверка редиректов,
  лимит размера через write-callback
- convert_units: температура, длина, масса, скорость + русские алиасы
- date_calc: разница дат и прибавление интервала ('!' в формате,
  чтобы дата без времени была полуночью)
- uuid и hash_text
- Http: request() с лимитом размера и заголовком Location, get() поверх него
- пример 07-tools.php, 55 тестов
This commit is contained in:
rsgrinko committed 2026-11-12 18:45:20 +03:00
1 parent 0109631e5e
commit 1dea787255
14 files changed
+1685 -14

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Перевод единиц: температура, длина, масса, скорость.
*
* Валют здесь нет осознанно: курс — это внешние изменяемые данные,
* а не арифметика.
*/
final class ConvertUnitsTool implements Tool
{
/** Коэффициенты к базовой единице (метры). */
private const LENGTH = [
'mm' => 0.001, 'cm' => 0.01, 'm' => 1.0, 'km' => 1000.0,
'in' => 0.0254, 'ft' => 0.3048, 'yd' => 0.9144, 'mi' => 1609.344,
];
/** Килограммы. */
private const MASS = [
'mg' => 0.000001, 'g' => 0.001, 'kg' => 1.0, 't' => 1000.0,
'oz' => 0.028349523125, 'lb' => 0.45359237,
];
/** Метры в секунду. */
private const SPEED = [
'mps' => 1.0, 'kmh' => 1 / 3.6, 'mph' => 0.44704, 'kn' => 0.514444444,
];
/** Синонимы -> канонический код. */
private const ALIASES = [
'мм' => 'mm', 'см' => 'cm', 'м' => 'm', 'км' => 'km',
'дюйм' => 'in', 'дюймы' => 'in', 'фут' => 'ft', 'футы' => 'ft', 'ярд' => 'yd', 'миля' => 'mi', 'мили' => 'mi',
'мг' => 'mg', 'г' => 'g', 'кг' => 'kg', 'т' => 't', 'тонна' => 't', 'тонны' => 't',
'унция' => 'oz', 'фунт' => 'lb', 'фунты' => 'lb',
'м/с' => 'mps', 'км/ч' => 'kmh', 'узел' => 'kn', 'узлов' => 'kn',
'°c' => 'c', 'celsius' => 'c', 'цельсий' => 'c', 'градус' => 'c',
'°f' => 'f', 'fahrenheit' => 'f', 'фаренгейт' => 'f',
'°k' => 'k', 'kelvin' => 'k', 'кельвин' => 'k',
'метр' => 'm', 'метры' => 'm', 'километр' => 'km', 'километры' => 'km',
'сантиметр' => 'cm', 'сантиметры' => 'cm', 'миллиметр' => 'mm', 'миллиметры' => 'mm',
'грамм' => 'g', 'граммы' => 'g', 'килограмм' => 'kg', 'килограммы' => 'kg',
];
public function name(): string
{
return 'convert_units';
}
public function description(): string
{
return 'Перевести величину между единицами. Температура: c, f, k. '
. 'Длина: mm, cm, m, km, in, ft, yd, mi. Масса: mg, g, kg, t, oz, lb. '
. 'Скорость: mps, kmh, mph, kn.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'value' => ['type' => 'number', 'description' => 'Число для перевода.'],
'from' => ['type' => 'string', 'description' => 'Исходная единица, например km.'],
'to' => ['type' => 'string', 'description' => 'Целевая единица, например mi.'],
],
'required' => ['value', 'from', 'to'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$value = $args['value'] ?? null;
if (!is_numeric($value)) {
return 'value должно быть числом.';
}
$from = $this->normalize((string) ($args['from'] ?? ''));
$to = $this->normalize((string) ($args['to'] ?? ''));
if ($from === '' || $to === '') {
return 'Укажи from и to, например from: km, to: mi.';
}
$value = (float) $value;
$result = $this->convert($value, $from, $to);
if ($result === null) {
return 'Не знаю единицы "' . $from . '" или "' . $to . '". '
. 'Доступно: c, f, k, mm, cm, m, km, in, ft, yd, mi, mg, g, kg, t, oz, lb, mps, kmh, mph, kn.';
}
return $this->format($value) . ' ' . $from . ' = ' . $this->format($result) . ' ' . $to;
}
private function convert(float $value, string $from, string $to): ?float
{
// Температура — не масштаб, а сдвиг, поэтому отдельно.
$temperatures = ['c', 'f', 'k'];
if (in_array($from, $temperatures, true) || in_array($to, $temperatures, true)) {
if (!in_array($from, $temperatures, true) || !in_array($to, $temperatures, true)) {
return null;
}
$celsius = match ($from) {
'c' => $value,
'f' => ($value - 32) * 5 / 9,
'k' => $value - 273.15,
};
return match ($to) {
'c' => $celsius,
'f' => $celsius * 9 / 5 + 32,
'k' => $celsius + 273.15,
};
}
foreach ([self::LENGTH, self::MASS, self::SPEED] as $table) {
if (isset($table[$from], $table[$to])) {
return $value * $table[$from] / $table[$to];
}
}
return null;
}
private function normalize(string $unit): string
{
$unit = mb_strtolower(trim($unit));
return self::ALIASES[$unit] ?? $unit;
}
private function format(float $value): string
{
if (abs($value - round($value)) < 1e-9) {
return (string) (int) round($value);
}
return rtrim(rtrim(number_format($value, 6, '.', ''), '0'), '.');
}
}
+268
View File
@@ -0,0 +1,268 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Выборка из CSV-файла внутри песочницы.
*
* where: "колонка=значение" — точное совпадение (без регистра),
* "колонка~значение" — вхождение подстроки.
*/
final class CsvQueryTool implements Tool
{
private const MAX_BYTES = 5 * 1024 * 1024;
private const MAX_ROWS = 100;
private const CELL_MAX = 60;
public function __construct(private readonly FileSandbox $sandbox)
{
}
public function name(): string
{
return 'csv_query';
}
public function description(): string
{
return 'Прочитать CSV и вернуть строки таблицей. '
. 'where — фильтр: "city=Тула" (точно) или "name~иван" (вхождение). '
. 'columns — какие колонки вернуть через запятую. path — относительно корня.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'path' => ['type' => 'string', 'description' => 'Путь к CSV относительно корня.'],
'where' => ['type' => 'string', 'description' => 'Фильтр: city=Тула или name~иван.'],
'columns' => ['type' => 'string', 'description' => 'Список колонок через запятую.'],
'limit' => ['type' => 'integer', 'description' => 'Сколько строк, по умолчанию 20, максимум ' . self::MAX_ROWS . '.'],
'delimiter' => ['type' => 'string', 'description' => 'Разделитель, по умолчанию запятая.'],
],
'required' => ['path'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$path = (string) ($args['path'] ?? '');
$limit = (int) ($args['limit'] ?? 20);
$delimiter = (string) ($args['delimiter'] ?? ',');
$delimiter = $delimiter !== '' ? $delimiter[0] : ',';
if ($limit < 1) {
$limit = 20;
}
$limit = min($limit, self::MAX_ROWS);
try {
$file = $this->sandbox->resolve($path);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
if (!is_file($file)) {
return 'Это не файл: ' . $path;
}
$size = filesize($file);
if ($size !== false && $size > self::MAX_BYTES) {
return 'CSV слишком большой: ' . round($size / 1048576, 1) . ' МБ (максимум 5 МБ).';
}
$handle = fopen($file, 'rb');
if ($handle === false) {
return 'Не удалось открыть файл.';
}
$header = fgetcsv($handle, 0, $delimiter);
if ($header === false || $header === [null] || $header === []) {
fclose($handle);
return 'Не удалось прочитать заголовок CSV.';
}
$header = array_map(static fn ($name): string => trim((string) $name), $header);
$requested = $this->requestedColumns($header, (string) ($args['columns'] ?? ''));
if (is_string($requested)) {
fclose($handle);
return $requested;
}
$filter = $this->parseWhere($header, (string) ($args['where'] ?? ''));
if (is_string($filter)) {
fclose($handle);
return $filter;
}
$allRows = [];
while (($row = fgetcsv($handle, 0, $delimiter)) !== false) {
$allRows[] = array_map(static fn ($cell): string => trim((string) $cell), $row);
}
fclose($handle);
$total = count($allRows);
$rows = [];
foreach ($allRows as $row) {
if ($filter !== null && !$this->matches($row, $header, $filter)) {
continue;
}
$picked = [];
foreach ($requested as $index) {
$picked[] = $this->cell($row[$index] ?? '');
}
$rows[] = $picked;
if (count($rows) >= $limit) {
break;
}
}
if ($rows === []) {
return 'Подходящих строк нет (всего строк: ' . $total . ').';
}
$table = [array_map(static fn (int $i): string => $header[$i], $requested)];
$table = array_merge($table, $rows);
return 'CSV ' . $path . ': ' . count($rows) . ' из ' . $total . " строк\n" . $this->render($table);
}
/**
* @param list<string> $header
* @return list<int>|string индексы колонок или текст ошибки
*/
private function requestedColumns(array $header, string $columns): array|string
{
if (trim($columns) === '') {
return array_keys($header);
}
$wanted = array_map('trim', explode(',', $columns));
$indexes = [];
foreach ($wanted as $name) {
$index = array_search($name, $header, true);
if ($index === false) {
return 'Нет колонки "' . $name . '". Есть: ' . implode(', ', $header) . '.';
}
$indexes[] = (int) $index;
}
return $indexes;
}
/**
* @param list<string> $header
* @return array{index: int, value: string, contains: bool}|string|null
*/
private function parseWhere(array $header, string $where): array|string|null
{
$where = trim($where);
if ($where === '') {
return null;
}
if (preg_match('/^([^=~]+)([=~])(.*)$/u', $where, $match) !== 1) {
return 'Фильтр должен быть вида "колонка=значение" или "колонка~значение".';
}
$column = trim($match[1]);
$index = array_search($column, $header, true);
if ($index === false) {
return 'Нет колонки "' . $column . '". Есть: ' . implode(', ', $header) . '.';
}
return [
'index' => (int) $index,
'value' => trim($match[3]),
'contains' => $match[2] === '~',
];
}
/**
* @param list<string> $row
* @param list<string> $header
* @param array{index: int, value: string, contains: bool} $filter
*/
private function matches(array $row, array $header, array $filter): bool
{
$cell = $row[$filter['index']] ?? '';
if ($filter['contains']) {
return mb_stripos($cell, $filter['value']) !== false;
}
return mb_strtolower($cell) === mb_strtolower($filter['value']);
}
private function cell(string $value): string
{
$value = str_replace(["\r", "\n"], ' ', $value);
return mb_strlen($value) > self::CELL_MAX
? mb_substr($value, 0, self::CELL_MAX) . '…'
: $value;
}
/**
* @param list<list<string>> $table
*/
private function render(array $table): string
{
$widths = [];
foreach ($table as $row) {
foreach ($row as $index => $cell) {
$widths[$index] = max($widths[$index] ?? 0, mb_strlen($cell));
}
}
$lines = [];
foreach ($table as $rowIndex => $row) {
$parts = [];
foreach ($row as $index => $cell) {
$parts[] = str_pad($cell, $widths[$index]);
}
$lines[] = implode(' | ', $parts);
if ($rowIndex === 0) {
$lines[] = implode('-+-', array_map(
static fn (int $width): string => str_repeat('-', $width),
$widths
));
}
}
return implode("\n", $lines);
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Арифметика с датами: разница между датами и прибавление интервала.
*
* Даты — в формате ISO (2026-11-12, 2026-11-12 15:00:00) или "now".
* Интервал — в формате PHP: "+30 days", "-2 weeks", "+3 hours", "last monday".
*/
final class DateCalcTool implements Tool
{
public function name(): string
{
return 'date_calc';
}
public function description(): string
{
return 'Посчитать даты: разницу между двумя (from и to) или прибавить интервал '
. '(from + modifier). Примеры modifier: "+30 days", "-2 weeks", "+3 hours". '
. 'Даты в ISO или "now". Часовой пояс по умолчанию UTC.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'from' => ['type' => 'string', 'description' => 'Начальная дата или now.'],
'to' => ['type' => 'string', 'description' => 'Конечная дата — если нужна разница.'],
'modifier' => ['type' => 'string', 'description' => 'Интервал, например +30 days.'],
'timezone' => ['type' => 'string', 'description' => 'IANA-пояс, по умолчанию UTC.'],
],
'required' => [],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$timezone = trim((string) ($args['timezone'] ?? ''));
$timezone = $timezone !== '' ? $timezone : 'UTC';
try {
$zone = new \DateTimeZone($timezone);
} catch (\Throwable) {
return 'Неизвестный часовой пояс: ' . $timezone . '.';
}
$fromRaw = trim((string) ($args['from'] ?? 'now'));
$toRaw = trim((string) ($args['to'] ?? ''));
$modifier = trim((string) ($args['modifier'] ?? ''));
$from = $this->parse($fromRaw !== '' ? $fromRaw : 'now', $zone);
if ($from === null) {
return 'Не понял дату: ' . $fromRaw . '. Пример: 2026-11-12 или now.';
}
if ($toRaw !== '') {
$to = $this->parse($toRaw, $zone);
if ($to === null) {
return 'Не понял дату: ' . $toRaw . '. Пример: 2026-11-12.';
}
return $this->diff($from, $to);
}
if ($modifier !== '') {
$shifted = $from->modify($modifier);
if ($shifted === false) {
return 'Не понял интервал: ' . $modifier . '. Пример: +30 days.';
}
return $from->format('Y-m-d H:i:s T') . ' ' . $modifier . ' = '
. $shifted->format('Y-m-d H:i:s T');
}
return 'Нужен либо to (разница), либо modifier (сдвиг).';
}
private function parse(string $value, \DateTimeZone $zone): ?\DateTimeImmutable
{
if (strcasecmp($value, 'now') === 0) {
return new \DateTimeImmutable('now', $zone);
}
// «!» сбрасывает незаданные части в ноль: без него PHP подставит
// текущее время вместо 00:00:00.
foreach (['!Y-m-d H:i:s', '!Y-m-d\TH:i:s', '!Y-m-d'] as $format) {
$date = \DateTimeImmutable::createFromFormat($format, $value, $zone);
if ($date !== false) {
return $date;
}
}
// Естественный язык: «next friday», «tomorrow».
try {
return new \DateTimeImmutable($value, $zone);
} catch (\Throwable) {
return null;
}
}
private function diff(\DateTimeImmutable $from, \DateTimeImmutable $to): string
{
$interval = $from->diff($to);
$sign = $to < $from ? ' (раньше)' : '';
$days = (int) $interval->days;
$hours = (int) $interval->h;
$minutes = (int) $interval->i;
return $from->format('Y-m-d H:i') . ' → ' . $to->format('Y-m-d H:i') . ': '
. $days . ' ' . $this->pluralDays($days) . ', '
. $hours . ' ч ' . $minutes . ' мин' . $sign;
}
private function pluralDays(int $days): string
{
$mod100 = $days % 100;
$mod10 = $days % 10;
if ($mod100 >= 11 && $mod100 <= 14) {
return 'дней';
}
return match ($mod10) {
1 => 'день',
2, 3, 4 => 'дня',
default => 'дней',
};
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
/**
* Ограничитель файловых инструментов: любой путь обязан лежать внутри корня.
*
* Никакой «магии»: относительный путь склеивается с корнем, приводится к
* реальному виду (realpath) и проверяется по префиксу. Всё, что выходит
* наружу — «..», абсолютные пути, симлинки за пределы каталога — отвергается.
*/
final class FileSandbox
{
private string $root;
public function __construct(string $root)
{
$resolved = realpath($root);
if ($resolved === false || !is_dir($resolved)) {
throw new \InvalidArgumentException('Корень файловой песочницы не существует: ' . $root);
}
$this->root = rtrim($resolved, DIRECTORY_SEPARATOR);
}
public function root(): string
{
return $this->root;
}
/**
* Привести относительный путь к абсолютному внутри корня.
*
* @throws \RuntimeException если путь вне корня или (для чтения) не найден
*/
public function resolve(string $path, bool $mustExist = true): string
{
$path = trim($path);
if ($path === '' || $path === '.') {
return $this->root;
}
if (str_contains($path, "\0")) {
throw new \RuntimeException('Некорректный путь.');
}
if (str_starts_with($path, '/') || preg_match('/^[A-Za-z]:[\\\\\/]/', $path) === 1) {
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
}
$candidate = $this->root . DIRECTORY_SEPARATOR . $path;
$real = realpath($candidate);
if ($real === false) {
if ($mustExist) {
throw new \RuntimeException('Путь не найден: ' . $path);
}
return $candidate;
}
if ($real !== $this->root && !$this->startsWithRoot($real)) {
throw new \RuntimeException('Путь выходит за пределы разрешённого каталога.');
}
return $real;
}
/**
* Путь для показа пользователю (относительно корня).
*/
public function relative(string $absolute): string
{
if ($absolute === $this->root) {
return '.';
}
$prefix = $this->root . DIRECTORY_SEPARATOR;
if ($this->startsWithRoot($absolute)) {
return str_replace(DIRECTORY_SEPARATOR, '/', substr($absolute, strlen($prefix)));
}
return $absolute;
}
private function startsWithRoot(string $path): bool
{
$prefix = $this->root . DIRECTORY_SEPARATOR;
// На Windows путь регистронезависим, на Unix — нет.
return DIRECTORY_SEPARATOR === '\\'
? stripos($path, $prefix) === 0
: str_starts_with($path, $prefix);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Хеш текста: sha256, sha1 или md5.
*/
final class HashTool implements Tool
{
private const ALGOS = ['sha256', 'sha1', 'md5'];
public function name(): string
{
return 'hash_text';
}
public function description(): string
{
return 'Посчитать хеш текста: sha256 (по умолчанию), sha1 или md5. Возвращает hex.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'text' => ['type' => 'string', 'description' => 'Текст для хеширования.'],
'algo' => [
'type' => 'string',
'enum' => self::ALGOS,
'description' => 'Алгоритм, по умолчанию sha256.',
],
],
'required' => ['text'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$text = (string) ($args['text'] ?? '');
$algo = strtolower(trim((string) ($args['algo'] ?? 'sha256')));
if ($algo === '') {
$algo = 'sha256';
}
if (!in_array($algo, self::ALGOS, true)) {
return 'Неизвестный алгоритм: ' . $algo . '. Доступно: ' . implode(', ', self::ALGOS) . '.';
}
return $algo . ': ' . hash($algo, $text);
}
}
+209
View File
@@ -0,0 +1,209 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Http;
use AiSdk\Tool;
/**
* GET-запрос к публичному URL.
*
* Защита от SSRF: только http/https, только публичные IP, локальные имена
* и служебные адреса запрещены, лимит размера и таймаут, редиректы проверяются
* повторно на каждом шаге.
*/
final class HttpGetTool implements Tool
{
private const MAX_REDIRECTS = 3;
private const TIMEOUT = 10.0;
private const MAX_BYTES = 262144;
public function __construct(private readonly int $defaultChars = 4000)
{
}
public function name(): string
{
return 'http_get';
}
public function description(): string
{
return 'Загрузить текст по URL (API, страница, JSON). '
. 'Только публичные адреса: локальная сеть и localhost запрещены. '
. 'Ответ обрезается по max_chars.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'url' => [
'type' => 'string',
'description' => 'Полный адрес, например https://api.example.com/status.',
],
'max_chars' => [
'type' => 'integer',
'description' => 'Сколько символов вернуть, по умолчанию ' . $this->defaultChars . ', максимум 20000.',
],
],
'required' => ['url'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$url = trim((string) ($args['url'] ?? ''));
$maxChars = (int) ($args['max_chars'] ?? $this->defaultChars);
$maxChars = max(200, min($maxChars, 20000));
if ($url === '') {
return 'Не указан URL.';
}
try {
$current = $this->normalize($url);
$response = null;
for ($hop = 0; $hop <= self::MAX_REDIRECTS; $hop++) {
$this->assertPublic($current);
$response = Http::request($current, self::TIMEOUT, false, self::MAX_BYTES);
$isRedirect = $response['status'] >= 300 && $response['status'] < 400;
if (!$isRedirect || $response['location'] === null) {
break;
}
$current = $this->normalize($this->absolute($current, $response['location']));
}
} catch (\Throwable $e) {
return 'Ошибка: ' . $e->getMessage();
}
if ($response === null) {
return 'Не удалось получить ответ.';
}
if ($response['status'] >= 400) {
return 'HTTP ' . $response['status'] . ' для ' . $current;
}
$text = trim($response['body']);
if ($text === '') {
return 'Пустой ответ (HTTP ' . $response['status'] . ') для ' . $current . '.';
}
$truncated = $response['truncated'] || mb_strlen($text) > $maxChars;
$text = mb_substr($text, 0, $maxChars);
return 'HTTP ' . $response['status'] . ', ' . $current
. ($truncated ? ' (обрезано)' : '')
. ":\n" . $text;
}
private function normalize(string $url): string
{
$url = trim($url);
// Схему не подменяем: пусть assertPublic сам скажет, что ftp не годится.
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;
}
private function assertPublic(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');
}
$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;
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Список файлов и каталогов внутри заданного корня.
*/
final class ListDirTool implements Tool
{
private const MAX_ENTRIES = 200;
public function __construct(private readonly FileSandbox $sandbox)
{
}
public function name(): string
{
return 'list_dir';
}
public function description(): string
{
return 'Показать содержимое каталога: файлы, подкаталоги и размеры. '
. 'Путь относительно корня; пустой — корень проекта.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'path' => [
'type' => 'string',
'description' => 'Каталог относительно корня. По умолчанию корень.',
],
],
'required' => [],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$path = (string) ($args['path'] ?? '');
try {
$dir = $this->sandbox->resolve($path);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
if (!is_dir($dir)) {
return 'Это не каталог: ' . $path;
}
$entries = @scandir($dir);
if ($entries === false) {
return 'Не удалось прочитать каталог.';
}
$entries = array_values(array_filter(
$entries,
static fn (string $name): bool => $name !== '.' && $name !== '..'
));
sort($entries);
$dirs = [];
$files = [];
foreach ($entries as $name) {
$full = $dir . DIRECTORY_SEPARATOR . $name;
if (is_dir($full)) {
$dirs[] = $name . '/';
continue;
}
$size = @filesize($full);
$files[] = $name . ' (' . $this->human($size === false ? 0 : $size) . ')';
}
$all = array_merge($dirs, $files);
$shown = array_slice($all, 0, self::MAX_ENTRIES);
$title = $this->sandbox->relative($dir);
$text = 'Каталог ' . $title . ': ' . count($all) . " объектов\n" . implode("\n", $shown);
if (count($all) > count($shown)) {
$text .= "\n…и ещё " . (count($all) - count($shown));
}
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 . ' Б';
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Чтение текстового файла внутри заданного корня.
*
* Умеет листать большие файлы: offset/limit в строках. Бинарные файлы
* не читает — сообщает размер, чтобы модель не гадала.
*/
final class ReadFileTool implements Tool
{
private const MAX_LINES = 2000;
private const MAX_BYTES = 262144;
public function __construct(private readonly FileSandbox $sandbox)
{
}
public function name(): string
{
return 'read_file';
}
public function description(): string
{
return 'Прочитать текстовый файл. Путь указывается относительно корня проекта. '
. 'Для больших файлов задавай offset и limit в строках.';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => [
'path' => [
'type' => 'string',
'description' => 'Путь к файлу относительно корня, например logs/bot.log.',
],
'offset' => [
'type' => 'integer',
'description' => 'С какой строки начать (с нуля). По умолчанию 0.',
],
'limit' => [
'type' => 'integer',
'description' => 'Сколько строк вернуть, максимум ' . self::MAX_LINES . '. По умолчанию 200.',
],
],
'required' => ['path'],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$path = (string) ($args['path'] ?? '');
$offset = max(0, (int) ($args['offset'] ?? 0));
$limit = (int) ($args['limit'] ?? 200);
if ($limit < 1) {
$limit = 200;
}
$limit = min($limit, self::MAX_LINES);
try {
$file = $this->sandbox->resolve($path);
} catch (\RuntimeException $e) {
return $e->getMessage();
}
if (!is_file($file)) {
return 'Это не файл: ' . $path;
}
$size = filesize($file);
if ($size === false) {
return 'Не удалось узнать размер файла.';
}
if ($size > 10 * 1024 * 1024) {
return 'Файл слишком большой (' . $this->human($size) . '). Читай частями через offset и limit.';
}
$handle = fopen($file, 'rb');
if ($handle === false) {
return 'Не удалось открыть файл.';
}
$first = fread($handle, 4096);
fclose($handle);
if ($first === false) {
return 'Не удалось прочитать файл.';
}
if ($first !== '' && !mb_check_encoding($first, 'UTF-8')) {
return 'Файл бинарный (' . $this->human($size) . '), не читаю.';
}
$lines = file($file, FILE_IGNORE_NEW_LINES);
if ($lines === false) {
return 'Не удалось прочитать файл.';
}
$total = count($lines);
$slice = array_slice($lines, $offset, $limit);
if ($slice === []) {
return 'В файле ' . $total . ' строк — диапазон пуст.';
}
$text = implode("\n", $slice);
if (strlen($text) > self::MAX_BYTES) {
$text = mb_strcut($text, 0, self::MAX_BYTES);
}
$from = $offset + 1;
$to = $offset + count($slice);
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 . ' Б';
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace AiSdk\Tools;
use AiSdk\Tool;
/**
* Генерация UUID v4.
*/
final class UuidTool implements Tool
{
public function name(): string
{
return 'uuid';
}
public function description(): string
{
return 'Сгенерировать UUID версии 4 (случайный идентификатор).';
}
public function parameters(): array
{
return [
'type' => 'object',
'properties' => (object) [],
'required' => [],
'additionalProperties' => false,
];
}
public function handle(array $args): string
{
$data = random_bytes(16);
// Версия 4 и вариант RFC 4122.
$data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
$data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
$hex = bin2hex($data);
return sprintf(
'%s-%s-%s-%s-%s',
substr($hex, 0, 8),
substr($hex, 8, 4),
substr($hex, 12, 4),
substr($hex, 16, 4),
substr($hex, 20, 12)
);
}
}