"""Stateless Mini App assistant: bounded caller context, original models, opt-in execution.""" import asyncio from collections import OrderedDict from contextlib import closing from datetime import datetime, timezone import json import os import re import secrets import sqlite3 import time import aiohttp from model_identity import ModelIdentityError, check_response_model # Redaction of tool output before it goes to the model provider. High-signal patterns, # best effort: this is not an isolation boundary (the sandbox service still sees raw # output, and nothing here is a claim about what providers retain on their side). _SECRET_REDACTIONS = ( (re.compile(r'(?s)-----BEGIN ((?:[A-Z0-9]+ )*)PRIVATE KEY-----.*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----'), lambda m: ('[redacted %sprivate key]' % m.group(1)).lower()), (re.compile(r'(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*'), '[redacted private key]'), (re.compile(r'eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}'), '[redacted jwt]'), (re.compile(r'\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b'), lambda m: m.group(0)[:6] + '…[redacted]'), (re.compile(r'(?i)\b(authorization)\b(["\']?\s*[:=]\s*["\']?\s*)(basic|bearer)\s+([A-Za-z0-9._~+/=-]+)'), lambda m: m.group(1) + m.group(2) + m.group(3) + ' [redacted]'), (re.compile(r'(?i)\b(bearer|authorization)\b(\s*[:=]?\s*)([A-Za-z0-9._~+/=-]{16,})'), lambda m: m.group(1) + m.group(2) + '[redacted]'), (re.compile(r'(?i)\b(password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|client[_-]?secret)\b' r'(\s*[:=]\s*)(["\']?)([^\s"\';,]{6,})(["\']?)'), lambda m: m.group(1) + m.group(2) + m.group(3) + '[redacted]' + (m.group(5) or '')), ) def redact_secrets(text): for pattern, repl in _SECRET_REDACTIONS: text = pattern.sub(repl, text) return text def tool_result_for_model(result): """Separate copy of a tool result for the upstream request: stdout/stderr redacted, cmd/exit_code/flags kept. The original stays in trace and in the client response.""" if not isinstance(result, dict) or not isinstance(result.get('out'), str): return result copy = dict(result) copy['out'] = redact_secrets(copy['out']) return copy class AssistantError(Exception): def __init__(self, status, code, message, **details): super().__init__(code) self.status, self.code, self.message = status, code, message self.details = details class UpstreamError(Exception): def __init__(self, status, reason=""): self.status, self.reason = status, reason super().__init__("upstream_%s" % status) class _Operation: def __init__(self, uid, operation_id): self.uid, self.operation_id = uid, operation_id self.task = None self.cancel_requested = False self.side_effect_started = False self.uncertain = False self.trace, self.reminders = [], [] class AssistantRuntime: def __init__(self, bot_db, newapi_db, base_url, models, reminders, sandbox_path): self.bot_db, self.newapi_db = bot_db, newapi_db self.base_url, self.models = base_url.rstrip('/'), tuple(models) self.reminders, self.sandbox_path = reminders, sandbox_path self.busy, self.rate = set(), {} self.operations, self.finished = {}, OrderedDict() self.operation_ttl, self.operation_limit = 3600, 2048 self.max_active, self.disconnect_interval = 128, 0.1 @staticmethod def operation_id(value, *, generate=False): if value is None and generate: return secrets.token_hex(16) if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}', value): raise AssistantError(400, 'invalid_operation_id', 'Некорректный идентификатор запроса.') return value def _prune_operations(self): cutoff = time.monotonic() - self.operation_ttl while self.finished: key, record = next(iter(self.finished.items())) if len(self.finished) <= self.operation_limit and record['finished_at'] > cutoff: break self.finished.pop(key) @staticmethod def _state(operation_id, state, uncertain=False): return {'ok': True, 'operation_id': operation_id, 'state': state, 'uncertain': bool(uncertain)} def _finish_operation(self, operation, task): if self.operations.get(operation.uid) is not operation: return failed = task.cancelled() or task.exception() is not None # [STATE-TRUTH 2610] упавшая задача — failed, не completed: UI не показывает «готово» на обломе state = ('cancelled' if operation.cancel_requested or task.cancelled() else 'failed' if failed else 'completed') uncertain = operation.uncertain or (failed and operation.side_effect_started) record = self._state(operation.operation_id, state, uncertain) # [TERMINAL-TRUTH 2810] честный флаг для UI: «внешних действий не было» можно утверждать # только при side_effect_started=False, иначе Stop/ошибка не обещают отмену и не отменяют её. record['side_effect_started'] = bool(operation.side_effect_started) self.finished[(operation.uid, operation.operation_id)] = dict(record, finished_at=time.monotonic()) self.operations.pop(operation.uid, None) self.busy.discard(operation.uid) self._prune_operations() def cancel(self, uid, operation_id): self._prune_operations() # Legacy callers without an ID must never cancel whichever operation happens to be current. if operation_id is None: return self._state(None, 'not_found') operation_id = self.operation_id(operation_id) operation = self.operations.get(uid) if operation and operation.operation_id == operation_id: if operation.task.done(): self._finish_operation(operation, operation.task) else: if not operation.cancel_requested: operation.cancel_requested = True operation.uncertain |= operation.side_effect_started operation.task.cancel() return self._state(operation_id, 'cancel_requested', operation.uncertain) record = self.finished.get((uid, operation_id)) if record: receipt = {key: value for key, value in record.items() if key != 'finished_at'} if receipt.get('state') == 'failed': # [CANCEL-COMPAT 2810] Живой старый UI валидирует state ответа cancel по # whitelist completed/cancelled/cancel_requested/not_found и на 'failed' # бросает invalid_cancel_receipt. Отдаём legacy-состояние, но помечаем # провал явно: новый UI обязан показать ошибку, а не «уже завершилось». receipt['terminal_state'] = 'failed' receipt['failed'] = True receipt['state'] = 'completed' return receipt # [STOP-FIX 2610] not_found не записываем в finished: операция не найдена → # ничего не гасим, Stop возвращает честный ответ, не блокируем повторные стопы return self._state(operation_id, 'not_found') @staticmethod async def _cleanup_await(awaitable): task = asyncio.create_task(awaitable) try: return await asyncio.shield(task) except asyncio.CancelledError: # A SQLite worker cannot be killed. Keep admission occupied until it actually closes. while not task.done(): try: await asyncio.shield(task) except asyncio.CancelledError: continue except Exception: break if not task.cancelled(): task.exception() raise async def _drive_operation(self, operation, payload, history, alive): async def monitor(): while True: if alive is not None and not alive(): self.cancel(operation.uid, operation.operation_id) return await asyncio.sleep(self.disconnect_interval) worker = asyncio.create_task(self._chat_work(operation.uid, payload, history, operation)) watcher = asyncio.create_task(monitor()) if alive is not None else None try: return await worker finally: if watcher is not None: watcher.cancel() await asyncio.gather(watcher, return_exceptions=True) async def close(self): pending = [operation.task for operation in list(self.operations.values())] for operation in list(self.operations.values()): self.cancel(operation.uid, operation.operation_id) if pending: await asyncio.gather(*pending, return_exceptions=True) def connect(self, path): con = sqlite3.connect(str(path), timeout=5) con.row_factory = sqlite3.Row return con def init_db(self): self.reminders.init_db(self.bot_db) def history(self, uid): return [], 0 def clear_history(self, uid): """Explicitly clear only this user's existing legacy row, if present.""" with closing(self.connect(self.bot_db)) as con: exists = con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_agent_history'").fetchone() if exists: con.execute("UPDATE wa_agent_history SET messages='[]',generation=generation+1,updated=? WHERE uid=?", (int(time.time()), uid)) con.commit() def save_history(self, uid, messages, generation): return False def user(self, uid): with closing(self.connect(self.bot_db)) as con: user = con.execute("SELECT token_name,banned,api_blocked,key_locked FROM users WHERE tg_id=?", (uid,)).fetchone() if user is None: raise AssistantError(403, 'need_start', 'Сначала открой чат с ботом и нажми /start.') if user['banned'] or user['api_blocked']: raise AssistantError(403, 'access_blocked', 'Доступ ограничен. Проверь условия доступа в боте.') return user def user_key(self, uid): user = self.user(uid) if user['key_locked']: raise AssistantError(403, 'key_locked', 'Твой ключ заблокирован тобой. Разблокируй его во вкладке «Ключи».') names = list(dict.fromkeys([user['token_name'], 'tg%d' % uid])) with closing(self.connect(self.newapi_db)) as con: for name in names: if not name: continue row = con.execute("SELECT key FROM tokens WHERE name=? AND status=1 AND deleted_at IS NULL " "ORDER BY remain_quota DESC LIMIT 1", (name,)).fetchone() if row and row['key']: key = row['key'] return key if key.startswith('sk-') else 'sk-' + key raise AssistantError(403, 'need_key', 'Сначала создай активный API-ключ во вкладке «Ключи».') def key_has_credit(self, key): plain = key[3:] if key.startswith('sk-') else key with closing(self.connect(self.newapi_db)) as con: row = con.execute( 'SELECT t.remain_quota,t.unlimited_quota,u.quota FROM tokens t ' 'JOIN users u ON u.id=t.user_id WHERE t.key IN (?,?) AND t.deleted_at IS NULL', (plain, key)).fetchone() return bool(row and (row[1] or row[0] > 0) and row[2] > 0) async def complete(self, model, messages, key, *, fast=False, max_tokens=2048): timeout = aiohttp.ClientTimeout(total=18 if fast else 85, connect=5) async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(self.base_url + '/chat/completions', headers={'Authorization': 'Bearer ' + key}, json={'model': model, 'messages': messages, 'max_tokens': max_tokens}) as response: if response.status != 200: raw_error = (await response.content.read(16384)).decode('utf-8', 'replace').lower() try: decoded = json.loads(raw_error) detail = decoded.get('error', decoded) if isinstance(decoded, dict) else decoded raw_error = str(detail.get('message', '') if isinstance(detail, dict) else detail).lower() except (ValueError, TypeError): pass quota_markers = ('用户额度不足', '余额不足', '剩余额度', 'insufficient_quota', 'insufficient balance', 'free quota', 'good standing', '请充值') reason = '' if any(marker in raw_error for marker in quota_markers): funded = await asyncio.to_thread(self.key_has_credit, key) reason = 'upstream_quota' if funded else 'local_quota' elif response.status == 401 and ('channel error' in raw_error or 'channel #' in raw_error): reason = 'upstream_auth' raise UpstreamError(response.status, reason) try: data = await response.json() except (ValueError, aiohttp.ContentTypeError): raise UpstreamError(502) from None if not isinstance(data, dict): raise UpstreamError(502) try: check_response_model(model, data) except ModelIdentityError: raise AssistantError(503, 'model_identity_mismatch', 'Выбранная модель сейчас недоступна. Повтори позже.') from None choices = data.get('choices') first = choices[0] if isinstance(choices, list) and choices else None message = first.get('message') if isinstance(first, dict) else None text = message.get('content') if isinstance(message, dict) else None if not isinstance(text, str) or not text.strip(): raise UpstreamError(502) return text.strip() async def execute(self, uid, command): if os.environ.get('IISHKO_SANDBOX_ENABLED') != '1': return {'error': 'sandbox_disabled', 'out': 'Выполнение команд отключено.', 'connected': False, 'uncertain': False} try: with open(self.sandbox_path, encoding='utf-8') as source: config = json.load(source) except (OSError, ValueError): return {'cmd': command, 'out': 'VM пока не настроена.', 'connected': False, 'uncertain': False} if not isinstance(config, dict): return {'cmd': command, 'out': 'Конфигурация VM некорректна.', 'connected': False, 'uncertain': False} if not config.get('url') or not config.get('key'): return {'cmd': command, 'out': 'VM пока не настроена.', 'connected': False, 'uncertain': False} # Isolation and resource limits are enforced by the existing sandbox service, not a substring filter. timeout = aiohttp.ClientTimeout(total=35, connect=5) try: async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(config['url'].rstrip('/') + '/exec', headers={'X-Sandbox-Key': config['key']}, json={'uid': uid, 'cmd': command, 'timeout': 25}) as response: if response.status != 200: return {'cmd': command, 'out': 'VM временно недоступна (HTTP %s).' % response.status, 'connected': False, 'uncertain': True} data = await response.json() if not isinstance(data, dict): return {'cmd': command, 'out': 'VM вернула некорректный ответ. Команда могла выполниться; проверь файлы.', 'connected': False, 'uncertain': True} code = data.get('exit', data.get('exit_code')) if not isinstance(code, int) or isinstance(code, bool): return {'cmd': command, 'out': 'VM не подтвердила завершение. Проверь файлы перед повтором.', 'connected': False, 'uncertain': True} output = str(data.get('stdout') or '')[:6000] if data.get('stderr'): output += '\n[stderr] ' + str(data['stderr'])[:2000] return {'cmd': command, 'out': output or '(нет вывода)', 'exit_code': code, 'connected': True, 'uncertain': False, 'timed_out': bool(data.get('timed_out') or code == 124)} except (aiohttp.ClientError, asyncio.TimeoutError, ValueError) as error: return {'cmd': command, 'out': 'VM не ответила: %s. Команда могла завершиться; проверь файлы перед повтором.' % type(error).__name__, 'connected': False, 'uncertain': True} def tool_reminder(self, uid, raw): data = json.loads(raw) if not isinstance(data, dict): raise ValueError('invalid_reminder') return self.reminders.create_reminder(self.bot_db, uid, data.get('text'), data.get('due_at')) @staticmethod def public_upstream_error(error): status = getattr(error, 'status', 503) reason = getattr(error, 'reason', '') if reason in ('upstream_quota', 'upstream_auth'): return AssistantError(503, reason, 'Аккаунт провайдера этой модели не может обслужить запрос. Ваш ключ не отозван; выбранная модель не подменялась.') if reason == 'local_quota': return AssistantError(402, 'credit_required', 'На ключе закончился API-кредит. Проверь баланс во вкладке «Ключи».') if status == 403: return AssistantError(403, 'request_forbidden', 'Маршрут модели отклонил запрос. Это не отсутствие Telegram-авторизации; ключ не удалён.') if status == 401: return AssistantError(403, 'key_rejected', 'Шлюз не принял API-ключ. Проверь его во вкладке «Ключи»; ключ сохранён.') if status == 402: return AssistantError(402, 'credit_required', 'На ключе закончился API-кредит. Проверь баланс во вкладке «Ключи».') if status == 429: return AssistantError(429, 'model_busy', 'Модель перегружена. Попробуй позже или выбери другую модель.') return AssistantError(503, 'model_unavailable', 'Модель сейчас не ответила. Повтори позже.') async def chat(self, uid, payload, alive=None): if not isinstance(payload, dict): raise AssistantError(400, 'invalid_body', 'Ожидается JSON-объект.') model = payload.get('model', 'auto') if not isinstance(model, str) or model not in ('auto', *self.models): raise AssistantError(400, 'invalid_model', 'Эта модель недоступна. Выбери модель из списка.') raw = payload.get('messages') if not isinstance(raw, list) or not raw or not isinstance(raw[-1], dict): raise AssistantError(400, 'invalid_messages', 'Напиши сообщение.') last = raw[-1] text = last.get('content') if last.get('role') != 'user' or not isinstance(text, str) or not text.strip() or len(text) > 12000: raise AssistantError(400, 'invalid_message', 'Сообщение должно содержать от 1 до 12 000 символов.') if len(raw) > 20: raise AssistantError(400, 'invalid_messages', 'Слишком длинный контекст: максимум 20 сообщений.') history = [] total_chars = 0 for item in raw: if not isinstance(item, dict) or item.get('role') not in ('user', 'assistant'): raise AssistantError(400, 'invalid_messages', 'Контекст может содержать только сообщения диалога.') content = item.get('content') if not isinstance(content, str) or not content.strip() or len(content) > 12000: raise AssistantError(400, 'invalid_messages', 'Некорректная длина сообщения контекста.') total_chars += len(content) if total_chars > 96000: raise AssistantError(400, 'invalid_messages', 'Слишком большой контекст диалога.') history.append({'role': item['role'], 'content': content}) operation_id = self.operation_id(payload.get('operation_id'), generate=True) self._prune_operations() current = self.operations.get(uid) if current and current.task.done(): self._finish_operation(current, current.task) current = None previous = self.finished.get((uid, operation_id)) if previous: raise AssistantError(409, 'operation_replayed', 'Этот запрос уже завершён или остановлен. Проверь результат перед новым действием.', operation_id=operation_id, state=previous['state'], uncertain=previous['uncertain']) if current: same = current.operation_id == operation_id raise AssistantError(409, 'operation_in_progress' if same else 'agent_busy', 'Предыдущий ответ ещё готовится.', operation_id=operation_id, state=('cancel_requested' if current.cancel_requested else 'running') if same else 'not_found', uncertain=current.uncertain if same else False) if len(self.operations) >= self.max_active: raise AssistantError(503, 'agent_capacity', 'Сервис занят. Попробуй позже.', operation_id=operation_id, state='not_found', uncertain=False) operation = _Operation(uid, operation_id) self.operations[uid] = operation self.busy.add(uid) task = asyncio.create_task(self._drive_operation(operation, payload, history, alive)) operation.task = task task.add_done_callback(lambda done: self._finish_operation(operation, done)) try: result = await asyncio.shield(task) return dict(result, operation_id=operation_id, state='completed', uncertain=operation.uncertain, side_effect_started=bool(operation.side_effect_started)) except asyncio.CancelledError: if asyncio.current_task().cancelling(): self.cancel(uid, operation_id) try: await asyncio.shield(task) except (asyncio.CancelledError, Exception): pass raise return dict(self._state(operation_id, 'cancelled', operation.uncertain), cancelled=True, partial=operation.side_effect_started, side_effect_started=bool(operation.side_effect_started), reply=('Ожидание остановлено. Команда или сохранение напоминания могли завершиться. ' 'Удалённая остановка не подтверждена; проверь результат перед повтором.' if operation.uncertain else 'Ожидание ответа остановлено.'), vm=operation.trace, reminders=operation.reminders, history_saved=False) except AssistantError as error: # [TERMINAL-TRUTH 2810] провайдерский отказ — failed, не completed: UI не рисует «готово» # и не утверждает, что внешних действий не было; флаг берём из самой операции. error.details.update(operation_id=operation_id, state='failed', uncertain=operation.uncertain or bool(operation.side_effect_started), side_effect_started=bool(operation.side_effect_started)) raise async def _chat_work(self, uid, payload, history, operation): model = payload.get('model', 'auto') sandbox_enabled = os.environ.get('IISHKO_SANDBOX_ENABLED') == '1' try: key = await self._cleanup_await(asyncio.to_thread(self.user_key, uid)) # Operational tool contract only (no persona/policy): the loop below parses # /, so the interface must be visible to the model. Exec is # advertised only while the sandbox flag is on; a stray tag then gets an honest # sandbox_disabled result instead of a fabricated action. system = ('Отвечай на языке пользователя. Не упоминай название провайдера или сервиса. ' 'Инструменты реальны, вызывай их тегом прямо в ответе, максимум 4 за запрос. ' 'Напоминание в Telegram: {"text":"текст","due_at":UNIX_SECONDS} ' '(не меньше 30 секунд и не больше года вперёд). ' 'Текущее UTC-время: %s; Unix: %d. ') if sandbox_enabled: system += ('Linux-песочница (bash, python3, node, git): shell-команда; ' 'результат придёт сообщением «[Результат инструмента]» перед твоим итогом. ') system += ('О выполненном говори только по фактически пришедшему результату инструмента: ' 'не описывай действие или вывод, которых в результате нет.') conversation = [{'role': 'system', 'content': system % (datetime.now(timezone.utc).isoformat(), int(time.time()))}] + history trace, reminders, tool_cache = operation.trace, operation.reminders, {} selected_model = model def check_alive(): if operation.cancel_requested: raise asyncio.CancelledError() async def run(): nonlocal selected_model if model == 'auto': raw_candidates = payload.get('candidates') if isinstance(raw_candidates, list) and raw_candidates: candidates = [c for c in raw_candidates if isinstance(c, str) and c in self.models] else: candidates = list(self.models) if not candidates: candidates = [self.models[0] if self.models else ''] else: candidates = [model] selected, answer, last_error = None, '', None for candidate in candidates: check_alive() try: answer = await self.complete(candidate, conversation, key, fast=model == 'auto') selected = candidate selected_model = candidate break except (UpstreamError, aiohttp.ClientError, asyncio.TimeoutError) as error: last_error = error if model != 'auto' or getattr(error, 'status', 503) in (401, 402) or getattr(error, 'reason', '') == 'local_quota': raise self.public_upstream_error(error) from None # auto: 403 (ранг/права на конкретную модель) и 5xx — пробуем следующего кандидата if selected is None: raise self.public_upstream_error(last_error) from None for step in range(5): check_alive() tool = re.search(r'<(exec|reminder)>(.*?)', answer, re.S) if not tool: return answer[:12000], selected, False if step == 4: return 'Достигнут лимит инструментов за один запрос. Выполненные действия и вывод сохранены; продолжим следующим сообщением.', selected, True kind, argument = tool.group(1), tool.group(2).strip() if len(argument) > 6000: result = {'error': 'tool_input_too_long'} elif (kind, argument) in tool_cache: result = tool_cache[(kind, argument)] elif kind == 'exec': operation.side_effect_started = True result = {'cmd': argument, 'out': 'Команда отправлена; завершение пока не подтверждено.', 'connected': False, 'uncertain': True} trace.append(result) tool_cache[(kind, argument)] = result result.update(await self.execute(uid, argument)) operation.uncertain |= bool(result.get('uncertain')) if result.get('uncertain'): return 'VM не подтвердила завершение команды. Автоматического повтора не будет. Проверь вывод и файлы перед новым действием.', selected, True else: async def save_reminder(): row = await asyncio.to_thread(self.tool_reminder, uid, argument) reminders.append(row) tool_cache[(kind, argument)] = row return row try: operation.side_effect_started = True result = await self._cleanup_await(save_reminder()) except (ValueError, TypeError) as error: result = {'error': str(error)[:80]} # Only the upstream copy is redacted; trace, tool_cache and the client # response keep the original result. conversation.extend([{'role': 'assistant', 'content': answer}, {'role': 'user', 'content': '[Результат инструмента]\n' + json.dumps(tool_result_for_model(result), ensure_ascii=False)}]) check_alive() try: answer = await self.complete(selected, conversation, key, fast=model == 'auto') except (UpstreamError, aiohttp.ClientError, asyncio.TimeoutError): return 'Инструмент завершил попытку, но модель не подготовила итог. Проверь вывод ниже и сохранённые напоминания. Не повторяй действие вслепую.', selected, True raise RuntimeError('unreachable_tool_loop') try: answer, selected, partial = await asyncio.wait_for(run(), timeout=145) except asyncio.TimeoutError: operation.uncertain |= operation.side_effect_started if not trace and not reminders: raise AssistantError(504, 'agent_timeout', 'Истекло время ожидания. Попробуй более быструю модель.') from None answer, selected, partial = ('Время ожидания истекло после запуска инструмента. Проверь вывод и файлы перед повтором.', selected_model, True) return {'reply': answer, 'model': selected, 'vm': trace, 'reminders': reminders, 'partial': partial, 'history_saved': False, 'workspace': ('/sandbox/users/%d' % uid) if sandbox_enabled else None} except asyncio.CancelledError: operation.uncertain |= operation.side_effect_started raise except Exception: operation.uncertain |= operation.side_effect_started raise