ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(ai): add core AI assistant primitive powered by Prompture
Juan Denis9cab065dc5d5
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 1322180e..ae1b80ce 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -303,6 +303,10 @@ def create_app(config_name=None):from app.api.pairing import pairing_bpapp.register_blueprint(pairing_bp, url_prefix='/api/v1/pairing')+ # Register blueprints - AI Assistant (core primitive, powered by Prompture)+ from app.api.ai import ai_bp+ app.register_blueprint(ai_bp, url_prefix='/api/v1/ai')+# Handle database migrations (Alembic) — must run before plugin loader# since the loader queries the installed_plugins table.with app.app_context():diff --git a/backend/app/api/ai.py b/backend/app/api/ai.pynew file mode 100644index 00000000..988b05ae--- /dev/null+++ b/backend/app/api/ai.py@@ -0,0 +1,509 @@+"""AI assistant API (core primitive — powered by Prompture).++Routes under ``/api/v1/ai``:+- ``GET /status`` capabilities probe (drives the bubble)+- ``GET/PUT /settings`` provider/model/key config (admin; key never returned)+- ``POST /settings/test`` validate a provider/model/key (admin)+- ``GET /providers`` / ``/models`` settings dropdown data (admin)+- ``GET/POST /conversations`` list / create (current user)+- ``GET/PATCH/DELETE /conversations/<id>`` transcript / rename / delete (owner)+- ``POST /chat`` non-streaming turn (fallback)+- ``POST /chat/stream`` SSE turn (fetch + ReadableStream; JWT header)+- ``POST /chat/confirm`` approve/deny a guarded write action+- ``POST /chat/cancel`` cancel an in-flight stream+- ``GET /tools`` registered-tool introspection (admin, debug)++SSE is driven by a worker thread bridged to the response generator via a+``queue.Queue`` so the model's blocking I/O never stalls the single gevent+worker. The production gevent-websocket worker monkey-patches threading, so the+stdlib ``threading``/``queue`` primitives used here are cooperative; the dev+server uses real threads. Either way the response generator only ever blocks on+``queue.get`` (with a heartbeat timeout), never on the LLM call directly.+"""+from __future__ import annotations++import json+import logging+import queue+import threading++from flask import Blueprint, Response, current_app, jsonify, request, stream_with_context+from flask_jwt_extended import jwt_required++from app import db+from app.middleware.rbac import admin_required, get_current_user+from app.models.ai import AiConversation, AiMessage, AiPendingAction+from app.services import ai_service+from app.services.ai_tool_registry import ai_tool_registry++logger = logging.getLogger(__name__)+ai_bp = Blueprint('ai', __name__)++HEARTBEAT_SECONDS = 15+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+def _sse(event: str, data: dict) -> str:+ return f"event: {event}\ndata: {json.dumps(data)}\n\n"+++def _owned_conversation(conversation_id: str, user):+ """Return the conversation if it exists and belongs to *user*, else None."""+ row = db.session.get(AiConversation, conversation_id)+ if row is None or row.user_id != user.id:+ return None+ return row+++def _load_or_create(conversation_id, user, mode):+ if conversation_id:+ row = _owned_conversation(conversation_id, user)+ return row # may be None -> caller 404s+ row = AiConversation(+ user_id=user.id,+ mode=mode or AiConversation.MODE_ASSISTANT,+ model_name=ai_service.current_model_name(),+ )+ db.session.add(row)+ db.session.commit()+ return row+++# ---------------------------------------------------------------------------+# Status / settings+# ---------------------------------------------------------------------------+@ai_bp.route('/status', methods=['GET'])+@jwt_required()+def status():+ ai_service.ensure_initialized()+ user = get_current_user()+ tools_count = len(ai_tool_registry.list_for(user, 'assistant')) if user else 0+ return jsonify({+ 'enabled': ai_service.is_enabled(),+ 'configured': ai_service.is_configured(),+ 'provider': ai_service._setting('ai_provider', ''),+ 'model': ai_service._setting('ai_model', ''),+ 'tools_count': tools_count,+ 'mode_default': AiConversation.MODE_ASSISTANT,+ 'pii_redaction': bool(ai_service._setting('ai_pii_redaction', True)),+ 'injection_detection': bool(ai_service._setting('ai_injection_detection', True)),+ })+++@ai_bp.route('/settings', methods=['GET'])+@admin_required+def get_settings():+ from app.services.settings_service import SettingsService+ return jsonify({+ 'enabled': bool(SettingsService.get('ai_enabled', False)),+ 'provider': SettingsService.get('ai_provider', ''),+ 'model': SettingsService.get('ai_model', ''),+ 'endpoint': SettingsService.get('ai_endpoint', ''),+ 'max_cost_usd': SettingsService.get('ai_max_cost_usd', 0.5),+ 'fallback_models': SettingsService.get('ai_fallback_models', []),+ 'pii_redaction': bool(SettingsService.get('ai_pii_redaction', True)),+ 'injection_detection': bool(SettingsService.get('ai_injection_detection', True)),+ # Never return the key itself — only whether one is configured.+ 'api_key_set': bool(SettingsService.get('ai_api_key_encrypted', '')),+ })+++@ai_bp.route('/settings', methods=['PUT'])+@admin_required+def update_settings():+ from app.services.settings_service import SettingsService+ from app.utils.crypto import encrypt_secret++ data = request.get_json(silent=True) or {}+ user = get_current_user()+ uid = user.id if user else None++ field_map = {+ 'enabled': ('ai_enabled', bool),+ 'provider': ('ai_provider', str),+ 'model': ('ai_model', str),+ 'endpoint': ('ai_endpoint', str),+ 'max_cost_usd': ('ai_max_cost_usd', str),+ 'pii_redaction': ('ai_pii_redaction', bool),+ 'injection_detection': ('ai_injection_detection', bool),+ }+ for field, (key, caster) in field_map.items():+ if field in data:+ SettingsService.set(key, caster(data[field]), user_id=uid)+ if 'fallback_models' in data and isinstance(data['fallback_models'], list):+ SettingsService.set('ai_fallback_models', data['fallback_models'], user_id=uid)++ # API key: encrypt and store; empty string clears it.+ if 'api_key' in data:+ raw = (data['api_key'] or '').strip()+ SettingsService.set('ai_api_key_encrypted', encrypt_secret(raw) if raw else '', user_id=uid)++ try:+ from app.plugins_sdk import audit+ audit('ai.settings.update', target_type='ai_settings', details={+ 'provider': SettingsService.get('ai_provider', ''),+ 'model': SettingsService.get('ai_model', ''),+ 'api_key_changed': 'api_key' in data,+ })+ except Exception:+ pass+ return jsonify({'ok': True, 'configured': ai_service.is_configured()})+++@ai_bp.route('/settings/test', methods=['POST'])+@admin_required+def test_settings():+ from app.services.settings_service import SettingsService+ data = request.get_json(silent=True) or {}+ provider = (data.get('provider') or SettingsService.get('ai_provider', '')).strip()+ model = (data.get('model') or SettingsService.get('ai_model', '')).strip()+ endpoint = data.get('endpoint')+ # Use the posted key if present, else the stored (decrypted) one.+ api_key = data.get('api_key')+ if not api_key:+ api_key = ai_service._decrypted_key()+ if not provider or not model:+ return jsonify({'ok': False, 'error': 'provider and model are required'}), 400+ return jsonify(ai_service.test_settings(provider, model, api_key=api_key, endpoint=endpoint))+++@ai_bp.route('/providers', methods=['GET'])+@admin_required+def providers():+ return jsonify({'providers': ai_service.list_providers()})+++@ai_bp.route('/models', methods=['GET'])+@admin_required+def models():+ provider = (request.args.get('provider') or '').strip()+ if not provider:+ return jsonify({'error': 'provider is required'}), 400+ return jsonify(ai_service.list_models(provider))+++@ai_bp.route('/tools', methods=['GET'])+@admin_required+def tools():+ ai_service.ensure_initialized()+ return jsonify({'tools': [+ {+ 'qualified_name': d.qualified_name, 'name': d.name, 'description': d.description,+ 'plugin_slug': d.plugin_slug, 'rbac_feature': d.rbac_feature,+ 'rbac_level': d.rbac_level, 'is_write': d.is_write,+ }+ for d in ai_tool_registry.all_descriptors()+ ]})+++# ---------------------------------------------------------------------------+# Conversations+# ---------------------------------------------------------------------------+@ai_bp.route('/conversations', methods=['GET'])+@jwt_required()+def list_conversations():+ user = get_current_user()+ rows = (AiConversation.query+ .filter_by(user_id=user.id)+ .order_by(AiConversation.updated_at.desc())+ .limit(100).all())+ return jsonify({'conversations': [r.to_dict() for r in rows]})+++@ai_bp.route('/conversations', methods=['POST'])+@jwt_required()+def create_conversation():+ user = get_current_user()+ data = request.get_json(silent=True) or {}+ mode = data.get('mode') or AiConversation.MODE_ASSISTANT+ row = AiConversation(user_id=user.id, mode=mode, title=data.get('title'),+ model_name=ai_service.current_model_name())+ db.session.add(row)+ db.session.commit()+ return jsonify(row.to_dict()), 201+++@ai_bp.route('/conversations/<conversation_id>', methods=['GET'])+@jwt_required()+def get_conversation(conversation_id):+ user = get_current_user()+ row = _owned_conversation(conversation_id, user)+ if row is None:+ return jsonify({'error': 'Conversation not found'}), 404+ return jsonify(row.to_dict(include_messages=True))+++@ai_bp.route('/conversations/<conversation_id>', methods=['PATCH'])+@jwt_required()+def rename_conversation(conversation_id):+ user = get_current_user()+ row = _owned_conversation(conversation_id, user)+ if row is None:+ return jsonify({'error': 'Conversation not found'}), 404+ data = request.get_json(silent=True) or {}+ if 'title' in data:+ row.title = (data['title'] or '').strip()[:256] or row.title+ db.session.commit()+ return jsonify(row.to_dict())+++@ai_bp.route('/conversations/<conversation_id>', methods=['DELETE'])+@jwt_required()+def delete_conversation(conversation_id):+ user = get_current_user()+ row = _owned_conversation(conversation_id, user)+ if row is None:+ return jsonify({'error': 'Conversation not found'}), 404+ db.session.delete(row)+ db.session.commit()+ try:+ from app.plugins_sdk import audit+ audit('ai.conversation.delete', target_type='ai_conversation', target_id=conversation_id)+ except Exception:+ pass+ return jsonify({'ok': True})+++# ---------------------------------------------------------------------------+# Chat (non-streaming fallback)+# ---------------------------------------------------------------------------+@ai_bp.route('/chat', methods=['POST'])+@jwt_required()+def chat():+ ai_service.ensure_initialized()+ user = get_current_user()+ if not ai_service.is_configured():+ return jsonify({'error': 'AI assistant is not configured'}), 503+ data = request.get_json(silent=True) or {}+ message = (data.get('message') or '').strip()+ if not message:+ return jsonify({'error': 'message is required'}), 400+ mode = data.get('mode') or AiConversation.MODE_ASSISTANT+ page_context = data.get('page_context') or {}++ row = _load_or_create(data.get('conversation_id'), user, mode)+ if row is None:+ return jsonify({'error': 'Conversation not found'}), 404++ if ai_service.injection_flagged(message):+ return jsonify({'error': 'Your message was flagged by the prompt-injection guardrail.'}), 400++ _persist_user_message(row, message)+ safe_message = ai_service.redact_input(message)+ try:+ # gate=None: write tools refuse (no interactive confirmation in this mode).+ conv = ai_service.build_conversation(row, user, mode, page_context, gate=None)+ reply = conv.ask(safe_message)+ except Exception as exc:+ logger.exception("AI /chat failed")+ return jsonify({'error': f'AI request failed: {exc}'}), 500++ _persist_assistant_message(row, reply, tool_calls=[], usage=conv.usage)+ ai_service.persist_conversation(row, conv, page_context=page_context)+ return jsonify({'conversation_id': row.id, 'reply': reply, 'usage': conv.usage})+++# ---------------------------------------------------------------------------+# Chat (SSE streaming)+# ---------------------------------------------------------------------------+@ai_bp.route('/chat/stream', methods=['POST'])+@jwt_required()+def chat_stream():+ ai_service.ensure_initialized()+ user = get_current_user()+ if not ai_service.is_configured():+ return jsonify({'error': 'AI assistant is not configured'}), 503+ data = request.get_json(silent=True) or {}+ message = (data.get('message') or '').strip()+ if not message:+ return jsonify({'error': 'message is required'}), 400+ mode = data.get('mode') or AiConversation.MODE_ASSISTANT+ page_context = data.get('page_context') or {}++ row = _load_or_create(data.get('conversation_id'), user, mode)+ if row is None:+ return jsonify({'error': 'Conversation not found'}), 404++ conversation_id = row.id+ user_id = user.id+ app = current_app._get_current_object()+ ttl = int(ai_service._setting('ai_pending_action_ttl_s', 300) or 300)++ # Persist the (original) user message + set title before streaming begins.+ if not row.title:+ row.title = ai_service.derive_title(message)+ _persist_user_message(row, message)++ flagged = ai_service.injection_flagged(message)+ safe_message = ai_service.redact_input(message)++ q: "queue.Queue" = queue.Queue(maxsize=512)+ cancel_event = threading.Event()++ def emit(event_name: str, payload: dict) -> None:+ q.put(('frame', (event_name, payload)))++ gate = ai_service.ConfirmationGate(conversation_id, user_id, emit, cancel_event, ttl)+ ai_service.register_gate(conversation_id, gate)++ def producer():+ with app.app_context():+ from app.models.user import User+ acc_text: list[str] = []+ tool_calls: dict[str, dict] = {}+ tool_order: list[str] = []+ last_usage: dict = {}+ conv = None+ try:+ if flagged:+ emit('error', {'message': 'Your message was flagged by the prompt-injection guardrail.'})+ return++ conv_row = db.session.get(AiConversation, conversation_id)+ conv_user = db.session.get(User, user_id)+ conv = ai_service.build_conversation(conv_row, conv_user, mode, page_context, gate)+ for event in conv.ask_live(safe_message):+ if cancel_event.is_set():+ break+ name, payload = ai_service.live_event_to_frame(event)+ if name == 'text_delta':+ acc_text.append(payload.get('text', ''))+ elif name == 'tool_use_start':+ tc = {'id': payload.get('id'), 'name': payload.get('name'),+ 'input': {}, 'output': None, 'is_error': False}+ tool_calls[payload.get('id')] = tc+ tool_order.append(payload.get('id'))+ elif name == 'tool_use_stop':+ tc = tool_calls.get(payload.get('id'))+ if tc:+ tc['input'] = payload.get('input', {})+ tc['name'] = payload.get('name', tc['name'])+ elif name == 'tool_result':+ tc = tool_calls.get(payload.get('id'))+ if tc is None:+ tc = {'id': payload.get('id'), 'name': payload.get('name'),+ 'input': {}, 'output': None, 'is_error': False}+ tool_calls[payload.get('id')] = tc+ tool_order.append(payload.get('id'))+ tc['output'] = payload.get('output')+ tc['is_error'] = payload.get('is_error', False)+ elif name in ('message_stop', 'turn_complete'):+ if payload.get('usage'):+ last_usage = payload['usage']+ emit(name, payload)+ except Exception as exc:+ logger.exception("AI stream worker failed")+ emit('error', {'message': str(exc)})+ finally:+ ai_service.unregister_gate(conversation_id)+ try:+ text = ''.join(acc_text)+ if text or tool_order:+ conv_row = db.session.get(AiConversation, conversation_id)+ if conv_row is not None:+ _persist_assistant_message(+ conv_row, text,+ tool_calls=[tool_calls[i] for i in tool_order if i in tool_calls],+ usage=last_usage,+ )+ if conv is not None:+ ai_service.persist_conversation(conv_row, conv, page_context=page_context)+ except Exception:+ logger.warning("Failed to persist assistant turn", exc_info=True)+ q.put(('frame', ('done', {'conversation_id': conversation_id, 'usage': last_usage})))+ q.put(('end', None))++ threading.Thread(target=producer, daemon=True).start()++ @stream_with_context+ def gen():+ yield _sse('open', {'conversation_id': conversation_id})+ try:+ while True:+ try:+ kind, payload = q.get(timeout=HEARTBEAT_SECONDS)+ except queue.Empty:+ yield ': keepalive\n\n'+ continue+ if kind == 'end':+ break+ event_name, data_obj = payload+ yield _sse(event_name, data_obj)+ finally:+ cancel_event.set()+ gate.cancel_all()+ ai_service.unregister_gate(conversation_id)++ return Response(gen(), mimetype='text/event-stream', headers={+ 'Cache-Control': 'no-cache',+ 'X-Accel-Buffering': 'no',+ 'Connection': 'keep-alive',+ })+++@ai_bp.route('/chat/confirm', methods=['POST'])+@jwt_required()+def chat_confirm():+ user = get_current_user()+ data = request.get_json(silent=True) or {}+ conversation_id = data.get('conversation_id')+ token = data.get('action_token')+ decision = 'approve' if data.get('decision') == 'approve' else 'deny'+ if not conversation_id or not token:+ return jsonify({'error': 'conversation_id and action_token are required'}), 400+ if _owned_conversation(conversation_id, user) is None:+ return jsonify({'error': 'Conversation not found'}), 404+ # Validate the pending action belongs to this user and is still actionable.+ pending = db.session.get(AiPendingAction, token)+ if pending is None or pending.user_id != user.id:+ return jsonify({'error': 'Pending action not found'}), 404+ if pending.status != AiPendingAction.STATUS_PENDING or pending.is_expired():+ return jsonify({'error': 'Pending action is no longer actionable'}), 409+ if not ai_service.resolve_pending(conversation_id, token, decision):+ return jsonify({'error': 'No active stream for this action (it may have expired)'}), 409+ return jsonify({'ok': True, 'decision': decision})+++@ai_bp.route('/chat/cancel', methods=['POST'])+@jwt_required()+def chat_cancel():+ user = get_current_user()+ data = request.get_json(silent=True) or {}+ conversation_id = data.get('conversation_id')+ if not conversation_id:+ return jsonify({'error': 'conversation_id is required'}), 400+ if _owned_conversation(conversation_id, user) is None:+ return jsonify({'error': 'Conversation not found'}), 404+ # Deny any pending confirmation, which also unblocks the worker.+ ai_service.resolve_pending(conversation_id, '__cancel__', 'deny')+ with ai_service._gates_lock:+ gate = ai_service._active_gates.get(conversation_id)+ if gate is not None:+ gate.cancel_all()+ return jsonify({'ok': True})+++# ---------------------------------------------------------------------------+# Persistence helpers+# ---------------------------------------------------------------------------+def _persist_user_message(row, content: str) -> None:+ try:+ db.session.add(AiMessage(conversation_id=row.id, role=AiMessage.ROLE_USER, content=content))+ db.session.commit()+ except Exception:+ db.session.rollback()+ logger.warning("Failed to persist user message", exc_info=True)+++def _persist_assistant_message(row, content: str, *, tool_calls, usage) -> None:+ try:+ msg = AiMessage(conversation_id=row.id, role=AiMessage.ROLE_ASSISTANT, content=content)+ msg.tool_calls = tool_calls or []+ msg.usage = usage or {}+ db.session.add(msg)+ db.session.commit()+ except Exception:+ db.session.rollback()+ logger.warning("Failed to persist assistant message", exc_info=True)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex c074ef07..5b632b22 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -33,6 +33,7 @@ from app.models.cloud_server import CloudProvider, CloudServer, CloudSnapshotfrom app.models.marketplace import Extension, ExtensionInstallfrom app.models.pending_agent import PendingAgentfrom app.models.plugin import InstalledPlugin+from app.models.ai import AiConversation, AiMessage, AiPendingAction__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',@@ -54,4 +55,5 @@ __all__ = ['Extension', 'ExtensionInstall','PendingAgent','InstalledPlugin',+ 'AiConversation', 'AiMessage', 'AiPendingAction',]diff --git a/backend/app/models/ai.py b/backend/app/models/ai.pynew file mode 100644index 00000000..d12569c5--- /dev/null+++ b/backend/app/models/ai.py@@ -0,0 +1,190 @@+"""AI assistant persistence models (core primitive — powered by Prompture).++Three tables back the in-panel assistant:++- ``AiConversation`` — one chat thread per user. Holds the full Prompture+ ``Conversation.export()`` blob so a thread can be resumed across requests+ (tools are re-supplied on resume; only the message/usage state is stored).+- ``AiMessage`` — denormalized per-turn rows for fast list/transcript rendering+ without re-parsing the export blob (also replays tool-call cards).+- ``AiPendingAction`` — audit/record of a guarded write-tool confirmation. The+ live approve/deny coordination happens in-memory (see ai_service streaming),+ but every request is persisted here for visibility and audit.++JSON columns use the store-as-Text + property pattern from ``plugin.py`` to stay+dialect-agnostic (SQLite/PostgreSQL).+"""+import json+import uuid+from datetime import datetime, timedelta++from app import db+++def _new_id() -> str:+ """Opaque, URL-safe conversation id (also used as Prompture conversation_id)."""+ return uuid.uuid4().hex+++class AiConversation(db.Model):+ """A single AI chat thread owned by a user."""+ __tablename__ = 'ai_conversations'++ MODE_ASSISTANT = 'assistant' # tools + page context+ MODE_SIMPLE = 'simple' # plain chat, no tools++ id = db.Column(db.String(64), primary_key=True, default=_new_id)+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True, nullable=False)+ title = db.Column(db.String(256))+ mode = db.Column(db.String(16), default=MODE_ASSISTANT)+ model_name = db.Column(db.String(128)) # 'provider/model' snapshot at creation+ export_json = db.Column(db.Text) # Prompture conv.export(strip_images=True)+ last_page = db.Column(db.String(256)) # last route the assistant saw (for resume context)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ messages = db.relationship(+ 'AiMessage', backref='conversation', cascade='all, delete-orphan',+ order_by='AiMessage.created_at', lazy='dynamic',+ )+ pending_actions = db.relationship(+ 'AiPendingAction', backref='conversation', cascade='all, delete-orphan', lazy='dynamic',+ )++ @property+ def export(self) -> dict:+ return json.loads(self.export_json) if self.export_json else {}++ @export.setter+ def export(self, value) -> None:+ self.export_json = json.dumps(value) if value is not None else None++ def to_dict(self, include_messages: bool = False) -> dict:+ data = {+ 'id': self.id,+ 'user_id': self.user_id,+ 'title': self.title or 'New chat',+ 'mode': self.mode,+ 'model_name': self.model_name,+ 'last_page': self.last_page,+ 'message_count': self.messages.count(),+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,+ }+ if include_messages:+ data['messages'] = [m.to_dict() for m in self.messages]+ return data+++class AiMessage(db.Model):+ """One persisted turn in a conversation (user, assistant, or tool)."""+ __tablename__ = 'ai_messages'++ ROLE_USER = 'user'+ ROLE_ASSISTANT = 'assistant'+ ROLE_TOOL = 'tool'++ id = db.Column(db.Integer, primary_key=True)+ conversation_id = db.Column(+ db.String(64), db.ForeignKey('ai_conversations.id', ondelete='CASCADE'), index=True, nullable=False,+ )+ role = db.Column(db.String(16), nullable=False)+ content = db.Column(db.Text)+ tool_calls_json = db.Column(db.Text) # [{id,name,input,output,is_error}] for ToolCallCard replay+ usage_json = db.Column(db.Text) # {input_tokens, output_tokens, cost}+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ @property+ def tool_calls(self) -> list:+ return json.loads(self.tool_calls_json) if self.tool_calls_json else []++ @tool_calls.setter+ def tool_calls(self, value) -> None:+ self.tool_calls_json = json.dumps(value) if value else None++ @property+ def usage(self) -> dict:+ return json.loads(self.usage_json) if self.usage_json else {}++ @usage.setter+ def usage(self, value) -> None:+ self.usage_json = json.dumps(value) if value else None++ def to_dict(self) -> dict:+ return {+ 'id': self.id,+ 'conversation_id': self.conversation_id,+ 'role': self.role,+ 'content': self.content,+ 'tool_calls': self.tool_calls,+ 'usage': self.usage,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ }+++class AiPendingAction(db.Model):+ """A guarded write-tool action awaiting human confirmation.++ Live approve/deny is coordinated in-memory by the streaming worker; this+ row is the durable record (status + result) for audit and admin visibility.+ """+ __tablename__ = 'ai_pending_actions'++ STATUS_PENDING = 'pending'+ STATUS_APPROVED = 'approved'+ STATUS_DENIED = 'denied'+ STATUS_EXPIRED = 'expired'+ STATUS_EXECUTED = 'executed'+ STATUS_FAILED = 'failed'++ DEFAULT_TTL_SECONDS = 300++ id = db.Column(db.String(64), primary_key=True) # action token (secrets.token_urlsafe)+ conversation_id = db.Column(+ db.String(64), db.ForeignKey('ai_conversations.id', ondelete='CASCADE'), index=True, nullable=False,+ )+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True, nullable=False)+ tool_name = db.Column(db.String(128), nullable=False) # qualified name, e.g. core__restart_docker_container+ plugin_slug = db.Column(db.String(128)) # None => built-in tool+ params_json = db.Column(db.Text)+ summary = db.Column(db.Text)+ status = db.Column(db.String(16), default=STATUS_PENDING)+ result_json = db.Column(db.Text)+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ expires_at = db.Column(db.DateTime)++ @property+ def params(self) -> dict:+ return json.loads(self.params_json) if self.params_json else {}++ @params.setter+ def params(self, value) -> None:+ self.params_json = json.dumps(value) if value else None++ @property+ def result(self):+ return json.loads(self.result_json) if self.result_json else None++ @result.setter+ def result(self, value) -> None:+ self.result_json = json.dumps(value) if value is not None else None++ def is_expired(self) -> bool:+ return self.expires_at is not None and datetime.utcnow() > self.expires_at++ def to_dict(self) -> dict:+ return {+ 'action_token': self.id,+ 'conversation_id': self.conversation_id,+ 'tool_name': self.tool_name,+ 'plugin_slug': self.plugin_slug,+ 'params': self.params,+ 'summary': self.summary,+ 'status': self.status,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'expires_at': self.expires_at.isoformat() if self.expires_at else None,+ }++ @classmethod+ def make_expiry(cls, ttl_seconds: int | None = None) -> datetime:+ return datetime.utcnow() + timedelta(seconds=ttl_seconds or cls.DEFAULT_TTL_SECONDS)diff --git a/backend/app/plugins_sdk/__init__.py b/backend/app/plugins_sdk/__init__.pyindex 934e02d0..f7d39ef0 100644--- a/backend/app/plugins_sdk/__init__.py+++ b/backend/app/plugins_sdk/__init__.py@@ -84,6 +84,11 @@ def audit(action, target_type, target_id=None, details=None, user_id=None):)+# AI extension SDK — plugins do `from app.plugins_sdk import ai` then register+# tools/context against the core assistant (see plugins_sdk/ai.py). Imported+# lazily-safe: ai.py only depends on the AI tool registry, not on a running app.+from app.plugins_sdk import ai+__all__ = ['db','jwt',@@ -93,4 +98,5 @@ __all__ = ['current_user','logger','audit',+ 'ai',]diff --git a/backend/app/plugins_sdk/ai.py b/backend/app/plugins_sdk/ai.pynew file mode 100644index 00000000..4baa364f--- /dev/null+++ b/backend/app/plugins_sdk/ai.py@@ -0,0 +1,103 @@+"""Plugin-facing AI extension SDK (powered by Prompture).++This is how a plugin EXTENDS the core assistant instead of building its own:+installing the plugin can teach the assistant new tools, contribute page+context, and let plugin code invoke the assistant in-process.++A plugin declares an ``ai`` block in its ``plugin.json``::++ "ai": {+ "entry_point": "ai:register", # app.plugins.<slug>.ai:register+ "suggested_prompts": [+ {"route": "/git", "label": "Summarize commits", "prompt": "Summarize the latest commits"}+ ],+ "context_routes": ["/git", "/git/*"]+ }++and ships ``app/plugins/<slug>/ai.py``::++ from app.plugins_sdk import ai++ def register(reg): # reg is a PluginToolBinder+ @reg.tool(rbac_feature="git", rbac_level="read")+ def list_branches(repo: str) -> list:+ \"\"\"List branches in a repo.+ Args:+ repo: repository slug.+ \"\"\"+ from app.services.git_service import GitService+ return GitService.list_branches(repo)++ @reg.tool(rbac_feature="git", rbac_level="write", is_write=True)+ def delete_branch(repo: str, branch: str) -> dict:+ \"\"\"Delete a branch. Args: repo: ...; branch: ...\"\"\"+ ... # runs only AFTER confirmation++ reg.register_context_provider("/git", lambda user, route, params: "...context...")++Tools are namespaced ``<slug>__<name>`` so they can never collide. RBAC is+declared per tool and enforced by the core (a tool the user can't use is never+even offered to the model). Write tools (``is_write=True``) always go through+the human confirmation handshake before they run.+"""+from __future__ import annotations++import logging+from typing import Any, Callable, Iterator, Optional++from app.services.ai_tool_registry import ai_tool_registry++logger = logging.getLogger(__name__)+++class PluginToolBinder:+ """Passed to a plugin's ``register(reg)`` function; binds tools to its slug."""++ def __init__(self, slug: str):+ self.slug = slug++ def tool(self, _fn: Optional[Callable] = None, *, rbac_feature: Optional[str] = None,+ rbac_level: str = "read", is_write: bool = False,+ name: Optional[str] = None, description: Optional[str] = None):+ """Register a function as an AI tool. Usable bare (``@reg.tool``) or with args."""+ def decorator(fn: Callable) -> Callable:+ ai_tool_registry.register(+ name=name or fn.__name__, func=fn, description=description,+ plugin_slug=self.slug, rbac_feature=rbac_feature,+ rbac_level=rbac_level, is_write=is_write,+ )+ return fn+ if _fn is not None and callable(_fn):+ return decorator(_fn)+ return decorator++ def register_tool(self, fn: Callable, **kwargs) -> Callable:+ """Imperative equivalent of the :meth:`tool` decorator."""+ return self.tool(**kwargs)(fn)++ def register_context_provider(self, route_pattern: str, func: Callable[..., Any]) -> None:+ """Register a callable ``fn(user, route, params) -> str`` that augments the+ system prompt for pages matching *route_pattern* (fnmatch glob)."""+ ai_tool_registry.register_context_provider(route_pattern, func, plugin_slug=self.slug)+++# Module-level convenience so a plugin can also register a context provider+# without holding the binder (defaults to no plugin slug → cleared only globally).+def register_context_provider(route_pattern: str, func: Callable[..., Any],+ plugin_slug: Optional[str] = None) -> None:+ ai_tool_registry.register_context_provider(route_pattern, func, plugin_slug=plugin_slug)+++def ask(prompt: str, *, mode: str = "simple", page_context: Optional[dict] = None) -> str:+ """Invoke the assistant in-process as the current JWT user (RBAC applies)."""+ from app.plugins_sdk import current_user+ from app.services import ai_service+ return ai_service.oneshot_ask(current_user(), prompt, mode=mode, page_context=page_context)+++def ask_stream(prompt: str, *, mode: str = "simple",+ page_context: Optional[dict] = None) -> Iterator[str]:+ """Streaming in-process assistant call; yields text chunks."""+ from app.plugins_sdk import current_user+ from app.services import ai_service+ return ai_service.oneshot_stream(current_user(), prompt, mode=mode, page_context=page_context)diff --git a/backend/app/services/ai_service.py b/backend/app/services/ai_service.pynew file mode 100644index 00000000..cf53be0b--- /dev/null+++ b/backend/app/services/ai_service.py@@ -0,0 +1,578 @@+"""Core AI assistant service (powered by Prompture).++Owns all Prompture wiring for the in-panel assistant:+- provider/key configuration via Prompture ``ProviderEnvironment`` (per-instance,+ never via ``os.environ``);+- system-prompt assembly (rebuilt every turn with the current page context and+ any plugin-contributed context providers);+- per-request Prompture ``ToolRegistry`` built from ``ai_tool_registry`` with+ read wrappers (RBAC re-check + optional PII redaction) and write wrappers+ (the human-in-the-loop confirmation gate);+- ``Conversation`` create/resume + persistence (``export()``/``from_export``);+- guardrails (prompt-injection refusal, PII redaction);+- the ``ConfirmationGate`` that lets a guarded write tool pause the streaming+ worker thread until the user approves/denies over ``/chat/confirm``.++Stateless module functions (ServerKit's three-layer convention) plus two small+helpers (the gate and an in-memory gate registry) that live in the single gevent+worker, consistent with ``agent_registry``.+"""+from __future__ import annotations++import dataclasses+import logging+import secrets+import threading+from typing import Any, Callable, Iterator, Optional++from prompture import Conversation, PIIRedactor, PromptInjectionDetector, ProviderEnvironment+from prompture.agents.tools_schema import ToolDefinition, ToolRegistry++from app import db+from app.services.ai_tool_registry import ai_tool_registry+from app.services.settings_service import SettingsService++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Provider catalog (curated; the user may also type a free-form provider/model)+# ---------------------------------------------------------------------------+# Maps provider -> the ProviderEnvironment attribute that carries its API key.+_KEY_ATTR = {+ "openai": "openai_api_key",+ "claude": "claude_api_key",+ "google": "google_api_key",+ "groq": "groq_api_key",+ "openrouter": "openrouter_api_key",+ "lmstudio": "lmstudio_api_key",+}+# Providers that take a custom endpoint instead of (or alongside) a key.+_ENDPOINT_ATTR = {+ "ollama": "ollama_endpoint",+ "lmstudio": "lmstudio_endpoint",+}++CURATED_PROVIDERS = [+ {"id": "openai", "label": "OpenAI", "needs_key": True, "supports_endpoint": False,+ "models": ["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "o4-mini"]},+ {"id": "claude", "label": "Anthropic (Claude)", "needs_key": True, "supports_endpoint": False,+ "models": ["claude-sonnet-4-6", "claude-3-5-sonnet-latest", "claude-3-5-haiku-latest"]},+ {"id": "google", "label": "Google (Gemini)", "needs_key": True, "supports_endpoint": False,+ "models": ["gemini-2.0-flash", "gemini-1.5-pro", "gemini-1.5-flash"]},+ {"id": "groq", "label": "Groq", "needs_key": True, "supports_endpoint": False,+ "models": ["llama-3.3-70b-versatile", "llama-3.1-8b-instant"]},+ {"id": "openrouter", "label": "OpenRouter", "needs_key": True, "supports_endpoint": False,+ "models": ["openai/gpt-4o", "anthropic/claude-3.5-sonnet", "meta-llama/llama-3.1-70b-instruct"]},+ {"id": "ollama", "label": "Ollama (local)", "needs_key": False, "supports_endpoint": True,+ "models": ["llama3.1:8b", "qwen2.5:7b", "mistral"]},+ {"id": "lmstudio", "label": "LM Studio (local)", "needs_key": False, "supports_endpoint": True,+ "models": []},+]+_PROVIDER_BY_ID = {p["id"]: p for p in CURATED_PROVIDERS}++SYSTEM_BASE = (+ "You are ServerKit AI, an assistant embedded in the ServerKit server control "+ "panel, powered by Prompture. You help operators understand and manage their "+ "servers, applications, Docker containers, and databases. Prefer calling tools "+ "to get LIVE data over guessing, and cite concrete numbers from tool results. "+ "Be concise and practical. For any state-changing action you MUST call the "+ "corresponding tool — it will pause for explicit human confirmation before "+ "anything actually runs. Never claim you performed an action unless a tool "+ "result confirms it."+)++# Guardrail detectors (cheap, regex-based) — instantiate once.+_injection_detector = PromptInjectionDetector(min_confidence=0.7)+_pii_redactor = PIIRedactor()++# In-memory registry of live confirmation gates, keyed by conversation id.+# Lives in the single gevent worker (like agent_registry).+_active_gates: dict[str, "ConfirmationGate"] = {}+_gates_lock = threading.Lock()++_init_lock = threading.Lock()+_initialized = False+++# ===========================================================================+# Initialization / discovery+# ===========================================================================+def ensure_initialized() -> None:+ """Register built-in tools and discover plugin AI contributions (once)."""+ global _initialized+ if _initialized:+ return+ with _init_lock:+ if _initialized:+ return+ from app.services.ai_tools_builtin import register_builtin_tools+ register_builtin_tools()+ try:+ ai_tool_registry.discover_plugins()+ except Exception:+ logger.warning("AI plugin discovery failed during init", exc_info=True)+ _initialized = True+++# ===========================================================================+# Settings / provider configuration+# ===========================================================================+def _setting(key: str, default=None):+ return SettingsService.get(key, default)+++def is_enabled() -> bool:+ return bool(_setting("ai_enabled", False))+++def is_configured() -> bool:+ """A provider + model are set and any required key is present."""+ provider = (_setting("ai_provider", "") or "").strip()+ model = (_setting("ai_model", "") or "").strip()+ if not provider or not model:+ return False+ meta = _PROVIDER_BY_ID.get(provider)+ needs_key = meta["needs_key"] if meta else True+ if needs_key and not _setting("ai_api_key_encrypted", ""):+ return False+ return True+++def current_model_name() -> str:+ provider = (_setting("ai_provider", "") or "").strip()+ model = (_setting("ai_model", "") or "").strip()+ return f"{provider}/{model}" if provider and model else ""+++def _decrypted_key() -> Optional[str]:+ enc = _setting("ai_api_key_encrypted", "")+ if not enc:+ return None+ try:+ from app.utils.crypto import decrypt_secret+ return decrypt_secret(enc)+ except Exception:+ logger.error("Failed to decrypt AI API key", exc_info=True)+ return None+++def build_provider_env(*, provider: Optional[str] = None, api_key: Optional[str] = None,+ endpoint: Optional[str] = None) -> ProviderEnvironment:+ """Build a per-instance ProviderEnvironment from stored (or supplied) config."""+ provider = (provider or _setting("ai_provider", "") or "").strip()+ if api_key is None:+ api_key = _decrypted_key()+ if endpoint is None:+ endpoint = (_setting("ai_endpoint", "") or "").strip() or None++ kwargs: dict[str, Any] = {}+ key_attr = _KEY_ATTR.get(provider)+ if key_attr and api_key:+ kwargs[key_attr] = api_key+ endpoint_attr = _ENDPOINT_ATTR.get(provider)+ if endpoint_attr and endpoint:+ kwargs[endpoint_attr] = endpoint+ return ProviderEnvironment(**kwargs)+++def list_providers() -> list[dict]:+ """Provider catalog for the settings dropdown (models = fallback suggestions)."""+ return [+ {"id": p["id"], "label": p["label"], "needs_key": p["needs_key"],+ "supports_endpoint": p["supports_endpoint"]}+ for p in CURATED_PROVIDERS+ ]+++def list_models(provider: str) -> dict:+ """Best-effort live model list for *provider*, falling back to curated suggestions."""+ provider = (provider or "").strip()+ fallback = _PROVIDER_BY_ID.get(provider, {}).get("models", [])+ try:+ from prompture.drivers import get_driver_for_model+ driver = get_driver_for_model(f"{provider}/", env=build_provider_env(provider=provider))+ lister = getattr(driver, "list_models", None)+ if callable(lister):+ models = lister()+ if models:+ return {"models": list(models), "source": "live"}+ except Exception:+ logger.debug("list_models(%s): live lookup failed, using fallback", provider, exc_info=True)+ return {"models": fallback, "source": "fallback"}+++def test_settings(provider: str, model: str, api_key: Optional[str] = None,+ endpoint: Optional[str] = None) -> dict:+ """Validate a provider/model/key by constructing the driver and probing models."""+ try:+ from prompture.drivers import get_driver_for_model+ env = build_provider_env(provider=provider, api_key=api_key, endpoint=endpoint)+ driver = get_driver_for_model(f"{provider}/{model}", env=env)+ lister = getattr(driver, "list_models", None)+ if callable(lister):+ try:+ lister()+ except Exception:+ pass # not all providers support listing; driver constructed = good enough+ return {"ok": True}+ except Exception as exc:+ return {"ok": False, "error": str(exc)}+++# ===========================================================================+# Guardrails+# ===========================================================================+def injection_flagged(text: str) -> bool:+ if not _setting("ai_injection_detection", True):+ return False+ try:+ return bool(_injection_detector.is_injection(text))+ except Exception:+ return False+++def _pii_enabled() -> bool:+ return bool(_setting("ai_pii_redaction", True))+++def redact_input(text: str) -> str:+ if not _pii_enabled():+ return text+ try:+ return _pii_redactor.redact(text).text+ except Exception:+ return text+++def _maybe_redact_result(result: Any) -> Any:+ if not _pii_enabled() or not isinstance(result, str):+ return result+ try:+ return _pii_redactor.redact(result).text+ except Exception:+ return result+++# ===========================================================================+# System prompt+# ===========================================================================+def build_system_prompt(user, mode: str, page_context: Optional[dict]) -> str:+ parts = [SYSTEM_BASE]+ instance = _setting("instance_name", "ServerKit")+ parts.append(f"\nThis panel instance is named '{instance}'.")+ if mode == "assistant" and page_context:+ route = page_context.get("route") or page_context.get("path") or ""+ label = page_context.get("label") or ""+ ids = page_context.get("ids") or page_context.get("params") or {}+ parts.append(+ f"\nCURRENT PAGE: {route} ({label}). Relevant ids: {ids}. "+ "When the user says 'this server/app/container/database', resolve it from these ids."+ )+ # Plugin-contributed context providers for this route.+ if route:+ for cp in ai_tool_registry.context_providers_for(route):+ try:+ extra = cp.func(user, route, ids)+ if extra:+ parts.append(f"\n[plugin:{cp.plugin_slug}] {extra}")+ except Exception:+ logger.debug("context provider failed for %s", cp.route_pattern, exc_info=True)+ role = getattr(user, "role", "viewer")+ parts.append(+ f"\nThe operator's role is '{role}'. Do not offer or attempt actions they "+ "lack permission for; tools you cannot see are unavailable to this user."+ )+ return "".join(parts)+++# ===========================================================================+# Per-request tool registry (read/write wrappers)+# ===========================================================================+def build_tool_registry(user, mode: str, gate: Optional["ConfirmationGate"]) -> Optional[ToolRegistry]:+ descriptors = ai_tool_registry.list_for(user, mode)+ if not descriptors:+ return None+ reg = ToolRegistry()+ for d in descriptors:+ fn = _make_write_wrapper(d, user, gate) if d.is_write else _make_read_wrapper(d, user)+ reg.add(ToolDefinition(name=d.qualified_name, description=d.description,+ parameters=d.parameters, function=fn))+ return reg+++def _make_read_wrapper(descriptor, user) -> Callable[..., Any]:+ def wrapper(**kwargs):+ if not descriptor.allowed_for(user):+ return f"Permission denied: you lack {descriptor.rbac_feature} {descriptor.rbac_level} access."+ result = descriptor.func(**kwargs)+ return _maybe_redact_result(result)+ return wrapper+++def _make_write_wrapper(descriptor, user, gate: Optional["ConfirmationGate"]) -> Callable[..., Any]:+ def wrapper(**kwargs):+ if not descriptor.allowed_for(user):+ return f"Permission denied: you lack {descriptor.rbac_feature} write access."+ if gate is None:+ return ("This is a state-changing action and needs explicit confirmation. "+ "Ask the user to run it from the streaming assistant so they can approve it.")+ decision, token = gate.request_confirmation(descriptor, kwargs)+ if decision != "approve":+ return f"The user declined to run '{descriptor.name}'."+ try:+ result = descriptor.func(**kwargs)+ gate.mark_executed(token, result)+ _audit_tool_execute(descriptor, kwargs, user, ok=True)+ return result+ except Exception as exc:+ gate.mark_failed(token, str(exc))+ _audit_tool_execute(descriptor, kwargs, user, ok=False, error=str(exc))+ return f"Action '{descriptor.name}' failed: {exc}"+ return wrapper+++def _audit_tool_execute(descriptor, params, user, *, ok: bool, error: Optional[str] = None) -> None:+ try:+ from app.services.audit_service import AuditService+ AuditService.log(+ action="ai.tool.execute" if ok else "ai.tool.failed",+ user_id=getattr(user, "id", None),+ target_type="ai_tool",+ target_id=descriptor.qualified_name,+ details={"params": params, "plugin_slug": descriptor.plugin_slug, "error": error},+ )+ except Exception:+ logger.debug("audit log failed for tool %s", descriptor.qualified_name, exc_info=True)+++def summarize_action(descriptor, params: dict) -> str:+ first_line = (descriptor.description or descriptor.name).split("\n")[0].rstrip(".")+ if params:+ kv = ", ".join(f"{k}={v}" for k, v in params.items())+ return f"{first_line} ({kv})"+ return first_line+++# ===========================================================================+# Conversation factory + persistence+# ===========================================================================+def build_conversation(row, user, mode: str, page_context: Optional[dict],+ gate: Optional["ConfirmationGate"]) -> Conversation:+ """Create a fresh Conversation or resume from the stored export (re-supplying tools)."""+ registry = build_tool_registry(user, mode, gate)+ system = build_system_prompt(user, mode, page_context)+ export = row.export+ if export:+ conv = Conversation.from_export(export, tools=registry)+ conv.system_prompt = system # refresh page context each turn+ return conv+ return Conversation(+ model_name=row.model_name or current_model_name(),+ system_prompt=system,+ tools=registry,+ env=build_provider_env(),+ max_tool_rounds=(6 if mode == "assistant" else 0),+ max_tool_result_length=4000,+ max_cost=_max_cost(),+ budget_policy="degrade" if _fallback_models() else None,+ fallback_models=_fallback_models() or None,+ simulated_tools="auto",+ conversation_id=row.id,+ )+++def _max_cost() -> Optional[float]:+ raw = _setting("ai_max_cost_usd", None)+ try:+ return float(raw) if raw not in (None, "", "0", 0) else None+ except (TypeError, ValueError):+ return None+++def _fallback_models() -> list[str]:+ fb = _setting("ai_fallback_models", []) or []+ return [m for m in fb if m] if isinstance(fb, list) else []+++def persist_conversation(row, conv: Conversation, *, page_context: Optional[dict] = None) -> None:+ """Persist the Prompture export + last page after a completed turn."""+ try:+ row.export = conv.export(strip_images=True)+ except Exception:+ logger.warning("Failed to export conversation %s", row.id, exc_info=True)+ if page_context and page_context.get("route"):+ row.last_page = page_context["route"][:256]+ db.session.add(row)+ db.session.commit()+++def derive_title(message: str) -> str:+ text = (message or "").strip().replace("\n", " ")+ return (text[:60] + "…") if len(text) > 60 else (text or "New chat")+++# ===========================================================================+# In-process invocation (used by plugins via app.plugins_sdk.ai)+# ===========================================================================+def _oneshot_conversation(user, mode: str, page_context: Optional[dict]) -> Conversation:+ ensure_initialized()+ registry = build_tool_registry(user, mode, gate=None)+ system = build_system_prompt(user, mode, page_context)+ return Conversation(+ model_name=current_model_name(),+ system_prompt=system,+ tools=registry,+ env=build_provider_env(),+ max_tool_rounds=(6 if mode == "assistant" else 0),+ max_tool_result_length=4000,+ simulated_tools="auto",+ )+++def oneshot_ask(user, prompt: str, *, mode: str = "simple",+ page_context: Optional[dict] = None) -> str:+ """Single-shot assistant call (no persistence) for in-process callers."""+ conv = _oneshot_conversation(user, mode, page_context)+ return conv.ask(redact_input(prompt))+++def oneshot_stream(user, prompt: str, *, mode: str = "simple",+ page_context: Optional[dict] = None) -> Iterator[str]:+ """Single-shot streaming assistant call yielding text chunks."""+ conv = _oneshot_conversation(user, mode, page_context)+ yield from conv.ask_stream(redact_input(prompt))+++# ===========================================================================+# Live event mapping+# ===========================================================================+def live_event_to_frame(event) -> tuple[str, dict]:+ """Map a Prompture LiveEvent to an (sse_event_name, data) pair."""+ data = dataclasses.asdict(event) if dataclasses.is_dataclass(event) else dict(getattr(event, "__dict__", {}))+ name = data.pop("event_type", None) or getattr(event, "event_type", "message")+ return name, data+++# ===========================================================================+# Confirmation gate (human-in-the-loop for write tools)+# ===========================================================================+class ConfirmationGate:+ """Pauses the streaming worker thread on a write tool until the user decides.++ The write-tool wrapper calls :meth:`request_confirmation`, which persists an+ ``AiPendingAction`` row, emits a ``pending_action`` SSE frame, and blocks on a+ ``threading.Event``. ``/chat/confirm`` calls :meth:`resolve` (in-memory) to+ unblock it. Because this runs in a dedicated worker thread (not the gevent+ hub), blocking here doesn't stall the rest of the panel.+ """++ def __init__(self, conversation_id: str, user_id: int, emit: Callable[[str, dict], None],+ cancel_event: threading.Event, ttl_seconds: int):+ self.conversation_id = conversation_id+ self.user_id = user_id+ self._emit = emit+ self._cancel = cancel_event+ self._ttl = ttl_seconds+ self._pending: dict[str, dict] = {}+ self._lock = threading.Lock()++ def request_confirmation(self, descriptor, params: dict) -> tuple[str, str]:+ """Block until the user approves/denies. Returns ('approve'|'deny', token)."""+ from app.models.ai import AiPendingAction++ token = secrets.token_urlsafe(16)+ summary = summarize_action(descriptor, params)+ row = AiPendingAction(+ id=token, conversation_id=self.conversation_id, user_id=self.user_id,+ tool_name=descriptor.qualified_name, plugin_slug=descriptor.plugin_slug,+ summary=summary, status=AiPendingAction.STATUS_PENDING,+ expires_at=AiPendingAction.make_expiry(self._ttl),+ )+ row.params = params+ try:+ db.session.add(row)+ db.session.commit()+ except Exception:+ db.session.rollback()+ logger.warning("Failed to persist pending action", exc_info=True)++ ev = threading.Event()+ with self._lock:+ self._pending[token] = {"event": ev, "decision": None}+ self._emit("pending_action", {+ "action_token": token, "tool_name": descriptor.qualified_name,+ "name": descriptor.name, "plugin_slug": descriptor.plugin_slug,+ "summary": summary, "params": params, "is_write": True,+ })++ signaled = ev.wait(timeout=self._ttl)+ with self._lock:+ info = self._pending.pop(token, {})++ if self._cancel.is_set():+ decision = "deny"+ elif not signaled:+ decision = "expired"+ else:+ decision = info.get("decision") or "deny"++ self._update_status(token, decision)+ return ("approve" if decision == "approve" else "deny"), token++ def resolve(self, token: str, decision: str) -> bool:+ """Called from /chat/confirm (in-memory). Returns True if the token was pending."""+ with self._lock:+ info = self._pending.get(token)+ if not info:+ return False+ info["decision"] = "approve" if decision == "approve" else "deny"+ info["event"].set()+ return True++ def has_pending(self) -> bool:+ with self._lock:+ return bool(self._pending)++ def mark_executed(self, token: str, result: Any) -> None:+ self._update_status(token, "executed", result=result)++ def mark_failed(self, token: str, error: str) -> None:+ self._update_status(token, "failed", result={"error": error})++ def _update_status(self, token: str, decision: str, result: Any = None) -> None:+ from app.models.ai import AiPendingAction+ status_map = {+ "approve": AiPendingAction.STATUS_APPROVED,+ "deny": AiPendingAction.STATUS_DENIED,+ "expired": AiPendingAction.STATUS_EXPIRED,+ "executed": AiPendingAction.STATUS_EXECUTED,+ "failed": AiPendingAction.STATUS_FAILED,+ }+ try:+ row = db.session.get(AiPendingAction, token)+ if row:+ row.status = status_map.get(decision, row.status)+ if result is not None:+ row.result = result+ db.session.add(row)+ db.session.commit()+ except Exception:+ db.session.rollback()+++def register_gate(conversation_id: str, gate: ConfirmationGate) -> None:+ with _gates_lock:+ _active_gates[conversation_id] = gate+++def unregister_gate(conversation_id: str) -> None:+ with _gates_lock:+ _active_gates.pop(conversation_id, None)+++def resolve_pending(conversation_id: str, token: str, decision: str) -> bool:+ with _gates_lock:+ gate = _active_gates.get(conversation_id)+ if gate is None:+ return False+ return gate.resolve(token, decision)diff --git a/backend/app/services/ai_tool_registry.py b/backend/app/services/ai_tool_registry.pynew file mode 100644index 00000000..cee48226--- /dev/null+++ b/backend/app/services/ai_tool_registry.py@@ -0,0 +1,245 @@+"""Process-global registry of AI tools (core primitive — powered by Prompture).++This is the aggregation point that makes the assistant *extensible*: built-in+``core.*`` tools plus tools contributed by installed plugins all live here. The+assistant builds a fresh Prompture ``ToolRegistry`` per request from these+descriptors, filtered by the requesting user's RBAC and the chat mode.++Singleton shape mirrors ``agent_registry`` (``__new__`` + ``_lock`` ++module-level instance) so all in-memory tool state lives in the one gevent+worker process — consistent with the rest of ServerKit.++Plugins register through ``app.plugins_sdk.ai`` (see plugins_sdk/ai.py); the+qualified tool name is always ``<plugin-slug>__<name>`` (or ``core__<name>``)+so plugin tools can never collide with each other or with built-ins. The double+underscore keeps names within the ``^[A-Za-z0-9_-]+$`` shape required by OpenAI+and Anthropic function-calling (dots are NOT allowed there).+"""+from __future__ import annotations++import logging+import threading+from dataclasses import dataclass, field+from fnmatch import fnmatch+from typing import Any, Callable, Optional++from prompture.agents.tools_schema import tool_from_function++logger = logging.getLogger(__name__)++CORE_PREFIX = "core"+# OpenAI caps function names at 64 chars; keep qualified names within that.+MAX_TOOL_NAME_LEN = 64+++@dataclass+class ToolDescriptor:+ """Metadata + callable for one registered tool."""+ name: str # bare name as registered by the author+ qualified_name: str # '<slug-or-core>__<name>' — the LLM-facing name+ func: Callable[..., Any]+ description: str+ parameters: dict # JSON Schema (derived once via tool_from_function)+ plugin_slug: Optional[str] = None # None => built-in+ rbac_feature: Optional[str] = None # e.g. 'docker'; None => any authenticated user+ rbac_level: str = "read" # 'read' | 'write'+ is_write: bool = False # write tools go through the confirmation handshake++ def allowed_for(self, user) -> bool:+ """True if *user* may use this tool given its RBAC tagging."""+ if self.rbac_feature is None:+ return True+ try:+ return bool(user.has_permission(self.rbac_feature, self.rbac_level))+ except Exception:+ return False+++@dataclass+class ContextProvider:+ """A plugin-registered callable that augments the system prompt for a route."""+ plugin_slug: Optional[str]+ route_pattern: str+ func: Callable[..., Any] # fn(user, route, params) -> str | dict | None+++class AiToolRegistry:+ """Singleton registry of built-in + plugin-contributed AI tools."""++ _instance: Optional["AiToolRegistry"] = None+ _lock = threading.Lock()++ def __new__(cls):+ if cls._instance is None:+ with cls._lock:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ cls._instance._initialized = False+ return cls._instance++ def __init__(self):+ if self._initialized:+ return+ self._initialized = True+ self._tools: dict[str, ToolDescriptor] = {} # keyed by qualified_name+ self._by_plugin: dict[str, set[str]] = {} # prefix -> {qualified_name}+ self._context_providers: list[ContextProvider] = []+ self._mutex = threading.Lock()+ self._discovered = False # plugin discovery has run?++ # ------------------------------------------------------------------+ # Registration+ # ------------------------------------------------------------------+ def register(+ self,+ *,+ name: str,+ func: Callable[..., Any],+ description: Optional[str] = None,+ plugin_slug: Optional[str] = None,+ rbac_feature: Optional[str] = None,+ rbac_level: str = "read",+ is_write: bool = False,+ ) -> ToolDescriptor:+ """Register a tool callable. Idempotent per qualified name (re-register overwrites)."""+ prefix = plugin_slug or CORE_PREFIX+ qualified = f"{prefix}__{name}"+ if len(qualified) > MAX_TOOL_NAME_LEN:+ logger.warning("AI tool name too long, truncating: %s", qualified)+ qualified = qualified[:MAX_TOOL_NAME_LEN]+ # Derive the JSON-Schema parameters + description once, from the real signature.+ td = tool_from_function(func, name=qualified, description=description)+ descriptor = ToolDescriptor(+ name=name,+ qualified_name=qualified,+ func=func,+ description=td.description,+ parameters=td.parameters,+ plugin_slug=plugin_slug,+ rbac_feature=rbac_feature,+ rbac_level=("write" if is_write else rbac_level),+ is_write=is_write,+ )+ with self._mutex:+ self._tools[qualified] = descriptor+ self._by_plugin.setdefault(prefix, set()).add(qualified)+ logger.debug("Registered AI tool %s (write=%s, rbac=%s/%s)",+ qualified, is_write, rbac_feature, descriptor.rbac_level)+ return descriptor++ def register_context_provider(self, route_pattern: str, func: Callable[..., Any],+ plugin_slug: Optional[str] = None) -> None:+ """Register a callable that contributes page context for matching routes."""+ with self._mutex:+ self._context_providers.append(ContextProvider(plugin_slug, route_pattern, func))++ # ------------------------------------------------------------------+ # Lifecycle (called by plugin_service on install/enable/disable/uninstall)+ # ------------------------------------------------------------------+ def unregister_plugin(self, slug: str) -> None:+ """Drop all tools + context providers contributed by a plugin."""+ with self._mutex:+ for qn in self._by_plugin.pop(slug, set()):+ self._tools.pop(qn, None)+ self._context_providers = [+ cp for cp in self._context_providers if cp.plugin_slug != slug+ ]+ logger.info("Unregistered AI tools for plugin '%s'", slug)++ def reload_plugin(self, slug: str) -> None:+ """Re-import and re-register a plugin's AI contributions (install/enable)."""+ self.unregister_plugin(slug)+ try:+ self._import_plugin_ai(slug)+ except Exception:+ logger.warning("Failed to (re)load AI tools for plugin '%s'", slug, exc_info=True)++ # ------------------------------------------------------------------+ # Discovery+ # ------------------------------------------------------------------+ def discover_plugins(self) -> None:+ """Import + register AI contributions from every active plugin (once)."""+ if self._discovered:+ return+ try:+ from app.models.plugin import InstalledPlugin+ rows = InstalledPlugin.query.filter_by(status=InstalledPlugin.STATUS_ACTIVE).all()+ except Exception:+ logger.warning("AI plugin discovery: could not query installed plugins", exc_info=True)+ self._discovered = True+ return+ for plugin in rows:+ manifest = plugin.manifest or {}+ if not isinstance(manifest.get("ai"), dict):+ continue+ try:+ self._import_plugin_ai(plugin.slug, manifest=manifest)+ except Exception:+ # One broken plugin must never kill discovery (mirrors load_all_plugins).+ logger.warning("AI discovery failed for plugin '%s'", plugin.slug, exc_info=True)+ self._discovered = True++ def _import_plugin_ai(self, slug: str, manifest: Optional[dict] = None) -> None:+ """Import a single plugin's AI entry point and call its register(binder)."""+ import importlib++ from app.models.plugin import InstalledPlugin++ if manifest is None:+ plugin = InstalledPlugin.query.filter_by(slug=slug).first()+ manifest = (plugin.manifest if plugin else {}) or {}+ ai_block = manifest.get("ai")+ if not isinstance(ai_block, dict):+ return+ entry_point = ai_block.get("entry_point")+ if not entry_point:+ return+ module_name, _, attr = entry_point.partition(":")+ attr = attr or "register"+ full_module = f"app.plugins.{slug}.{module_name}"+ mod = importlib.import_module(full_module)+ register_fn = getattr(mod, attr)++ # Bind registration to this plugin's slug. Imported lazily to avoid a+ # circular import (plugins_sdk.ai imports this registry).+ from app.plugins_sdk.ai import PluginToolBinder+ register_fn(PluginToolBinder(slug))+ logger.info("Registered AI contributions for plugin '%s'", slug)++ # ------------------------------------------------------------------+ # Query (used by ai_service per request)+ # ------------------------------------------------------------------+ def list_for(self, user, mode: str) -> list[ToolDescriptor]:+ """Tools available to *user* in *mode* (simple mode → none)."""+ if mode != "assistant":+ return []+ with self._mutex:+ descriptors = list(self._tools.values())+ return [d for d in descriptors if d.allowed_for(user)]++ def get(self, qualified_name: str) -> Optional[ToolDescriptor]:+ with self._mutex:+ return self._tools.get(qualified_name)++ def all_descriptors(self) -> list[ToolDescriptor]:+ with self._mutex:+ return list(self._tools.values())++ def context_providers_for(self, route: str) -> list[ContextProvider]:+ """Context providers whose route pattern matches *route* (fnmatch)."""+ with self._mutex:+ providers = list(self._context_providers)+ return [cp for cp in providers if _route_matches(cp.route_pattern, route)]+++def _route_matches(pattern: str, route: str) -> bool:+ if not pattern or not route:+ return False+ if pattern == route:+ return True+ # Support fnmatch globs ('/git/*') and a trailing-segment convenience match.+ return fnmatch(route, pattern) or route.startswith(pattern.rstrip("/*") + "/")+++# Module-level singleton — import as: from app.services.ai_tool_registry import ai_tool_registry+ai_tool_registry = AiToolRegistry()diff --git a/backend/app/services/ai_tools_builtin.py b/backend/app/services/ai_tools_builtin.pynew file mode 100644index 00000000..84285e13--- /dev/null+++ b/backend/app/services/ai_tools_builtin.py@@ -0,0 +1,166 @@+"""Built-in ``core.*`` AI tools (powered by Prompture).++These wrap existing ServerKit services so the assistant can answer with LIVE+data and (with confirmation) take action. Each function has type hints + a+Google-style docstring — Prompture derives the tool's JSON-Schema from those.++RBAC is declared at registration (``rbac_feature``/``rbac_level``) and enforced+by the registry + the per-request wrapper in ai_service; these bodies assume the+caller already passed the check. Write tools (``is_write=True``) execute the real+effect here — the confirmation handshake happens in the wrapper *before* this+body runs.++Tools run inside the streaming worker thread (or the request) with an active+Flask app context, so DB/service calls work normally.+"""+from __future__ import annotations++import logging++from app.services.ai_tool_registry import ai_tool_registry++logger = logging.getLogger(__name__)++_REGISTERED = False+++# ---------------------------------------------------------------------------+# Read tools+# ---------------------------------------------------------------------------+def get_system_metrics() -> dict:+ """Get live CPU, memory, disk, and network usage for the panel host.++ Returns:+ A dict of current system metrics (cpu, memory, disk, network, uptime).+ """+ from app.services.system_service import SystemService+ return SystemService.get_all_metrics()+++def list_docker_containers(include_stopped: bool = True) -> list:+ """List Docker containers on the host.++ Args:+ include_stopped: If true, include stopped containers; otherwise only running ones.+ """+ from app.services.docker_service import DockerService+ return DockerService.list_containers(all_containers=include_stopped)+++def get_docker_info() -> dict:+ """Get Docker engine status and summary info (version, container/image counts)."""+ from app.services.docker_service import DockerService+ return DockerService.get_docker_info()+++def list_applications() -> list:+ """List the web applications managed by this ServerKit panel.++ Returns:+ A list of apps with name, status, type, and port.+ """+ from app.models.application import Application+ return [a.to_dict() for a in Application.query.all()]+++def list_servers() -> list:+ """List the servers in this ServerKit fleet (the panel host plus paired agents).++ Returns:+ A list of servers with name, status, and address.+ """+ from app.models.server import Server+ out = []+ for s in Server.query.all():+ if hasattr(s, "to_dict"):+ out.append(s.to_dict())+ else:+ out.append({"id": getattr(s, "id", None), "name": getattr(s, "name", None),+ "status": getattr(s, "status", None)})+ return out+++def list_databases() -> dict:+ """List MySQL/MariaDB databases managed on the host.++ Returns:+ A dict with the database list, or a message if MySQL is not available.+ """+ from app.services.database_service import DatabaseService+ try:+ if not DatabaseService.mysql_is_installed():+ return {"available": False, "message": "MySQL/MariaDB is not installed on this host."}+ if not DatabaseService.mysql_is_running():+ return {"available": False, "message": "MySQL/MariaDB is installed but not running."}+ return {"available": True, "databases": DatabaseService.mysql_list_databases()}+ except Exception as exc: # pragma: no cover - environment dependent+ return {"available": False, "message": f"Could not list databases: {exc}"}+++# ---------------------------------------------------------------------------+# Write tools (guarded by the confirmation handshake before execution)+# ---------------------------------------------------------------------------+def restart_docker_container(container_id: str) -> dict:+ """Restart a Docker container. STATE-CHANGING — requires human confirmation.++ Args:+ container_id: The container id or name to restart.+ """+ from app.services.docker_service import DockerService+ DockerService.restart_container(container_id)+ return {"ok": True, "action": "restart", "container": container_id}+++def stop_docker_container(container_id: str) -> dict:+ """Stop a running Docker container. STATE-CHANGING — requires human confirmation.++ Args:+ container_id: The container id or name to stop.+ """+ from app.services.docker_service import DockerService+ DockerService.stop_container(container_id)+ return {"ok": True, "action": "stop", "container": container_id}+++def register_builtin_tools() -> None:+ """Register all ``core.*`` tools with the global registry (idempotent)."""+ global _REGISTERED+ if _REGISTERED:+ return++ ai_tool_registry.register(+ name="get_system_metrics", func=get_system_metrics,+ rbac_feature="monitoring", rbac_level="read",+ )+ ai_tool_registry.register(+ name="list_docker_containers", func=list_docker_containers,+ rbac_feature="docker", rbac_level="read",+ )+ ai_tool_registry.register(+ name="get_docker_info", func=get_docker_info,+ rbac_feature="docker", rbac_level="read",+ )+ ai_tool_registry.register(+ name="list_applications", func=list_applications,+ rbac_feature="applications", rbac_level="read",+ )+ ai_tool_registry.register(+ name="list_servers", func=list_servers,+ rbac_feature="servers", rbac_level="read",+ )+ ai_tool_registry.register(+ name="list_databases", func=list_databases,+ rbac_feature="databases", rbac_level="read",+ )+ # --- guarded write tools ---+ ai_tool_registry.register(+ name="restart_docker_container", func=restart_docker_container,+ rbac_feature="docker", is_write=True,+ )+ ai_tool_registry.register(+ name="stop_docker_container", func=stop_docker_container,+ rbac_feature="docker", is_write=True,+ )++ _REGISTERED = True+ logger.info("Registered %d built-in AI tools", 8)diff --git a/backend/app/services/contribution_service.py b/backend/app/services/contribution_service.pyindex 5cd7f93b..aa9d0d3a 100644--- a/backend/app/services/contribution_service.py+++ b/backend/app/services/contribution_service.py@@ -54,6 +54,9 @@ def get_active_contributions():command_palette = []widgets = []layouts = []+ # AI assistant contributions: per-route suggested prompts + custom+ # tool-result renderers, consumed by the core AIAssistant.+ ai = {'suggested_prompts': [], 'tool_renderers': []}for p in plugins:contrib = (p.manifest or {}).get('contributions') or {}@@ -66,6 +69,11 @@ def get_active_contributions():widgets.extend(_tag(contrib.get('widgets'), p.slug))layouts.extend(_tag(contrib.get('layouts'), p.slug))+ ai_contrib = contrib.get('ai')+ if isinstance(ai_contrib, dict):+ ai['suggested_prompts'].extend(_tag(ai_contrib.get('suggested_prompts'), p.slug))+ ai['tool_renderers'].extend(_tag(ai_contrib.get('tool_renderers'), p.slug))+titles = contrib.get('page_titles')if isinstance(titles, dict):for path, title in titles.items():@@ -79,4 +87,5 @@ def get_active_contributions():'command_palette': command_palette,'widgets': widgets,'layouts': layouts,+ 'ai': ai,}diff --git a/backend/app/services/marketplace_service.py b/backend/app/services/marketplace_service.pyindex b1999248..b94babc4 100644--- a/backend/app/services/marketplace_service.py+++ b/backend/app/services/marketplace_service.py@@ -8,7 +8,7 @@ logger = logging.getLogger(__name__)class MarketplaceService:"""Service for the extension marketplace."""- CATEGORIES = ['monitoring', 'security', 'deployment', 'integration', 'ui', 'utility']+ CATEGORIES = ['ai', 'monitoring', 'security', 'deployment', 'integration', 'ui', 'utility']@staticmethoddef list_extensions(category=None, search=None, status='published'):diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.pyindex 75777c50..0a20dffd 100644--- a/backend/app/services/plugin_service.py+++ b/backend/app/services/plugin_service.py@@ -520,6 +520,11 @@ def _install_from_buffer(buf, source_url, source_type, user_id=None):# convenience setup (e.g. creating default rows)._run_lifecycle_hook(plugin, manifest, 'install')+ # If the plugin declares an "ai" block, register its tools/context with+ # the core assistant now so installing it teaches the assistant new+ # abilities without a restart. Best effort.+ _refresh_plugin_ai(plugin)+logger.info(f'Plugin {slug} v{manifest["version"]} installed successfully')if template_results:plugin._template_install_results = template_results # surfaced via to_dict if needed@@ -700,6 +705,9 @@ def uninstall_plugin(plugin_id):# may need to read its own files). Best effort — never block teardown._run_lifecycle_hook(plugin, manifest, 'uninstall')+ # Drop any AI tools/context this plugin contributed to the assistant.+ _unregister_plugin_ai(slug)+# Remove backend filesbackend_dest = os.path.join(BACKEND_PLUGINS_DIR, slug)if os.path.exists(backend_dest):@@ -729,6 +737,7 @@ def enable_plugin(plugin_id):plugin.error_message = Nonedb.session.commit()_regenerate_frontend_manifest()+ _refresh_plugin_ai(plugin)return plugin@@ -740,9 +749,31 @@ def disable_plugin(plugin_id):plugin.status = InstalledPlugin.STATUS_DISABLEDdb.session.commit()_regenerate_frontend_manifest()+ _unregister_plugin_ai(plugin.slug)return plugin+def _refresh_plugin_ai(plugin):+ """Register a plugin's AI tools/context with the core assistant (if it has an+ ``ai`` manifest block). Idempotent; safe whether or not AI is initialized."""+ try:+ manifest = plugin.manifest or {}+ if isinstance(manifest.get('ai'), dict):+ from app.services.ai_tool_registry import ai_tool_registry+ ai_tool_registry.reload_plugin(plugin.slug)+ except Exception:+ logger.warning(f'AI tool refresh failed for plugin {plugin.slug}', exc_info=True)+++def _unregister_plugin_ai(slug):+ """Drop a plugin's AI tools/context from the core assistant."""+ try:+ from app.services.ai_tool_registry import ai_tool_registry+ ai_tool_registry.unregister_plugin(slug)+ except Exception:+ logger.warning(f'AI tool unregister failed for plugin {slug}', exc_info=True)++def _run_lifecycle_hook(plugin, manifest, phase):"""Execute a plugin's lifecycle hook.diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex 465a29d8..19876147 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -75,8 +75,23 @@ class SettingsService:'rate_limit_elevated': {'value': '500 per minute', 'type': 'string', 'description': 'Rate limit for elevated API keys'},'rate_limit_unlimited': {'value': '5000 per minute', 'type': 'string', 'description': 'Rate limit for unlimited API keys'},'rate_limit_unauthenticated': {'value': '30 per minute', 'type': 'string', 'description': 'Rate limit for unauthenticated requests'},+ # AI assistant (core primitive — powered by Prompture). The API key is+ # stored encrypted and is NEVER returned by the settings API (see SECRET_AI_KEYS).+ 'ai_enabled': {'value': False, 'type': 'boolean', 'description': 'Enable the AI assistant'},+ 'ai_provider': {'value': '', 'type': 'string', 'description': 'Prompture provider (openai/claude/google/groq/openrouter/ollama/lmstudio)'},+ 'ai_model': {'value': '', 'type': 'string', 'description': 'Model id for the selected provider'},+ 'ai_api_key_encrypted': {'value': '', 'type': 'string', 'description': 'Encrypted provider API key (never returned by the API)'},+ 'ai_endpoint': {'value': '', 'type': 'string', 'description': 'Custom endpoint (ollama/lmstudio; reserved for OpenAI-compatible gateways)'},+ 'ai_max_cost_usd': {'value': 0.5, 'type': 'string', 'description': 'Per-conversation cost ceiling in USD (budget_policy=degrade)'},+ 'ai_fallback_models': {'value': [], 'type': 'json', 'description': 'Ordered fallback model ids when the primary is over budget/unavailable'},+ 'ai_pii_redaction': {'value': True, 'type': 'boolean', 'description': 'Redact PII from AI input and tool output'},+ 'ai_injection_detection': {'value': True, 'type': 'boolean', 'description': 'Refuse prompts flagged as prompt-injection'},+ 'ai_pending_action_ttl_s': {'value': 300, 'type': 'integer', 'description': 'Seconds a write-tool confirmation stays valid'},}+ # Settings that must never be returned through the API (only "is it set?").+ SECRET_AI_KEYS = {'ai_api_key_encrypted'}+@staticmethoddef get(key, default=None):"""Get a setting value by key."""diff --git a/backend/migrations/versions/013_ai_assistant.py b/backend/migrations/versions/013_ai_assistant.pynew file mode 100644index 00000000..0658d11a--- /dev/null+++ b/backend/migrations/versions/013_ai_assistant.py@@ -0,0 +1,81 @@+"""AI assistant core primitive (powered by Prompture).++Adds the three tables backing the in-panel assistant:+- ai_conversations (one chat thread per user; holds the Prompture export blob)+- ai_messages (denormalized per-turn rows for fast transcript rendering)+- ai_pending_actions (durable record of guarded write-tool confirmations)++Idempotent: MigrationService._fix_missing_columns runs db.create_all() on boot+before Alembic, so these tables may already exist — guard on the live schema+exactly like 009/010/011.++Revision ID: 013_ai_assistant+Revises: 012_wordpress_update_runs+Create Date: 2026-06-01+"""+from alembic import op+import sqlalchemy as sa++revision = '013_ai_assistant'+down_revision = '012_wordpress_update_runs'+branch_labels = None+depends_on = None+++def upgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())++ if 'ai_conversations' not in existing:+ op.create_table(+ 'ai_conversations',+ sa.Column('id', sa.String(length=64), primary_key=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False, index=True),+ sa.Column('title', sa.String(length=256)),+ sa.Column('mode', sa.String(length=16)),+ sa.Column('model_name', sa.String(length=128)),+ sa.Column('export_json', sa.Text()),+ sa.Column('last_page', sa.String(length=256)),+ sa.Column('created_at', sa.DateTime()),+ sa.Column('updated_at', sa.DateTime()),+ )++ if 'ai_messages' not in existing:+ op.create_table(+ 'ai_messages',+ sa.Column('id', sa.Integer(), primary_key=True),+ sa.Column('conversation_id', sa.String(length=64),+ sa.ForeignKey('ai_conversations.id', ondelete='CASCADE'), nullable=False, index=True),+ sa.Column('role', sa.String(length=16), nullable=False),+ sa.Column('content', sa.Text()),+ sa.Column('tool_calls_json', sa.Text()),+ sa.Column('usage_json', sa.Text()),+ sa.Column('created_at', sa.DateTime()),+ )++ if 'ai_pending_actions' not in existing:+ op.create_table(+ 'ai_pending_actions',+ sa.Column('id', sa.String(length=64), primary_key=True),+ sa.Column('conversation_id', sa.String(length=64),+ sa.ForeignKey('ai_conversations.id', ondelete='CASCADE'), nullable=False, index=True),+ sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=False, index=True),+ sa.Column('tool_name', sa.String(length=128), nullable=False),+ sa.Column('plugin_slug', sa.String(length=128)),+ sa.Column('params_json', sa.Text()),+ sa.Column('summary', sa.Text()),+ sa.Column('status', sa.String(length=16)),+ sa.Column('result_json', sa.Text()),+ sa.Column('created_at', sa.DateTime()),+ sa.Column('expires_at', sa.DateTime()),+ )+++def downgrade():+ conn = op.get_bind()+ inspector = sa.inspect(conn)+ existing = set(inspector.get_table_names())+ for table in ('ai_pending_actions', 'ai_messages', 'ai_conversations'):+ if table in existing:+ op.drop_table(table)diff --git a/backend/requirements.txt b/backend/requirements.txtindex 651172f4..90c0e61e 100644--- a/backend/requirements.txt+++ b/backend/requirements.txt@@ -63,4 +63,11 @@ python3-saml==1.16.0# OpenAPI documentationapispec==6.4.0-apispec-webframeworks==1.2.0\ No newline at end of file+apispec-webframeworks==1.2.0++# AI assistant (core primitive — powered by Prompture)+# Multi-provider LLM orchestration: Conversation, ToolRegistry, ask_live streaming,+# ProviderEnvironment, guardrails. Provider SDKs (openai/anthropic/...) are optional+# extras installed per the configured provider; the base package is provider-agnostic.+# Installed from the Prompture repo (pip install -e path/to/prompture) until published.+prompture>=1.4\ No newline at end of filediff --git a/backend/tests/test_ai_assistant.py b/backend/tests/test_ai_assistant.pynew file mode 100644index 00000000..fe8f8a82--- /dev/null+++ b/backend/tests/test_ai_assistant.py@@ -0,0 +1,194 @@+"""Tests for the core AI assistant primitive (powered by Prompture)."""+import pytest++from prompture.agents.live_events import (+ TextDelta, ToolResult, ToolUseStart, TurnComplete,+)++from app.services import ai_service+from app.services.ai_tool_registry import ai_tool_registry+++class FakeUser:+ def __init__(self, role='admin', perms=None):+ self.role = role+ self.id = 1+ self._perms = perms or {}++ def has_permission(self, feature, level='read'):+ if self.role == 'admin':+ return True+ return self._perms.get((feature, level), False)+++# --------------------------------------------------------------------------+# LiveEvent -> SSE frame mapping+# --------------------------------------------------------------------------+def test_live_event_to_frame_text_delta():+ name, data = ai_service.live_event_to_frame(TextDelta(text='hello'))+ assert name == 'text_delta'+ assert data == {'text': 'hello'}+++def test_live_event_to_frame_tool_use_start():+ name, data = ai_service.live_event_to_frame(ToolUseStart(id='t1', name='core__list_apps'))+ assert name == 'tool_use_start'+ assert data == {'id': 't1', 'name': 'core__list_apps'}+++def test_live_event_to_frame_tool_result():+ name, data = ai_service.live_event_to_frame(+ ToolResult(id='t1', name='core__x', output='ok', is_error=False))+ assert name == 'tool_result'+ assert data['id'] == 't1' and data['output'] == 'ok' and data['is_error'] is False+++def test_live_event_to_frame_turn_complete():+ name, data = ai_service.live_event_to_frame(TurnComplete(usage={'cost': 0.12}))+ assert name == 'turn_complete'+ assert data['usage'] == {'cost': 0.12}+++# --------------------------------------------------------------------------+# Tool registry: register / unregister / reload + RBAC + namespacing+# --------------------------------------------------------------------------+def test_registry_register_and_unregister():+ def dbl(x: int) -> int:+ """Double a number.++ Args:+ x: the number to double.+ """+ return x * 2++ ai_tool_registry.register(name='dbl', func=dbl, plugin_slug='tpA',+ rbac_feature='docker', rbac_level='read')+ d = ai_tool_registry.get('tpA__dbl')+ assert d is not None+ assert d.qualified_name == 'tpA__dbl'+ assert d.is_write is False+ assert d.parameters['properties']['x']['type'] == 'integer'++ ai_tool_registry.unregister_plugin('tpA')+ assert ai_tool_registry.get('tpA__dbl') is None+++def test_registry_rbac_and_mode_filter():+ def peek() -> str:+ """Peek at something secret."""+ return 'ok'++ ai_tool_registry.register(name='peek', func=peek, plugin_slug='tpB',+ rbac_feature='security', rbac_level='read')+ try:+ admin = FakeUser(role='admin')+ viewer = FakeUser(role='viewer', perms={('security', 'read'): False})++ admin_names = [d.qualified_name for d in ai_tool_registry.list_for(admin, 'assistant')]+ viewer_names = [d.qualified_name for d in ai_tool_registry.list_for(viewer, 'assistant')]+ assert 'tpB__peek' in admin_names+ assert 'tpB__peek' not in viewer_names++ # Simple mode never offers tools.+ assert ai_tool_registry.list_for(admin, 'simple') == []+ finally:+ ai_tool_registry.unregister_plugin('tpB')+++def test_plugin_binder_namespaces_and_flags():+ from app.plugins_sdk.ai import PluginToolBinder+ binder = PluginToolBinder('demo')++ @binder.tool(rbac_feature='git', is_write=True)+ def delete_branch(repo: str, branch: str) -> dict:+ """Delete a branch.++ Args:+ repo: repository slug.+ branch: branch name.+ """+ return {}++ try:+ d = ai_tool_registry.get('demo__delete_branch')+ assert d is not None+ assert d.plugin_slug == 'demo'+ assert d.is_write is True+ assert d.rbac_level == 'write'+ finally:+ ai_tool_registry.unregister_plugin('demo')+++# --------------------------------------------------------------------------+# Provider environment construction (Prompture ProviderEnvironment)+# --------------------------------------------------------------------------+def test_build_provider_env_openai_key(monkeypatch):+ monkeypatch.setattr(ai_service, '_setting',+ lambda k, d=None: {'ai_provider': 'openai', 'ai_endpoint': ''}.get(k, d))+ monkeypatch.setattr(ai_service, '_decrypted_key', lambda: 'sk-test-123')+ env = ai_service.build_provider_env()+ assert env.openai_api_key == 'sk-test-123'+ assert env.ollama_endpoint is None+++def test_build_provider_env_ollama_endpoint(monkeypatch):+ monkeypatch.setattr(ai_service, '_setting',+ lambda k, d=None: {'ai_provider': 'ollama', 'ai_endpoint': 'http://h:11434'}.get(k, d))+ monkeypatch.setattr(ai_service, '_decrypted_key', lambda: None)+ env = ai_service.build_provider_env()+ assert env.ollama_endpoint == 'http://h:11434'+ assert env.openai_api_key is None+++def test_summarize_action_includes_params():+ class D:+ name = 'restart_docker_container'+ description = 'Restart a Docker container. STATE-CHANGING'++ summary = ai_service.summarize_action(D(), {'container_id': 'nginx'})+ assert 'container_id=nginx' in summary+++# --------------------------------------------------------------------------+# API: RBAC gating + secret never leaked+# --------------------------------------------------------------------------+def test_status_requires_auth_and_reports_configured(client, auth_headers):+ r = client.get('/api/v1/ai/status', headers=auth_headers)+ assert r.status_code == 200+ body = r.get_json()+ assert 'configured' in body and 'enabled' in body+++def test_settings_get_never_returns_api_key(client, auth_headers, app):+ from app.services.settings_service import SettingsService+ with app.app_context():+ SettingsService.set('ai_api_key_encrypted', 'ENCRYPTED_SECRET_XYZ')++ r = client.get('/api/v1/ai/settings', headers=auth_headers)+ assert r.status_code == 200+ body = r.get_json()+ assert body['api_key_set'] is True+ assert 'api_key' not in body+ assert 'ENCRYPTED_SECRET_XYZ' not in r.get_data(as_text=True)+++def test_settings_put_requires_admin(client, app):+ from app import db+ from app.models import User+ from flask_jwt_extended import create_access_token+ from werkzeug.security import generate_password_hash++ with app.app_context():+ viewer = User(+ email='[email protected]', username='viewer_ai',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_VIEWER, is_active=True,+ )+ db.session.add(viewer)+ db.session.commit()+ token = create_access_token(identity=viewer.id)++ r = client.put('/api/v1/ai/settings',+ headers={'Authorization': f'Bearer {token}'},+ json={'provider': 'openai'})+ assert r.status_code == 403diff --git a/frontend/src/components/ai/AIAssistant.jsx b/frontend/src/components/ai/AIAssistant.jsxnew file mode 100644index 00000000..cab7935f--- /dev/null+++ b/frontend/src/components/ai/AIAssistant.jsx@@ -0,0 +1,40 @@+import { useEffect } from 'react';+import { useAuth } from '../../contexts/AuthContext';+import { useServerkitAI } from '../../contexts/AIContext';+import ChatBubble from './ChatBubble';+import ChatDrawer from './ChatDrawer';++// Core assistant overlay. Mounted once in DashboardLayout (owns its own+// z-index — no plugin coexistence hacks). Renders the bubble everywhere and+// the drawer when open.+const AIAssistant = () => {+ const { isAuthenticated } = useAuth();+ const { isOpen, toggle, isStreaming, unread, pageContext } = useServerkitAI();++ // Alt+A toggles the assistant (ignored while typing in a field).+ useEffect(() => {+ const onKeyDown = (e) => {+ if (!e.altKey || (e.key !== 'a' && e.key !== 'A')) return;+ const t = document.activeElement;+ const tag = t?.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || t?.isContentEditable) return;+ e.preventDefault();+ toggle();+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [toggle]);++ if (!isAuthenticated) return null;++ const raised = /^\/servers\/[^/]+/.test(pageContext.route || '');++ return (+ <>+ <ChatBubble open={isOpen} unread={unread} streaming={isStreaming} raised={raised} onToggle={toggle} />+ {isOpen ? <ChatDrawer /> : null}+ </>+ );+};++export default AIAssistant;diff --git a/frontend/src/components/ai/ChatBubble.jsx b/frontend/src/components/ai/ChatBubble.jsxnew file mode 100644index 00000000..c3be6afb--- /dev/null+++ b/frontend/src/components/ai/ChatBubble.jsx@@ -0,0 +1,24 @@+import { MessageSquare, X } from 'lucide-react';++// Intercom-style launcher. `raised` lifts it above the serverkit-gui FAB on+// server-detail routes so the two don't overlap.+const ChatBubble = ({ open, unread, streaming, raised, onToggle }) => (+ <button+ type="button"+ className={[+ 'sk-ai-bubble',+ open ? 'is-open' : '',+ raised ? 'is-raised' : '',+ streaming && !open ? 'is-busy' : '',+ ].filter(Boolean).join(' ')}+ onClick={onToggle}+ aria-label={open ? 'Close assistant (Alt+A)' : 'Open assistant (Alt+A)'}+ aria-expanded={open}+ aria-controls="sk-ai-drawer"+ >+ {open ? <X size={22} /> : <MessageSquare size={22} />}+ {!open && unread > 0 ? <span className="sk-ai-bubble__dot" aria-hidden="true" /> : null}+ </button>+);++export default ChatBubble;diff --git a/frontend/src/components/ai/ChatDrawer.jsx b/frontend/src/components/ai/ChatDrawer.jsxnew file mode 100644index 00000000..655bb253--- /dev/null+++ b/frontend/src/components/ai/ChatDrawer.jsx@@ -0,0 +1,79 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useServerkitAI } from '../../contexts/AIContext';+import useMediaQuery from '../../hooks/useMediaQuery';+import useFocusTrap from '../../hooks/ai/useFocusTrap';+import DrawerHeader from './DrawerHeader';+import ContextChip from './ContextChip';+import MessageList from './MessageList';+import Composer from './Composer';++const WIDTH_KEY = 'sk-ai:width';+const MIN_W = 360;++const clampWidth = (w) => {+ const max = Math.min(560, Math.round(window.innerWidth * 0.9));+ return Math.max(MIN_W, Math.min(w, max));+};++const ChatDrawer = () => {+ const { close } = useServerkitAI();+ const isMobile = useMediaQuery('(max-width: 768px)');+ const panelRef = useRef(null);+ const [width, setWidth] = useState(() => {+ const saved = parseInt(localStorage.getItem(WIDTH_KEY) || '', 10);+ return Number.isFinite(saved) ? saved : 420;+ });++ useFocusTrap(panelRef, { active: true, onEscape: close });++ // Lock body scroll on mobile (full-screen sheet).+ useEffect(() => {+ if (!isMobile) return undefined;+ const prev = document.body.style.overflow;+ document.body.style.overflow = 'hidden';+ return () => { document.body.style.overflow = prev; };+ }, [isMobile]);++ const startResize = useCallback((e) => {+ if (isMobile) return;+ e.preventDefault();+ const onMove = (ev) => {+ const next = clampWidth(window.innerWidth - ev.clientX);+ setWidth(next);+ };+ const onUp = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ setWidth((w) => { localStorage.setItem(WIDTH_KEY, String(w)); return w; });+ };+ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ }, [isMobile]);++ const style = isMobile ? undefined : { '--sk-ai-drawer-w': `${width}px` };++ return (+ <div className="sk-ai-overlay" data-mobile={isMobile ? 'true' : 'false'}>+ {isMobile ? <div className="sk-ai-overlay__backdrop" onClick={close} aria-hidden="true" /> : null}+ <aside+ ref={panelRef}+ id="sk-ai-drawer"+ className="sk-ai-drawer"+ role="dialog"+ aria-modal={isMobile ? 'true' : 'false'}+ aria-label="ServerKit AI assistant"+ style={style}+ >+ {!isMobile ? (+ <div className="sk-ai-drawer__resize" onPointerDown={startResize} aria-hidden="true" />+ ) : null}+ <DrawerHeader />+ <ContextChip />+ <MessageList />+ <Composer />+ </aside>+ </div>+ );+};++export default ChatDrawer;diff --git a/frontend/src/components/ai/Composer.jsx b/frontend/src/components/ai/Composer.jsxnew file mode 100644index 00000000..8ecf8a3e--- /dev/null+++ b/frontend/src/components/ai/Composer.jsx@@ -0,0 +1,64 @@+import { useRef, useState } from 'react';+import { Send, Square } from 'lucide-react';+import { useServerkitAI } from '../../contexts/AIContext';++const Composer = () => {+ const { send, stop, isStreaming, providerConfigured } = useServerkitAI();+ const [value, setValue] = useState('');+ const textareaRef = useRef(null);++ const submit = () => {+ const text = value.trim();+ if (!text || isStreaming) return;+ send(text);+ setValue('');+ if (textareaRef.current) textareaRef.current.style.height = 'auto';+ };++ const onKeyDown = (e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ submit();+ }+ };++ const onInput = (e) => {+ setValue(e.target.value);+ const el = e.target;+ el.style.height = 'auto';+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;+ };++ return (+ <div className="sk-ai-composer">+ <textarea+ ref={textareaRef}+ className="sk-ai-composer__input"+ rows={1}+ placeholder={providerConfigured ? 'Ask about your servers…' : 'Assistant not configured'}+ value={value}+ disabled={!providerConfigured}+ onChange={onInput}+ onKeyDown={onKeyDown}+ aria-label="Message the assistant"+ />+ {isStreaming ? (+ <button type="button" className="sk-ai-composer__btn sk-ai-composer__btn--stop" onClick={stop} aria-label="Stop">+ <Square size={16} />+ </button>+ ) : (+ <button+ type="button"+ className="sk-ai-composer__btn"+ onClick={submit}+ disabled={!providerConfigured || !value.trim()}+ aria-label="Send"+ >+ <Send size={16} />+ </button>+ )}+ </div>+ );+};++export default Composer;diff --git a/frontend/src/components/ai/ConfirmActionCard.jsx b/frontend/src/components/ai/ConfirmActionCard.jsxnew file mode 100644index 00000000..a201a5bb--- /dev/null+++ b/frontend/src/components/ai/ConfirmActionCard.jsx@@ -0,0 +1,54 @@+import { useEffect, useRef } from 'react';+import { ShieldAlert } from 'lucide-react';+import { useServerkitAI } from '../../contexts/AIContext';++const formatParams = (params) => {+ if (!params || !Object.keys(params).length) return null;+ try { return JSON.stringify(params, null, 2); } catch { return String(params); }+};++// Inline approve/deny card for a guarded write tool. The model only ever+// proposes; the action runs server-side only after the user approves.+const ConfirmActionCard = () => {+ const { pendingConfirm, confirmAction } = useServerkitAI();+ const denyRef = useRef(null);++ useEffect(() => {+ if (pendingConfirm) denyRef.current?.focus();+ }, [pendingConfirm]);++ if (!pendingConfirm) return null;+ const params = formatParams(pendingConfirm.params);++ return (+ <div className="sk-ai-confirm" role="group" aria-label="Confirm action">+ <div className="sk-ai-confirm__head">+ <ShieldAlert size={16} />+ <span>Confirm action</span>+ </div>+ <p className="sk-ai-confirm__summary">{pendingConfirm.summary}</p>+ {params ? (+ <pre className="sk-ai-code sk-ai-confirm__params"><code>{params}</code></pre>+ ) : null}+ <div className="sk-ai-confirm__actions">+ <button+ ref={denyRef}+ type="button"+ className="sk-ai-btn sk-ai-btn--ghost"+ onClick={() => confirmAction('deny')}+ >+ Deny+ </button>+ <button+ type="button"+ className="sk-ai-btn sk-ai-btn--danger"+ onClick={() => confirmAction('approve')}+ >+ Approve & run+ </button>+ </div>+ </div>+ );+};++export default ConfirmActionCard;diff --git a/frontend/src/components/ai/ContextChip.jsx b/frontend/src/components/ai/ContextChip.jsxnew file mode 100644index 00000000..0d1e893b--- /dev/null+++ b/frontend/src/components/ai/ContextChip.jsx@@ -0,0 +1,26 @@+import { MapPin } from 'lucide-react';+import { useServerkitAI } from '../../contexts/AIContext';++// Shows the page the assistant is aware of, and lets the user toggle whether+// that context is attached to the next message. Assistant mode only.+const ContextChip = () => {+ const { mode, pageContext, includeContext, setIncludeContext } = useServerkitAI();+ if (mode !== 'assistant') return null;++ return (+ <button+ type="button"+ className={`sk-ai-context-chip${includeContext ? ' is-on' : ' is-off'}`}+ aria-pressed={includeContext}+ title={includeContext+ ? 'The assistant can read live data for this page and call ServerKit tools. Click to detach.'+ : 'Page context is detached. Click to attach.'}+ onClick={() => setIncludeContext(!includeContext)}+ >+ <MapPin size={13} />+ <span>{includeContext ? `Asking about: ${pageContext.label}` : 'No page context'}</span>+ </button>+ );+};++export default ContextChip;diff --git a/frontend/src/components/ai/ConversationMenu.jsx b/frontend/src/components/ai/ConversationMenu.jsxnew file mode 100644index 00000000..bb58ee89--- /dev/null+++ b/frontend/src/components/ai/ConversationMenu.jsx@@ -0,0 +1,75 @@+import { useEffect, useRef, useState } from 'react';+import { History, Plus, Trash2 } from 'lucide-react';+import { useServerkitAI } from '../../contexts/AIContext';++const ConversationMenu = () => {+ const {+ conversations, activeId, newConversation, switchConversation, deleteConversation, loadConversations,+ } = useServerkitAI();+ const [open, setOpen] = useState(false);+ const wrapRef = useRef(null);++ useEffect(() => {+ if (!open) return undefined;+ loadConversations();+ const onClick = (e) => {+ if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);+ };+ document.addEventListener('mousedown', onClick);+ return () => document.removeEventListener('mousedown', onClick);+ }, [open, loadConversations]);++ return (+ <div className="sk-ai-convo" ref={wrapRef}>+ <button+ type="button"+ className="sk-ai-iconbtn"+ aria-label="Conversations"+ aria-expanded={open}+ onClick={() => setOpen((v) => !v)}+ >+ <History size={16} />+ </button>+ {open ? (+ <div className="sk-ai-convo__menu" role="menu">+ <button+ type="button"+ className="sk-ai-convo__new"+ onClick={() => { newConversation(); setOpen(false); }}+ >+ <Plus size={14} /> New chat+ </button>+ <div className="sk-ai-convo__list">+ {conversations.length === 0 ? (+ <div className="sk-ai-convo__empty">No past conversations</div>+ ) : conversations.map((c) => (+ <div+ key={c.id}+ className={`sk-ai-convo__item${c.id === activeId ? ' is-active' : ''}`}+ >+ <button+ type="button"+ className="sk-ai-convo__title"+ onClick={() => { switchConversation(c.id); setOpen(false); }}+ title={c.title}+ >+ {c.title}+ </button>+ <button+ type="button"+ className="sk-ai-convo__del"+ aria-label="Delete conversation"+ onClick={() => deleteConversation(c.id)}+ >+ <Trash2 size={13} />+ </button>+ </div>+ ))}+ </div>+ </div>+ ) : null}+ </div>+ );+};++export default ConversationMenu;diff --git a/frontend/src/components/ai/DrawerHeader.jsx b/frontend/src/components/ai/DrawerHeader.jsxnew file mode 100644index 00000000..f0f71738--- /dev/null+++ b/frontend/src/components/ai/DrawerHeader.jsx@@ -0,0 +1,40 @@+import { useNavigate } from 'react-router-dom';+import { Settings, X } from 'lucide-react';+import { useAuth } from '../../contexts/AuthContext';+import { useServerkitAI } from '../../contexts/AIContext';+import ModeToggle from './ModeToggle';+import ConversationMenu from './ConversationMenu';++const DrawerHeader = () => {+ const { close } = useServerkitAI();+ const { isAdmin } = useAuth();+ const navigate = useNavigate();++ return (+ <header className="sk-ai-header">+ <div className="sk-ai-header__title">+ <span className="sk-ai-header__name">ServerKit AI</span>+ <span className="sk-ai-header__by">powered by Prompture</span>+ </div>+ <div className="sk-ai-header__actions">+ <ModeToggle />+ <ConversationMenu />+ {isAdmin ? (+ <button+ type="button"+ className="sk-ai-iconbtn"+ aria-label="AI settings"+ onClick={() => { close(); navigate('/settings?tab=ai'); }}+ >+ <Settings size={16} />+ </button>+ ) : null}+ <button type="button" className="sk-ai-iconbtn" aria-label="Close assistant" onClick={close}>+ <X size={16} />+ </button>+ </div>+ </header>+ );+};++export default DrawerHeader;diff --git a/frontend/src/components/ai/Markdown.jsx b/frontend/src/components/ai/Markdown.jsxnew file mode 100644index 00000000..726d2862--- /dev/null+++ b/frontend/src/components/ai/Markdown.jsx@@ -0,0 +1,11 @@+import { useMemo } from 'react';+import { renderMarkdownToHtml } from '../../lib/ai/markdown';++// Renders assistant text. The renderer escapes all input before injecting its+// own allowlisted tags, so dangerouslySetInnerHTML is safe here.+const Markdown = ({ text }) => {+ const html = useMemo(() => renderMarkdownToHtml(text || ''), [text]);+ return <div className="sk-ai-markdown" dangerouslySetInnerHTML={{ __html: html }} />;+};++export default Markdown;diff --git a/frontend/src/components/ai/Message.jsx b/frontend/src/components/ai/Message.jsxnew file mode 100644index 00000000..f47016fa--- /dev/null+++ b/frontend/src/components/ai/Message.jsx@@ -0,0 +1,26 @@+import Markdown from './Markdown';+import ToolCallCard from './ToolCallCard';++const Message = ({ message }) => {+ if (message.role === 'user') {+ return (+ <div className="sk-ai-message sk-ai-message--user">+ <div className="sk-ai-message__bubble">{message.content}</div>+ </div>+ );+ }++ return (+ <div className="sk-ai-message sk-ai-message--assistant">+ {(message.toolCalls || []).map((tc) => (+ <ToolCallCard key={tc.id} call={tc} />+ ))}+ {message.content ? <Markdown text={message.content} /> : null}+ {message.status === 'error' ? (+ <div className="sk-ai-message__error">{message.error || 'Something went wrong.'}</div>+ ) : null}+ </div>+ );+};++export default Message;diff --git a/frontend/src/components/ai/MessageList.jsx b/frontend/src/components/ai/MessageList.jsxnew file mode 100644index 00000000..a1bf07e3--- /dev/null+++ b/frontend/src/components/ai/MessageList.jsx@@ -0,0 +1,81 @@+import { ArrowDown, Sparkles } from 'lucide-react';+import { useServerkitAI } from '../../contexts/AIContext';+import { useContributions } from '../../plugins/contributions';+import useAutoScroll from '../../hooks/ai/useAutoScroll';+import Message from './Message';+import TypingIndicator from './TypingIndicator';+import ConfirmActionCard from './ConfirmActionCard';++const routeMatches = (pattern, route) => {+ if (!pattern || pattern === '*') return true;+ if (pattern === route) return true;+ return route.startsWith(pattern.replace(/\/?\*$/, ''));+};++const MessageList = () => {+ const {+ messages, isStreaming, pageContext, mode, ask, providerConfigured, pendingConfirm,+ } = useServerkitAI();+ const contributions = useContributions();+ const { ref, isPinned, checkPinned, scrollToBottom } = useAutoScroll([messages, isStreaming]);++ const lastAssistant = [...messages].reverse().find((m) => m.role === 'assistant');+ const showTyping = isStreaming+ && lastAssistant+ && !lastAssistant.content+ && !(lastAssistant.toolCalls || []).length+ && !pendingConfirm;++ const isEmpty = messages.length === 0;+ // Core per-page prompts + any plugin-contributed prompts matching this route.+ const corePrompts = (pageContext.suggestedPrompts || []).map((p) => ({ label: p, prompt: p }));+ const pluginPrompts = (contributions.ai?.suggested_prompts || [])+ .filter((p) => p && p.prompt && routeMatches(p.route, pageContext.route))+ .map((p) => ({ label: p.label || p.prompt, prompt: p.prompt }));+ const suggestions = mode === 'assistant' ? [...corePrompts, ...pluginPrompts] : [];++ return (+ <div className="sk-ai-messages" ref={ref} onScroll={checkPinned} aria-live="polite">+ {isEmpty ? (+ <div className="sk-ai-empty">+ <div className="sk-ai-empty__icon"><Sparkles size={22} /></div>+ <h3 className="sk-ai-empty__title">ServerKit AI</h3>+ <p className="sk-ai-empty__sub">powered by Prompture</p>+ {!providerConfigured ? (+ <p className="sk-ai-empty__hint">+ The assistant isn't configured yet. An admin can set a provider in+ {' '}Settings → AI Assistant.+ </p>+ ) : (+ <div className="sk-ai-empty__prompts">+ {suggestions.map((p) => (+ <button+ key={p.label}+ type="button"+ className="sk-ai-suggested"+ onClick={() => ask(p.prompt, { open: true })}+ >+ {p.label}+ </button>+ ))}+ </div>+ )}+ </div>+ ) : (+ <>+ {messages.map((m) => <Message key={m.id} message={m} />)}+ {showTyping ? <TypingIndicator label={lastAssistant?.thinking ? 'Thinking…' : null} /> : null}+ <ConfirmActionCard />+ </>+ )}++ {!isPinned && !isEmpty ? (+ <button type="button" className="sk-ai-jump" onClick={scrollToBottom} aria-label="Jump to latest">+ <ArrowDown size={16} />+ </button>+ ) : null}+ </div>+ );+};++export default MessageList;diff --git a/frontend/src/components/ai/ModeToggle.jsx b/frontend/src/components/ai/ModeToggle.jsxnew file mode 100644index 00000000..007eebbe--- /dev/null+++ b/frontend/src/components/ai/ModeToggle.jsx@@ -0,0 +1,29 @@+import { useServerkitAI } from '../../contexts/AIContext';++const MODES = [+ { id: 'assistant', label: 'Assistant' },+ { id: 'simple', label: 'Simple' },+];++// Assistant = tools + current-page context; Simple = plain chat, no tools.+const ModeToggle = () => {+ const { mode, setMode } = useServerkitAI();+ return (+ <div className="sk-ai-modes" role="tablist" aria-label="Chat mode">+ {MODES.map((m) => (+ <button+ key={m.id}+ type="button"+ role="tab"+ aria-selected={mode === m.id}+ className={`sk-ai-modes__item${mode === m.id ? ' is-active' : ''}`}+ onClick={() => setMode(m.id)}+ >+ {m.label}+ </button>+ ))}+ </div>+ );+};++export default ModeToggle;diff --git a/frontend/src/components/ai/ToolCallCard.jsx b/frontend/src/components/ai/ToolCallCard.jsxnew file mode 100644index 00000000..e611b0b9--- /dev/null+++ b/frontend/src/components/ai/ToolCallCard.jsx@@ -0,0 +1,74 @@+import { useState } from 'react';+import { Wrench, Check, AlertTriangle, Loader2, ChevronDown } from 'lucide-react';+import { useServerkitAI } from '../../contexts/AIContext';++// Strip the "<prefix>__" namespace for display (e.g. core__list_apps -> list_apps).+const displayName = (qualified) => {+ if (!qualified) return 'tool';+ const idx = qualified.indexOf('__');+ return idx === -1 ? qualified : qualified.slice(idx + 2);+};++const formatValue = (v) => {+ if (v == null) return '';+ if (typeof v === 'string') return v;+ try { return JSON.stringify(v, null, 2); } catch { return String(v); }+};++const ToolCallCard = ({ call }) => {+ const { getToolRenderer } = useServerkitAI();+ const [expanded, setExpanded] = useState(call.status === 'running');+ const Custom = getToolRenderer(call.name);++ const statusIcon = call.status === 'running'+ ? <Loader2 size={14} className="sk-ai-spin" />+ : call.isError+ ? <AlertTriangle size={14} />+ : <Check size={14} />;++ const inputText = Object.keys(call.input || {}).length+ ? formatValue(call.input)+ : (call.inputRaw || '');++ return (+ <div className={`sk-ai-tool-card${call.isError ? ' sk-ai-tool-card--error' : ''}`}>+ <button+ type="button"+ className="sk-ai-tool-card__head"+ onClick={() => setExpanded((v) => !v)}+ aria-expanded={expanded}+ >+ <Wrench size={14} />+ <span className="sk-ai-tool-card__name">{displayName(call.name)}</span>+ <span className={`sk-ai-tool-card__status sk-ai-tool-card__status--${call.status}`}>+ {statusIcon}+ </span>+ <ChevronDown size={14} className={`sk-ai-tool-card__chev${expanded ? ' is-open' : ''}`} />+ </button>+ {expanded && (+ <div className="sk-ai-tool-card__body">+ {Custom ? (+ <Custom input={call.input} output={call.output} isError={call.isError} />+ ) : (+ <>+ {inputText ? (+ <div className="sk-ai-tool-card__section">+ <div className="sk-ai-tool-card__label">Arguments</div>+ <pre className="sk-ai-code"><code>{inputText}</code></pre>+ </div>+ ) : null}+ {call.output != null ? (+ <div className="sk-ai-tool-card__section">+ <div className="sk-ai-tool-card__label">Result</div>+ <pre className="sk-ai-code sk-ai-tool-card__result"><code>{formatValue(call.output)}</code></pre>+ </div>+ ) : null}+ </>+ )}+ </div>+ )}+ </div>+ );+};++export default ToolCallCard;diff --git a/frontend/src/components/ai/TypingIndicator.jsx b/frontend/src/components/ai/TypingIndicator.jsxnew file mode 100644index 00000000..6577266b--- /dev/null+++ b/frontend/src/components/ai/TypingIndicator.jsx@@ -0,0 +1,10 @@+const TypingIndicator = ({ label }) => (+ <div className="sk-ai-typing" role="status" aria-label="Assistant is thinking">+ {label ? <span className="sk-ai-typing__label">{label}</span> : null}+ <span className="sk-ai-typing__dots" aria-hidden="true">+ <i /><i /><i />+ </span>+ </div>+);++export default TypingIndicator;diff --git a/frontend/src/components/settings/AISettingsTab.jsx b/frontend/src/components/settings/AISettingsTab.jsxnew file mode 100644index 00000000..3150f4b8--- /dev/null+++ b/frontend/src/components/settings/AISettingsTab.jsx@@ -0,0 +1,226 @@+import { useEffect, useState } from 'react';+import api from '../../services/api';+import { useAuth } from '../../contexts/AuthContext';+import { Switch } from '@/components/ui/switch';+import { Label } from '@/components/ui/label';+import { Button } from '@/components/ui/button';++const AI_CONFIG_CHANGED_EVENT = 'serverkit:ai-config-changed';++const AISettingsTab = () => {+ const { isAdmin } = useAuth();+ const [settings, setSettings] = useState({+ enabled: false, provider: '', model: '', endpoint: '',+ pii_redaction: true, injection_detection: true, max_cost_usd: '0.5',+ api_key_set: false,+ });+ const [providers, setProviders] = useState([]);+ const [models, setModels] = useState([]);+ const [apiKey, setApiKey] = useState(''); // write-only; '' means "unchanged"+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [testing, setTesting] = useState(false);+ const [message, setMessage] = useState(null);++ useEffect(() => {+ if (!isAdmin) { setLoading(false); return; }+ Promise.all([api.aiGetSettings(), api.aiGetProviders()])+ .then(([s, p]) => {+ setSettings((prev) => ({ ...prev, ...s, max_cost_usd: String(s.max_cost_usd ?? '0.5') }));+ setProviders(p.providers || []);+ if (s.provider) loadModels(s.provider);+ })+ .catch((e) => setMessage({ type: 'error', text: e.message || 'Failed to load AI settings' }))+ .finally(() => setLoading(false));+ }, [isAdmin]);++ const loadModels = (provider) => {+ if (!provider) { setModels([]); return; }+ api.aiGetModels(provider).then((d) => setModels(d.models || [])).catch(() => setModels([]));+ };++ const onProviderChange = (provider) => {+ setSettings((s) => ({ ...s, provider, model: '' }));+ loadModels(provider);+ };++ const buildPayload = () => {+ const payload = {+ enabled: settings.enabled,+ provider: settings.provider,+ model: settings.model,+ endpoint: settings.endpoint,+ pii_redaction: settings.pii_redaction,+ injection_detection: settings.injection_detection,+ max_cost_usd: settings.max_cost_usd,+ };+ if (apiKey.trim()) payload.api_key = apiKey.trim();+ return payload;+ };++ const handleSave = async () => {+ setSaving(true);+ setMessage(null);+ try {+ await api.aiUpdateSettings(buildPayload());+ setApiKey('');+ const fresh = await api.aiGetSettings();+ setSettings((prev) => ({ ...prev, ...fresh, max_cost_usd: String(fresh.max_cost_usd ?? '0.5') }));+ window.dispatchEvent(new Event(AI_CONFIG_CHANGED_EVENT));+ setMessage({ type: 'success', text: 'AI settings saved' });+ } catch (e) {+ setMessage({ type: 'error', text: e.message || 'Failed to save AI settings' });+ } finally {+ setSaving(false);+ }+ };++ const handleTest = async () => {+ setTesting(true);+ setMessage(null);+ try {+ const body = { provider: settings.provider, model: settings.model, endpoint: settings.endpoint };+ if (apiKey.trim()) body.api_key = apiKey.trim();+ const res = await api.aiTestSettings(body);+ setMessage(res.ok+ ? { type: 'success', text: 'Connection OK' }+ : { type: 'error', text: `Connection failed: ${res.error || 'unknown error'}` });+ } catch (e) {+ setMessage({ type: 'error', text: e.message || 'Test failed' });+ } finally {+ setTesting(false);+ }+ };++ if (!isAdmin) {+ return <div className="settings-section"><p>Admin access required.</p></div>;+ }+ if (loading) {+ return <div className="settings-section"><p>Loading…</p></div>;+ }++ const activeProvider = providers.find((p) => p.id === settings.provider);+ const needsKey = activeProvider ? activeProvider.needs_key : true;++ return (+ <div className="settings-section">+ <h2>AI Assistant</h2>+ <p className="section-description">+ Configure the in-panel assistant — powered by Prompture. The API key is stored+ encrypted and never returned by the API.+ </p>++ {message && <div className={`message ${message.type}`}>{message.text}</div>}++ <div className="settings-card">+ <div className="form-group">+ <div className="settings-row">+ <div className="settings-label"><Label>Enable AI assistant</Label></div>+ <Switch+ checked={settings.enabled}+ onCheckedChange={(v) => setSettings((s) => ({ ...s, enabled: v }))}+ />+ </div>+ </div>++ <div className="form-group">+ <label htmlFor="ai-provider">Provider</label>+ <select+ id="ai-provider"+ value={settings.provider}+ onChange={(e) => onProviderChange(e.target.value)}+ >+ <option value="">Select a provider…</option>+ {providers.map((p) => (+ <option key={p.id} value={p.id}>{p.label}</option>+ ))}+ </select>+ </div>++ <div className="form-group">+ <label htmlFor="ai-model">Model</label>+ <input+ id="ai-model"+ type="text"+ list="ai-model-options"+ placeholder="e.g. gpt-4o"+ value={settings.model}+ onChange={(e) => setSettings((s) => ({ ...s, model: e.target.value }))}+ />+ <datalist id="ai-model-options">+ {models.map((m) => <option key={m} value={m} />)}+ </datalist>+ </div>++ {needsKey && (+ <div className="form-group">+ <label htmlFor="ai-key">API key</label>+ <input+ id="ai-key"+ type="password"+ autoComplete="off"+ placeholder={settings.api_key_set ? 'Configured ✓ (leave blank to keep)' : 'Paste your API key'}+ value={apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ />+ </div>+ )}++ {activeProvider && activeProvider.supports_endpoint && (+ <div className="form-group">+ <label htmlFor="ai-endpoint">Endpoint (optional)</label>+ <input+ id="ai-endpoint"+ type="text"+ placeholder="http://localhost:11434"+ value={settings.endpoint}+ onChange={(e) => setSettings((s) => ({ ...s, endpoint: e.target.value }))}+ />+ </div>+ )}++ <div className="form-group">+ <label htmlFor="ai-max-cost">Per-conversation cost ceiling (USD)</label>+ <input+ id="ai-max-cost"+ type="number"+ step="0.1"+ min="0"+ value={settings.max_cost_usd}+ onChange={(e) => setSettings((s) => ({ ...s, max_cost_usd: e.target.value }))}+ />+ </div>++ <div className="form-group">+ <div className="settings-row">+ <div className="settings-label"><Label>Redact PII from messages & tool output</Label></div>+ <Switch+ checked={settings.pii_redaction}+ onCheckedChange={(v) => setSettings((s) => ({ ...s, pii_redaction: v }))}+ />+ </div>+ </div>+ <div className="form-group">+ <div className="settings-row">+ <div className="settings-label"><Label>Block prompt-injection attempts</Label></div>+ <Switch+ checked={settings.injection_detection}+ onCheckedChange={(v) => setSettings((s) => ({ ...s, injection_detection: v }))}+ />+ </div>+ </div>++ <div className="settings-actions" style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>+ <Button variant="outline" onClick={handleTest} disabled={testing || !settings.provider || !settings.model}>+ {testing ? 'Testing…' : 'Test connection'}+ </Button>+ <Button variant="primary" onClick={handleSave} disabled={saving}>+ {saving ? 'Saving…' : 'Save'}+ </Button>+ </div>+ </div>+ </div>+ );+};++export default AISettingsTab;diff --git a/frontend/src/contexts/AIContext.jsx b/frontend/src/contexts/AIContext.jsxnew file mode 100644index 00000000..a836e58a--- /dev/null+++ b/frontend/src/contexts/AIContext.jsx@@ -0,0 +1,357 @@+import {+ createContext, useCallback, useContext, useEffect, useMemo, useReducer, useRef,+} from 'react';+import api from '../services/api';+import usePageContext from '../hooks/ai/usePageContext';++const AIContext = createContext(null);++const AI_CONFIG_CHANGED_EVENT = 'serverkit:ai-config-changed';++const newId = () => (globalThis.crypto?.randomUUID?.() || `m_${Math.random().toString(36).slice(2)}`);++const initialState = {+ open: false,+ mode: 'assistant', // 'assistant' (tools + context) | 'simple'+ includeContext: true,+ providerConfigured: false,+ statusLoaded: false,+ conversations: [],+ activeId: null,+ messages: [], // [{ id, role, content, toolCalls, thinking, status, error }]+ isStreaming: false,+ error: null,+ pendingConfirm: null,+ unread: 0,+};++// Mutate the last assistant message (the one currently streaming).+function patchLastAssistant(messages, patch) {+ const next = [...messages];+ for (let i = next.length - 1; i >= 0; i--) {+ if (next[i].role === 'assistant') {+ next[i] = typeof patch === 'function' ? patch(next[i]) : { ...next[i], ...patch };+ break;+ }+ }+ return next;+}++function reducer(state, action) {+ switch (action.type) {+ case 'SET_OPEN':+ return { ...state, open: action.open, unread: action.open ? 0 : state.unread };+ case 'TOGGLE_OPEN':+ return { ...state, open: !state.open, unread: !state.open ? 0 : state.unread };+ case 'SET_MODE':+ return { ...state, mode: action.mode };+ case 'SET_INCLUDE_CONTEXT':+ return { ...state, includeContext: action.value };+ case 'SET_STATUS':+ return { ...state, providerConfigured: action.configured, statusLoaded: true };+ case 'SET_CONVERSATIONS':+ return { ...state, conversations: action.conversations };+ case 'SET_ACTIVE':+ return { ...state, activeId: action.id };+ case 'LOAD_MESSAGES':+ return { ...state, messages: action.messages, activeId: action.id, pendingConfirm: null, error: null };+ case 'NEW_CONVERSATION':+ return { ...state, activeId: null, messages: [], pendingConfirm: null, error: null };+ case 'ADD_USER_MESSAGE':+ return {+ ...state,+ messages: [...state.messages, { id: action.id, role: 'user', content: action.content, status: 'done' }],+ };+ case 'BEGIN_ASSISTANT':+ return {+ ...state,+ isStreaming: true,+ error: null,+ messages: [...state.messages, {+ id: action.id, role: 'assistant', content: '', thinking: '',+ toolCalls: [], status: 'streaming',+ }],+ };+ case 'APPEND_TEXT':+ return { ...state, messages: patchLastAssistant(state.messages, (m) => ({ ...m, content: m.content + action.text })) };+ case 'APPEND_THINKING':+ return { ...state, messages: patchLastAssistant(state.messages, (m) => ({ ...m, thinking: (m.thinking || '') + action.text })) };+ case 'TOOL_START':+ return {+ ...state,+ messages: patchLastAssistant(state.messages, (m) => ({+ ...m,+ toolCalls: [...m.toolCalls, { id: action.id, name: action.name, input: {}, output: null, isError: false, status: 'running' }],+ })),+ };+ case 'TOOL_INPUT_DELTA':+ return {+ ...state,+ messages: patchLastAssistant(state.messages, (m) => ({+ ...m,+ toolCalls: m.toolCalls.map((tc) => (tc.id === action.id+ ? { ...tc, inputRaw: (tc.inputRaw || '') + action.fragment } : tc)),+ })),+ };+ case 'TOOL_STOP':+ return {+ ...state,+ messages: patchLastAssistant(state.messages, (m) => ({+ ...m,+ toolCalls: m.toolCalls.map((tc) => (tc.id === action.id+ ? { ...tc, input: action.input || tc.input, name: action.name || tc.name } : tc)),+ })),+ };+ case 'TOOL_RESULT':+ return {+ ...state,+ messages: patchLastAssistant(state.messages, (m) => ({+ ...m,+ toolCalls: m.toolCalls.map((tc) => (tc.id === action.id+ ? { ...tc, output: action.output, isError: action.isError, status: action.isError ? 'error' : 'done' } : tc)),+ })),+ };+ case 'SET_PENDING_CONFIRM':+ return { ...state, pendingConfirm: action.payload };+ case 'CLEAR_PENDING_CONFIRM':+ return { ...state, pendingConfirm: null };+ case 'TURN_DONE':+ return {+ ...state,+ isStreaming: false,+ activeId: action.conversationId || state.activeId,+ unread: state.open ? 0 : state.unread + 1,+ messages: patchLastAssistant(state.messages, (m) => ({ ...m, status: m.status === 'streaming' ? 'done' : m.status })),+ };+ case 'SET_ERROR':+ return {+ ...state,+ isStreaming: false,+ error: action.message,+ messages: patchLastAssistant(state.messages, (m) => (+ m.status === 'streaming' ? { ...m, status: 'error', error: action.message } : m+ )),+ };+ case 'SET_STREAMING':+ return { ...state, isStreaming: action.value };+ default:+ return state;+ }+}++export function AIProvider({ children }) {+ const [state, dispatch] = useReducer(reducer, initialState);+ const pageContext = usePageContext();++ const abortRef = useRef(null);+ const activeIdRef = useRef(null);+ const contextProviders = useRef(new Map()); // routePattern -> fn+ const toolRenderers = useRef(new Map()); // toolName -> Component++ useEffect(() => { activeIdRef.current = state.activeId; }, [state.activeId]);++ // --- status ---+ const loadStatus = useCallback(() => {+ api.aiStatus()+ .then((s) => dispatch({ type: 'SET_STATUS', configured: !!s.configured }))+ .catch(() => dispatch({ type: 'SET_STATUS', configured: false }));+ }, []);++ useEffect(() => {+ loadStatus();+ const onChanged = () => loadStatus();+ window.addEventListener(AI_CONFIG_CHANGED_EVENT, onChanged);+ return () => window.removeEventListener(AI_CONFIG_CHANGED_EVENT, onChanged);+ }, [loadStatus]);++ // --- conversations ---+ const loadConversations = useCallback(() => {+ api.aiListConversations()+ .then((d) => dispatch({ type: 'SET_CONVERSATIONS', conversations: d.conversations || [] }))+ .catch(() => {});+ }, []);++ const switchConversation = useCallback(async (id) => {+ try {+ const data = await api.aiGetConversation(id);+ const messages = (data.messages || []).map((m) => ({+ id: `srv_${m.id}`,+ role: m.role === 'assistant' ? 'assistant' : 'user',+ content: m.content || '',+ toolCalls: (m.tool_calls || []).map((tc) => ({+ id: tc.id, name: tc.name, input: tc.input, output: tc.output,+ isError: tc.is_error, status: tc.is_error ? 'error' : 'done',+ })),+ status: 'done',+ })).filter((m) => m.role === 'user' || m.content || m.toolCalls.length);+ dispatch({ type: 'LOAD_MESSAGES', messages, id });+ } catch { /* ignore */ }+ }, []);++ const newConversation = useCallback(() => dispatch({ type: 'NEW_CONVERSATION' }), []);++ const deleteConversation = useCallback(async (id) => {+ try { await api.aiDeleteConversation(id); } catch { /* ignore */ }+ if (activeIdRef.current === id) dispatch({ type: 'NEW_CONVERSATION' });+ loadConversations();+ }, [loadConversations]);++ // --- page context assembly (core + plugin providers + caller extra) ---+ const buildPageContext = useCallback((extra) => {+ const ctx = { route: pageContext.route, label: pageContext.label, ids: { ...pageContext.ids } };+ for (const [pattern, fn] of contextProviders.current.entries()) {+ try {+ if (matchRoute(pattern, pageContext.route)) {+ const provided = fn();+ if (provided && typeof provided === 'object') Object.assign(ctx, provided);+ }+ } catch { /* ignore provider errors */ }+ }+ if (extra && typeof extra === 'object') Object.assign(ctx, extra);+ return ctx;+ }, [pageContext]);++ // --- SSE event handling ---+ const handleEvent = useCallback(({ event, data }) => {+ switch (event) {+ case 'open':+ if (data.conversation_id) { activeIdRef.current = data.conversation_id; dispatch({ type: 'SET_ACTIVE', id: data.conversation_id }); }+ break;+ case 'text_delta': dispatch({ type: 'APPEND_TEXT', text: data.text || '' }); break;+ case 'thinking_delta': dispatch({ type: 'APPEND_THINKING', text: data.text || '' }); break;+ case 'tool_use_start': dispatch({ type: 'TOOL_START', id: data.id, name: data.name }); break;+ case 'tool_input_delta': dispatch({ type: 'TOOL_INPUT_DELTA', id: data.id, fragment: data.fragment || '' }); break;+ case 'tool_use_stop': dispatch({ type: 'TOOL_STOP', id: data.id, name: data.name, input: data.input }); break;+ case 'tool_result': dispatch({ type: 'TOOL_RESULT', id: data.id, output: data.output, isError: !!data.is_error }); break;+ case 'pending_action': dispatch({ type: 'SET_PENDING_CONFIRM', payload: data }); break;+ case 'error': dispatch({ type: 'SET_ERROR', message: data.message || 'The assistant hit an error.' }); break;+ case 'done': dispatch({ type: 'TURN_DONE', conversationId: data.conversation_id }); break;+ default: break;+ }+ }, []);++ // --- send a message ---+ const send = useCallback(async (prompt, opts = {}) => {+ const text = (prompt || '').trim();+ if (!text || state.isStreaming) return;+ const mode = opts.mode || state.mode;+ const payload = {+ conversation_id: activeIdRef.current || undefined,+ message: text,+ mode,+ };+ if (mode === 'assistant' && state.includeContext) {+ payload.page_context = buildPageContext(opts.context);+ } else if (opts.context) {+ payload.page_context = opts.context;+ }++ dispatch({ type: 'ADD_USER_MESSAGE', id: newId(), content: text });+ dispatch({ type: 'BEGIN_ASSISTANT', id: newId() });++ const controller = new AbortController();+ abortRef.current = controller;+ try {+ await api.aiStreamChat(payload, { signal: controller.signal, onEvent: handleEvent });+ } catch (e) {+ if (e.name !== 'AbortError') {+ dispatch({ type: 'SET_ERROR', message: e.message || 'AI request failed' });+ } else {+ dispatch({ type: 'SET_STREAMING', value: false });+ }+ } finally {+ abortRef.current = null;+ loadConversations();+ }+ }, [state.isStreaming, state.mode, state.includeContext, buildPageContext, handleEvent, loadConversations]);++ const stop = useCallback(() => {+ abortRef.current?.abort();+ const id = activeIdRef.current;+ if (id) api.aiCancel(id).catch(() => {});+ dispatch({ type: 'CLEAR_PENDING_CONFIRM' });+ }, []);++ const confirmAction = useCallback(async (decision) => {+ const pending = state.pendingConfirm;+ if (!pending) return;+ dispatch({ type: 'CLEAR_PENDING_CONFIRM' });+ try {+ await api.aiConfirmAction({+ conversation_id: activeIdRef.current,+ action_token: pending.action_token,+ decision,+ });+ // The worker resumes on the SAME open stream — no new request needed.+ } catch (e) {+ dispatch({ type: 'SET_ERROR', message: e.message || 'Could not submit your decision' });+ }+ }, [state.pendingConfirm]);++ // --- imperative controls ---+ const open = useCallback((prompt, opts) => {+ dispatch({ type: 'SET_OPEN', open: true });+ if (!state.conversations.length) loadConversations();+ if (prompt) setTimeout(() => send(prompt, opts), 0);+ }, [send, loadConversations, state.conversations.length]);++ const close = useCallback(() => dispatch({ type: 'SET_OPEN', open: false }), []);+ const toggle = useCallback(() => {+ dispatch({ type: 'TOGGLE_OPEN' });+ if (!state.open && !state.conversations.length) loadConversations();+ }, [state.open, state.conversations.length, loadConversations]);++ const ask = useCallback((prompt, opts = {}) => {+ if (opts.open !== false) dispatch({ type: 'SET_OPEN', open: true });+ if (opts.mode) dispatch({ type: 'SET_MODE', mode: opts.mode });+ send(prompt, opts);+ }, [send]);++ const setMode = useCallback((mode) => dispatch({ type: 'SET_MODE', mode }), []);+ const setIncludeContext = useCallback((value) => dispatch({ type: 'SET_INCLUDE_CONTEXT', value }), []);++ // --- plugin registries (returned to plugin components via useServerkitAI) ---+ const registerContextProvider = useCallback((routePattern, fn) => {+ contextProviders.current.set(routePattern, fn);+ return () => contextProviders.current.delete(routePattern);+ }, []);+ const registerToolRenderer = useCallback((toolName, Component) => {+ toolRenderers.current.set(toolName, Component);+ return () => toolRenderers.current.delete(toolName);+ }, []);+ const getToolRenderer = useCallback((toolName) => toolRenderers.current.get(toolName) || null, []);++ const value = useMemo(() => ({+ // state+ ...state,+ isOpen: state.open,+ pageContext,+ // controls+ open, close, toggle, ask, send, stop, confirmAction, setMode, setIncludeContext,+ loadConversations, switchConversation, newConversation, deleteConversation, loadStatus,+ // plugin SDK surface+ registerContextProvider, registerToolRenderer, getToolRenderer,+ }), [+ state, pageContext, open, close, toggle, ask, send, stop, confirmAction, setMode,+ setIncludeContext, loadConversations, switchConversation, newConversation,+ deleteConversation, loadStatus, registerContextProvider, registerToolRenderer, getToolRenderer,+ ]);++ return <AIContext.Provider value={value}>{children}</AIContext.Provider>;+}++function matchRoute(pattern, route) {+ if (!pattern || !route) return false;+ if (pattern === route) return true;+ if (pattern.endsWith('/*')) return route.startsWith(pattern.slice(0, -1));+ if (pattern.endsWith('*')) return route.startsWith(pattern.slice(0, -1));+ return route === pattern || route.startsWith(`${pattern}/`);+}++export function useServerkitAI() {+ const ctx = useContext(AIContext);+ if (!ctx) throw new Error('useServerkitAI must be used within AIProvider');+ return ctx;+}++export { AIContext };diff --git a/frontend/src/hooks/ai/useAutoScroll.js b/frontend/src/hooks/ai/useAutoScroll.jsnew file mode 100644index 00000000..01d50de7--- /dev/null+++ b/frontend/src/hooks/ai/useAutoScroll.js@@ -0,0 +1,33 @@+import { useCallback, useEffect, useRef, useState } from 'react';++// Keeps a scroll container pinned to the bottom as content streams in, unless+// the user has scrolled up (then we stop auto-scrolling and expose `isPinned`+// so the UI can show a "jump to latest" affordance). `deps` triggers a+// re-scroll when content changes.+export default function useAutoScroll(deps) {+ const ref = useRef(null);+ const [isPinned, setIsPinned] = useState(true);++ const checkPinned = useCallback(() => {+ const el = ref.current;+ if (!el) return;+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight;+ setIsPinned(distance < 48);+ }, []);++ const scrollToBottom = useCallback(() => {+ const el = ref.current;+ if (el) el.scrollTop = el.scrollHeight;+ setIsPinned(true);+ }, []);++ useEffect(() => {+ if (isPinned) {+ const el = ref.current;+ if (el) el.scrollTop = el.scrollHeight;+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [deps]);++ return { ref, isPinned, checkPinned, scrollToBottom };+}diff --git a/frontend/src/hooks/ai/useFocusTrap.js b/frontend/src/hooks/ai/useFocusTrap.jsnew file mode 100644index 00000000..eb9b58c0--- /dev/null+++ b/frontend/src/hooks/ai/useFocusTrap.js@@ -0,0 +1,51 @@+import { useEffect } from 'react';++const FOCUSABLE = [+ 'a[href]', 'button:not([disabled])', 'textarea:not([disabled])',+ 'input:not([disabled])', 'select:not([disabled])', '[tabindex]:not([tabindex="-1"])',+].join(',');++// Traps focus within `ref` while `active`, calls `onEscape` on Esc, and+// restores focus to `restoreFocusRef` (or the previously focused element) on+// deactivation.+export default function useFocusTrap(ref, { active, onEscape, restoreFocusRef } = {}) {+ useEffect(() => {+ if (!active || !ref.current) return undefined;+ const node = ref.current;+ const previouslyFocused = document.activeElement;++ const focusFirst = () => {+ const focusable = node.querySelectorAll(FOCUSABLE);+ (focusable[0] || node).focus?.();+ };+ focusFirst();++ const onKeyDown = (e) => {+ if (e.key === 'Escape') {+ onEscape?.();+ return;+ }+ if (e.key !== 'Tab') return;+ const focusable = Array.from(node.querySelectorAll(FOCUSABLE)).filter(+ (el) => el.offsetParent !== null,+ );+ if (!focusable.length) return;+ const first = focusable[0];+ const last = focusable[focusable.length - 1];+ if (e.shiftKey && document.activeElement === first) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ };++ node.addEventListener('keydown', onKeyDown);+ return () => {+ node.removeEventListener('keydown', onKeyDown);+ const restoreTo = restoreFocusRef?.current || previouslyFocused;+ restoreTo?.focus?.();+ };+ }, [active, ref, onEscape, restoreFocusRef]);+}diff --git a/frontend/src/hooks/ai/usePageContext.js b/frontend/src/hooks/ai/usePageContext.jsnew file mode 100644index 00000000..a4116b76--- /dev/null+++ b/frontend/src/hooks/ai/usePageContext.js@@ -0,0 +1,15 @@+import { useMemo } from 'react';+import { useLocation, useParams } from 'react-router-dom';+import { getCoreContext, getSuggestedPrompts } from '../../lib/ai/pageContextMap';++// Resolves the current route into the assistant's page context (label + entity+// ids) plus page-appropriate suggested prompts. Plugin-registered context+// providers are merged on top by AIContext when a message is sent.+export default function usePageContext() {+ const location = useLocation();+ const params = useParams();+ return useMemo(() => {+ const ctx = getCoreContext(location.pathname, params);+ return { ...ctx, suggestedPrompts: getSuggestedPrompts(ctx.entity) };+ }, [location.pathname, params]);+}diff --git a/frontend/src/layouts/DashboardLayout.jsx b/frontend/src/layouts/DashboardLayout.jsxindex 3e679c24..fb4ffddf 100644--- a/frontend/src/layouts/DashboardLayout.jsx+++ b/frontend/src/layouts/DashboardLayout.jsx@@ -5,6 +5,8 @@ import MobileTopBar from '../components/MobileTopBar';import CommandPalette from '../components/CommandPalette';import LogsDrawer from '../components/LogsDrawer';import { LogsDrawerProvider } from '../contexts/LogsDrawerContext';+import { AIProvider } from '../contexts/AIContext';+import AIAssistant from '../components/ai/AIAssistant';import PluginLoader from '../plugins/PluginLoader';import { refreshContributions, useContributions } from '../plugins/contributions';import useMediaQuery from '../hooks/useMediaQuery';@@ -77,6 +79,7 @@ const DashboardLayout = () => {return (<LogsDrawerProvider>+ <AIProvider><div className="dashboard-layout"><MobileTopBar navOpen={navOpen} onToggle={() => setNavOpen(prev => !prev)} /><Sidebar@@ -96,8 +99,10 @@ const DashboardLayout = () => {</main><CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} /><LogsDrawer />+ <AIAssistant /><PluginLoader api={api} /></div>+ </AIProvider></LogsDrawerProvider>);};diff --git a/frontend/src/lib/ai/markdown.js b/frontend/src/lib/ai/markdown.jsnew file mode 100644index 00000000..fbd17fff--- /dev/null+++ b/frontend/src/lib/ai/markdown.js@@ -0,0 +1,67 @@+// Minimal, dependency-free, XSS-safe markdown renderer for assistant messages.+//+// Strategy: extract fenced code blocks, escape ALL remaining HTML, then apply a+// small allowlist of transforms (inline code, bold, links, paragraphs/line+// breaks). Because everything is escaped before we inject our own tags, raw+// HTML in the model output can never execute. This intentionally supports only+// what a chat assistant typically emits; swap in `marked` + `DOMPurify` later+// if richer markdown is needed.++// Sentinel char that cannot appear in normal text and survives HTML-escaping.+const S = String.fromCharCode(0);++function escapeHtml(s) {+ return s+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}++export function renderMarkdownToHtml(src) {+ if (!src) return '';++ // 1) Pull out fenced code blocks first (contents escaped, never transformed).+ const codeBlocks = [];+ let text = String(src).replace(/```(\w*)\n?([\s\S]*?)```/g, (_m, lang, code) => {+ const i = codeBlocks.length;+ const label = lang ? `<span class="sk-ai-code__lang">${escapeHtml(lang)}</span>` : '';+ codeBlocks.push(+ `<pre class="sk-ai-code">${label}<code>${escapeHtml(code.replace(/\n$/, ''))}</code></pre>`,+ );+ return `${S}CODE${i}${S}`;+ });++ // 2) Escape everything else.+ text = escapeHtml(text);++ // 3) Inline code (escaped content already).+ const inline = [];+ text = text.replace(/`([^`\n]+)`/g, (_m, c) => {+ const i = inline.length;+ inline.push(`<code class="sk-ai-inline-code">${c}</code>`);+ return `${S}INL${i}${S}`;+ });++ // 4) Bold + links.+ text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');+ text = text.replace(+ /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,+ (_m, label, url) => `<a href="${url}" target="_blank" rel="noopener noreferrer">${label}</a>`,+ );++ // 5) Paragraphs + line breaks.+ text = text+ .split(/\n{2,}/)+ .map((para) => {+ const block = para.trim();+ if (!block) return '';+ if (new RegExp(`^${S}CODE\\d+${S}$`).test(block)) return block; // standalone code block+ return `<p>${block.replace(/\n/g, '<br>')}</p>`;+ })+ .join('');++ // 6) Restore placeholders.+ text = text.replace(new RegExp(`${S}INL(\\d+)${S}`, 'g'), (_m, i) => inline[+i] || '');+ text = text.replace(new RegExp(`${S}CODE(\\d+)${S}`, 'g'), (_m, i) => codeBlocks[+i] || '');+ return text;+}diff --git a/frontend/src/lib/ai/pageContextMap.js b/frontend/src/lib/ai/pageContextMap.jsnew file mode 100644index 00000000..c6896cb4--- /dev/null+++ b/frontend/src/lib/ai/pageContextMap.js@@ -0,0 +1,57 @@+// Maps the current route to a human-readable context label + entity ids the+// assistant can use ("this server", "this app"), plus per-page suggested+// prompts for the empty state. Ordered: first matching pattern wins.++const ROUTES = [+ { re: /^\/docker(\/|$)/, label: 'Docker', entity: 'docker' },+ { re: /^\/services\/([^/]+)$/, label: 'Service', entity: 'service', idKey: 'service_id' },+ { re: /^\/services(\/|$)/, label: 'Services', entity: 'services' },+ { re: /^\/apps\/([^/]+)/, label: 'Application', entity: 'app', idKey: 'app_id' },+ { re: /^\/apps(\/|$)/, label: 'Applications', entity: 'apps' },+ { re: /^\/databases(\/|$)/, label: 'Databases', entity: 'databases' },+ { re: /^\/wordpress\/([^/]+)/, label: 'WordPress site', entity: 'wp_site', idKey: 'site_id' },+ { re: /^\/wordpress(\/|$)/, label: 'WordPress', entity: 'wordpress' },+ { re: /^\/servers\/([^/]+)/, label: 'Server', entity: 'server', idKey: 'server_id' },+ { re: /^\/servers(\/|$)/, label: 'Servers', entity: 'servers' },+ { re: /^\/fleet/, label: 'Fleet', entity: 'fleet' },+ { re: /^\/monitoring(\/|$)/, label: 'Monitoring', entity: 'monitoring' },+ { re: /^\/security(\/|$)/, label: 'Security', entity: 'security' },+ { re: /^\/backups(\/|$)/, label: 'Backups', entity: 'backups' },+ { re: /^\/dns(\/|$)/, label: 'DNS', entity: 'dns' },+ { re: /^\/domains(\/|$)/, label: 'Domains', entity: 'domains' },+ { re: /^\/files(\/|$)/, label: 'File Manager', entity: 'files' },+ { re: /^\/marketplace/, label: 'Marketplace', entity: 'marketplace' },+ { re: /^\/$/, label: 'Dashboard', entity: 'dashboard' },+];++const SUGGESTED = {+ docker: ['List my running containers', "Why might a container keep restarting?"],+ apps: ['List my applications and their status', 'Which apps are unhealthy?'],+ app: ['Summarize the status of this application'],+ databases: ['List my databases', 'How big is each database?'],+ monitoring: ["What's my current CPU, memory, and disk usage?"],+ servers: ['List the servers in my fleet'],+ server: ["Summarize this server's health"],+ dashboard: ['What can you do?', "Give me a quick health summary of this panel"],+};++const GLOBAL_SUGGESTED = ['What can you do?', "What's my system's CPU and memory usage?"];++export function getCoreContext(pathname, params = {}) {+ for (const entry of ROUTES) {+ const m = pathname.match(entry.re);+ if (!m) continue;+ const ids = {};+ if (entry.idKey && m[1]) ids[entry.idKey] = m[1];+ // Merge any router params (covers deeper routes).+ for (const [k, v] of Object.entries(params || {})) {+ if (v != null) ids[k] = v;+ }+ return { route: pathname, label: entry.label, entity: entry.entity, ids };+ }+ return { route: pathname, label: 'Dashboard', entity: 'dashboard', ids: {} };+}++export function getSuggestedPrompts(entity) {+ return SUGGESTED[entity] || GLOBAL_SUGGESTED;+}diff --git a/frontend/src/lib/ai/sse.js b/frontend/src/lib/ai/sse.jsnew file mode 100644index 00000000..8ee7c713--- /dev/null+++ b/frontend/src/lib/ai/sse.js@@ -0,0 +1,40 @@+// Incremental Server-Sent-Events parser for the AI chat stream.+//+// Frames are separated by a blank line. Each frame has an optional `event:`+// line and one or more `data:` lines (JSON). Lines starting with `:` are+// comments (our keepalive heartbeat) and are ignored. Returns the parsed+// events plus any trailing partial frame to carry into the next read.++export function parseSSEChunk(buffer) {+ const events = [];+ const sep = buffer.lastIndexOf('\n\n');+ if (sep === -1) {+ return { events, rest: buffer };+ }+ const complete = buffer.slice(0, sep);+ const rest = buffer.slice(sep + 2);++ for (const block of complete.split('\n\n')) {+ if (!block.trim()) continue;+ let eventName = 'message';+ const dataLines = [];+ for (const line of block.split('\n')) {+ if (line.startsWith(':')) continue; // comment / keepalive+ if (line.startsWith('event:')) {+ eventName = line.slice(6).trim();+ } else if (line.startsWith('data:')) {+ dataLines.push(line.slice(5).replace(/^ /, ''));+ }+ }+ if (!dataLines.length && eventName === 'message') continue;+ const raw = dataLines.join('\n');+ let data = {};+ try {+ data = raw ? JSON.parse(raw) : {};+ } catch {+ data = { raw };+ }+ events.push({ event: eventName, data });+ }+ return { events, rest };+}diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex d385eccb..0c3c33ef 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -17,12 +17,13 @@ import SourceConnectionsTab from '../components/settings/SourceConnectionsTab';import ApiSettingsTab from '../components/settings/ApiSettingsTab';import MigrationHistoryTab from '../components/settings/MigrationHistoryTab';import IconReferenceTab from '../components/settings/IconReferenceTab';+import AISettingsTab from '../components/settings/AISettingsTab';import AboutTab from '../components/settings/AboutTab';-import { Activity, Code, Database, Layers, Link2, PaintBucket } from 'lucide-react';+import { Activity, Code, Database, Layers, Link2, PaintBucket, Sparkles } from 'lucide-react';import { Button } from '@/components/ui/button';import { useNavigate } from 'react-router-dom';-const VALID_TABS = ['profile', 'security', 'connections', 'appearance', 'sidebar', 'whitelabel', 'notifications', 'system', 'users', 'activity', 'site', 'sso', 'api', 'migrations', 'developer', 'about'];+const VALID_TABS = ['profile', 'security', 'connections', 'appearance', 'sidebar', 'whitelabel', 'notifications', 'system', 'users', 'activity', 'site', 'sso', 'api', 'ai', 'migrations', 'developer', 'about'];const Settings = () => {const [activeTab, setActiveTab] = useTabParam('/settings', VALID_TABS);@@ -184,6 +185,14 @@ const Settings = () => {<Code size={18} />API</Button>+ <Button+ variant="ghost"+ className={`settings-nav-item ${activeTab === 'ai' ? 'active' : ''}`}+ onClick={() => setActiveTab('ai')}+ >+ <Sparkles size={18} />+ AI Assistant+ </Button><Buttonvariant="ghost"className={`settings-nav-item ${activeTab === 'migrations' ? 'active' : ''}`}@@ -267,6 +276,7 @@ const Settings = () => {{activeTab === 'site' && isAdmin && <SiteSettingsTab onDevModeChange={setDevMode} />}{activeTab === 'sso' && isAdmin && <SSOConfigTab />}{activeTab === 'api' && isAdmin && <ApiSettingsTab />}+ {activeTab === 'ai' && isAdmin && <AISettingsTab />}{activeTab === 'migrations' && isAdmin && <MigrationHistoryTab />}{activeTab === 'system' && isAdmin && <SystemTab />}{activeTab === 'developer' && devMode && isAdmin && <IconReferenceTab />}diff --git a/frontend/src/plugins/contributions.js b/frontend/src/plugins/contributions.jsindex ced7417d..a718ec23 100644--- a/frontend/src/plugins/contributions.js+++ b/frontend/src/plugins/contributions.js@@ -75,6 +75,10 @@ const EMPTY = {command_palette: [],widgets: [],layouts: [],+ // AI assistant contributions: per-route suggested prompts + custom+ // tool-result renderers. Consumed by the core AIAssistant via+ // useContributions().ai.+ ai: { suggested_prompts: [], tool_renderers: [] },};const GIT_PLUGIN_SLUG = 'serverkit-git';@@ -151,6 +155,7 @@ function getBuildTimeContributions() {const command_palette = [];const widgets = [];const layouts = [];+ const ai = { suggested_prompts: [], tool_renderers: [] };for (const entry of installed) {const slug = entry?.slug || entry?.name;@@ -166,6 +171,11 @@ function getBuildTimeContributions() {widgets.push(...tagItems(contrib.widgets, slug));layouts.push(...tagItems(contrib.layouts, slug));+ if (contrib.ai && typeof contrib.ai === 'object') {+ ai.suggested_prompts.push(...tagItems(contrib.ai.suggested_prompts, slug));+ ai.tool_renderers.push(...tagItems(contrib.ai.tool_renderers, slug));+ }+if (contrib.page_titles && typeof contrib.page_titles === 'object') {Object.assign(page_titles, contrib.page_titles);}@@ -178,6 +188,7 @@ function getBuildTimeContributions() {command_palette,widgets,layouts,+ ai,};}diff --git a/frontend/src/plugins/sdk/index.js b/frontend/src/plugins/sdk/index.jsindex bc6b3a91..97af2ec2 100644--- a/frontend/src/plugins/sdk/index.js+++ b/frontend/src/plugins/sdk/index.js@@ -37,6 +37,19 @@ export { useToast } from '../../contexts/ToastContext';export { useAuth } from '../../contexts/AuthContext';export { useTheme } from '../../contexts/ThemeContext';+// AI assistant — plugins consume the core assistant rather than building their+// own chat UI. `useServerkitAI()` exposes:+// open() / close() / toggle() / isOpen+// ask(prompt, { context?, mode?: 'assistant'|'simple', open?=true })+// mode / setMode(mode)+// registerContextProvider(routePattern, () => contextObj) -> unregister+// registerToolRenderer(toolName, Component) -> unregister+// isStreaming / providerConfigured+//+// Plugins can also declare contributions.ai = { suggested_prompts: [{route,label,prompt}],+// tool_renderers: [{tool, component}] } in plugin.json.+export { useServerkitAI, AIContext } from '../../contexts/AIContext';+// Routing helpers — plugin pages need these to navigate within the SPA.export {Link,diff --git a/frontend/src/services/api/ai.js b/frontend/src/services/api/ai.jsnew file mode 100644index 00000000..ef3f95c8--- /dev/null+++ b/frontend/src/services/api/ai.js@@ -0,0 +1,98 @@+// AI assistant API methods (core primitive — powered by Prompture).+//+// These are bound onto the shared ApiService instance (see services/api/index.js),+// so they run with `this` = the client and reuse `this.baseUrl` / `this.getToken()`.+// All names are prefixed `ai*` to avoid collisions with other domain modules.+//+// `aiStreamChat` does its own fetch + ReadableStream read (the base `request()`+// isn't stream-aware) so the JWT rides in the Authorization header — no token in+// the URL, unlike EventSource.+import { parseSSEChunk } from '../../lib/ai/sse';++export async function aiStatus() {+ return this.request('/ai/status');+}++export async function aiGetSettings() {+ return this.request('/ai/settings');+}++export async function aiUpdateSettings(body) {+ return this.request('/ai/settings', { method: 'PUT', body });+}++export async function aiTestSettings(body) {+ return this.request('/ai/settings/test', { method: 'POST', body });+}++export async function aiGetProviders() {+ return this.request('/ai/providers');+}++export async function aiGetModels(provider) {+ return this.request(`/ai/models?provider=${encodeURIComponent(provider)}`);+}++export async function aiListConversations() {+ return this.request('/ai/conversations');+}++export async function aiCreateConversation(body = {}) {+ return this.request('/ai/conversations', { method: 'POST', body });+}++export async function aiGetConversation(id) {+ return this.request(`/ai/conversations/${id}`);+}++export async function aiRenameConversation(id, title) {+ return this.request(`/ai/conversations/${id}`, { method: 'PATCH', body: { title } });+}++export async function aiDeleteConversation(id) {+ return this.request(`/ai/conversations/${id}`, { method: 'DELETE' });+}++export async function aiConfirmAction(body) {+ return this.request('/ai/chat/confirm', { method: 'POST', body });+}++export async function aiCancel(conversationId) {+ return this.request('/ai/chat/cancel', { method: 'POST', body: { conversation_id: conversationId } });+}++// Streaming turn. Reads SSE frames and calls onEvent({ event, data }) for each.+// Resolves when the stream ends; throws on a non-OK pre-flight response.+export async function aiStreamChat(payload, { signal, onEvent } = {}) {+ const token = this.getToken();+ const res = await fetch(`${this.baseUrl}/ai/chat/stream`, {+ method: 'POST',+ signal,+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'text/event-stream',+ ...(token && { Authorization: `Bearer ${token}` }),+ },+ body: JSON.stringify(payload),+ });+ if (!res.ok || !res.body) {+ let data = {};+ try { data = await res.json(); } catch { /* non-JSON error body */ }+ const err = new Error(data.error || data.msg || 'AI stream failed');+ err.status = res.status;+ throw err;+ }+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ const { events, rest } = parseSSEChunk(buffer);+ buffer = rest;+ for (const ev of events) {+ if (onEvent) onEvent(ev);+ }+ }+}diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex 6af848ef..a56857a2 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -13,6 +13,7 @@ import * as pluginMethods from './plugins.js';import * as deploymentJobMethods from './deploymentJobs.js';import * as pairingMethods from './pairing.js';import * as sourceConnectionMethods from './sourceConnections.js';+import * as aiMethods from './ai.js';class ApiService extends ApiClient {constructor() {@@ -33,6 +34,7 @@ class ApiService extends ApiClient {deploymentJobMethods,pairingMethods,sourceConnectionMethods,+ aiMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/styles/components/_ai-assistant.scss b/frontend/src/styles/components/_ai-assistant.scssnew file mode 100644index 00000000..03de9fe7--- /dev/null+++ b/frontend/src/styles/components/_ai-assistant.scss@@ -0,0 +1,459 @@+// ServerKit AI assistant — core primitive (powered by Prompture).+// Scoped under .sk-ai-* and themed entirely through runtime CSS custom+// properties (with fallbacks) so it follows dark/light/accent automatically.+// Owns its own z-index as a core overlay — no plugin coexistence hacks.++$sk-ai-z: 1100;++%sk-ai-tokens {+ --sk-ai-bg: var(--bg-card, #18181b);+ --sk-ai-bg-body: var(--bg-body, #09090b);+ --sk-ai-hover: var(--bg-hover, #27272a);+ --sk-ai-elevated: var(--bg-elevated, #1f1f23);+ --sk-ai-border: var(--border-subtle, #27272a);+ --sk-ai-fg: var(--text-primary, #f4f4f5);+ --sk-ai-fg-2: var(--text-secondary, #a1a1aa);+ --sk-ai-fg-3: var(--text-tertiary, #71717a);+ --sk-ai-accent: var(--accent-primary, #6366f1);+ --sk-ai-accent-hover: var(--accent-hover, #4f46e5);+ --sk-ai-glow: var(--accent-glow, rgba(99, 102, 241, 0.15));+ --sk-ai-shadow: var(--shadow-lg, 0 20px 60px rgba(0, 0, 0, 0.5));+ --sk-ai-code-bg: var(--bg-code, var(--bg-body, #0c0c0f));+ --sk-ai-code-fg: var(--text-code, var(--text-primary, #f4f4f5));+ --sk-ai-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;+ --sk-ai-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;+ --sk-ai-radius: 14px;+}++// ---------------------------------------------------------------- Bubble+.sk-ai-bubble {+ @extend %sk-ai-tokens;+ position: fixed;+ bottom: 24px;+ right: 24px;+ z-index: $sk-ai-z - 1;+ width: 52px;+ height: 52px;+ border-radius: 50%;+ border: none;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--sk-ai-accent);+ color: #fff;+ cursor: pointer;+ box-shadow: 0 6px 20px var(--sk-ai-glow), 0 2px 8px rgba(0, 0, 0, 0.25);+ transition: transform 0.18s cubic-bezier(0.22, 1, 0.36, 1), background 0.18s ease;++ &:hover { background: var(--sk-ai-accent-hover); transform: translateY(-2px); }+ &:focus-visible { outline: 2px solid var(--sk-ai-accent); outline-offset: 3px; }+ &.is-raised { bottom: 92px; } // lift above the serverkit-gui launcher on /servers/:id+ &.is-busy { animation: sk-ai-pulse 1.6s ease-in-out infinite; }++ @media (max-width: 768px) {+ bottom: 88px;+ right: 16px;+ width: 48px;+ height: 48px;+ &.is-raised { bottom: 152px; }+ }+}++.sk-ai-bubble__dot {+ position: absolute;+ top: 8px;+ right: 8px;+ width: 10px;+ height: 10px;+ border-radius: 50%;+ background: #ef4444;+ border: 2px solid var(--sk-ai-accent);+}++// ---------------------------------------------------------------- Overlay / drawer+.sk-ai-overlay {+ @extend %sk-ai-tokens;+ position: fixed;+ inset: 0;+ z-index: $sk-ai-z;+ pointer-events: none; // let the page through except the drawer itself++ &[data-mobile='true'] { pointer-events: auto; }+}++.sk-ai-overlay__backdrop {+ position: absolute;+ inset: 0;+ background: rgba(0, 0, 0, 0.45);+ animation: sk-ai-fade 0.15s ease;+}++.sk-ai-drawer {+ --sk-ai-drawer-w: 420px;+ pointer-events: auto;+ position: absolute;+ top: 0;+ right: 0;+ bottom: 0;+ width: var(--sk-ai-drawer-w);+ max-width: 100vw;+ display: flex;+ flex-direction: column;+ background: var(--sk-ai-bg);+ border-left: 1px solid var(--sk-ai-border);+ box-shadow: var(--sk-ai-shadow);+ font-family: var(--sk-ai-sans);+ color: var(--sk-ai-fg);+ animation: sk-ai-slide-in 0.22s cubic-bezier(0.16, 1, 0.3, 1);++ @media (max-width: 768px) {+ width: 100vw;+ height: 100dvh;+ border-left: none;+ }+}++.sk-ai-drawer__resize {+ position: absolute;+ top: 0;+ left: -3px;+ width: 6px;+ height: 100%;+ cursor: col-resize;+ z-index: 2;+}++// ---------------------------------------------------------------- Header+.sk-ai-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 12px 14px;+ border-bottom: 1px solid var(--sk-ai-border);+}++.sk-ai-header__title { display: flex; flex-direction: column; line-height: 1.1; }+.sk-ai-header__name { font-weight: 600; font-size: 14px; }+.sk-ai-header__by { font-size: 11px; color: var(--sk-ai-fg-3); }+.sk-ai-header__actions { display: flex; align-items: center; gap: 6px; }++.sk-ai-iconbtn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 30px;+ height: 30px;+ border-radius: 8px;+ border: 1px solid transparent;+ background: transparent;+ color: var(--sk-ai-fg-2);+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease;+ &:hover { background: var(--sk-ai-hover); color: var(--sk-ai-fg); }+ &:focus-visible { outline: 2px solid var(--sk-ai-accent); outline-offset: 1px; }+}++// ---------------------------------------------------------------- Mode toggle+.sk-ai-modes {+ display: inline-flex;+ background: var(--sk-ai-bg-body);+ border: 1px solid var(--sk-ai-border);+ border-radius: 999px;+ padding: 2px;+}+.sk-ai-modes__item {+ border: none;+ background: transparent;+ color: var(--sk-ai-fg-2);+ font-size: 12px;+ padding: 4px 10px;+ border-radius: 999px;+ cursor: pointer;+ &.is-active { background: var(--sk-ai-accent); color: #fff; }+}++// ---------------------------------------------------------------- Context chip+.sk-ai-context-chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ margin: 10px 14px 0;+ padding: 4px 10px;+ border-radius: 999px;+ font-size: 12px;+ cursor: pointer;+ border: 1px solid var(--sk-ai-border);+ background: var(--sk-ai-glow);+ color: var(--sk-ai-fg-2);+ align-self: flex-start;+ &.is-off { background: transparent; color: var(--sk-ai-fg-3); }+}++// ---------------------------------------------------------------- Messages+.sk-ai-messages {+ flex: 1;+ overflow-y: auto;+ padding: 14px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ position: relative;+}++.sk-ai-message { display: flex; flex-direction: column; gap: 8px; max-width: 100%; }+.sk-ai-message--user { align-items: flex-end; }+.sk-ai-message--user .sk-ai-message__bubble {+ background: var(--sk-ai-accent);+ color: #fff;+ padding: 8px 12px;+ border-radius: 14px 14px 4px 14px;+ max-width: 85%;+ white-space: pre-wrap;+ word-break: break-word;+}+.sk-ai-message--assistant { align-items: stretch; }+.sk-ai-message__error {+ color: #fca5a5;+ font-size: 13px;+ border: 1px solid rgba(239, 68, 68, 0.4);+ border-radius: 8px;+ padding: 8px 10px;+}++.sk-ai-markdown {+ font-size: 14px;+ line-height: 1.55;+ color: var(--sk-ai-fg);+ p { margin: 0 0 8px; }+ p:last-child { margin-bottom: 0; }+ a { color: var(--sk-ai-accent); }+ strong { font-weight: 600; }+}++.sk-ai-code {+ background: var(--sk-ai-code-bg);+ color: var(--sk-ai-code-fg);+ font-family: var(--sk-ai-mono);+ font-size: 12.5px;+ border: 1px solid var(--sk-ai-border);+ border-radius: 8px;+ padding: 10px 12px;+ overflow-x: auto;+ margin: 6px 0;+ position: relative;+ code { font-family: inherit; white-space: pre; }+}+.sk-ai-code__lang {+ display: block;+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--sk-ai-fg-3);+ margin-bottom: 4px;+}+.sk-ai-inline-code {+ font-family: var(--sk-ai-mono);+ font-size: 0.9em;+ background: var(--sk-ai-hover);+ padding: 1px 5px;+ border-radius: 4px;+}++// ---------------------------------------------------------------- Tool cards+.sk-ai-tool-card {+ border: 1px solid var(--sk-ai-border);+ border-radius: 10px;+ background: var(--sk-ai-bg-body);+ overflow: hidden;+ &--error { border-color: rgba(239, 68, 68, 0.5); }+}+.sk-ai-tool-card__head {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 8px 10px;+ background: transparent;+ border: none;+ color: var(--sk-ai-fg);+ font-size: 13px;+ cursor: pointer;+ text-align: left;+}+.sk-ai-tool-card__name { font-family: var(--sk-ai-mono); font-size: 12.5px; flex: 1; }+.sk-ai-tool-card__status { display: inline-flex; color: var(--sk-ai-fg-2); }+.sk-ai-tool-card__status--done { color: #4ade80; }+.sk-ai-tool-card__status--error { color: #f87171; }+.sk-ai-tool-card__chev { color: var(--sk-ai-fg-3); transition: transform 0.15s ease; &.is-open { transform: rotate(180deg); } }+.sk-ai-tool-card__body { padding: 0 10px 10px; }+.sk-ai-tool-card__label { font-size: 11px; color: var(--sk-ai-fg-3); margin: 6px 0 2px; }+.sk-ai-tool-card__result { max-height: 240px; overflow: auto; }+.sk-ai-spin { animation: sk-ai-spin 1s linear infinite; }++// ---------------------------------------------------------------- Confirm card+.sk-ai-confirm {+ border: 1px solid var(--sk-ai-accent);+ border-radius: 10px;+ background: var(--sk-ai-glow);+ padding: 12px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.sk-ai-confirm__head { display: flex; align-items: center; gap: 6px; font-weight: 600; font-size: 13px; }+.sk-ai-confirm__summary { font-size: 13px; color: var(--sk-ai-fg); margin: 0; }+.sk-ai-confirm__params { max-height: 160px; overflow: auto; }+.sk-ai-confirm__actions { display: flex; justify-content: flex-end; gap: 8px; }++// ---------------------------------------------------------------- Buttons+.sk-ai-btn {+ border-radius: 8px;+ padding: 6px 14px;+ font-size: 13px;+ cursor: pointer;+ border: 1px solid var(--sk-ai-border);+ background: var(--sk-ai-bg);+ color: var(--sk-ai-fg);+ &--ghost { background: transparent; }+ &--danger { background: var(--sk-ai-accent); border-color: var(--sk-ai-accent); color: #fff; }+ &:focus-visible { outline: 2px solid var(--sk-ai-accent); outline-offset: 1px; }+}++// ---------------------------------------------------------------- Composer+.sk-ai-composer {+ display: flex;+ align-items: flex-end;+ gap: 8px;+ padding: 12px 14px;+ border-top: 1px solid var(--sk-ai-border);+}+.sk-ai-composer__input {+ flex: 1;+ resize: none;+ border-radius: 10px;+ border: 1px solid var(--sk-ai-border);+ background: var(--sk-ai-bg-body);+ color: var(--sk-ai-fg);+ padding: 10px 12px;+ font-family: var(--sk-ai-sans);+ font-size: 14px;+ line-height: 1.4;+ max-height: 160px;+ &:focus { outline: none; border-color: var(--sk-ai-accent); box-shadow: 0 0 0 3px var(--sk-ai-glow); }+ @media (max-width: 768px) { font-size: 16px; } // avoid iOS zoom-on-focus+}+.sk-ai-composer__btn {+ flex: none;+ width: 40px;+ height: 40px;+ border-radius: 10px;+ border: none;+ background: var(--sk-ai-accent);+ color: #fff;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ &:disabled { opacity: 0.5; cursor: not-allowed; }+ &--stop { background: var(--sk-ai-hover); color: var(--sk-ai-fg); }+}++// ---------------------------------------------------------------- Typing+.sk-ai-typing { display: flex; align-items: center; gap: 8px; color: var(--sk-ai-fg-3); font-size: 12px; }+.sk-ai-typing__dots { display: inline-flex; gap: 3px; }+.sk-ai-typing__dots i {+ width: 6px; height: 6px; border-radius: 50%;+ background: var(--sk-ai-fg-3);+ animation: sk-ai-bounce 1.2s infinite ease-in-out;+ &:nth-child(2) { animation-delay: 0.15s; }+ &:nth-child(3) { animation-delay: 0.3s; }+}++// ---------------------------------------------------------------- Empty state+.sk-ai-empty { margin: auto; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 24px; }+.sk-ai-empty__icon {+ width: 48px; height: 48px; border-radius: 14px;+ display: flex; align-items: center; justify-content: center;+ background: var(--sk-ai-glow); color: var(--sk-ai-accent);+}+.sk-ai-empty__title { margin: 6px 0 0; font-size: 16px; }+.sk-ai-empty__sub { margin: 0; font-size: 12px; color: var(--sk-ai-fg-3); }+.sk-ai-empty__hint { font-size: 13px; color: var(--sk-ai-fg-2); max-width: 260px; }+.sk-ai-empty__prompts { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; width: 100%; }+.sk-ai-suggested {+ border: 1px solid var(--sk-ai-border);+ background: var(--sk-ai-bg-body);+ color: var(--sk-ai-fg);+ border-radius: 10px;+ padding: 8px 12px;+ font-size: 13px;+ cursor: pointer;+ text-align: left;+ &:hover { background: var(--sk-ai-hover); }+}++// ---------------------------------------------------------------- Conversation menu+.sk-ai-convo { position: relative; }+.sk-ai-convo__menu {+ position: absolute;+ right: 0;+ top: 36px;+ width: 240px;+ background: var(--sk-ai-elevated);+ border: 1px solid var(--sk-ai-border);+ border-radius: 10px;+ box-shadow: var(--sk-ai-shadow);+ padding: 6px;+ z-index: 3;+}+.sk-ai-convo__new {+ width: 100%; display: flex; align-items: center; gap: 6px;+ padding: 8px; border: none; background: transparent; color: var(--sk-ai-fg);+ border-radius: 8px; cursor: pointer; font-size: 13px;+ &:hover { background: var(--sk-ai-hover); }+}+.sk-ai-convo__list { max-height: 280px; overflow-y: auto; margin-top: 4px; }+.sk-ai-convo__empty { color: var(--sk-ai-fg-3); font-size: 12px; padding: 8px; text-align: center; }+.sk-ai-convo__item {+ display: flex; align-items: center; gap: 4px; border-radius: 8px;+ &:hover { background: var(--sk-ai-hover); }+ &.is-active { background: var(--sk-ai-glow); }+}+.sk-ai-convo__title {+ flex: 1; text-align: left; border: none; background: transparent; color: var(--sk-ai-fg);+ padding: 7px 8px; font-size: 13px; cursor: pointer;+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;+}+.sk-ai-convo__del {+ border: none; background: transparent; color: var(--sk-ai-fg-3);+ padding: 6px; cursor: pointer; border-radius: 6px;+ &:hover { color: #f87171; }+}++// ---------------------------------------------------------------- Jump-to-latest+.sk-ai-jump {+ position: sticky;+ bottom: 4px;+ align-self: center;+ width: 32px; height: 32px;+ border-radius: 50%;+ border: 1px solid var(--sk-ai-border);+ background: var(--sk-ai-elevated);+ color: var(--sk-ai-fg);+ display: inline-flex; align-items: center; justify-content: center;+ cursor: pointer;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+}++// ---------------------------------------------------------------- Animations+@keyframes sk-ai-slide-in { from { transform: translateX(100%); } to { transform: translateX(0); } }+@keyframes sk-ai-fade { from { opacity: 0; } to { opacity: 1; } }+@keyframes sk-ai-pulse { 0%, 100% { box-shadow: 0 6px 20px var(--sk-ai-glow), 0 2px 8px rgba(0,0,0,0.25); } 50% { box-shadow: 0 0 0 6px var(--sk-ai-glow); } }+@keyframes sk-ai-spin { to { transform: rotate(360deg); } }+@keyframes sk-ai-bounce { 0%, 80%, 100% { transform: scale(0.6); opacity: 0.5; } 40% { transform: scale(1); opacity: 1; } }++@media (prefers-reduced-motion: reduce) {+ .sk-ai-drawer, .sk-ai-bubble, .sk-ai-overlay__backdrop { animation: none !important; transition: none !important; }+ .sk-ai-bubble.is-busy { animation: none !important; }+}diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex 0d53a00c..1f2cabdd 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -61,6 +61,7 @@@import 'components/_contribution-graph';@import 'components/_command-palette';@import 'components/_logs-drawer';+@import 'components/_ai-assistant';@import 'components/_ui';// --------------------------------------------