Open-source personal finance manager. Self-hosted, privacy-first.
feat: adding llm agents (#186)
Tássio Noronha377d26821db4
diff --git a/.gitignore b/.gitignoreindex 2a4f527e..3864bbb0 100644--- a/.gitignore+++ b/.gitignore@@ -9,3 +9,8 @@ docker-compose.override.yml# Ignore local configuration files.vscode/++# Runtime artifacts written by the agents feature (uploaded KB files,+# downloaded ONNX embedding models, transaction attachments). User data+# — never commit.+backend/data/diff --git a/backend/alembic/env.py b/backend/alembic/env.pyindex a794a8ac..6b2cdb2e 100644--- a/backend/alembic/env.py+++ b/backend/alembic/env.py@@ -10,6 +10,9 @@ from alembic import contextfrom app.core.config import get_settingsfrom app.core.database import Basefrom app.models import * # noqa: F401,F403+# Agents module models (always loaded so migrations stay in sync; the+# feature itself is gated at runtime by AGENTS_ENABLED).+from app.agents.models import * # noqa: F401,F403config = context.configsettings = get_settings()diff --git a/backend/alembic/versions/046_agents_foundation.py b/backend/alembic/versions/046_agents_foundation.pynew file mode 100644index 00000000..a1728986--- /dev/null+++ b/backend/alembic/versions/046_agents_foundation.py@@ -0,0 +1,154 @@+"""agents foundation: agents, conversations, messages, knowledge, usage++Revision ID: 046+Revises: 045+Create Date: 2026-05-11++This migration is always applied; the agents feature itself is gated by+the AGENTS_ENABLED env var. Empty tables cost nothing.+"""++from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects import postgresql+from pgvector.sqlalchemy import Vector++from app.agents.config import get_agent_settings++revision = "046"+down_revision = "045"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.execute("CREATE EXTENSION IF NOT EXISTS vector")++ embed_dim = get_agent_settings().embedding_dim++ op.create_table(+ "agents",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),+ sa.Column("name", sa.String(120), nullable=False),+ sa.Column("description", sa.Text, nullable=True),+ sa.Column("system_prompt", sa.Text, nullable=False, server_default=""),+ sa.Column("icon", sa.String(50), nullable=False, server_default="bot"),+ sa.Column("color", sa.String(7), nullable=False, server_default="#6B7280"),+ sa.Column("provider", sa.String(40), nullable=True),+ sa.Column("model", sa.String(120), nullable=True),+ sa.Column("temperature", sa.Float, nullable=False, server_default="0.4"),+ sa.Column("max_history_messages", sa.Integer, nullable=False, server_default="20"),+ sa.Column("top_n", sa.Integer, nullable=False, server_default="6"),+ sa.Column("similarity_threshold", sa.Float, nullable=False, server_default="0.25"),+ sa.Column("extra", postgresql.JSON, nullable=False, server_default="{}"),+ sa.Column("is_archived", sa.Boolean, nullable=False, server_default="false"),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ )+ op.create_index("ix_agents_user_id", "agents", ["user_id"])++ op.create_table(+ "agent_tools",+ sa.Column("agent_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agents.id", ondelete="CASCADE"), primary_key=True),+ sa.Column("server", sa.String(80), primary_key=True),+ sa.Column("tool_name", sa.String(120), primary_key=True),+ sa.Column("enabled", sa.Boolean, nullable=False, server_default="true"),+ )++ op.create_table(+ "agent_conversations",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("agent_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agents.id", ondelete="CASCADE"), nullable=False),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),+ sa.Column("channel", sa.String(40), nullable=False, server_default="web"),+ sa.Column("title", sa.String(200), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ )+ op.create_index("ix_agent_conversations_agent_id", "agent_conversations", ["agent_id"])+ op.create_index("ix_agent_conversations_user_id", "agent_conversations", ["user_id"])++ op.create_table(+ "agent_messages",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("conversation_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agent_conversations.id", ondelete="CASCADE"), nullable=False),+ sa.Column("ordinal", sa.Integer, nullable=False),+ sa.Column("role", sa.String(20), nullable=False),+ sa.Column("content", sa.Text, nullable=True),+ sa.Column("tool_calls", postgresql.JSON, nullable=True),+ sa.Column("tool_result", postgresql.JSON, nullable=True),+ sa.Column("citations", postgresql.JSON, nullable=True),+ sa.Column("input_tokens", sa.Integer, nullable=True),+ sa.Column("output_tokens", sa.Integer, nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ )+ op.create_index("ix_agent_messages_conv_ord", "agent_messages", ["conversation_id", "ordinal"])++ op.create_table(+ "agent_knowledge_docs",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("agent_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agents.id", ondelete="CASCADE"), nullable=False),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),+ sa.Column("title", sa.String(255), nullable=False),+ sa.Column("source", sa.String(500), nullable=True),+ sa.Column("mime", sa.String(80), nullable=False),+ sa.Column("storage_path", sa.String(500), nullable=True),+ sa.Column("size_bytes", sa.Integer, nullable=False, server_default="0"),+ sa.Column("status", sa.String(20), nullable=False, server_default="pending"),+ sa.Column("error", sa.Text, nullable=True),+ sa.Column("chunk_count", sa.Integer, nullable=False, server_default="0"),+ sa.Column("pinned", sa.Boolean, nullable=False, server_default="false"),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ )+ op.create_index("ix_agent_knowledge_docs_agent_id", "agent_knowledge_docs", ["agent_id"])++ op.create_table(+ "agent_knowledge_chunks",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("doc_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agent_knowledge_docs.id", ondelete="CASCADE"), nullable=False),+ sa.Column("agent_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agents.id", ondelete="CASCADE"), nullable=False),+ sa.Column("ordinal", sa.Integer, nullable=False),+ sa.Column("content", sa.Text, nullable=False),+ sa.Column("embedding", Vector(embed_dim), nullable=True),+ sa.Column("embedding_model", sa.String(120), nullable=True),+ )+ op.create_index("ix_agent_knowledge_chunks_doc_ord", "agent_knowledge_chunks", ["doc_id", "ordinal"])+ # IVFFlat index for ANN search; tune lists later as corpus grows.+ op.execute(+ "CREATE INDEX ix_agent_knowledge_chunks_embedding "+ "ON agent_knowledge_chunks USING ivfflat (embedding vector_cosine_ops) "+ "WITH (lists = 100)"+ )++ op.create_table(+ "agent_llm_usage",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),+ sa.Column("agent_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agents.id", ondelete="SET NULL"), nullable=True),+ sa.Column("conversation_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agent_conversations.id", ondelete="SET NULL"), nullable=True),+ sa.Column("message_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("agent_messages.id", ondelete="SET NULL"), nullable=True),+ sa.Column("provider", sa.String(40), nullable=False),+ sa.Column("model", sa.String(120), nullable=False),+ sa.Column("kind", sa.String(20), nullable=False, server_default="chat"),+ sa.Column("input_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("output_tokens", sa.Integer, nullable=False, server_default="0"),+ sa.Column("cost_usd", sa.Numeric(10, 6), nullable=True),+ sa.Column("latency_ms", sa.Integer, nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ )+ op.create_index("ix_agent_llm_usage_user_id", "agent_llm_usage", ["user_id"])+ op.create_index("ix_agent_llm_usage_agent_id", "agent_llm_usage", ["agent_id"])+++def downgrade() -> None:+ op.drop_table("agent_llm_usage")+ op.execute("DROP INDEX IF EXISTS ix_agent_knowledge_chunks_embedding")+ op.drop_table("agent_knowledge_chunks")+ op.drop_table("agent_knowledge_docs")+ op.drop_table("agent_messages")+ op.drop_table("agent_conversations")+ op.drop_table("agent_tools")+ op.drop_table("agents")+ # Leave the `vector` extension in place — other features may use it later.diff --git a/backend/alembic/versions/047_agent_llm_connections.py b/backend/alembic/versions/047_agent_llm_connections.pynew file mode 100644index 00000000..23a99bc6--- /dev/null+++ b/backend/alembic/versions/047_agent_llm_connections.py@@ -0,0 +1,53 @@+"""LLM connections (user-managed provider endpoints) + agents.connection_id++Revision ID: 047+Revises: 046+Create Date: 2026-05-11+"""++from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects import postgresql++revision = "047"+down_revision = "046"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "agent_llm_connections",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),+ sa.Column("name", sa.String(120), nullable=False),+ sa.Column("kind", sa.String(40), nullable=False),+ sa.Column("base_url", sa.String(500), nullable=True),+ sa.Column("api_key_encrypted", sa.String(500), nullable=True),+ sa.Column("default_model", sa.String(120), nullable=True),+ sa.Column("extra", postgresql.JSON, nullable=False, server_default="{}"),+ sa.Column("is_default", sa.Boolean, nullable=False, server_default="false"),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ )+ op.create_index("ix_agent_llm_connections_user_id", "agent_llm_connections", ["user_id"])++ op.add_column(+ "agents",+ sa.Column("connection_id", postgresql.UUID(as_uuid=True), nullable=True),+ )+ op.create_foreign_key(+ "fk_agents_connection_id",+ "agents",+ "agent_llm_connections",+ ["connection_id"],+ ["id"],+ ondelete="SET NULL",+ )+++def downgrade() -> None:+ op.drop_constraint("fk_agents_connection_id", "agents", type_="foreignkey")+ op.drop_column("agents", "connection_id")+ op.drop_index("ix_agent_llm_connections_user_id", table_name="agent_llm_connections")+ op.drop_table("agent_llm_connections")diff --git a/backend/alembic/versions/048_agent_auto_context.py b/backend/alembic/versions/048_agent_auto_context.pynew file mode 100644index 00000000..972676db--- /dev/null+++ b/backend/alembic/versions/048_agent_auto_context.py@@ -0,0 +1,30 @@+"""agents.auto_context flag++Revision ID: 048+Revises: 047+Create Date: 2026-05-11+"""++from alembic import op+import sqlalchemy as sa++revision = "048"+down_revision = "047"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column(+ "agents",+ sa.Column(+ "auto_context",+ sa.Boolean(),+ nullable=False,+ server_default=sa.text("true"),+ ),+ )+++def downgrade() -> None:+ op.drop_column("agents", "auto_context")diff --git a/backend/alembic/versions/049_agent_is_default.py b/backend/alembic/versions/049_agent_is_default.pynew file mode 100644index 00000000..2dc6610a--- /dev/null+++ b/backend/alembic/versions/049_agent_is_default.py@@ -0,0 +1,40 @@+"""agents.is_default flag + at-most-one constraint per user++Revision ID: 049+Revises: 048+Create Date: 2026-05-11+"""++from alembic import op+import sqlalchemy as sa++revision = "049"+down_revision = "048"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column(+ "agents",+ sa.Column(+ "is_default",+ sa.Boolean(),+ nullable=False,+ server_default=sa.text("false"),+ ),+ )+ # Partial unique index — at most one default per user, but multiple+ # non-defaults are fine.+ op.create_index(+ "uq_agents_one_default_per_user",+ "agents",+ ["user_id"],+ unique=True,+ postgresql_where=sa.text("is_default = true"),+ )+++def downgrade() -> None:+ op.drop_index("uq_agents_one_default_per_user", table_name="agents")+ op.drop_column("agents", "is_default")diff --git a/backend/app/agents/__init__.py b/backend/app/agents/__init__.pynew file mode 100644index 00000000..b177f864--- /dev/null+++ b/backend/app/agents/__init__.py@@ -0,0 +1,6 @@+"""Self-contained agents module.++The whole feature is gated by the AGENTS_ENABLED setting. When disabled,+nothing in this package is imported by the rest of the app — see app/main.py+for the conditional router registration.+"""diff --git a/backend/app/agents/api/__init__.py b/backend/app/agents/api/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/backend/app/agents/api/agents.py b/backend/app/agents/api/agents.pynew file mode 100644index 00000000..98c5d305--- /dev/null+++ b/backend/app/agents/api/agents.py@@ -0,0 +1,132 @@+from __future__ import annotations++import uuid+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.mcp.client import MCPRegistry+from app.agents.schemas.agent import AgentCreate, AgentRead, AgentToolToggle, AgentUpdate+from app.agents.services import agent_service+from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User++router = APIRouter(prefix="/api/agents", tags=["agents"])++[email protected]("", response_model=list[AgentRead])+async def list_agents(+ include_archived: bool = False,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await agent_service.list_agents(session, user.id, include_archived=include_archived)++[email protected]("/default", response_model=AgentRead)+async def get_default_agent(+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Used by the global slide-over chat panel. Returns the user-flagged+ default agent, or the most-recently-created one as a fallback."""+ agent = await agent_service.get_default_agent(session, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="no agent available")+ return agent++[email protected]("", response_model=AgentRead, status_code=status.HTTP_201_CREATED)+async def create_agent(+ data: AgentCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await agent_service.create_agent(session, user.id, data)++[email protected]("/{agent_id}", response_model=AgentRead)+async def get_agent(+ agent_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ agent = await agent_service.get_agent(session, agent_id, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")+ return agent++[email protected]("/{agent_id}", response_model=AgentRead)+async def update_agent(+ agent_id: uuid.UUID,+ data: AgentUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ agent = await agent_service.update_agent(session, agent_id, user.id, data)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")+ return agent++[email protected]("/{agent_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_agent(+ agent_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ ok = await agent_service.delete_agent(session, agent_id, user.id)+ if not ok:+ raise HTTPException(status_code=404, detail="agent not found")++[email protected]("/{agent_id}/tools")+async def get_agent_tools(+ agent_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+) -> dict[str, Any]:+ """Discover all tools from registered MCP servers and merge with the+ per-agent enablement state. Returns shape:+ { servers: [{name}], tools: [{server, name, description, enabled, is_proposal}] }+ """+ agent = await agent_service.get_agent(session, agent_id, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")++ mcp = MCPRegistry()+ handles = await mcp.discover(user_id=user.id)+ rows = await agent_service.list_tools(session, agent_id)+ enabled_lookup = {(r.server, r.tool_name): r.enabled for r in rows}+ no_explicit_rows = len(rows) == 0+ tools = [+ {+ "server": h.server,+ "name": h.name,+ "description": h.description,+ "is_proposal": h.is_proposal,+ # If no explicit rows yet, default to enabled (allow-all).+ "enabled": enabled_lookup.get((h.server, h.name), True if no_explicit_rows else False),+ }+ for h in handles+ ]+ return {"servers": [{"name": s} for s in mcp.server_names()], "tools": tools}++[email protected]("/{agent_id}/tools")+async def put_agent_tools(+ agent_id: uuid.UUID,+ items: list[AgentToolToggle],+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ agent = await agent_service.get_agent(session, agent_id, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")+ await agent_service.replace_tool_enablement(+ session, agent_id, [(t.server, t.tool_name, t.enabled) for t in items]+ )+ return {"updated": len(items)}diff --git a/backend/app/agents/api/chat.py b/backend/app/agents/api/chat.pynew file mode 100644index 00000000..887f1c0e--- /dev/null+++ b/backend/app/agents/api/chat.py@@ -0,0 +1,78 @@+"""SSE chat endpoint.++POST /api/agents/{agent_id}/chat with {content, conversation_id?, channel?}.+Returns Server-Sent Events streaming text + tool-call + result events. The+client UI renders deltas as they arrive and replaces tool-call spinners+with summaries when results land.+"""+from __future__ import annotations++import json+import uuid+from dataclasses import asdict+from typing import AsyncIterator++from fastapi import APIRouter, Depends, HTTPException+from sqlalchemy.ext.asyncio import AsyncSession+from starlette.responses import StreamingResponse++from app.agents.runtime.executor import AgentExecutor, ExecutorEvent+from app.agents.schemas.conversation import SendMessageRequest+from app.agents.services import agent_service, conversation_service+from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User++router = APIRouter(prefix="/api/agents", tags=["agents"])+++def _format_event(event: ExecutorEvent) -> bytes:+ payload = {k: v for k, v in asdict(event).items() if v is not None}+ return f"event: {event.type}\ndata: {json.dumps(payload, default=str)}\n\n".encode()++[email protected]("/{agent_id}/chat")+async def chat(+ agent_id: uuid.UUID,+ body: SendMessageRequest,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ agent = await agent_service.get_agent(session, agent_id, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")++ conv = None+ if body.conversation_id:+ conv = await conversation_service.get_conversation(session, body.conversation_id, user.id)+ if conv is None or conv.agent_id != agent_id:+ raise HTTPException(status_code=404, detail="conversation not found")+ if conv is None:+ conv = await conversation_service.create_conversation(+ session, user_id=user.id, agent_id=agent_id, channel=body.channel,+ )++ executor = AgentExecutor()++ async def gen() -> AsyncIterator[bytes]:+ # Send the conversation id immediately so the client can update its URL.+ yield f"event: conversation\ndata: {json.dumps({'conversation_id': str(conv.id)})}\n\n".encode()+ try:+ async for ev in executor.run(+ session=session,+ agent=agent,+ user_id=user.id,+ conversation_id=conv.id,+ user_message=body.content,+ channel=body.channel,+ page_context=body.page_context,+ ):+ yield _format_event(ev)+ except Exception as exc: # noqa: BLE001+ yield f"event: error\ndata: {json.dumps({'error_code': 'unknown', 'error_message': str(exc)})}\n\n".encode()++ return StreamingResponse(gen(), media_type="text/event-stream", headers={+ "Cache-Control": "no-cache",+ "X-Accel-Buffering": "no",+ "Connection": "keep-alive",+ })diff --git a/backend/app/agents/api/connections.py b/backend/app/agents/api/connections.pynew file mode 100644index 00000000..1a1cfe4a--- /dev/null+++ b/backend/app/agents/api/connections.py@@ -0,0 +1,93 @@+from __future__ import annotations++import uuid++from fastapi import APIRouter, Depends, HTTPException, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.schemas.connection import ConnectionCreate, ConnectionRead, ConnectionTestResult, ConnectionUpdate+from app.agents.services import connection_service+from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User++# Mounted BEFORE the agents/{agent_id} router so the literal path wins.+router = APIRouter(prefix="/api/agents", tags=["agents"])++[email protected]("/connections", response_model=list[ConnectionRead])+async def list_connections(+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ rows = await connection_service.list_connections(session, user.id)+ return [ConnectionRead.from_orm_row(r) for r in rows]++[email protected]("/connections", response_model=ConnectionRead, status_code=status.HTTP_201_CREATED)+async def create_connection(+ data: ConnectionCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ try:+ conn = await connection_service.create_connection(+ session, user.id,+ name=data.name, kind=data.kind, base_url=data.base_url, api_key=data.api_key,+ default_model=data.default_model, extra=data.extra, is_default=data.is_default,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return ConnectionRead.from_orm_row(conn)++[email protected]("/connections/{conn_id}", response_model=ConnectionRead)+async def get_connection(+ conn_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ conn = await connection_service.get_connection(session, conn_id, user.id)+ if conn is None:+ raise HTTPException(status_code=404, detail="connection not found")+ return ConnectionRead.from_orm_row(conn)++[email protected]("/connections/{conn_id}", response_model=ConnectionRead)+async def update_connection(+ conn_id: uuid.UUID,+ data: ConnectionUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ conn = await connection_service.update_connection(+ session, conn_id, user.id,+ name=data.name, base_url=data.base_url, api_key=data.api_key,+ default_model=data.default_model, extra=data.extra, is_default=data.is_default,+ )+ if conn is None:+ raise HTTPException(status_code=404, detail="connection not found")+ return ConnectionRead.from_orm_row(conn)++[email protected]("/connections/{conn_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_connection(+ conn_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ ok = await connection_service.delete_connection(session, conn_id, user.id)+ if not ok:+ raise HTTPException(status_code=404, detail="connection not found")++[email protected]("/connections/{conn_id}/test", response_model=ConnectionTestResult)+async def test_connection(+ conn_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ conn = await connection_service.get_connection(session, conn_id, user.id)+ if conn is None:+ raise HTTPException(status_code=404, detail="connection not found")+ return await connection_service.test_connection(conn)diff --git a/backend/app/agents/api/conversations.py b/backend/app/agents/api/conversations.pynew file mode 100644index 00000000..cb107a74--- /dev/null+++ b/backend/app/agents/api/conversations.py@@ -0,0 +1,145 @@+from __future__ import annotations++import logging+import uuid+from typing import Optional++from fastapi import APIRouter, Depends, HTTPException, Query, status+from pydantic import BaseModel, Field+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.schemas.conversation import ConversationRead, MessageRead+from app.agents.services import agent_service, conversation_service+from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/api/agents", tags=["agents"])+++class RenameConversationBody(BaseModel):+ title: str = Field(..., min_length=1, max_length=200)+++_TITLE_PROMPT = (+ "Generate a very short title (max 6 words, no punctuation, no quotes) "+ "summarizing the topic of this conversation. Return ONLY the title text "+ "with no preamble, no explanation, no quotes."+)++[email protected]("/conversations", response_model=list[ConversationRead])+async def list_conversations(+ agent_id: Optional[uuid.UUID] = Query(None),+ limit: int = Query(50, ge=1, le=200),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await conversation_service.list_conversations(session, user.id, agent_id=agent_id, limit=limit)++[email protected]("/conversations/{conversation_id}", response_model=ConversationRead)+async def get_conversation(+ conversation_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ conv = await conversation_service.get_conversation(session, conversation_id, user.id)+ if conv is None:+ raise HTTPException(status_code=404, detail="conversation not found")+ return conv++[email protected]("/conversations/{conversation_id}/messages", response_model=list[MessageRead])+async def list_messages(+ conversation_id: uuid.UUID,+ limit: int = Query(200, ge=1, le=500),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ conv = await conversation_service.get_conversation(session, conversation_id, user.id)+ if conv is None:+ raise HTTPException(status_code=404, detail="conversation not found")+ return await conversation_service.list_messages(session, conversation_id, limit=limit)++[email protected]("/conversations/{conversation_id}", response_model=ConversationRead)+async def rename_conversation(+ conversation_id: uuid.UUID,+ body: RenameConversationBody,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ conv = await conversation_service.update_title(session, conversation_id, user.id, body.title)+ if conv is None:+ raise HTTPException(status_code=404, detail="conversation not found")+ return conv++[email protected]("/conversations/{conversation_id}/generate-title", response_model=ConversationRead)+async def generate_title(+ conversation_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Ask the conversation's agent's LLM to summarize the chat into a+ short title. Persists the result and returns the updated row. Best-+ effort: if the LLM call fails, the existing title is left in place+ and a 200 is still returned with whatever was there before."""+ from app.agents.providers.base import ChatMessage+ from app.agents.runtime.executor import _provider_and_model_for++ conv = await conversation_service.get_conversation(session, conversation_id, user.id)+ if conv is None:+ raise HTTPException(status_code=404, detail="conversation not found")++ msgs = await conversation_service.list_messages(session, conversation_id, limit=12)+ transcript = []+ for m in msgs:+ if m.role in ("user", "assistant") and m.content:+ transcript.append(f"{m.role.upper()}: {m.content[:600]}")+ if not transcript:+ return conv # nothing to summarize yet++ agent = await agent_service.get_agent(session, conv.agent_id, user.id)+ if agent is None:+ return conv++ try:+ provider, model = await _provider_and_model_for(session, agent)+ if not model:+ return conv+ prompt_messages = [+ ChatMessage(role="system", content=_TITLE_PROMPT),+ ChatMessage(role="user", content="\n".join(transcript)),+ ]+ resp = await provider.chat(prompt_messages, model=model, temperature=0.2, max_tokens=40)+ content = (resp.content or "").strip()+ # Some local models emit reasoning tags before the answer; strip+ # those FIRST so the answer line isn't accidentally swallowed.+ for marker in ("</think>", "</reasoning>"):+ if marker in content:+ content = content.split(marker, 1)[1]+ content = content.strip().strip('"').strip("'")+ # First non-empty line wins.+ candidate = next((line.strip().strip('"').strip("'") for line in content.splitlines() if line.strip()), "")+ if candidate:+ conv = await conversation_service.update_title(+ session, conversation_id, user.id, candidate[:80]+ )+ except Exception: # noqa: BLE001+ logger.exception("title generation failed for conversation %s", conversation_id)+ return conv++[email protected]("/conversations/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_conversation(+ conversation_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ ok = await conversation_service.delete_conversation(session, conversation_id, user.id)+ if not ok:+ raise HTTPException(status_code=404, detail="conversation not found")diff --git a/backend/app/agents/api/info.py b/backend/app/agents/api/info.pynew file mode 100644index 00000000..40e29efa--- /dev/null+++ b/backend/app/agents/api/info.py@@ -0,0 +1,21 @@+from fastapi import APIRouter++from app.agents.config import get_agent_settings+from app.agents.providers import list_providers++router = APIRouter(prefix="/api/agents", tags=["agents"])++[email protected]("/info")+async def get_agents_info():+ """Capability discovery for the frontend. Always available when the+ agents router is mounted (i.e. the feature is enabled instance-wide)."""+ s = get_agent_settings()+ return {+ "enabled": True,+ "providers": list_providers(),+ "embedding_dim": s.embedding_dim,+ "default_top_n": s.default_top_n,+ "default_similarity_threshold": s.default_similarity_threshold,+ "extra_mcp_servers_configured": bool(s.extra_mcp_servers.strip()),+ }diff --git a/backend/app/agents/api/knowledge.py b/backend/app/agents/api/knowledge.pynew file mode 100644index 00000000..c3429278--- /dev/null+++ b/backend/app/agents/api/knowledge.py@@ -0,0 +1,105 @@+from __future__ import annotations++import uuid+from typing import Any++from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.services import agent_service, knowledge_service+from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User++router = APIRouter(prefix="/api/agents", tags=["agents"])+++def _serialize(doc) -> dict[str, Any]:+ return {+ "id": str(doc.id),+ "agent_id": str(doc.agent_id),+ "title": doc.title,+ "source": doc.source,+ "mime": doc.mime,+ "size_bytes": doc.size_bytes,+ "status": doc.status,+ "error": doc.error,+ "chunk_count": doc.chunk_count,+ "pinned": doc.pinned,+ "created_at": doc.created_at.isoformat() if doc.created_at else None,+ "updated_at": doc.updated_at.isoformat() if doc.updated_at else None,+ }++[email protected]("/{agent_id}/knowledge")+async def list_knowledge(+ agent_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ agent = await agent_service.get_agent(session, agent_id, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")+ docs = await knowledge_service.list_docs(session, agent_id)+ return {"items": [_serialize(d) for d in docs], "total": len(docs)}++[email protected]("/{agent_id}/knowledge", status_code=status.HTTP_201_CREATED)+async def upload_knowledge(+ agent_id: uuid.UUID,+ file: UploadFile = File(...),+ pinned: bool = Form(False),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ agent = await agent_service.get_agent(session, agent_id, user.id)+ if agent is None:+ raise HTTPException(status_code=404, detail="agent not found")+ payload = await file.read()+ try:+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=agent_id,+ user_id=user.id,+ filename=file.filename or "document",+ mime=file.content_type or "application/octet-stream",+ payload=payload,+ pinned=pinned,+ )+ except ValueError as exc:+ raise HTTPException(status_code=413, detail=str(exc)) from exc++ # Fire-and-forget Celery dispatch — task does the parsing/embedding.+ try:+ from app.worker import celery_app+ celery_app.send_task("app.agents.tasks.ingest.ingest_doc", args=[str(doc.id), str(agent_id)])+ except Exception: # noqa: BLE001 — embedding failure shouldn't kill the upload+ await knowledge_service.mark_status(session, doc.id, status="failed", error="celery dispatch failed")++ return _serialize(doc)++[email protected]("/{agent_id}/knowledge/{doc_id}/pin")+async def toggle_pin(+ agent_id: uuid.UUID,+ doc_id: uuid.UUID,+ pinned: bool,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ doc = await knowledge_service.set_pinned(session, doc_id, user.id, pinned)+ if doc is None:+ raise HTTPException(status_code=404, detail="doc not found")+ return _serialize(doc)++[email protected]("/{agent_id}/knowledge/{doc_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_knowledge(+ agent_id: uuid.UUID,+ doc_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ ok = await knowledge_service.delete_doc(session, doc_id, user.id)+ if not ok:+ raise HTTPException(status_code=404, detail="doc not found")diff --git a/backend/app/agents/config.py b/backend/app/agents/config.pynew file mode 100644index 00000000..5c227d0f--- /dev/null+++ b/backend/app/agents/config.py@@ -0,0 +1,56 @@+from functools import lru_cache++from pydantic_settings import BaseSettings, SettingsConfigDict+++class AgentSettings(BaseSettings):+ # Master switch. When false, the router is not mounted, MCP servers are+ # not contacted, and no background tasks run.+ enabled: bool = False++ # Built-in MCP server URL. The mcp-server container speaks JSON-RPC 2.0.+ builtin_mcp_url: str = "http://mcp-server:8765/mcp"++ # Comma-separated extra MCP servers users can plug in (URL[|name]).+ # Example: "http://my-tools:9000/mcp|my-tools,http://other:9001/mcp"+ extra_mcp_servers: str = ""++ # Shared secret used to mint short-lived JWTs for MCP calls. Distinct+ # from the main app secret so revocation is independent.+ mcp_jwt_secret: str = "change-me-in-production"+ mcp_jwt_ttl_seconds: int = 600++ # Embedding dimension for the knowledge_chunks vector column. Locked at+ # migration time. 1536 covers OpenAI text-embedding-3-small (default) and+ # nomic-embed-text via Matryoshka padding/truncation.+ embedding_dim: int = 1536++ # Default RAG parameters (overridable per agent in the DB row).+ default_top_n: int = 6+ default_similarity_threshold: float = 0.25++ # Embedding provider/model. Both MCP-server and Celery worker honor+ # these. Switching requires re-embedding existing docs (their+ # embeddings are tied to the model that produced them).+ #+ # Default `native` uses fastembed with a small multilingual model+ # bundled in-process — works zero-config (no Ollama/OpenAI/etc).+ # Users can switch to ollama/openai/openai_compatible for higher+ # quality or faster inference.+ embedding_provider: str = "native"+ embedding_model: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"+ embedding_native_cache_dir: str = "/app/data/embedding_models"+ embedding_ollama_base_url: str = "http://ollama:11434"+ embedding_openai_base_url: str = "https://api.openai.com/v1"+ embedding_openai_api_key: str = ""++ # Where uploaded knowledge files live on disk (per-instance).+ knowledge_storage_path: str = "/app/data/agent_knowledge"+ knowledge_max_file_size_mb: int = 25++ model_config = SettingsConfigDict(env_file=".env", env_prefix="AGENTS_", extra="ignore")+++@lru_cache+def get_agent_settings() -> AgentSettings:+ return AgentSettings()diff --git a/backend/app/agents/mcp/__init__.py b/backend/app/agents/mcp/__init__.pynew file mode 100644index 00000000..82d82d3b--- /dev/null+++ b/backend/app/agents/mcp/__init__.py@@ -0,0 +1,4 @@+from app.agents.mcp.auth import mint_token+from app.agents.mcp.client import MCPClient, MCPRegistry, ToolHandle++__all__ = ["mint_token", "MCPClient", "MCPRegistry", "ToolHandle"]diff --git a/backend/app/agents/mcp/auth.py b/backend/app/agents/mcp/auth.pynew file mode 100644index 00000000..368d99ef--- /dev/null+++ b/backend/app/agents/mcp/auth.py@@ -0,0 +1,37 @@+from __future__ import annotations++import time+import uuid+from typing import Optional++from jose import jwt++from app.agents.config import get_agent_settings+++JWT_ISSUER = "securo-backend"+JWT_AUDIENCE = "securo-mcp"+JWT_ALGO = "HS256"+++def mint_token(+ *,+ user_id: uuid.UUID,+ conversation_id: Optional[uuid.UUID] = None,+ agent_id: Optional[uuid.UUID] = None,+ ttl_seconds: Optional[int] = None,+) -> str:+ s = get_agent_settings()+ now = int(time.time())+ payload = {+ "sub": str(user_id),+ "iss": JWT_ISSUER,+ "aud": JWT_AUDIENCE,+ "iat": now,+ "exp": now + (ttl_seconds or s.mcp_jwt_ttl_seconds),+ }+ if conversation_id:+ payload["conv_id"] = str(conversation_id)+ if agent_id:+ payload["agent_id"] = str(agent_id)+ return jwt.encode(payload, s.mcp_jwt_secret, algorithm=JWT_ALGO)diff --git a/backend/app/agents/mcp/client.py b/backend/app/agents/mcp/client.pynew file mode 100644index 00000000..14c31424--- /dev/null+++ b/backend/app/agents/mcp/client.py@@ -0,0 +1,199 @@+"""Minimal JSON-RPC 2.0 MCP client used by the agent runtime.++Talks to one or more MCP servers (Securo's built-in + any user-supplied).+Per call, mints a short-lived JWT scoped to (user_id, conversation_id).+"""+from __future__ import annotations++import uuid+from dataclasses import dataclass+from typing import Any, Optional++import httpx++from app.agents.config import get_agent_settings+from app.agents.mcp.auth import mint_token+from app.agents.providers.base import ToolDefinition+++@dataclass+class ToolHandle:+ """One discovered tool, with the server it belongs to and its schema."""+ server: str+ name: str+ description: str+ parameters: dict[str, Any]+ is_proposal: bool = False+++@dataclass+class _ServerSpec:+ name: str+ url: str+++def _parse_servers() -> list[_ServerSpec]:+ s = get_agent_settings()+ out = [_ServerSpec(name="securo", url=s.builtin_mcp_url)]+ extra = (s.extra_mcp_servers or "").strip()+ if extra:+ for raw in extra.split(","):+ raw = raw.strip()+ if not raw:+ continue+ if "|" in raw:+ url, name = raw.split("|", 1)+ else:+ url, name = raw, raw+ out.append(_ServerSpec(name=name.strip(), url=url.strip()))+ return out+++class MCPClient:+ """Single-server JSON-RPC client. One instance per server URL."""++ def __init__(self, *, name: str, url: str):+ self.name = name+ self.url = url+ self._next_id = 0++ def _id(self) -> int:+ self._next_id += 1+ return self._next_id++ async def _post(self, method: str, params: dict[str, Any], *, token: str) -> Any:+ payload = {"jsonrpc": "2.0", "id": self._id(), "method": method, "params": params}+ headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}+ async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0)) as client:+ resp = await client.post(self.url, json=payload, headers=headers)+ resp.raise_for_status()+ data = resp.json()+ if "error" in data and data["error"]:+ raise RuntimeError(f"MCP {self.name} error: {data['error']}")+ return data.get("result")++ async def list_tools(self, *, token: str) -> list[ToolHandle]:+ result = await self._post("tools/list", {}, token=token)+ out: list[ToolHandle] = []+ for t in (result or {}).get("tools", []):+ extras = t.get("_securo") or {}+ out.append(ToolHandle(+ server=self.name,+ name=t.get("name") or "",+ description=t.get("description") or "",+ parameters=t.get("inputSchema") or {"type": "object", "properties": {}},+ is_proposal=bool(extras.get("is_proposal", False)),+ ))+ return out++ async def call_tool(+ self,+ *,+ name: str,+ arguments: dict[str, Any],+ token: str,+ ) -> dict[str, Any]:+ result = await self._post("tools/call", {"name": name, "arguments": arguments}, token=token)+ # Prefer structuredContent when present (our server emits both).+ if isinstance(result, dict) and "structuredContent" in result:+ return {+ "ok": not bool(result.get("isError")),+ "data": result.get("structuredContent"),+ "text": _join_text(result.get("content")),+ }+ return {"ok": not bool((result or {}).get("isError")), "data": result, "text": ""}+++def _join_text(content: Any) -> str:+ if not isinstance(content, list):+ return ""+ parts = []+ for c in content:+ if isinstance(c, dict) and c.get("type") == "text":+ parts.append(str(c.get("text") or ""))+ return "\n".join(parts)+++class MCPRegistry:+ """Aggregates tools from multiple MCP servers and routes calls. The+ namespacing convention is `<server>.<tool>` to avoid collisions when+ two servers expose tools with the same name.+ """++ def __init__(self):+ self._servers: dict[str, MCPClient] = {}+ for spec in _parse_servers():+ self._servers[spec.name] = MCPClient(name=spec.name, url=spec.url)++ def server_names(self) -> list[str]:+ return list(self._servers.keys())++ async def discover(+ self,+ *,+ user_id: uuid.UUID,+ conversation_id: Optional[uuid.UUID] = None,+ agent_id: Optional[uuid.UUID] = None,+ ) -> list[ToolHandle]:+ token = mint_token(user_id=user_id, conversation_id=conversation_id, agent_id=agent_id)+ out: list[ToolHandle] = []+ for client in self._servers.values():+ try:+ tools = await client.list_tools(token=token)+ except Exception:+ continue+ out.extend(tools)+ return out++ @staticmethod+ def to_provider_tools(handles: list[ToolHandle], *, allowed: Optional[set[tuple[str, str]]] = None) -> list[ToolDefinition]:+ """Convert MCP tool handles into provider-agnostic ToolDefinition.++ `allowed` is a set of (server, tool_name) pairs. When None, all are+ passed through. Tool name on the wire is `<server>__<name>` so the+ server can be recovered from the LLM's tool call.+ """+ out: list[ToolDefinition] = []+ for h in handles:+ if allowed is not None and (h.server, h.name) not in allowed:+ continue+ out.append(ToolDefinition(+ name=f"{h.server}__{h.name}",+ description=h.description,+ parameters=h.parameters or {"type": "object", "properties": {}},+ ))+ return out++ async def call(+ self,+ *,+ wire_name: str,+ arguments: dict[str, Any],+ user_id: uuid.UUID,+ conversation_id: Optional[uuid.UUID] = None,+ agent_id: Optional[uuid.UUID] = None,+ ) -> dict[str, Any]:+ # Pass agent_id so per-agent tools (search_knowledge_base) can+ # scope their results. Without this, MCP-side ctx.agent_id is+ # None and the knowledge tool refuses.+ token = mint_token(user_id=user_id, conversation_id=conversation_id, agent_id=agent_id)++ # Happy path: namespaced name (server__tool).+ if "__" in wire_name:+ server, tool_name = wire_name.split("__", 1)+ client = self._servers.get(server)+ if client is not None:+ return await client.call_tool(name=tool_name, arguments=arguments, token=token)++ # Fallback: many LLMs drop the namespace prefix and emit just the+ # bare tool name. Resolve by scanning every registered server.+ bare = wire_name.split("__", 1)[-1]+ for server_name, client in self._servers.items():+ try:+ handles = await client.list_tools(token=token)+ except Exception:+ continue+ if any(h.name == bare for h in handles):+ return await client.call_tool(name=bare, arguments=arguments, token=token)++ raise ValueError(f"unknown tool: {wire_name}")diff --git a/backend/app/agents/models/__init__.py b/backend/app/agents/models/__init__.pynew file mode 100644index 00000000..96a2c7ac--- /dev/null+++ b/backend/app/agents/models/__init__.py@@ -0,0 +1,16 @@+from app.agents.models.agent import Agent, AgentTool+from app.agents.models.connection import LlmConnection+from app.agents.models.conversation import Conversation, Message+from app.agents.models.knowledge import KnowledgeDoc, KnowledgeChunk+from app.agents.models.usage import LlmUsage++__all__ = [+ "Agent",+ "AgentTool",+ "LlmConnection",+ "Conversation",+ "Message",+ "KnowledgeDoc",+ "KnowledgeChunk",+ "LlmUsage",+]diff --git a/backend/app/agents/models/agent.py b/backend/app/agents/models/agent.pynew file mode 100644index 00000000..d28687ad--- /dev/null+++ b/backend/app/agents/models/agent.py@@ -0,0 +1,77 @@+import uuid+from datetime import datetime+from typing import Optional++from sqlalchemy import JSON, Boolean, DateTime, Float, ForeignKey, Integer, String, Text+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship+from sqlalchemy.sql import func++from app.core.database import Base+++class Agent(Base):+ __tablename__ = "agents"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True)+ name: Mapped[str] = mapped_column(String(120))+ description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ system_prompt: Mapped[str] = mapped_column(Text, default="")+ icon: Mapped[str] = mapped_column(String(50), default="bot")+ color: Mapped[str] = mapped_column(String(7), default="#6B7280")++ # LLM config. There are three layers (most→least specific):+ # 1. agent.connection_id — user-managed connection (recommended)+ # 2. agent.provider — kind name; instance env vars supply creds+ # 3. instance defaults — env vars only+ # `model` is the model id within whichever provider/connection wins.+ connection_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("agent_llm_connections.id", ondelete="SET NULL"),+ nullable=True,+ )+ provider: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)+ model: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)+ temperature: Mapped[float] = mapped_column(Float, default=0.4)+ max_history_messages: Mapped[int] = mapped_column(Integer, default=20)++ # RAG tuning+ top_n: Mapped[int] = mapped_column(Integer, default=6)+ similarity_threshold: Mapped[float] = mapped_column(Float, default=0.25)++ # Free-form: per-agent overrides like {"language": "pt-BR"} or+ # {"channels": {"web": {...}, "whatsapp": {...}}}. Schema-light so we+ # can iterate without migrations.+ extra: Mapped[dict] = mapped_column(JSON, default=dict)++ # When True, the executor prepends a small "context primer" system+ # message before each turn — user name, currency, today's date,+ # account list. Saves the user from having to repeat themselves.+ auto_context: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")++ is_archived: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ # At most one agent per user has is_default=True (enforced by partial+ # unique index). The global slide-over chat panel uses this agent.+ is_default: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())++ tools: Mapped[list["AgentTool"]] = relationship(back_populates="agent", cascade="all, delete-orphan")+ conversations: Mapped[list["Conversation"]] = relationship(back_populates="agent", cascade="all, delete-orphan") # noqa: F821+ knowledge_docs: Mapped[list["KnowledgeDoc"]] = relationship(back_populates="agent", cascade="all, delete-orphan") # noqa: F821+++class AgentTool(Base):+ """Per-agent tool whitelist. Tools are discovered from registered MCP+ servers; this row records that the user has enabled a given tool for a+ given agent. Absence = disabled (closed-by-default for safety on writes).+ """+ __tablename__ = "agent_tools"++ agent_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE"), primary_key=True)+ server: Mapped[str] = mapped_column(String(80), primary_key=True)+ tool_name: Mapped[str] = mapped_column(String(120), primary_key=True)+ enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")++ agent: Mapped["Agent"] = relationship(back_populates="tools")diff --git a/backend/app/agents/models/connection.py b/backend/app/agents/models/connection.pynew file mode 100644index 00000000..fa015f1f--- /dev/null+++ b/backend/app/agents/models/connection.py@@ -0,0 +1,46 @@+import uuid+from datetime import datetime+from typing import Optional++from sqlalchemy import Boolean, DateTime, ForeignKey, JSON, String+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column+from sqlalchemy.sql import func++from app.core.database import Base+++class LlmConnection(Base):+ """User-managed LLM endpoint config.++ One row per (user, named connection). Agents reference these via+ `agents.connection_id`. When an agent has no connection set, the+ executor falls back to the instance-wide env-var defaults so the+ feature still works out of the box.+ """+ __tablename__ = "agent_llm_connections"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True)++ name: Mapped[str] = mapped_column(String(120))+ # kind ∈ {"ollama","openai","anthropic","openai_compatible"}+ kind: Mapped[str] = mapped_column(String(40))++ # Endpoint base URL. Optional for openai/anthropic (they have defaults).+ base_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+ # Fernet ciphertext (base64). Decrypted on use only — see crypto.py.+ api_key_encrypted: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)++ # Just a hint shown in the agent form when picking this connection.+ default_model: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)++ # Free-form per-connection config (org_id, project, custom headers, etc.)+ extra: Mapped[dict] = mapped_column(JSON, default=dict)++ # When an agent doesn't pick a connection explicitly, the user's+ # is_default=True row wins over the env-based fallback.+ is_default: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())diff --git a/backend/app/agents/models/conversation.py b/backend/app/agents/models/conversation.pynew file mode 100644index 00000000..4e343313--- /dev/null+++ b/backend/app/agents/models/conversation.py@@ -0,0 +1,62 @@+import uuid+from datetime import datetime+from typing import Optional++from sqlalchemy import JSON, DateTime, ForeignKey, Index, Integer, String, Text+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship+from sqlalchemy.sql import func++from app.core.database import Base+++class Conversation(Base):+ __tablename__ = "agent_conversations"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ agent_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE"), index=True)+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True)++ # Channel of origin: "web", "whatsapp", "api", etc. The runtime is+ # channel-agnostic; this column lets us segment conversations later.+ channel: Mapped[str] = mapped_column(String(40), default="web")+ title: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())++ agent: Mapped["Agent"] = relationship(back_populates="conversations") # noqa: F821+ messages: Mapped[list["Message"]] = relationship(+ back_populates="conversation",+ cascade="all, delete-orphan",+ order_by="Message.ordinal",+ )+++class Message(Base):+ __tablename__ = "agent_messages"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ conversation_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agent_conversations.id", ondelete="CASCADE"))+ ordinal: Mapped[int] = mapped_column(Integer)++ # role ∈ {"system","user","assistant","tool"}+ role: Mapped[str] = mapped_column(String(20))+ content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)++ # When role="assistant" with tool calls, list of {id,name,arguments}.+ tool_calls: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)+ # When role="tool", payload is {tool_call_id, server, name, result, error?}.+ tool_result: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)+ # Citations attached to this message (RAG hits, transactions, etc.).+ citations: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)++ input_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ output_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())++ conversation: Mapped["Conversation"] = relationship(back_populates="messages")++ __table_args__ = (+ Index("ix_agent_messages_conv_ord", "conversation_id", "ordinal"),+ )diff --git a/backend/app/agents/models/knowledge.py b/backend/app/agents/models/knowledge.pynew file mode 100644index 00000000..9d24952f--- /dev/null+++ b/backend/app/agents/models/knowledge.py@@ -0,0 +1,60 @@+import uuid+from datetime import datetime+from typing import Optional++from pgvector.sqlalchemy import Vector+from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String, Text+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship+from sqlalchemy.sql import func++from app.agents.config import get_agent_settings+from app.core.database import Base++_EMBED_DIM = get_agent_settings().embedding_dim+++class KnowledgeDoc(Base):+ __tablename__ = "agent_knowledge_docs"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ agent_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE"), index=True)+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"))++ title: Mapped[str] = mapped_column(String(255))+ source: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+ mime: Mapped[str] = mapped_column(String(80))+ storage_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+ size_bytes: Mapped[int] = mapped_column(Integer, default=0)++ # status ∈ {"pending","processing","ready","failed"}+ status: Mapped[str] = mapped_column(String(20), default="pending")+ error: Mapped[Optional[str]] = mapped_column(Text, nullable=True)++ chunk_count: Mapped[int] = mapped_column(Integer, default=0)+ pinned: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())++ agent: Mapped["Agent"] = relationship(back_populates="knowledge_docs") # noqa: F821+ chunks: Mapped[list["KnowledgeChunk"]] = relationship(back_populates="doc", cascade="all, delete-orphan")+++class KnowledgeChunk(Base):+ __tablename__ = "agent_knowledge_chunks"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ doc_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agent_knowledge_docs.id", ondelete="CASCADE"), index=True)+ agent_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE"), index=True)++ ordinal: Mapped[int] = mapped_column(Integer)+ content: Mapped[str] = mapped_column(Text)+ embedding: Mapped[Optional[list[float]]] = mapped_column(Vector(_EMBED_DIM), nullable=True)+ embedding_model: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)++ doc: Mapped["KnowledgeDoc"] = relationship(back_populates="chunks")++ __table_args__ = (+ Index("ix_agent_knowledge_chunks_doc_ord", "doc_id", "ordinal"),+ )diff --git a/backend/app/agents/models/usage.py b/backend/app/agents/models/usage.pynew file mode 100644index 00000000..bba83eeb--- /dev/null+++ b/backend/app/agents/models/usage.py@@ -0,0 +1,36 @@+import uuid+from datetime import datetime+from typing import Optional++from sqlalchemy import DateTime, ForeignKey, Integer, Numeric, String+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column+from sqlalchemy.sql import func++from app.core.database import Base+++class LlmUsage(Base):+ """Per-call LLM usage record. Drives cost dashboards and rate-limit+ decisions per user/agent. Conversation/message FKs are nullable so we+ can also log embedding calls and other non-chat usage.+ """+ __tablename__ = "agent_llm_usage"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True)+ agent_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("agents.id", ondelete="SET NULL"), nullable=True, index=True)+ conversation_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("agent_conversations.id", ondelete="SET NULL"), nullable=True)+ message_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("agent_messages.id", ondelete="SET NULL"), nullable=True)++ provider: Mapped[str] = mapped_column(String(40))+ model: Mapped[str] = mapped_column(String(120))+ # kind ∈ {"chat","embedding"}+ kind: Mapped[str] = mapped_column(String(20), default="chat")++ input_tokens: Mapped[int] = mapped_column(Integer, default=0)+ output_tokens: Mapped[int] = mapped_column(Integer, default=0)+ cost_usd: Mapped[Optional[float]] = mapped_column(Numeric(10, 6), nullable=True)+ latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)++ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())diff --git a/backend/app/agents/providers/__init__.py b/backend/app/agents/providers/__init__.pynew file mode 100644index 00000000..363290b3--- /dev/null+++ b/backend/app/agents/providers/__init__.py@@ -0,0 +1,22 @@+from app.agents.providers.base import (+ ChatChunk,+ ChatMessage,+ ChatResponse,+ LLMError,+ LLMProvider,+ ToolCall,+ ToolDefinition,+)+from app.agents.providers.registry import build_provider, list_providers++__all__ = [+ "ChatChunk",+ "ChatMessage",+ "ChatResponse",+ "LLMError",+ "LLMProvider",+ "ToolCall",+ "ToolDefinition",+ "build_provider",+ "list_providers",+]diff --git a/backend/app/agents/providers/anthropic.py b/backend/app/agents/providers/anthropic.pynew file mode 100644index 00000000..98aa0c73--- /dev/null+++ b/backend/app/agents/providers/anthropic.py@@ -0,0 +1,175 @@+from __future__ import annotations++import json+from typing import AsyncIterator, Optional++import httpx++from app.agents.providers.base import (+ ChatChunk,+ ChatMessage,+ LLMAuthError,+ LLMNotSupportedError,+ LLMProvider,+ LLMRateLimitError,+ LLMUnavailableError,+ ToolDefinition,+ Usage,+)+++def _split_system(messages: list[ChatMessage]) -> tuple[Optional[str], list[ChatMessage]]:+ sys: list[str] = []+ rest: list[ChatMessage] = []+ for m in messages:+ if m.role == "system" and m.content:+ sys.append(m.content)+ else:+ rest.append(m)+ return ("\n\n".join(sys) if sys else None), rest+++def _serialize_messages(messages: list[ChatMessage]) -> list[dict]:+ """Anthropic Messages API: alternating user/assistant, tool results+ are user-role messages with content blocks."""+ out: list[dict] = []+ for m in messages:+ if m.role == "tool":+ out.append({+ "role": "user",+ "content": [{+ "type": "tool_result",+ "tool_use_id": m.tool_call_id or "",+ "content": m.content or "",+ }],+ })+ continue+ if m.role == "assistant" and m.tool_calls:+ blocks: list[dict] = []+ if m.content:+ blocks.append({"type": "text", "text": m.content})+ for tc in m.tool_calls:+ blocks.append({"type": "tool_use", "id": tc.id, "name": tc.name, "input": tc.arguments})+ out.append({"role": "assistant", "content": blocks})+ continue+ out.append({"role": m.role, "content": m.content or ""})+ return out+++def _serialize_tools(tools: Optional[list[ToolDefinition]]) -> Optional[list[dict]]:+ if not tools:+ return None+ return [{"name": t.name, "description": t.description, "input_schema": t.parameters} for t in tools]+++def _raise_for_status(status: int, body: str) -> None:+ if status in (401, 403):+ raise LLMAuthError(f"Anthropic auth failed: {body}", status=status)+ if status == 429:+ raise LLMRateLimitError(f"Anthropic rate limit: {body}", status=status)+ if status >= 500:+ raise LLMUnavailableError(f"Anthropic {status}: {body}", status=status)+ if status >= 400:+ raise LLMUnavailableError(f"Anthropic {status}: {body}", status=status)+++class AnthropicProvider(LLMProvider):+ name = "anthropic"+ supports_embeddings = False++ def __init__(self, *, api_key: str, base_url: str = "https://api.anthropic.com/v1", model: Optional[str] = None):+ super().__init__(api_key=api_key, base_url=base_url, model=model)++ def _headers(self) -> dict[str, str]:+ return {+ "x-api-key": self.api_key,+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ }++ async def chat_stream(+ self,+ messages: list[ChatMessage],+ *,+ model: str,+ tools: Optional[list[ToolDefinition]] = None,+ temperature: float = 0.4,+ max_tokens: Optional[int] = None,+ ) -> AsyncIterator[ChatChunk]:+ url = f"{self.base_url.rstrip('/')}/messages"+ system, rest = _split_system(messages)+ payload: dict = {+ "model": model,+ "messages": _serialize_messages(rest),+ "max_tokens": max_tokens or 4096,+ "temperature": temperature,+ "stream": True,+ }+ if system:+ payload["system"] = system+ if tools:+ payload["tools"] = _serialize_tools(tools)++ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0)) as client:+ async with client.stream("POST", url, json=payload, headers=self._headers()) as resp:+ if resp.status_code >= 400:+ body = (await resp.aread()).decode("utf-8", errors="replace")+ _raise_for_status(resp.status_code, body)+ open_block: dict = {}+ usage = Usage()+ async for line in resp.aiter_lines():+ if not line.startswith("data:"):+ continue+ data_str = line[5:].strip()+ if not data_str:+ continue+ evt = json.loads(data_str)+ et = evt.get("type")+ if et == "content_block_start":+ block = evt.get("content_block") or {}+ idx = evt.get("index", 0)+ if block.get("type") == "tool_use":+ tcid = block.get("id") or f"toolu_{idx}"+ open_block[idx] = {"kind": "tool", "id": tcid, "name": block.get("name") or ""}+ yield ChatChunk(type="tool_call_start", tool_call_id=tcid, tool_name=open_block[idx]["name"])+ elif block.get("type") == "text":+ open_block[idx] = {"kind": "text"}+ elif et == "content_block_delta":+ idx = evt.get("index", 0)+ delta = evt.get("delta") or {}+ blk = open_block.get(idx) or {}+ if delta.get("type") == "text_delta" and delta.get("text"):+ yield ChatChunk(type="text_delta", text=delta["text"])+ elif delta.get("type") == "input_json_delta" and blk.get("kind") == "tool":+ yield ChatChunk(+ type="tool_call_args_delta",+ tool_call_id=blk["id"],+ args_delta=delta.get("partial_json") or "",+ )+ elif et == "content_block_stop":+ idx = evt.get("index", 0)+ blk = open_block.pop(idx, None)+ if blk and blk.get("kind") == "tool":+ yield ChatChunk(type="tool_call_end", tool_call_id=blk["id"])+ elif et == "message_delta":+ u = (evt.get("usage") or {})+ usage = Usage(+ input_tokens=usage.input_tokens or int(u.get("input_tokens") or 0),+ output_tokens=int(u.get("output_tokens") or usage.output_tokens),+ )+ stop = (evt.get("delta") or {}).get("stop_reason")+ if stop:+ yield ChatChunk(type="usage", usage=usage)+ yield ChatChunk(type="finish", finish_reason=stop)+ elif et == "message_start":+ u = ((evt.get("message") or {}).get("usage") or {})+ usage = Usage(+ input_tokens=int(u.get("input_tokens") or 0),+ output_tokens=int(u.get("output_tokens") or 0),+ )+ except httpx.HTTPError as exc:+ raise LLMUnavailableError(f"Anthropic unreachable: {exc}") from exc++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ raise LLMNotSupportedError("Anthropic does not provide an embeddings endpoint")diff --git a/backend/app/agents/providers/base.py b/backend/app/agents/providers/base.pynew file mode 100644index 00000000..9a627eb4--- /dev/null+++ b/backend/app/agents/providers/base.py@@ -0,0 +1,166 @@+from __future__ import annotations++from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from typing import Any, AsyncIterator, Literal, Optional+++# --- Errors ---------------------------------------------------------------++class LLMError(Exception):+ """Base class for provider failures. Subclasses let the runtime show+ the user a friendly message instead of a stack trace."""++ code: str = "unknown"++ def __init__(self, message: str, *, retryable: bool = False, status: Optional[int] = None):+ super().__init__(message)+ self.retryable = retryable+ self.status = status+++class LLMAuthError(LLMError):+ code = "auth"+++class LLMRateLimitError(LLMError):+ code = "rate_limit"++ def __init__(self, message: str, *, status: Optional[int] = None):+ super().__init__(message, retryable=True, status=status)+++class LLMUnavailableError(LLMError):+ code = "unavailable"++ def __init__(self, message: str, *, status: Optional[int] = None):+ super().__init__(message, retryable=True, status=status)+++class LLMNotSupportedError(LLMError):+ code = "not_supported"+++# --- Messages, tools, chunks ---------------------------------------------++Role = Literal["system", "user", "assistant", "tool"]+++@dataclass+class ToolCall:+ id: str+ name: str+ arguments: dict[str, Any]+++@dataclass+class ChatMessage:+ role: Role+ content: Optional[str] = None+ tool_calls: list[ToolCall] = field(default_factory=list)+ # For role="tool":+ tool_call_id: Optional[str] = None+ name: Optional[str] = None+++@dataclass+class ToolDefinition:+ """Provider-agnostic tool spec. Matches MCP/JSON-Schema shape."""+ name: str+ description: str+ parameters: dict[str, Any] # JSON Schema for the arguments object+++@dataclass+class Usage:+ input_tokens: int = 0+ output_tokens: int = 0+++@dataclass+class ChatChunk:+ """Streaming event. Exactly one of these fields is populated per chunk."""+ type: Literal["text_delta", "tool_call_start", "tool_call_args_delta", "tool_call_end", "finish", "usage"]+ text: Optional[str] = None+ tool_call_id: Optional[str] = None+ tool_name: Optional[str] = None+ args_delta: Optional[str] = None # incremental JSON args while streaming+ finish_reason: Optional[str] = None+ usage: Optional[Usage] = None+++@dataclass+class ChatResponse:+ content: str+ tool_calls: list[ToolCall] = field(default_factory=list)+ finish_reason: str = "stop"+ usage: Usage = field(default_factory=Usage)+++# --- Provider interface ---------------------------------------------------++class LLMProvider(ABC):+ name: str+ supports_native_tools: bool = True+ # Embedding capability — Anthropic returns False, others True.+ supports_embeddings: bool = True++ def __init__(self, *, api_key: str = "", base_url: Optional[str] = None, model: Optional[str] = None):+ self.api_key = api_key+ self.base_url = base_url+ self.default_model = model++ @abstractmethod+ async def chat_stream(+ self,+ messages: list[ChatMessage],+ *,+ model: str,+ tools: Optional[list[ToolDefinition]] = None,+ temperature: float = 0.4,+ max_tokens: Optional[int] = None,+ ) -> AsyncIterator[ChatChunk]:+ """Yield streaming chunks. Implementations are async generators."""+ ...++ async def chat(+ self,+ messages: list[ChatMessage],+ *,+ model: str,+ tools: Optional[list[ToolDefinition]] = None,+ temperature: float = 0.4,+ max_tokens: Optional[int] = None,+ ) -> ChatResponse:+ """Convenience: collect a streaming response into one ChatResponse."""+ text_parts: list[str] = []+ tool_calls: dict[str, dict] = {}+ finish: str = "stop"+ usage = Usage()+ async for chunk in self.chat_stream(+ messages, model=model, tools=tools, temperature=temperature, max_tokens=max_tokens+ ):+ if chunk.type == "text_delta" and chunk.text:+ text_parts.append(chunk.text)+ elif chunk.type == "tool_call_start" and chunk.tool_call_id:+ tool_calls[chunk.tool_call_id] = {"id": chunk.tool_call_id, "name": chunk.tool_name or "", "args_buf": ""}+ elif chunk.type == "tool_call_args_delta" and chunk.tool_call_id:+ tc = tool_calls.setdefault(chunk.tool_call_id, {"id": chunk.tool_call_id, "name": chunk.tool_name or "", "args_buf": ""})+ tc["args_buf"] += chunk.args_delta or ""+ elif chunk.type == "finish" and chunk.finish_reason:+ finish = chunk.finish_reason+ elif chunk.type == "usage" and chunk.usage:+ usage = chunk.usage+ import json+ parsed_calls = []+ for tc in tool_calls.values():+ try:+ args = json.loads(tc["args_buf"]) if tc["args_buf"] else {}+ except json.JSONDecodeError:+ args = {"_raw": tc["args_buf"]}+ parsed_calls.append(ToolCall(id=tc["id"], name=tc["name"], arguments=args))+ return ChatResponse(content="".join(text_parts), tool_calls=parsed_calls, finish_reason=finish, usage=usage)++ @abstractmethod+ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ ...diff --git a/backend/app/agents/providers/ollama.py b/backend/app/agents/providers/ollama.pynew file mode 100644index 00000000..908fd7bb--- /dev/null+++ b/backend/app/agents/providers/ollama.py@@ -0,0 +1,129 @@+from __future__ import annotations++import json+from typing import AsyncIterator, Optional++import httpx++from app.agents.providers.base import (+ ChatChunk,+ ChatMessage,+ LLMProvider,+ LLMUnavailableError,+ ToolDefinition,+ Usage,+)+++def _serialize_messages(messages: list[ChatMessage]) -> list[dict]:+ out: list[dict] = []+ for m in messages:+ msg: dict = {"role": m.role}+ if m.content is not None:+ msg["content"] = m.content+ if m.tool_calls:+ msg["tool_calls"] = [+ {"function": {"name": tc.name, "arguments": tc.arguments}} for tc in m.tool_calls+ ]+ if m.role == "tool":+ # Ollama expects content + name for tool results+ if m.name:+ msg["name"] = m.name+ out.append(msg)+ return out+++def _serialize_tools(tools: Optional[list[ToolDefinition]]) -> Optional[list[dict]]:+ if not tools:+ return None+ return [+ {+ "type": "function",+ "function": {+ "name": t.name,+ "description": t.description,+ "parameters": t.parameters,+ },+ }+ for t in tools+ ]+++class OllamaProvider(LLMProvider):+ name = "ollama"++ def __init__(self, *, base_url: str = "http://ollama:11434", api_key: str = "", model: Optional[str] = None):+ super().__init__(api_key=api_key, base_url=base_url, model=model)++ async def chat_stream(+ self,+ messages: list[ChatMessage],+ *,+ model: str,+ tools: Optional[list[ToolDefinition]] = None,+ temperature: float = 0.4,+ max_tokens: Optional[int] = None,+ ) -> AsyncIterator[ChatChunk]:+ url = f"{self.base_url.rstrip('/')}/api/chat"+ payload: dict = {+ "model": model,+ "messages": _serialize_messages(messages),+ "stream": True,+ "options": {"temperature": temperature},+ }+ if max_tokens is not None:+ payload["options"]["num_predict"] = max_tokens+ if tools:+ payload["tools"] = _serialize_tools(tools)++ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0)) as client:+ async with client.stream("POST", url, json=payload) as resp:+ if resp.status_code >= 400:+ body = (await resp.aread()).decode("utf-8", errors="replace")+ raise LLMUnavailableError(f"Ollama {resp.status_code}: {body}", status=resp.status_code)+ tool_idx = 0+ async for line in resp.aiter_lines():+ if not line.strip():+ continue+ data = json.loads(line)+ msg = data.get("message") or {}+ content = msg.get("content") or ""+ if content:+ yield ChatChunk(type="text_delta", text=content)+ for call in (msg.get("tool_calls") or []):+ fn = call.get("function") or {}+ args = fn.get("arguments") or {}+ if not isinstance(args, str):+ args = json.dumps(args)+ tcid = call.get("id") or f"call_{tool_idx}"+ tool_idx += 1+ yield ChatChunk(type="tool_call_start", tool_call_id=tcid, tool_name=fn.get("name") or "")+ yield ChatChunk(type="tool_call_args_delta", tool_call_id=tcid, args_delta=args)+ yield ChatChunk(type="tool_call_end", tool_call_id=tcid)+ if data.get("done"):+ usage = Usage(+ input_tokens=int(data.get("prompt_eval_count") or 0),+ output_tokens=int(data.get("eval_count") or 0),+ )+ yield ChatChunk(type="usage", usage=usage)+ yield ChatChunk(type="finish", finish_reason=data.get("done_reason") or "stop")+ except httpx.HTTPError as exc:+ raise LLMUnavailableError(f"Ollama unreachable: {exc}") from exc++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ url = f"{self.base_url.rstrip('/')}/api/embed"+ out: list[list[float]] = []+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0)) as client:+ # /api/embed accepts a list under `input` since Ollama 0.2+.+ resp = await client.post(url, json={"model": model, "input": texts})+ if resp.status_code >= 400:+ raise LLMUnavailableError(f"Ollama embed {resp.status_code}: {resp.text}", status=resp.status_code)+ data = resp.json()+ embeddings = data.get("embeddings") or []+ for vec in embeddings:+ out.append(list(vec))+ except httpx.HTTPError as exc:+ raise LLMUnavailableError(f"Ollama unreachable: {exc}") from exc+ return outdiff --git a/backend/app/agents/providers/openai.py b/backend/app/agents/providers/openai.pynew file mode 100644index 00000000..b7e57078--- /dev/null+++ b/backend/app/agents/providers/openai.py@@ -0,0 +1,232 @@+from __future__ import annotations++import json+from typing import AsyncIterator, Optional+from urllib.parse import urlparse++import httpx++from app.agents.providers.base import (+ ChatChunk,+ ChatMessage,+ LLMAuthError,+ LLMProvider,+ LLMRateLimitError,+ LLMUnavailableError,+ ToolDefinition,+ Usage,+)+++def normalize_openai_base_url(url: str) -> str:+ """Ensure the URL points to an OpenAI-compatible /v1 root.++ Most local OpenAI-compatible servers (LM Studio, vLLM, Ollama's+ openai endpoint, etc.) live under `/v1/*`. Users typically paste+ just the host — `http://lmstudio:1234` — expecting the client to+ append `/v1`. Without this, requests hit `/chat/completions` and+ silently 404 (LM Studio in particular returns 200 with no body).++ Rules:+ - empty → returned as-is+ - trailing slashes stripped+ - if any path segment looks like a version (`v1`, `v2`, `beta`,+ `latest`, `api/v3`, etc.), leave the URL alone+ - otherwise, append `/v1`+ """+ if not url:+ return url+ url = url.rstrip("/")+ path_segments = [s for s in (urlparse(url).path or "").split("/") if s]+ for seg in path_segments:+ if (+ (seg.startswith("v") and seg[1:].isdigit())+ or seg in {"beta", "latest"}+ ):+ return url+ return url + "/v1"+++def _serialize_messages(messages: list[ChatMessage]) -> list[dict]:+ out: list[dict] = []+ for m in messages:+ msg: dict = {"role": m.role}+ if m.content is not None:+ msg["content"] = m.content+ if m.tool_calls:+ msg["tool_calls"] = [+ {+ "id": tc.id,+ "type": "function",+ "function": {"name": tc.name, "arguments": json.dumps(tc.arguments)},+ }+ for tc in m.tool_calls+ ]+ if m.role == "tool":+ if m.tool_call_id:+ msg["tool_call_id"] = m.tool_call_id+ out.append(msg)+ return out+++def _serialize_tools(tools: Optional[list[ToolDefinition]]) -> Optional[list[dict]]:+ if not tools:+ return None+ return [+ {+ "type": "function",+ "function": {"name": t.name, "description": t.description, "parameters": t.parameters},+ }+ for t in tools+ ]+++def _raise_for_status(status: int, body: str) -> None:+ if status == 401 or status == 403:+ raise LLMAuthError(f"OpenAI auth failed: {body}", status=status)+ if status == 429:+ raise LLMRateLimitError(f"OpenAI rate limit: {body}", status=status)+ if status >= 500:+ raise LLMUnavailableError(f"OpenAI {status}: {body}", status=status)+ if status >= 400:+ raise LLMUnavailableError(f"OpenAI {status}: {body}", status=status)+++class OpenAIProvider(LLMProvider):+ name = "openai"++ def __init__(self, *, api_key: str = "", base_url: str = "https://api.openai.com/v1", model: Optional[str] = None):+ # Normalize at construction so every URL helper sees a `/v1`-rooted base.+ super().__init__(api_key=api_key, base_url=normalize_openai_base_url(base_url), model=model)++ def _headers(self) -> dict[str, str]:+ # Only attach Authorization when we actually have a key. Many local+ # OpenAI-compatible servers (LM Studio, vLLM, Ollama's OpenAI mode)+ # don't require auth — and httpx refuses to send the literal+ # `Bearer ` (with trailing space) as an illegal header value.+ h = {"Content-Type": "application/json"}+ if self.api_key:+ h["Authorization"] = f"Bearer {self.api_key}"+ return h++ async def chat_stream(+ self,+ messages: list[ChatMessage],+ *,+ model: str,+ tools: Optional[list[ToolDefinition]] = None,+ temperature: float = 0.4,+ max_tokens: Optional[int] = None,+ ) -> AsyncIterator[ChatChunk]:+ url = f"{self.base_url.rstrip('/')}/chat/completions"+ payload: dict = {+ "model": model,+ "messages": _serialize_messages(messages),+ "temperature": temperature,+ "stream": True,+ "stream_options": {"include_usage": True},+ }+ if tools:+ payload["tools"] = _serialize_tools(tools)+ if max_tokens is not None:+ payload["max_tokens"] = max_tokens++ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0)) as client:+ async with client.stream("POST", url, json=payload, headers=self._headers()) as resp:+ if resp.status_code >= 400:+ body = (await resp.aread()).decode("utf-8", errors="replace")+ _raise_for_status(resp.status_code, body)+ # OpenAI's streaming protocol uses `index` (an integer)+ # as the stable key for tool calls across chunks. The+ # first chunk for an index carries `id` and `name`;+ # subsequent chunks only carry `arguments` deltas.+ # We MUST key by index, not by id — otherwise later+ # chunks (without id) get registered as new entries+ # with empty names and the dispatcher fails with+ # "unknown tool: ".+ idx_state: dict[int, dict] = {}+ finish_reason: Optional[str] = None+ usage: Optional[Usage] = None+ async for raw in resp.aiter_lines():+ if not raw.startswith("data:"):+ continue+ chunk_str = raw[5:].strip()+ if not chunk_str or chunk_str == "[DONE]":+ continue+ chunk = json.loads(chunk_str)+ if chunk.get("usage"):+ u = chunk["usage"]+ usage = Usage(+ input_tokens=int(u.get("prompt_tokens") or 0),+ output_tokens=int(u.get("completion_tokens") or 0),+ )+ for choice in chunk.get("choices", []):+ delta = choice.get("delta") or {}+ if delta.get("content"):+ yield ChatChunk(type="text_delta", text=delta["content"])+ for tc in delta.get("tool_calls") or []:+ idx = int(tc.get("index", 0))+ fn = tc.get("function") or {}+ state = idx_state.setdefault(idx, {+ "id": None,+ "name": "",+ "started": False,+ "pending_args": "",+ })+ # First chunk usually carries both id and name;+ # some servers split the name across chunks.+ if tc.get("id") and not state["id"]:+ state["id"] = tc["id"]+ if fn.get("name"):+ state["name"] += fn["name"]+ # Emit start exactly once, when we have enough+ # info to dispatch (name is the must-have).+ if not state["started"] and state["name"]:+ if not state["id"]:+ state["id"] = f"_idx_{idx}"+ state["started"] = True+ yield ChatChunk(+ type="tool_call_start",+ tool_call_id=state["id"],+ tool_name=state["name"],+ )+ if state["pending_args"]:+ yield ChatChunk(+ type="tool_call_args_delta",+ tool_call_id=state["id"],+ args_delta=state["pending_args"],+ )+ state["pending_args"] = ""+ if fn.get("arguments"):+ if state["started"]:+ yield ChatChunk(+ type="tool_call_args_delta",+ tool_call_id=state["id"],+ args_delta=fn["arguments"],+ )+ else:+ # Args arrived before name (rare).+ state["pending_args"] += fn["arguments"]+ if choice.get("finish_reason"):+ finish_reason = choice["finish_reason"]+ for state in idx_state.values():+ if state["started"]:+ yield ChatChunk(type="tool_call_end", tool_call_id=state["id"])+ if usage:+ yield ChatChunk(type="usage", usage=usage)+ yield ChatChunk(type="finish", finish_reason=finish_reason or "stop")+ except httpx.HTTPError as exc:+ raise LLMUnavailableError(f"OpenAI unreachable: {exc}") from exc++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ url = f"{self.base_url.rstrip('/')}/embeddings"+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, connect=10.0)) as client:+ resp = await client.post(url, json={"model": model, "input": texts}, headers=self._headers())+ if resp.status_code >= 400:+ _raise_for_status(resp.status_code, resp.text)+ data = resp.json()+ return [item["embedding"] for item in data.get("data", [])]+ except httpx.HTTPError as exc:+ raise LLMUnavailableError(f"OpenAI unreachable: {exc}") from excdiff --git a/backend/app/agents/providers/openai_compatible.py b/backend/app/agents/providers/openai_compatible.pynew file mode 100644index 00000000..ba93cd56--- /dev/null+++ b/backend/app/agents/providers/openai_compatible.py@@ -0,0 +1,21 @@+from __future__ import annotations++from typing import Optional++from app.agents.providers.openai import OpenAIProvider+++class OpenAICompatibleProvider(OpenAIProvider):+ """Talks to any OpenAI-compatible /v1/chat/completions endpoint:+ Groq, Together, OpenRouter, LM Studio, vLLM, Mistral La Plateforme, etc.++ Caller supplies base_url (required) and api_key. Same wire format as+ OpenAIProvider, so we just swap the URL.+ """++ name = "openai_compatible"++ def __init__(self, *, base_url: str, api_key: str = "", model: Optional[str] = None):+ if not base_url:+ raise ValueError("openai_compatible provider requires base_url")+ super().__init__(api_key=api_key, base_url=base_url, model=model)diff --git a/backend/app/agents/providers/registry.py b/backend/app/agents/providers/registry.pynew file mode 100644index 00000000..20a6a5be--- /dev/null+++ b/backend/app/agents/providers/registry.py@@ -0,0 +1,37 @@+from __future__ import annotations++from typing import Optional++from app.agents.providers.anthropic import AnthropicProvider+from app.agents.providers.base import LLMProvider+from app.agents.providers.ollama import OllamaProvider+from app.agents.providers.openai import OpenAIProvider+from app.agents.providers.openai_compatible import OpenAICompatibleProvider+++_PROVIDERS: dict[str, type[LLMProvider]] = {+ "ollama": OllamaProvider,+ "openai": OpenAIProvider,+ "anthropic": AnthropicProvider,+ "openai_compatible": OpenAICompatibleProvider,+}+++def list_providers() -> list[str]:+ return sorted(_PROVIDERS.keys())+++def build_provider(+ name: str,+ *,+ api_key: str = "",+ base_url: Optional[str] = None,+ model: Optional[str] = None,+) -> LLMProvider:+ cls = _PROVIDERS.get(name)+ if cls is None:+ raise ValueError(f"Unknown LLM provider: {name}. Available: {list_providers()}")+ kwargs: dict = {"api_key": api_key, "model": model}+ if base_url:+ kwargs["base_url"] = base_url+ return cls(**{k: v for k, v in kwargs.items() if v is not None})diff --git a/backend/app/agents/runtime/__init__.py b/backend/app/agents/runtime/__init__.pynew file mode 100644index 00000000..3ccfef9a--- /dev/null+++ b/backend/app/agents/runtime/__init__.py@@ -0,0 +1,3 @@+from app.agents.runtime.executor import AgentExecutor, ExecutorEvent++__all__ = ["AgentExecutor", "ExecutorEvent"]diff --git a/backend/app/agents/runtime/executor.py b/backend/app/agents/runtime/executor.pynew file mode 100644index 00000000..04849a40--- /dev/null+++ b/backend/app/agents/runtime/executor.py@@ -0,0 +1,648 @@+"""Channel-agnostic agent execution loop.++Takes (agent, user_id, conversation_id, user_message) and yields a stream+of structured events. Whether the caller is the web SSE endpoint or a+future WhatsApp gateway, this loop is the same.++Flow:+ 1. Load conversation history from DB.+ 2. Discover tools from MCP servers; filter by per-agent whitelist.+ 3. Loop:+ a. Stream LLM response.+ b. If LLM emits tool calls, run them in parallel against MCP and+ feed results back as `role=tool` messages, then continue.+ c. Stop when finish_reason is `stop` (no tool call this turn).+ 4. Persist user + assistant messages and any tool messages.+"""+from __future__ import annotations++import asyncio+import logging+import os+import time+import uuid+from dataclasses import dataclass+from typing import Any, AsyncIterator, Literal, Optional++from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.config import get_agent_settings+from app.agents.mcp.client import MCPRegistry+from app.agents.models.agent import Agent+from app.agents.providers.base import (+ ChatChunk,+ ChatMessage,+ LLMAuthError,+ LLMError,+ LLMNotSupportedError,+ LLMRateLimitError,+ LLMUnavailableError,+ ToolCall,+)+from app.agents.providers.registry import build_provider+from app.agents.services import agent_service, context_service, conversation_service, usage_service++logger = logging.getLogger(__name__)+++@dataclass+class ExecutorEvent:+ type: Literal[+ "text_delta",+ "tool_call", # tool name + args (after assembly)+ "tool_result", # tool name + ok + summary+ "citation",+ "error",+ "done",+ ]+ text: Optional[str] = None+ tool_name: Optional[str] = None+ tool_args: Optional[dict[str, Any]] = None+ tool_result: Optional[dict[str, Any]] = None+ citation: Optional[dict[str, Any]] = None+ error_code: Optional[str] = None+ error_message: Optional[str] = None+ finish_reason: Optional[str] = None+++def _provider_for(agent: Agent):+ """Build a provider from env-var defaults (no connection lookup).++ Kept as a separate function so tests can monkey-patch this single+ seam to inject a scripted provider. Production goes through+ `_provider_and_model_for` which prefers user-managed connections.+ """+ name = agent.provider or os.getenv("AGENTS_DEFAULT_PROVIDER", "ollama")+ api_key = ""+ base_url = None+ if name == "openai":+ api_key = os.getenv("AGENTS_OPENAI_API_KEY", "")+ elif name == "anthropic":+ api_key = os.getenv("AGENTS_ANTHROPIC_API_KEY", "")+ elif name == "ollama":+ base_url = os.getenv("AGENTS_OLLAMA_BASE_URL", "http://ollama:11434")+ elif name == "openai_compatible":+ api_key = os.getenv("AGENTS_OPENAI_COMPAT_API_KEY", "")+ base_url = os.getenv("AGENTS_OPENAI_COMPAT_BASE_URL")+ return build_provider(name, api_key=api_key, base_url=base_url, model=agent.model)+++def _model_for(agent: Agent) -> str:+ if agent.model:+ return agent.model+ return os.getenv("AGENTS_DEFAULT_MODEL", "")+++async def _provider_and_model_for(session, agent: Agent):+ """Resolve (provider, model) using this priority:+ 1. agent.connection_id — explicit user-managed connection+ 2. user's default connection — is_default=True+ 3. _provider_for(agent) — env-var fallback (testable seam)++ Returns (LLMProvider, model_id_str).+ """+ from app.agents.services import connection_service # local import: cycle safety++ conn = None+ if agent.connection_id:+ conn = await connection_service.get_connection(session, agent.connection_id, agent.user_id)+ if conn is None:+ conn = await connection_service.get_default_connection(session, agent.user_id)++ if conn is not None:+ provider = connection_service.build_provider_for_connection(conn)+ model = agent.model or conn.default_model or os.getenv("AGENTS_DEFAULT_MODEL", "")+ return provider, model++ return _provider_for(agent), _model_for(agent)+++_RUNTIME_GUARDRAIL = (+ "## Runtime rules (always apply, regardless of the agent's own prompt)\n"+ "\n"+ "1. Tools whose name starts with `propose_` are PREVIEWS, not actions. "+ "Calling them does NOT change the user's data. They return a structured "+ "proposal and the UI renders an Apply button. After calling one, "+ "describe it as a proposal — say 'I prepared a proposal…' or 'Here's a "+ "preview…'. NEVER say 'I created', 'I added', 'Done', 'Ready', or "+ "anything that implies the action has been executed.\n"+ "\n"+ "2. Don't silently substitute entities the user named. If the user "+ "asks for a category/account/payee/group 'X' and the lookup returns "+ "no match, you MUST stop and tell the user before doing anything else. "+ "Never quietly pick a similar-looking one (e.g. user said 'Coleguinhas', "+ "only 'Amigos' exists → STOP, ask, do not build a proposal against "+ "'Amigos'). For categories specifically: if the user-named category "+ "doesn't exist, prefer leaving `category_id` null in the transaction "+ "proposal and mention it in your reply — don't chain a "+ "propose_create_category step unless the user explicitly asked to "+ "create the category.\n"+ "\n"+ "3. The auto-context primer (when present) is orientation only — never "+ "quote balances or counts from it; query the tools for live numbers.\n"+ "\n"+ "4. When responding in Portuguese (or any non-English language), keep "+ "your phrasing language-consistent — don't mix English snippets like "+ "'I prepared a proposal' into a Portuguese reply. Use 'Preparei uma "+ "proposta…' / 'Aqui está uma prévia…'.\n"+ "\n"+ "5. Charts: when a visualization would clearly help (trends over "+ "time, category breakdowns, comparisons), render one inline by "+ "emitting a fenced code block tagged `securo-chart`. The body is "+ "JSON. Multi-series example:\n"+ "\n"+ "```securo-chart\n"+ "{\n"+ ' "type": "line", // line | bar | area | pie\n'+ ' "title": "Income vs expenses (last 6 months)",\n'+ ' "currency": "BRL", // optional, formats Y axis as money\n'+ ' "data": [\n'+ ' {"x": "Jan", "income": 3200, "expense": 2100},\n'+ ' {"x": "Feb", "income": 3400, "expense": 2300}\n'+ " ],\n"+ ' "series": [\n'+ ' {"key": "income", "name": "Income"},\n'+ ' {"key": "expense", "name": "Expense"}\n'+ " ]\n"+ "}\n"+ "```\n"+ "\n"+ "Single-series shorthand: omit `series` and use the key `y`. "+ 'Example: `{\"type\":\"bar\",\"data\":[{\"x\":\"Food\",\"y\":500},'+ '{\"x\":\"Rent\",\"y\":1200}]}`. For pie use '+ '`{\"type\":\"pie\",\"data\":[{\"name\":\"Food\",\"value\":500},...]}`.\n'+ "\n"+ "Add a one-sentence summary above the chart; do NOT also list every "+ "data point in prose — let the chart speak. Only render charts when "+ "you have at least 2 data points to show.\n"+ "\n"+ "6. Knowledge base: if `search_knowledge_base` is available, the user "+ "has uploaded reference documents to this agent. Treat the KB as the "+ "authoritative source for anything that is NOT plainly transactional "+ "data in the user's accounts — including laws, regulations, tax rules, "+ "accounting standards, contracts, internal policies, project briefs, "+ "team/people names, internal codes, identifiers, dates, addresses, "+ "definitions, jargon, or any domain-specific knowledge.\n"+ "\n"+ " - You MUST call `search_knowledge_base` before any answer that "+ "claims something is or isn't in the documents. Phrases like 'não "+ "encontrei nos documentos', 'I didn't find this in the docs', or 'isso "+ "não consta' are forbidden unless you actually called the tool first "+ "and got no relevant result. Pre-judging without searching is a bug, "+ "even if you think the question is out of scope.\n"+ " - Use the user's own wording as the query (translate if needed). "+ "Try a second query with related terms if the first returns nothing.\n"+ " - If the KB returns relevant chunks, answer from them and cite the "+ "doc title or filename inline (e.g. 'segundo o briefing X…').\n"+ " - If the KB returns nothing relevant (no items, or only low-score "+ "chunks unrelated to the question), DO NOT invent an answer and DO NOT "+ "fall back to general world knowledge as if it were authoritative. "+ "Say plainly that you searched and didn't find this in the uploaded "+ "documents, and offer to look at it differently if the user can share "+ "a doc or rephrase. It's better to say 'I don't know' than to guess.\n"+ "\n"+ "7. Trust the tools' arithmetic. When `aggregate` or any other server-"+ "side total returns a value, that IS the answer — quote it directly. "+ "NEVER list the individual transactions and re-sum them by hand: model "+ "arithmetic over long lists is unreliable and will drift from the SQL "+ "result. If you need a keyword filter (merchant name, payee), pass "+ "`description_contains` to `aggregate` rather than listing and "+ "summing. The only acceptable place to do arithmetic yourself is a "+ "single combine step on tool outputs (e.g. `1847 * 12` = 22164).\n"+)+++def _format_page_context(page_context: Optional[dict[str, Any]]) -> Optional[str]:+ """Render the frontend's page-context blob as a short system message.++ The frontend builds a free-form dict — typically:+ {"path": "/transactions", "label": "Transactions",+ "filters": {...}, "selection": {...}, "summary": "..."}+ We render it as a compact bullet list so the model can parse it but+ the cost stays small. Empty/None values are dropped.+ """+ if not page_context:+ return None+ path = page_context.get("path") or page_context.get("route")+ label = page_context.get("label") or path+ lines = ["## Current page context",+ "The user is sending this message from the page below — when they refer "+ "to 'this', 'these', 'aqui', etc., it most likely refers to what's on "+ "this page right now."]+ if label or path:+ lines.append(f"- **Page:** {label or '?'}{f' ({path})' if (path and label != path) else ''}")+ summary = page_context.get("summary")+ if summary:+ lines.append(f"- **Summary:** {summary}")+ filters = page_context.get("filters")+ if filters:+ try:+ parts = ", ".join(f"{k}={v}" for k, v in filters.items() if v not in (None, "", []))+ if parts:+ lines.append(f"- **Active filters:** {parts}")+ except Exception: # noqa: BLE001+ lines.append(f"- **Active filters:** {filters!r}")+ selection = page_context.get("selection")+ if selection:+ try:+ n = len(selection) if hasattr(selection, "__len__") else None+ if isinstance(selection, list) and n:+ lines.append(f"- **Selected items ({n}):** {selection[:5]}{' …' if n > 5 else ''}")+ else:+ lines.append(f"- **Selection:** {selection!r}")+ except Exception: # noqa: BLE001+ lines.append(f"- **Selection:** {selection!r}")+ extra = {k: v for k, v in page_context.items() if k not in {"path", "route", "label", "summary", "filters", "selection"}}+ for k, v in extra.items():+ if v in (None, "", [], {}):+ continue+ lines.append(f"- **{k}:** {v}")+ return "\n".join(lines) if len(lines) > 2 else None+++def _build_agent_identity_primer(agent: Agent) -> str:+ """Baseline persona injected BEFORE the user's system_prompt.++ Tells the model two things it had no way to know before:+ 1. It's running inside Securo — an open-source, self-hosted+ personal-finance app — and what kind of help that implies.+ 2. Its own name and stated role, taken from the agent row itself+ (the user picked them in the UI).++ The user's `system_prompt` then runs AFTER this, so it can extend+ or override anything here without losing the product framing.+ """+ name = (agent.name or "Assistant").strip()+ description = (agent.description or "").strip()+ lines = [+ "## Who you are",+ f"You are **{name}**, an AI assistant running inside **Securo** — an "+ "open-source, self-hosted personal-finance app the user owns and "+ "runs on their own infrastructure. The user is the owner of the "+ "data you operate on; everything you read/write belongs to them.",+ ]+ if description:+ lines.append(f"\nYour stated role / specialty: {description}")+ lines.append(+ "\nGround rules:\n"+ "- Answer in the user's language (Portuguese, English, Spanish, etc.).\n"+ "- You have tools that read the user's data and `propose_*` tools "+ "that draft changes for the user to approve — those never apply "+ "by themselves.\n"+ "- Be concise, direct, and willing to make calls. Don't pad with "+ "warnings or boilerplate."+ )+ return "\n".join(lines)+++def _classify_error(exc: Exception) -> tuple[str, str]:+ # Always include the underlying exception message — without it the+ # UI just shows "unreachable" / "auth" with no clue about the actual+ # cause (wrong model id, expired key, missing endpoint, etc.).+ detail = str(exc).strip() or exc.__class__.__name__+ if isinstance(exc, LLMAuthError):+ return ("auth", f"LLM provider rejected the credentials. {detail}")+ if isinstance(exc, LLMRateLimitError):+ return ("rate_limit", f"LLM provider is rate-limiting. {detail}")+ if isinstance(exc, LLMUnavailableError):+ return ("unavailable", f"LLM provider error: {detail}")+ if isinstance(exc, LLMNotSupportedError):+ return ("not_supported", detail)+ if isinstance(exc, LLMError):+ return (exc.code, detail)+ return ("unknown", detail)+++class AgentExecutor:+ def __init__(self, *, mcp: Optional[MCPRegistry] = None):+ self.mcp = mcp or MCPRegistry()+ self.settings = get_agent_settings()++ async def run(+ self,+ *,+ session: AsyncSession,+ agent: Agent,+ user_id: uuid.UUID,+ conversation_id: uuid.UUID,+ user_message: str,+ channel: str = "web",+ page_context: Optional[dict[str, Any]] = None,+ ) -> AsyncIterator[ExecutorEvent]:+ # 1. Persist the user message first so it survives crashes.+ await conversation_service.append_message(+ session, conversation_id=conversation_id, role="user", content=user_message+ )+ await conversation_service.update_title_if_empty(session, conversation_id, user_message)++ # 2. Build the message list. Order, top to bottom:+ # 1. Runtime guardrail (app-level invariants — always)+ # 2. Agent identity primer (who you are + Securo framing)+ # 3. User-defined system_prompt (extends or overrides #2)+ # 4. Auto-context primer (user data: name, currency, accounts)+ # 5. Page-context primer (where the user is right now)+ # 6. Conversation history+ # 7. The new user message (appended in step 4 below)+ history = await conversation_service.list_messages(session, conversation_id, limit=agent.max_history_messages * 2 + 2)+ messages: list[ChatMessage] = []+ # Runtime guardrail goes FIRST and applies to every conversation,+ # regardless of agent settings or per-agent system prompt. Locks+ # in the propose-vs-action framing and the no-silent-substitution+ # rule. Agents can build on top of these but can't undo them.+ messages.append(ChatMessage(role="system", content=_RUNTIME_GUARDRAIL))+ # Agent identity — name + description + Securo framing. Ensures+ # the model knows what product it lives in and what role it was+ # configured for, even when the user leaves system_prompt blank.+ messages.append(ChatMessage(role="system", content=_build_agent_identity_primer(agent)))+ # User-defined system prompt extends/overrides the identity+ # primer. Goes BEFORE the data primers so it shapes the persona,+ # not just the per-turn answer.+ if agent.system_prompt and agent.system_prompt.strip():+ messages.append(ChatMessage(role="system", content=agent.system_prompt))+ # Optional context primer — user name, currency, accounts, etc.+ # Cheap orientation so the agent doesn't need to call list_accounts+ # on every "what's my balance?" question.+ if getattr(agent, "auto_context", True):+ try:+ from app.models.user import User+ user = await session.get(User, user_id)+ if user is not None:+ primer = await context_service.build_context_primer(session, user)+ if primer:+ messages.append(ChatMessage(role="system", content=primer))+ except Exception: # noqa: BLE001+ logger.exception("context primer failed; continuing without it")+ # Page-context primer — orientation about where the user is when+ # they sent THIS message. Goes after the agent's prompt so the+ # base persona always wins, but before history so prior turns+ # don't overshadow the current page.+ page_primer = _format_page_context(page_context)+ if page_primer:+ messages.append(ChatMessage(role="system", content=page_primer))+ for m in history:+ tcs = []+ for raw in (m.tool_calls or []):+ tcs.append(ToolCall(id=raw.get("id"), name=raw.get("name"), arguments=raw.get("arguments") or {}))+ tool_call_id = (m.tool_result or {}).get("tool_call_id") if m.role == "tool" else None+ content = m.content+ if m.role == "tool":+ # Encode tool result as content for the LLM.+ tr = m.tool_result or {}+ content = tr.get("text") or _safe_json(tr.get("data"))+ messages.append(ChatMessage(+ role=m.role, # type: ignore[arg-type]+ content=content,+ tool_calls=tcs,+ tool_call_id=tool_call_id,+ ))++ # 3. Discover tools from MCP and filter by per-agent whitelist.+ try:+ handles = await self.mcp.discover(user_id=user_id, conversation_id=conversation_id, agent_id=agent.id)+ except Exception:+ logger.exception("MCP discovery failed; running without tools")+ handles = []+ allowed = await agent_service.allowed_tool_pairs(session, agent.id)+ tool_defs = self.mcp.to_provider_tools(handles, allowed=allowed)++ # Resolve provider+model once per request. Monkey-patched in tests+ # via _provider_for; production prefers _provider_and_model_for.+ try:+ provider, model = await _provider_and_model_for(session, agent)+ except Exception: # noqa: BLE001+ logger.exception("provider resolution failed; falling back to legacy path")+ provider = _provider_for(agent)+ model = _model_for(agent)+ if not model:+ yield ExecutorEvent(+ type="error",+ error_code="config",+ error_message="Agent has no model configured. Pick a connection or set agent.model.",+ )+ yield ExecutorEvent(type="done", finish_reason="error")+ return++ # 4. Tool-calling loop. Cap iterations to prevent runaway agents.+ MAX_ITERS = 6+ for iteration in range(MAX_ITERS):+ text_buf: list[str] = []+ open_calls: dict[str, dict] = {}+ finish_reason = "stop"+ usage_input = 0+ usage_output = 0+ iter_start = time.time()+ try:+ async for chunk in provider.chat_stream(+ messages,+ model=model,+ tools=tool_defs or None,+ temperature=agent.temperature,+ ):+ async for ev in _process_chunk(chunk, text_buf, open_calls):+ yield ev+ if chunk.type == "finish":+ finish_reason = chunk.finish_reason or "stop"+ elif chunk.type == "usage" and chunk.usage:+ usage_input = chunk.usage.input_tokens+ usage_output = chunk.usage.output_tokens+ except LLMError as exc:+ # Log the full chain — the user-facing string is short by+ # design, but we want the traceback (and any wrapped+ # httpx error) in the backend logs for debugging.+ logger.exception("LLM provider call failed (kind=%s)", type(exc).__name__)+ code, msg = _classify_error(exc)+ yield ExecutorEvent(type="error", error_code=code, error_message=msg)+ yield ExecutorEvent(type="done", finish_reason="error")+ return+ except Exception as exc: # noqa: BLE001+ logger.exception("provider stream failed")+ yield ExecutorEvent(type="error", error_code="unknown", error_message=str(exc))+ yield ExecutorEvent(type="done", finish_reason="error")+ return++ assistant_text = "".join(text_buf)+ assembled_calls: list[ToolCall] = []+ for tc in open_calls.values():+ import json+ try:+ args = json.loads(tc["args_buf"]) if tc["args_buf"] else {}+ except json.JSONDecodeError:+ args = {"_raw": tc["args_buf"]}+ assembled_calls.append(ToolCall(id=tc["id"], name=tc["name"], arguments=args))++ # Persist assistant turn.+ assistant_msg = await conversation_service.append_message(+ session,+ conversation_id=conversation_id,+ role="assistant",+ content=assistant_text or None,+ tool_calls=[{"id": c.id, "name": c.name, "arguments": c.arguments} for c in assembled_calls] or None,+ input_tokens=usage_input or None,+ output_tokens=usage_output or None,+ )+ messages.append(ChatMessage(role="assistant", content=assistant_text or None, tool_calls=assembled_calls))++ # Record one usage row per provider call. Best-effort: a logging+ # failure should never break the user's chat.+ try:+ await usage_service.record_usage(+ session,+ user_id=user_id,+ agent_id=agent.id,+ conversation_id=conversation_id,+ message_id=assistant_msg.id,+ provider=provider.name,+ model=model,+ kind="chat",+ input_tokens=usage_input,+ output_tokens=usage_output,+ latency_ms=int((time.time() - iter_start) * 1000),+ )+ except Exception: # noqa: BLE001+ logger.exception("failed to record llm usage")++ if not assembled_calls:+ # If the model returned nothing at all (no text, no tool+ # call, no usage), the endpoint probably isn't actually+ # an LLM — surface that as a friendly error instead of a+ # silent close that leaves the UI hanging. Most common+ # cause: openai_compatible base_url missing the /v1 path.+ if not assistant_text and not usage_input and not usage_output:+ yield ExecutorEvent(+ type="error",+ error_code="empty_response",+ error_message=(+ f"The {provider.name} endpoint returned no content. "+ "Check that the connection's base URL is correct and points to an OpenAI-compatible /v1 root, "+ "and that the model name matches what's loaded on the server."+ ),+ )+ yield ExecutorEvent(type="done", finish_reason="error")+ return+ yield ExecutorEvent(type="done", finish_reason=finish_reason)+ return++ # 5. Run tool calls in parallel, persist + emit results, loop.+ for ev in [ExecutorEvent(type="tool_call", tool_name=c.name, tool_args=c.arguments) for c in assembled_calls]:+ yield ev++ results = await asyncio.gather(*[+ _safe_call_tool(self.mcp, c, user_id=user_id, conversation_id=conversation_id, agent_id=agent.id)+ for c in assembled_calls+ ])+ for c, res in zip(assembled_calls, results):+ # Two views of the same result:+ # - `summary` is a SHORT preview for the UI chip header+ # (e.g. "5 items returned"). Truncating this is fine.+ # - `llm_content` is the FULL JSON for the model to read.+ # Truncating this is what caused the model to think the+ # data was incomplete and report fake "truncated" rows.+ summary = _summarize_result(res)+ llm_content = _safe_json(res.get("data") if res.get("data") is not None else res.get("text"))+ yield ExecutorEvent(type="tool_result", tool_name=c.name, tool_result=summary)+ await conversation_service.append_message(+ session,+ conversation_id=conversation_id,+ role="tool",+ content=llm_content,+ tool_result={+ "tool_call_id": c.id,+ "name": c.name,+ "data": summary.get("data"),+ "ok": summary.get("ok", False),+ },+ )+ messages.append(ChatMessage(+ role="tool",+ content=llm_content,+ tool_call_id=c.id,+ name=c.name,+ ))++ # Reached the tool-call ceiling without the model producing a final+ # answer. Emit a visible fallback so the UI doesn't show an empty+ # assistant bubble, and persist it so the conversation has a+ # readable transcript. The friendliest message reuses any text we+ # accumulated mid-loop if there is some.+ fallback = (+ "Não consegui completar essa consulta — pedi muitas ferramentas em sequência "+ "e o limite foi atingido. Reformule a pergunta de forma mais específica e eu tento "+ "de novo (por exemplo, restrinja a um período ou a uma categoria)."+ )+ yield ExecutorEvent(type="text_delta", text=fallback)+ await conversation_service.append_message(+ session, conversation_id=conversation_id, role="assistant", content=fallback,+ )+ yield ExecutorEvent(type="error", error_code="max_iterations", error_message="Agent reached its tool-call limit.")+ yield ExecutorEvent(type="done", finish_reason="max_iterations")+++async def _process_chunk(chunk: ChatChunk, text_buf: list[str], open_calls: dict[str, dict]) -> AsyncIterator[ExecutorEvent]:+ if chunk.type == "text_delta" and chunk.text:+ text_buf.append(chunk.text)+ yield ExecutorEvent(type="text_delta", text=chunk.text)+ elif chunk.type == "tool_call_start" and chunk.tool_call_id:+ open_calls[chunk.tool_call_id] = {+ "id": chunk.tool_call_id,+ "name": chunk.tool_name or "",+ "args_buf": "",+ }+ elif chunk.type == "tool_call_args_delta" and chunk.tool_call_id:+ tc = open_calls.setdefault(chunk.tool_call_id, {"id": chunk.tool_call_id, "name": "", "args_buf": ""})+ tc["args_buf"] += chunk.args_delta or ""+++async def _safe_call_tool(+ mcp: MCPRegistry,+ call: ToolCall,+ *,+ user_id: uuid.UUID,+ conversation_id: uuid.UUID,+ agent_id: Optional[uuid.UUID] = None,+) -> dict[str, Any]:+ started = time.time()+ try:+ return await mcp.call(+ wire_name=call.name,+ arguments=call.arguments,+ user_id=user_id,+ conversation_id=conversation_id,+ agent_id=agent_id,+ )+ except Exception as exc: # noqa: BLE001+ logger.exception("tool call %s failed", call.name)+ return {"ok": False, "data": None, "text": f"Tool error: {exc}", "elapsed_ms": int((time.time() - started) * 1000)}+++def _summarize_result(res: dict[str, Any]) -> dict[str, Any]:+ """Compact summary used by the UI tool-call chip — just a one-line+ hint plus the structured `data` (which the chip's expand view shows+ in full). Never feed this `text` back to the LLM directly; the LLM+ needs the complete payload, see executor.run().+ """+ data = res.get("data")+ short = ""+ if isinstance(data, dict):+ if isinstance(data.get("items"), list):+ total = data.get("total")+ n = total if isinstance(total, int) else len(data["items"])+ short = f"{n} item(s) returned"+ elif "error" in data:+ short = f"error: {data['error']}"+ elif "kind" in data:+ short = f"{data['kind']}"+ return {+ "ok": bool(res.get("ok", False)),+ "data": data,+ "text": short or None,+ }+++def _safe_json(obj: Any) -> str:+ """Serialize tool data for the LLM to read. No length cap — the+ model needs the full payload or it'll hallucinate truncation."""+ import json+ try:+ return json.dumps(obj, default=str)+ except Exception:+ return str(obj)diff --git a/backend/app/agents/schemas/__init__.py b/backend/app/agents/schemas/__init__.pynew file mode 100644index 00000000..57731772--- /dev/null+++ b/backend/app/agents/schemas/__init__.py@@ -0,0 +1,31 @@+from app.agents.schemas.agent import (+ AgentCreate,+ AgentRead,+ AgentToolToggle,+ AgentUpdate,+)+from app.agents.schemas.connection import (+ ConnectionCreate,+ ConnectionRead,+ ConnectionTestResult,+ ConnectionUpdate,+)+from app.agents.schemas.conversation import (+ ConversationRead,+ MessageRead,+ SendMessageRequest,+)++__all__ = [+ "AgentCreate",+ "AgentRead",+ "AgentToolToggle",+ "AgentUpdate",+ "ConnectionCreate",+ "ConnectionRead",+ "ConnectionTestResult",+ "ConnectionUpdate",+ "ConversationRead",+ "MessageRead",+ "SendMessageRequest",+]diff --git a/backend/app/agents/schemas/agent.py b/backend/app/agents/schemas/agent.pynew file mode 100644index 00000000..4cc70e10--- /dev/null+++ b/backend/app/agents/schemas/agent.py@@ -0,0 +1,82 @@+from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any, Optional++from pydantic import BaseModel, ConfigDict, Field+++class AgentCreate(BaseModel):+ name: str = Field(..., min_length=1, max_length=120)+ description: Optional[str] = None+ system_prompt: str = ""+ icon: str = "bot"+ color: str = "#6B7280"+ connection_id: Optional[uuid.UUID] = Field(+ None,+ description="LlmConnection to use; falls back to instance default when null",+ )+ provider: Optional[str] = None+ model: Optional[str] = None+ temperature: float = Field(0.4, ge=0.0, le=2.0)+ max_history_messages: int = Field(20, ge=1, le=200)+ top_n: int = Field(6, ge=0, le=50)+ similarity_threshold: float = Field(0.25, ge=0.0, le=1.0)+ extra: dict[str, Any] = Field(default_factory=dict)+ auto_context: bool = True+ is_default: bool = False+++class AgentUpdate(BaseModel):+ name: Optional[str] = Field(None, min_length=1, max_length=120)+ description: Optional[str] = None+ system_prompt: Optional[str] = None+ icon: Optional[str] = None+ color: Optional[str] = None+ connection_id: Optional[uuid.UUID] = None+ provider: Optional[str] = None+ model: Optional[str] = None+ temperature: Optional[float] = Field(None, ge=0.0, le=2.0)+ max_history_messages: Optional[int] = Field(None, ge=1, le=200)+ top_n: Optional[int] = Field(None, ge=0, le=50)+ similarity_threshold: Optional[float] = Field(None, ge=0.0, le=1.0)+ extra: Optional[dict[str, Any]] = None+ auto_context: Optional[bool] = None+ is_archived: Optional[bool] = None+ is_default: Optional[bool] = None+++class AgentToolToggle(BaseModel):+ server: str+ tool_name: str+ enabled: bool+++class AgentRead(BaseModel):+ model_config = ConfigDict(from_attributes=True)++ id: uuid.UUID+ name: str+ description: Optional[str]+ system_prompt: str+ icon: str+ color: str+ connection_id: Optional[uuid.UUID]+ provider: Optional[str]+ model: Optional[str]+ temperature: float+ max_history_messages: int+ top_n: int+ similarity_threshold: float+ extra: dict[str, Any]+ auto_context: bool = True+ is_archived: bool+ is_default: bool = False+ # Convenience counts populated by list_agents so the agents list+ # page can display them without N+1 round-trips. Defaults to 0 so+ # single-agent endpoints (which don't compute these) still validate.+ conversation_count: int = 0+ knowledge_count: int = 0+ created_at: datetime+ updated_at: datetimediff --git a/backend/app/agents/schemas/connection.py b/backend/app/agents/schemas/connection.pynew file mode 100644index 00000000..85a32736--- /dev/null+++ b/backend/app/agents/schemas/connection.py@@ -0,0 +1,65 @@+from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any, Optional++from pydantic import BaseModel, ConfigDict, Field+++class ConnectionCreate(BaseModel):+ name: str = Field(..., min_length=1, max_length=120)+ kind: str = Field(..., description="ollama|openai|anthropic|openai_compatible")+ base_url: Optional[str] = None+ api_key: Optional[str] = None+ default_model: Optional[str] = None+ extra: dict[str, Any] = Field(default_factory=dict)+ is_default: bool = False+++class ConnectionUpdate(BaseModel):+ name: Optional[str] = Field(None, min_length=1, max_length=120)+ base_url: Optional[str] = None+ # None = leave unchanged; empty string = clear; non-empty = replace+ api_key: Optional[str] = None+ default_model: Optional[str] = None+ extra: Optional[dict[str, Any]] = None+ is_default: Optional[bool] = None+++class ConnectionRead(BaseModel):+ """Note: api_key is NEVER returned. The presence of credentials is+ indicated by `has_api_key`."""+ model_config = ConfigDict(from_attributes=True)++ id: uuid.UUID+ name: str+ kind: str+ base_url: Optional[str]+ default_model: Optional[str]+ extra: dict[str, Any]+ is_default: bool+ has_api_key: bool+ created_at: datetime+ updated_at: datetime++ @classmethod+ def from_orm_row(cls, row) -> "ConnectionRead":+ return cls(+ id=row.id,+ name=row.name,+ kind=row.kind,+ base_url=row.base_url,+ default_model=row.default_model,+ extra=row.extra or {},+ is_default=bool(row.is_default),+ has_api_key=bool(row.api_key_encrypted),+ created_at=row.created_at,+ updated_at=row.updated_at,+ )+++class ConnectionTestResult(BaseModel):+ ok: bool+ detail: str+ models: Optional[list[str]] = Nonediff --git a/backend/app/agents/schemas/conversation.py b/backend/app/agents/schemas/conversation.pynew file mode 100644index 00000000..13ddf8e6--- /dev/null+++ b/backend/app/agents/schemas/conversation.py@@ -0,0 +1,44 @@+from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any, Optional++from pydantic import BaseModel, ConfigDict+++class MessageRead(BaseModel):+ model_config = ConfigDict(from_attributes=True)++ id: uuid.UUID+ role: str+ ordinal: int+ content: Optional[str]+ tool_calls: Optional[list[Any]]+ tool_result: Optional[dict[str, Any]]+ citations: Optional[list[Any]]+ input_tokens: Optional[int]+ output_tokens: Optional[int]+ created_at: datetime+++class ConversationRead(BaseModel):+ model_config = ConfigDict(from_attributes=True)++ id: uuid.UUID+ agent_id: uuid.UUID+ channel: str+ title: Optional[str]+ created_at: datetime+ updated_at: datetime+++class SendMessageRequest(BaseModel):+ content: str+ conversation_id: Optional[uuid.UUID] = None+ channel: str = "web"+ # Where the user is in the app when this message was sent. The+ # executor injects a short system message so the agent can answer+ # context-aware questions like "what about THIS row?". Format is+ # free-form — the frontend builds it from the active page.+ page_context: Optional[dict[str, Any]] = Nonediff --git a/backend/app/agents/services/__init__.py b/backend/app/agents/services/__init__.pynew file mode 100644index 00000000..6da26f51--- /dev/null+++ b/backend/app/agents/services/__init__.py@@ -0,0 +1,17 @@+from app.agents.services import (+ agent_service,+ connection_service,+ context_service,+ conversation_service,+ knowledge_service,+ usage_service,+)++__all__ = [+ "agent_service",+ "connection_service",+ "context_service",+ "conversation_service",+ "knowledge_service",+ "usage_service",+]diff --git a/backend/app/agents/services/agent_service.py b/backend/app/agents/services/agent_service.pynew file mode 100644index 00000000..e0caa291--- /dev/null+++ b/backend/app/agents/services/agent_service.py@@ -0,0 +1,170 @@+from __future__ import annotations++import uuid+from typing import Optional++from sqlalchemy import delete, func, select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.models.agent import Agent, AgentTool+from app.agents.models.conversation import Conversation+from app.agents.models.knowledge import KnowledgeDoc+from app.agents.schemas.agent import AgentCreate, AgentUpdate+++async def list_agents(session: AsyncSession, user_id: uuid.UUID, *, include_archived: bool = False) -> list[Agent]:+ q = select(Agent).where(Agent.user_id == user_id).order_by(Agent.created_at.desc())+ if not include_archived:+ q = q.where(Agent.is_archived.is_(False))+ rows = list((await session.execute(q)).scalars().all())+ # One scalar query per (conv, kb) so the agents list page can show+ # counts without N+1. Cheap on small fan-out; if agent counts grow+ # we should switch to a single GROUP BY join.+ if rows:+ ids = [a.id for a in rows]+ conv_counts = dict(+ (await session.execute(+ select(Conversation.agent_id, func.count(Conversation.id))+ .where(Conversation.agent_id.in_(ids))+ .group_by(Conversation.agent_id)+ )).all()+ )+ kb_counts = dict(+ (await session.execute(+ select(KnowledgeDoc.agent_id, func.count(KnowledgeDoc.id))+ .where(KnowledgeDoc.agent_id.in_(ids))+ .group_by(KnowledgeDoc.agent_id)+ )).all()+ )+ # Stash on the model instances; pydantic AgentRead reads them.+ for a in rows:+ a.conversation_count = int(conv_counts.get(a.id, 0)) # type: ignore[attr-defined]+ a.knowledge_count = int(kb_counts.get(a.id, 0)) # type: ignore[attr-defined]+ return rows+++async def get_agent(session: AsyncSession, agent_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Agent]:+ return (await session.execute(+ select(Agent).where(Agent.id == agent_id, Agent.user_id == user_id)+ )).scalar_one_or_none()+++async def create_agent(session: AsyncSession, user_id: uuid.UUID, data: AgentCreate) -> Agent:+ agent = Agent(+ user_id=user_id,+ name=data.name,+ description=data.description,+ system_prompt=data.system_prompt,+ icon=data.icon,+ color=data.color,+ connection_id=data.connection_id,+ provider=data.provider,+ model=data.model,+ temperature=data.temperature,+ max_history_messages=data.max_history_messages,+ top_n=data.top_n,+ similarity_threshold=data.similarity_threshold,+ extra=data.extra or {},+ auto_context=data.auto_context,+ )+ session.add(agent)+ await session.commit()+ await session.refresh(agent)+ return agent+++async def update_agent(+ session: AsyncSession, agent_id: uuid.UUID, user_id: uuid.UUID, data: AgentUpdate+) -> Optional[Agent]:+ agent = await get_agent(session, agent_id, user_id)+ if agent is None:+ return None+ payload = data.model_dump(exclude_unset=True)+ # If turning this agent into the default, clear the flag on every+ # other agent of the same user first — the partial unique index+ # would otherwise reject the commit.+ if payload.get("is_default") is True:+ await session.execute(+ update(Agent)+ .where(Agent.user_id == user_id, Agent.id != agent_id, Agent.is_default.is_(True))+ .values(is_default=False)+ )+ for field, value in payload.items():+ setattr(agent, field, value)+ await session.commit()+ await session.refresh(agent)+ return agent+++async def get_default_agent(session: AsyncSession, user_id: uuid.UUID) -> Optional[Agent]:+ """The default agent is what the global slide-over chat panel uses.+ Falls back to the most-recently-created non-archived agent so the+ panel still works for users who haven't picked one yet."""+ explicit = (await session.execute(+ select(Agent).where(+ Agent.user_id == user_id,+ Agent.is_default.is_(True),+ Agent.is_archived.is_(False),+ )+ )).scalar_one_or_none()+ if explicit is not None:+ return explicit+ return (await session.execute(+ select(Agent)+ .where(Agent.user_id == user_id, Agent.is_archived.is_(False))+ .order_by(Agent.created_at.desc())+ .limit(1)+ )).scalar_one_or_none()+++async def delete_agent(session: AsyncSession, agent_id: uuid.UUID, user_id: uuid.UUID) -> bool:+ agent = await get_agent(session, agent_id, user_id)+ if agent is None:+ return False+ await session.delete(agent)+ await session.commit()+ return True+++async def list_tools(session: AsyncSession, agent_id: uuid.UUID) -> list[AgentTool]:+ return list((await session.execute(+ select(AgentTool).where(AgentTool.agent_id == agent_id)+ )).scalars().all())+++async def set_tool_enabled(+ session: AsyncSession, agent_id: uuid.UUID, server: str, tool_name: str, enabled: bool+) -> AgentTool:+ existing = (await session.execute(+ select(AgentTool).where(+ AgentTool.agent_id == agent_id,+ AgentTool.server == server,+ AgentTool.tool_name == tool_name,+ )+ )).scalar_one_or_none()+ if existing is None:+ existing = AgentTool(agent_id=agent_id, server=server, tool_name=tool_name, enabled=enabled)+ session.add(existing)+ else:+ existing.enabled = enabled+ await session.commit()+ return existing+++async def allowed_tool_pairs(session: AsyncSession, agent_id: uuid.UUID) -> Optional[set[tuple[str, str]]]:+ """Returns the set of (server, tool_name) pairs the agent is permitted+ to call. Returns None when no rows exist — interpreted as 'allow all'+ so first-run agents work without setup."""+ rows = await list_tools(session, agent_id)+ if not rows:+ return None+ return {(r.server, r.tool_name) for r in rows if r.enabled}+++async def replace_tool_enablement(+ session: AsyncSession, agent_id: uuid.UUID, items: list[tuple[str, str, bool]]+) -> None:+ await session.execute(delete(AgentTool).where(AgentTool.agent_id == agent_id))+ for server, name, enabled in items:+ session.add(AgentTool(agent_id=agent_id, server=server, tool_name=name, enabled=enabled))+ await session.commit()diff --git a/backend/app/agents/services/chunking.py b/backend/app/agents/services/chunking.pynew file mode 100644index 00000000..189f2bdd--- /dev/null+++ b/backend/app/agents/services/chunking.py@@ -0,0 +1,72 @@+"""Format-aware chunking for knowledge-base ingestion.++Goal: produce chunks of roughly TARGET characters with light paragraph-aware+splits and OVERLAP between adjacent chunks to preserve context. Cheap and+predictable; good enough for a v1 RAG pipeline.+"""+from __future__ import annotations++import io+import re+from typing import Iterable+++TARGET_CHARS = 2000+OVERLAP_CHARS = 200+++def chunk_text(text: str, *, target: int = TARGET_CHARS, overlap: int = OVERLAP_CHARS) -> list[str]:+ text = (text or "").strip()+ if not text:+ return []+ paragraphs = re.split(r"\n\s*\n", text)+ out: list[str] = []+ buf: list[str] = []+ buf_len = 0+ for p in paragraphs:+ p = p.strip()+ if not p:+ continue+ if buf_len + len(p) + 2 <= target or not buf:+ buf.append(p)+ buf_len += len(p) + 2+ else:+ out.append("\n\n".join(buf))+ # Start the next chunk with the tail of the previous one for+ # context continuity.+ tail = "\n\n".join(buf)[-overlap:] if overlap else ""+ buf = [tail, p] if tail else [p]+ buf_len = len(tail) + len(p) + 2+ if buf:+ out.append("\n\n".join(buf))+ # Final pass: anything still way too big gets hard-split.+ final: list[str] = []+ for c in out:+ if len(c) <= target * 1.5:+ final.append(c)+ else:+ for i in range(0, len(c), target):+ final.append(c[i:i + target])+ return [c.strip() for c in final if c.strip()]+++def parse_pdf_to_text(payload: bytes) -> str:+ from pypdf import PdfReader+ reader = PdfReader(io.BytesIO(payload))+ pages = [page.extract_text() or "" for page in reader.pages]+ return "\n\n".join(pages)+++def extract_text(payload: bytes, mime: str, filename: str = "") -> str:+ mime_l = (mime or "").lower()+ if "pdf" in mime_l or filename.lower().endswith(".pdf"):+ return parse_pdf_to_text(payload)+ # Default: treat as utf-8 text (covers .md, .txt, .markdown, .rst).+ try:+ return payload.decode("utf-8", errors="replace")+ except Exception:+ return ""+++def chunks_from_upload(payload: bytes, mime: str, filename: str = "") -> Iterable[str]:+ return chunk_text(extract_text(payload, mime, filename))diff --git a/backend/app/agents/services/connection_service.py b/backend/app/agents/services/connection_service.pynew file mode 100644index 00000000..27ac36fc--- /dev/null+++ b/backend/app/agents/services/connection_service.py@@ -0,0 +1,198 @@+"""User-managed LLM connections (provider endpoints + API keys)."""+from __future__ import annotations++import uuid+from typing import Any, Optional++from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.models.connection import LlmConnection+from app.agents.providers.registry import build_provider, list_providers+from app.agents.services.crypto import decrypt, encrypt+++VALID_KINDS = set(list_providers()) # ollama, openai, anthropic, openai_compatible+++async def list_connections(session: AsyncSession, user_id: uuid.UUID) -> list[LlmConnection]:+ return list((await session.execute(+ select(LlmConnection).where(LlmConnection.user_id == user_id).order_by(LlmConnection.created_at.desc())+ )).scalars().all())+++async def get_connection(+ session: AsyncSession, conn_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[LlmConnection]:+ return (await session.execute(+ select(LlmConnection).where(LlmConnection.id == conn_id, LlmConnection.user_id == user_id)+ )).scalar_one_or_none()+++async def get_default_connection(session: AsyncSession, user_id: uuid.UUID) -> Optional[LlmConnection]:+ return (await session.execute(+ select(LlmConnection).where(LlmConnection.user_id == user_id, LlmConnection.is_default.is_(True)).limit(1)+ )).scalar_one_or_none()+++async def create_connection(+ session: AsyncSession,+ user_id: uuid.UUID,+ *,+ name: str,+ kind: str,+ base_url: Optional[str] = None,+ api_key: Optional[str] = None,+ default_model: Optional[str] = None,+ extra: Optional[dict[str, Any]] = None,+ is_default: bool = False,+) -> LlmConnection:+ if kind not in VALID_KINDS:+ raise ValueError(f"unknown kind '{kind}', expected one of {sorted(VALID_KINDS)}")+ if kind == "openai_compatible" and not base_url:+ raise ValueError("openai_compatible requires base_url")++ if is_default:+ await _clear_default(session, user_id)++ conn = LlmConnection(+ user_id=user_id,+ name=name.strip(),+ kind=kind,+ base_url=(base_url or None),+ api_key_encrypted=encrypt(api_key) if api_key else None,+ default_model=(default_model or None),+ extra=extra or {},+ is_default=is_default,+ )+ session.add(conn)+ await session.commit()+ await session.refresh(conn)+ return conn+++async def update_connection(+ session: AsyncSession,+ conn_id: uuid.UUID,+ user_id: uuid.UUID,+ *,+ name: Optional[str] = None,+ base_url: Optional[str] = None,+ api_key: Optional[str] = None, # None = leave unchanged; "" = clear+ default_model: Optional[str] = None,+ extra: Optional[dict[str, Any]] = None,+ is_default: Optional[bool] = None,+) -> Optional[LlmConnection]:+ conn = await get_connection(session, conn_id, user_id)+ if conn is None:+ return None+ if name is not None:+ conn.name = name.strip()+ if base_url is not None:+ conn.base_url = base_url or None+ if api_key is not None:+ conn.api_key_encrypted = encrypt(api_key) if api_key else None+ if default_model is not None:+ conn.default_model = default_model or None+ if extra is not None:+ conn.extra = extra+ if is_default is True:+ await _clear_default(session, user_id, except_id=conn.id)+ conn.is_default = True+ elif is_default is False:+ conn.is_default = False+ await session.commit()+ await session.refresh(conn)+ return conn+++async def delete_connection(session: AsyncSession, conn_id: uuid.UUID, user_id: uuid.UUID) -> bool:+ conn = await get_connection(session, conn_id, user_id)+ if conn is None:+ return False+ await session.delete(conn)+ await session.commit()+ return True+++async def _clear_default(session: AsyncSession, user_id: uuid.UUID, *, except_id: Optional[uuid.UUID] = None) -> None:+ stmt = update(LlmConnection).where(LlmConnection.user_id == user_id, LlmConnection.is_default.is_(True))+ if except_id is not None:+ stmt = stmt.where(LlmConnection.id != except_id)+ await session.execute(stmt.values(is_default=False))+++def build_provider_for_connection(conn: LlmConnection):+ """Materialize a runtime LLMProvider instance for this connection."""+ return build_provider(+ conn.kind,+ api_key=decrypt(conn.api_key_encrypted) or "",+ base_url=conn.base_url or None,+ model=conn.default_model,+ )+++async def test_connection(conn: LlmConnection) -> dict[str, Any]:+ """Live probe. For Ollama we list models; for OpenAI/Anthropic we do+ a tiny embedding or a 1-token chat. Returns {ok, detail, models?}."""+ import httpx++ api_key = decrypt(conn.api_key_encrypted) or ""+ timeout = httpx.Timeout(10.0, connect=5.0)++ try:+ if conn.kind == "ollama":+ url = (conn.base_url or "http://ollama:11434").rstrip("/") + "/api/tags"+ async with httpx.AsyncClient(timeout=timeout) as client:+ r = await client.get(url)+ r.raise_for_status()+ models = [m.get("name") for m in (r.json().get("models") or [])]+ return {"ok": True, "detail": f"reachable ({len(models)} models)", "models": models}++ if conn.kind in ("openai", "openai_compatible"):+ # Use the same normalization the runtime provider applies, so+ # "test" hits the same URL "chat" will use. Detects bare-host+ # URLs (e.g. http://lmstudio:1234) and auto-appends /v1.+ from app.agents.providers.openai import normalize_openai_base_url++ base = normalize_openai_base_url(conn.base_url or "https://api.openai.com/v1")+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}+ async with httpx.AsyncClient(timeout=timeout) as client:+ r = await client.get(f"{base}/models", headers=headers)+ if r.status_code == 401 or r.status_code == 403:+ return {"ok": False, "detail": "auth rejected (check api key)"}+ if r.status_code >= 400:+ return {"ok": False, "detail": f"HTTP {r.status_code}: {r.text[:200]}"}+ # Some servers (LM Studio with a bad path) return 200 with+ # no JSON body — surface that as a useful warning instead+ # of a misleading "ok".+ try:+ payload = r.json()+ except Exception:+ return {"ok": False, "detail": f"reachable but {base}/models did not return JSON — wrong path?"}+ models = [m.get("id") for m in (payload.get("data") or [])][:50]+ if not models and conn.kind == "openai_compatible":+ return {+ "ok": False,+ "detail": f"reachable but {base}/models returned no models — check the base URL",+ }+ return {"ok": True, "detail": f"reachable at {base} ({len(models)} models)", "models": models}++ if conn.kind == "anthropic":+ base = (conn.base_url or "https://api.anthropic.com/v1").rstrip("/")+ headers = {"x-api-key": api_key, "anthropic-version": "2023-06-01"}+ async with httpx.AsyncClient(timeout=timeout) as client:+ r = await client.get(f"{base}/models", headers=headers)+ if r.status_code in (401, 403):+ return {"ok": False, "detail": "auth rejected (check api key)"}+ if r.status_code >= 400:+ return {"ok": False, "detail": f"HTTP {r.status_code}: {r.text[:200]}"}+ models = [m.get("id") for m in (r.json().get("data") or [])][:50]+ return {"ok": True, "detail": f"reachable ({len(models)} models)", "models": models}++ return {"ok": False, "detail": f"unknown kind: {conn.kind}"}++ except httpx.HTTPError as exc:+ return {"ok": False, "detail": f"unreachable: {exc}"}+ except Exception as exc: # noqa: BLE001+ return {"ok": False, "detail": str(exc)}diff --git a/backend/app/agents/services/context_service.py b/backend/app/agents/services/context_service.pynew file mode 100644index 00000000..09c27275--- /dev/null+++ b/backend/app/agents/services/context_service.py@@ -0,0 +1,110 @@+"""Builds a small "context primer" injected at the start of each+conversation when the agent has `auto_context=True`.++Goals:+ - Tiny budget: ~300 tokens. Cheap on every turn.+ - Stable orientation, not authoritative data — the LLM should still+ use tools for precise queries (balances, transactions, etc.).+ - Locale-aware: respects the user's primary currency and language.+"""+from __future__ import annotations++from datetime import datetime, timezone+from decimal import Decimal+from typing import Optional++from sqlalchemy.ext.asyncio import AsyncSession++from app.models.user import User+++def _fmt_amount(value: Optional[float | Decimal], currency: str) -> str:+ if value is None:+ return ""+ try:+ return f"{currency} {float(value):,.2f}"+ except Exception: # noqa: BLE001+ return f"{currency} {value}"+++def _user_label(user: User) -> str:+ prefs = getattr(user, "preferences", None) or {}+ name = (prefs.get("name") or prefs.get("display_name") or "").strip()+ email = (user.email or "").strip()+ if name and email:+ return f"{name} ({email})"+ if name:+ return name+ if "@" in email:+ return f"{email.split('@', 0)[0]} ({email})" if False else email+ return email or "the user"+++async def build_context_primer(session: AsyncSession, user: User, *, max_accounts: int = 10) -> str:+ """Returns a short Markdown block describing who the user is and+ what their accounts look like. Empty string when there's nothing+ useful to say."""+ from app.services import account_service++ prefs = getattr(user, "preferences", None) or {}+ primary_currency = prefs.get("currency_display") or "USD"+ language = prefs.get("language") or "en"+ timezone_label = prefs.get("timezone") or "UTC"++ today_utc = datetime.now(timezone.utc).date().isoformat()++ lines: list[str] = []+ lines.append("# Context for this conversation")+ lines.append("")+ lines.append("The user you are helping (Securo, a personal finance app):")+ lines.append(f"- Identity: {_user_label(user)}")+ lines.append(f"- Primary currency: {primary_currency}")+ lines.append(f"- Preferred language: {language}")+ lines.append(f"- Timezone: {timezone_label}")+ lines.append(f"- Today is {today_utc} (UTC)")+ lines.append("")++ try:+ rows = await account_service.get_accounts(session, user.id, include_closed=False)+ except Exception: # noqa: BLE001+ rows = []++ if rows:+ lines.append(f"Their open accounts (top {min(len(rows), max_accounts)}):")+ for row in rows[:max_accounts]:+ name = row.get("name") or "?"+ kind = row.get("type") or "account"+ currency = row.get("currency") or primary_currency+ balance = row.get("balance")+ balance_str = _fmt_amount(balance, currency) if balance is not None else ""+ account_id = row.get("id")+ piece = f"- {name} ({kind}"+ if balance_str:+ piece += f", {balance_str}"+ piece += ")"+ if account_id:+ piece += f" — id: {account_id}"+ lines.append(piece)+ lines.append("")++ lines.append(+ "Use the available tools (list_transactions, get_dashboard_snapshot, "+ "aggregate, etc.) for precise current data. The summary above is "+ "orientation only — never quote balances from this primer; query the "+ "tools instead."+ )+ lines.append("")+ lines.append("Tool-use rules:")+ lines.append(+ "- `propose_*` tools NEVER execute the action; they return a preview "+ "that renders as a card with an Apply button. After calling one, say "+ "'I prepared a proposal — review and click Apply to confirm', NOT "+ "'I created' or 'Done'."+ )+ lines.append(+ "- When the user names an entity (category, account, payee) you "+ "haven't seen, list it first. Do NOT silently substitute a "+ "different one — ask the user to pick from the existing list, or "+ "use `propose_create_category` to add the missing one."+ )+ return "\n".join(lines).strip()diff --git a/backend/app/agents/services/conversation_service.py b/backend/app/agents/services/conversation_service.pynew file mode 100644index 00000000..10c0c275--- /dev/null+++ b/backend/app/agents/services/conversation_service.py@@ -0,0 +1,126 @@+from __future__ import annotations++import uuid+from typing import Any, Optional++from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.models.conversation import Conversation, Message+++async def list_conversations(+ session: AsyncSession, user_id: uuid.UUID, agent_id: Optional[uuid.UUID] = None, limit: int = 50+) -> list[Conversation]:+ q = select(Conversation).where(Conversation.user_id == user_id)+ if agent_id:+ q = q.where(Conversation.agent_id == agent_id)+ q = q.order_by(Conversation.updated_at.desc()).limit(limit)+ return list((await session.execute(q)).scalars().all())+++async def get_conversation(+ session: AsyncSession, conversation_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[Conversation]:+ return (await session.execute(+ select(Conversation).where(Conversation.id == conversation_id, Conversation.user_id == user_id)+ )).scalar_one_or_none()+++async def create_conversation(+ session: AsyncSession,+ *,+ user_id: uuid.UUID,+ agent_id: uuid.UUID,+ channel: str = "web",+ title: Optional[str] = None,+) -> Conversation:+ conv = Conversation(user_id=user_id, agent_id=agent_id, channel=channel, title=title)+ session.add(conv)+ await session.commit()+ await session.refresh(conv)+ return conv+++async def delete_conversation(+ session: AsyncSession, conversation_id: uuid.UUID, user_id: uuid.UUID+) -> bool:+ conv = await get_conversation(session, conversation_id, user_id)+ if conv is None:+ return False+ await session.delete(conv)+ await session.commit()+ return True+++async def list_messages(+ session: AsyncSession, conversation_id: uuid.UUID, limit: int = 200+) -> list[Message]:+ q = (+ select(Message)+ .where(Message.conversation_id == conversation_id)+ .order_by(Message.ordinal.asc())+ .limit(limit)+ )+ return list((await session.execute(q)).scalars().all())+++async def append_message(+ session: AsyncSession,+ *,+ conversation_id: uuid.UUID,+ role: str,+ content: Optional[str] = None,+ tool_calls: Optional[list[Any]] = None,+ tool_result: Optional[dict[str, Any]] = None,+ citations: Optional[list[Any]] = None,+ input_tokens: Optional[int] = None,+ output_tokens: Optional[int] = None,+) -> Message:+ next_ord = (await session.execute(+ select(func.coalesce(func.max(Message.ordinal), 0) + 1).where(+ Message.conversation_id == conversation_id+ )+ )).scalar_one()+ msg = Message(+ conversation_id=conversation_id,+ ordinal=int(next_ord),+ role=role,+ content=content,+ tool_calls=tool_calls,+ tool_result=tool_result,+ citations=citations,+ input_tokens=input_tokens,+ output_tokens=output_tokens,+ )+ session.add(msg)+ await session.commit()+ await session.refresh(msg)+ return msg+++async def update_title_if_empty(+ session: AsyncSession, conversation_id: uuid.UUID, candidate: str+) -> None:+ conv = (await session.execute(+ select(Conversation).where(Conversation.id == conversation_id)+ )).scalar_one_or_none()+ if conv is None or conv.title:+ return+ conv.title = (candidate or "").strip()[:200] or None+ await session.commit()+++async def update_title(+ session: AsyncSession, conversation_id: uuid.UUID, user_id: uuid.UUID, title: str+) -> Optional[Conversation]:+ """Always overwrites the title (used by the rename UI and by the+ LLM-generated title endpoint). Returns the updated row, or None if+ not found / not owned by this user."""+ conv = await get_conversation(session, conversation_id, user_id)+ if conv is None:+ return None+ conv.title = (title or "").strip()[:200] or None+ await session.commit()+ await session.refresh(conv)+ return convdiff --git a/backend/app/agents/services/crypto.py b/backend/app/agents/services/crypto.pynew file mode 100644index 00000000..017705a7--- /dev/null+++ b/backend/app/agents/services/crypto.py@@ -0,0 +1,41 @@+"""Symmetric encryption for stored secrets (LLM API keys, etc.).++Key derivation: PBKDF2(SHA256, app SECRET_KEY) so we don't need a+separate key file. If the operator rotates SECRET_KEY, existing+ciphertexts become unreadable — that's by design (rotation = re-enter+your provider keys).+"""+from __future__ import annotations++import base64+import functools+import hashlib++from cryptography.fernet import Fernet, InvalidToken++from app.core.config import get_settings+++_SALT = b"securo-agents-llm-keys-v1"++[email protected]_cache(maxsize=1)+def _fernet() -> Fernet:+ secret = get_settings().secret_key.encode("utf-8")+ raw = hashlib.pbkdf2_hmac("sha256", secret, _SALT, iterations=100_000, dklen=32)+ return Fernet(base64.urlsafe_b64encode(raw))+++def encrypt(plaintext: str | None) -> str | None:+ if not plaintext:+ return None+ return _fernet().encrypt(plaintext.encode("utf-8")).decode("ascii")+++def decrypt(ciphertext: str | None) -> str | None:+ if not ciphertext:+ return None+ try:+ return _fernet().decrypt(ciphertext.encode("ascii")).decode("utf-8")+ except (InvalidToken, ValueError):+ return None # silently treat corrupt/rotated entries as missingdiff --git a/backend/app/agents/services/embedding.py b/backend/app/agents/services/embedding.pynew file mode 100644index 00000000..624840cf--- /dev/null+++ b/backend/app/agents/services/embedding.py@@ -0,0 +1,103 @@+"""Embedding helper.++Centralizes the choice of embedding provider+model and the dimension+adjustment (since pgvector columns are fixed-dimension and we lock to+`AGENTS_EMBEDDING_DIM`).++Providers:+ - `native`: in-process via fastembed (default). Multilingual MiniLM+ by default. Lazy-imports fastembed on first use so users not on the+ agents feature pay zero memory/import cost.+ - `ollama`: external Ollama embedding model.+ - `openai`: OpenAI's text-embedding-* endpoints.+ - `openai_compatible`: any OpenAI-shaped /v1/embeddings endpoint.+"""+from __future__ import annotations++import asyncio+import functools+import logging+from typing import Any, Optional++from app.agents.config import get_agent_settings+from app.agents.providers.base import LLMNotSupportedError+from app.agents.providers.registry import build_provider++logger = logging.getLogger(__name__)+++def _adjust_dim(vec: list[float], target: int) -> list[float]:+ """Pad with zeros or truncate to match the column dimension."""+ if len(vec) == target:+ return list(vec)+ if len(vec) > target:+ return list(vec[:target])+ out = list(vec)+ out.extend([0.0] * (target - len(vec)))+ return out++[email protected]_cache(maxsize=4)+def _get_native_embedder(model_name: str, cache_dir: str) -> Any:+ """Lazy-import fastembed and instantiate the model exactly once per+ (model, cache_dir). The first call downloads the ONNX model to+ `cache_dir` (~120 MB for the default multilingual MiniLM); subsequent+ calls hit the in-memory instance.++ Importing fastembed is intentionally inside this function — modules+ using `app.agents.services.embedding` don't drag fastembed in unless+ they actually trigger embedding (i.e. only the agents feature does).+ """+ from fastembed import TextEmbedding # heavy: onnxruntime + numpy++ logger.info("loading native embedder %s (cache=%s)", model_name, cache_dir)+ return TextEmbedding(model_name=model_name, cache_dir=cache_dir)+++def _embed_native_sync(texts: list[str], model_name: str, cache_dir: str) -> list[list[float]]:+ """Synchronous embed call. Runs in a thread via run_in_executor so+ we don't block the event loop on what's effectively CPU + I/O work."""+ emb = _get_native_embedder(model_name, cache_dir)+ return [list(map(float, v)) for v in emb.embed(texts)]+++async def _embed_native(texts: list[str]) -> tuple[list[list[float]], str]:+ s = get_agent_settings()+ loop = asyncio.get_running_loop()+ vectors = await loop.run_in_executor(+ None, _embed_native_sync, texts, s.embedding_model, s.embedding_native_cache_dir+ )+ return vectors, f"native:{s.embedding_model}"+++def _build_remote_provider():+ s = get_agent_settings()+ name = s.embedding_provider+ if name == "ollama":+ return build_provider("ollama", base_url=s.embedding_ollama_base_url)+ if name == "openai":+ return build_provider("openai", api_key=s.embedding_openai_api_key, base_url=s.embedding_openai_base_url)+ if name == "openai_compatible":+ return build_provider("openai_compatible", api_key=s.embedding_openai_api_key, base_url=s.embedding_openai_base_url)+ raise LLMNotSupportedError(f"embedding provider '{name}' has no embedding endpoint")+++async def embed_texts(texts: list[str]) -> tuple[list[list[float]], str]:+ """Returns (vectors, model_label). Vectors are dimension-adjusted to+ `AGENTS_EMBEDDING_DIM`."""+ if not texts:+ return [], get_agent_settings().embedding_model+ s = get_agent_settings()+ target = s.embedding_dim+ if s.embedding_provider == "native":+ raw, label = await _embed_native(texts)+ else:+ provider = _build_remote_provider()+ raw = await provider.embed(texts, model=s.embedding_model)+ label = f"{s.embedding_provider}:{s.embedding_model}"+ return ([_adjust_dim(v, target) for v in raw], label)+++async def embed_one(text: str) -> Optional[list[float]]:+ vecs, _ = await embed_texts([text])+ return vecs[0] if vecs else Nonediff --git a/backend/app/agents/services/knowledge_service.py b/backend/app/agents/services/knowledge_service.pynew file mode 100644index 00000000..2753c949--- /dev/null+++ b/backend/app/agents/services/knowledge_service.py@@ -0,0 +1,221 @@+"""Knowledge document upload + search.++Upload path:+ 1. Save raw bytes to disk under AGENTS_KNOWLEDGE_STORAGE_PATH.+ 2. Insert KnowledgeDoc with status="pending".+ 3. Dispatch Celery task to parse → chunk → embed asynchronously.++Search path:+ 1. Embed the query.+ 2. Cosine-distance similarity search against agent's chunks (pgvector).+ 3. Filter by similarity_threshold, sort by score, top_n.+"""+from __future__ import annotations++import hashlib+import os+import uuid+from typing import Any, Optional++from sqlalchemy import delete, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.config import get_agent_settings+from app.agents.models.knowledge import KnowledgeChunk, KnowledgeDoc+++def _storage_dir() -> str:+ base = get_agent_settings().knowledge_storage_path+ os.makedirs(base, exist_ok=True)+ return base+++def _disk_path(doc_id: uuid.UUID, filename: str) -> str:+ safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in filename)[-80:]+ return os.path.join(_storage_dir(), f"{doc_id}__{safe}")+++async def list_docs(session: AsyncSession, agent_id: uuid.UUID) -> list[KnowledgeDoc]:+ return list((await session.execute(+ select(KnowledgeDoc).where(KnowledgeDoc.agent_id == agent_id).order_by(KnowledgeDoc.created_at.desc())+ )).scalars().all())+++async def get_doc(session: AsyncSession, doc_id: uuid.UUID, user_id: uuid.UUID) -> Optional[KnowledgeDoc]:+ return (await session.execute(+ select(KnowledgeDoc).where(KnowledgeDoc.id == doc_id, KnowledgeDoc.user_id == user_id)+ )).scalar_one_or_none()+++async def upload_doc(+ session: AsyncSession,+ *,+ agent_id: uuid.UUID,+ user_id: uuid.UUID,+ filename: str,+ mime: str,+ payload: bytes,+ pinned: bool = False,+) -> KnowledgeDoc:+ settings = get_agent_settings()+ if len(payload) > settings.knowledge_max_file_size_mb * 1024 * 1024:+ raise ValueError(f"file exceeds {settings.knowledge_max_file_size_mb} MB limit")++ doc = KnowledgeDoc(+ agent_id=agent_id,+ user_id=user_id,+ title=filename,+ source=filename,+ mime=mime,+ size_bytes=len(payload),+ status="pending",+ pinned=pinned,+ )+ session.add(doc)+ await session.flush() # need doc.id to build the disk path+ path = _disk_path(doc.id, filename)+ with open(path, "wb") as fh:+ fh.write(payload)+ doc.storage_path = path+ await session.commit()+ await session.refresh(doc)+ return doc+++async def delete_doc(session: AsyncSession, doc_id: uuid.UUID, user_id: uuid.UUID) -> bool:+ doc = await get_doc(session, doc_id, user_id)+ if doc is None:+ return False+ path = doc.storage_path+ await session.delete(doc)+ await session.commit()+ if path and os.path.exists(path):+ try:+ os.remove(path)+ except OSError:+ pass+ return True+++async def set_pinned(session: AsyncSession, doc_id: uuid.UUID, user_id: uuid.UUID, pinned: bool) -> Optional[KnowledgeDoc]:+ doc = await get_doc(session, doc_id, user_id)+ if doc is None:+ return None+ doc.pinned = pinned+ await session.commit()+ await session.refresh(doc)+ return doc+++async def replace_chunks(+ session: AsyncSession,+ *,+ doc_id: uuid.UUID,+ agent_id: uuid.UUID,+ chunks: list[tuple[str, list[float]]],+ embedding_model: str,+) -> int:+ """Replace any existing chunks for this doc with new (content, embedding)+ pairs. Used by the Celery ingest task."""+ await session.execute(delete(KnowledgeChunk).where(KnowledgeChunk.doc_id == doc_id))+ for ordinal, (content, embedding) in enumerate(chunks):+ session.add(KnowledgeChunk(+ doc_id=doc_id,+ agent_id=agent_id,+ ordinal=ordinal,+ content=content,+ embedding=embedding,+ embedding_model=embedding_model,+ ))+ await session.commit()+ return len(chunks)+++async def mark_status(+ session: AsyncSession,+ doc_id: uuid.UUID,+ *,+ status: str,+ error: Optional[str] = None,+ chunk_count: Optional[int] = None,+) -> None:+ doc = (await session.execute(select(KnowledgeDoc).where(KnowledgeDoc.id == doc_id))).scalar_one_or_none()+ if doc is None:+ return+ doc.status = status+ # On success, always clear any stale error from prior attempts. Without+ # this the UI keeps showing "embed failed: …" alongside a green ready+ # badge, which is confusing.+ if status == "ready":+ doc.error = None+ elif error is not None:+ doc.error = error+ if chunk_count is not None:+ doc.chunk_count = chunk_count+ await session.commit()+++async def similarity_search(+ session: AsyncSession,+ *,+ agent_id: uuid.UUID,+ query_embedding: list[float],+ top_n: int = 6,+ similarity_threshold: float = 0.0,+) -> list[dict[str, Any]]:+ """Run cosine-distance ANN search. Lower distance = closer match.+ Returns rows with `score` = 1 - distance (so higher = better)."""+ distance = KnowledgeChunk.embedding.cosine_distance(query_embedding)+ q = (+ select(+ KnowledgeChunk.id,+ KnowledgeChunk.doc_id,+ KnowledgeChunk.ordinal,+ KnowledgeChunk.content,+ distance.label("distance"),+ )+ .where(KnowledgeChunk.agent_id == agent_id)+ .order_by(distance.asc())+ .limit(int(top_n) * 3) # over-fetch then threshold-filter+ )+ rows = (await session.execute(q)).all()+ out: list[dict[str, Any]] = []+ for r in rows:+ score = 1.0 - float(r.distance)+ if score < similarity_threshold:+ continue+ out.append({+ "id": str(r.id),+ "doc_id": str(r.doc_id),+ "ordinal": int(r.ordinal),+ "content": r.content,+ "score": score,+ })+ if len(out) >= top_n:+ break+ return out+++async def list_pinned_chunks(+ session: AsyncSession, *, agent_id: uuid.UUID, max_chunks: int = 20+) -> list[dict[str, Any]]:+ q = (+ select(KnowledgeChunk.id, KnowledgeChunk.doc_id, KnowledgeChunk.ordinal, KnowledgeChunk.content)+ .join(KnowledgeDoc, KnowledgeDoc.id == KnowledgeChunk.doc_id)+ .where(KnowledgeChunk.agent_id == agent_id, KnowledgeDoc.pinned.is_(True))+ .order_by(KnowledgeChunk.doc_id, KnowledgeChunk.ordinal)+ .limit(max_chunks)+ )+ rows = (await session.execute(q)).all()+ return [+ {"id": str(r.id), "doc_id": str(r.doc_id), "ordinal": int(r.ordinal), "content": r.content}+ for r in rows+ ]+++def hash_payload(payload: bytes) -> str:+ return hashlib.sha256(payload).hexdigest()+++def file_size_limit_mb() -> int:+ return get_agent_settings().knowledge_max_file_size_mbdiff --git a/backend/app/agents/services/usage_service.py b/backend/app/agents/services/usage_service.pynew file mode 100644index 00000000..df6ec8c0--- /dev/null+++ b/backend/app/agents/services/usage_service.py@@ -0,0 +1,72 @@+"""LLM usage logging.++Every provider call (chat or embedding) writes one row to `agent_llm_usage`.+Drives the per-user cost dashboard and any future rate-limiting.+"""+from __future__ import annotations++import uuid+from typing import Optional++from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.models.usage import LlmUsage+++# Rough per-1M-token USD pricing for cost estimates. Inaccurate by design —+# prices change weekly and this is just a budget ballpark for the user. Out+# of date entries default to 0 (logged for tokens but no cost shown).+_PRICING_PER_M = {+ # OpenAI+ ("openai", "gpt-4o"): (2.50, 10.00),+ ("openai", "gpt-4o-mini"): (0.15, 0.60),+ ("openai", "gpt-4-turbo"): (10.0, 30.0),+ ("openai", "gpt-3.5-turbo"): (0.50, 1.50),+ ("openai", "text-embedding-3-small"): (0.02, 0.0),+ ("openai", "text-embedding-3-large"): (0.13, 0.0),+ # Anthropic+ ("anthropic", "claude-opus-4-5"): (15.0, 75.0),+ ("anthropic", "claude-sonnet-4-5"): (3.0, 15.0),+ ("anthropic", "claude-haiku-4-5"): (0.25, 1.25),+}+++def estimate_cost_usd(provider: str, model: str, input_tokens: int, output_tokens: int) -> Optional[float]:+ rates = _PRICING_PER_M.get((provider, model))+ if rates is None:+ return None+ in_rate, out_rate = rates+ return round((input_tokens * in_rate + output_tokens * out_rate) / 1_000_000, 6)+++async def record_usage(+ session: AsyncSession,+ *,+ user_id: uuid.UUID,+ agent_id: Optional[uuid.UUID],+ conversation_id: Optional[uuid.UUID],+ message_id: Optional[uuid.UUID],+ provider: str,+ model: str,+ kind: str,+ input_tokens: int,+ output_tokens: int,+ latency_ms: Optional[int] = None,+) -> LlmUsage:+ cost = estimate_cost_usd(provider, model, input_tokens, output_tokens)+ row = LlmUsage(+ user_id=user_id,+ agent_id=agent_id,+ conversation_id=conversation_id,+ message_id=message_id,+ provider=provider,+ model=model,+ kind=kind,+ input_tokens=int(input_tokens or 0),+ output_tokens=int(output_tokens or 0),+ cost_usd=cost,+ latency_ms=latency_ms,+ )+ session.add(row)+ await session.commit()+ return rowdiff --git a/backend/app/agents/tasks/__init__.py b/backend/app/agents/tasks/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/backend/app/agents/tasks/ingest.py b/backend/app/agents/tasks/ingest.pynew file mode 100644index 00000000..b047272a--- /dev/null+++ b/backend/app/agents/tasks/ingest.py@@ -0,0 +1,85 @@+"""Celery task: parse → chunk → embed an uploaded knowledge document.++Registered with the existing celery_app. Only fires when AGENTS_ENABLED+is on, because the upload endpoint that dispatches it lives behind the+same flag.+"""+from __future__ import annotations++import asyncio+import logging+import uuid+from pathlib import Path++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from sqlalchemy.pool import NullPool++from app.core.config import get_settings+from app.worker import celery_app++logger = logging.getLogger(__name__)+++@celery_app.task(name="app.agents.tasks.ingest.ingest_doc", bind=True, max_retries=2, default_retry_delay=30)+def ingest_doc(self, doc_id_str: str, agent_id_str: str) -> dict:+ """Sync entry point that runs the async ingest in a fresh loop."""+ return asyncio.run(_async_ingest(doc_id_str, agent_id_str))+++async def _async_ingest(doc_id_str: str, agent_id_str: str) -> dict:+ doc_id = uuid.UUID(doc_id_str)+ agent_id = uuid.UUID(agent_id_str)++ # Create a fresh engine per task. Reusing the global async_session_maker+ # inside Celery prefork workers reuses asyncpg connections bound to+ # event loops that asyncio.run() has already closed, raising "another+ # operation is in progress" on the next task. NullPool ensures the+ # engine doesn't cache anything beyond this task.+ engine = create_async_engine(get_settings().database_url, poolclass=NullPool)+ session_maker = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)+ try:+ return await _do_ingest(session_maker, doc_id, agent_id)+ finally:+ await engine.dispose()+++async def _do_ingest(session_maker, doc_id: uuid.UUID, agent_id: uuid.UUID) -> dict:+ from app.agents.models.knowledge import KnowledgeDoc+ from app.agents.services import knowledge_service+ from app.agents.services.chunking import chunks_from_upload+ from app.agents.services.embedding import embed_texts+ from sqlalchemy import select++ async with session_maker() as session:+ await knowledge_service.mark_status(session, doc_id, status="processing")+ doc = (await session.execute(select(KnowledgeDoc).where(KnowledgeDoc.id == doc_id))).scalar_one_or_none()+ if doc is None or not doc.storage_path:+ return {"ok": False, "reason": "doc missing"}++ try:+ payload = Path(doc.storage_path).read_bytes()+ except Exception as exc: # noqa: BLE001+ await knowledge_service.mark_status(session, doc_id, status="failed", error=f"read failed: {exc}")+ return {"ok": False, "reason": "read failed"}++ chunks = list(chunks_from_upload(payload, doc.mime, doc.title))+ if not chunks:+ await knowledge_service.mark_status(session, doc_id, status="failed", error="no extractable text", chunk_count=0)+ return {"ok": False, "reason": "no text"}++ try:+ embeddings, model_label = await embed_texts(chunks)+ except Exception as exc: # noqa: BLE001+ logger.exception("embedding failed for doc %s", doc_id)+ await knowledge_service.mark_status(session, doc_id, status="failed", error=f"embed failed: {exc}")+ return {"ok": False, "reason": "embed failed"}++ n = await knowledge_service.replace_chunks(+ session,+ doc_id=doc_id,+ agent_id=agent_id,+ chunks=list(zip(chunks, embeddings)),+ embedding_model=model_label,+ )+ await knowledge_service.mark_status(session, doc_id, status="ready", error=None, chunk_count=n)+ return {"ok": True, "chunks": n}diff --git a/backend/app/api/info.py b/backend/app/api/info.pynew file mode 100644index 00000000..da4a2c18--- /dev/null+++ b/backend/app/api/info.py@@ -0,0 +1,23 @@+"""Public capability/feature-flag endpoint.++Tells the frontend which optional features are enabled so it can hide+nav items, routes, etc. Lightweight — no auth required.+"""+import os++from fastapi import APIRouter++router = APIRouter(prefix="/api", tags=["info"])+++def _flag(name: str, default: str = "false") -> bool:+ return os.getenv(name, default).strip().lower() in ("1", "true", "yes", "on")++[email protected]("/info")+async def get_app_info():+ return {+ "features": {+ "agents": _flag("AGENTS_ENABLED"),+ },+ }diff --git a/backend/app/main.py b/backend/app/main.pyindex 471479c5..6c3b2ffa 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -1,4 +1,5 @@import logging+import osfrom contextlib import asynccontextmanagerfrom fastapi import Depends, FastAPI@@ -15,6 +16,7 @@ from app.api.custom_auth import router as custom_auth_routerfrom app.api.dashboard import router as dashboard_routerfrom app.api.import_logs import router as import_logs_routerfrom app.api.import_transactions import router as import_router+from app.api.info import router as info_routerfrom app.api.recurring_transactions import router as recurring_routerfrom app.api.rules import router as rules_routerfrom app.api.assets import router as assets_router@@ -132,6 +134,33 @@ app.include_router(attachments_router)app.include_router(payees_router)app.include_router(settings_router)app.include_router(admin_router)+app.include_router(info_router)+++# Optional agents/MCP/LLM module — fully gated by AGENTS_ENABLED so users+# who don't want this feature pay zero cost (no imports, no routes, no+# background tasks). The module itself is self-contained in app/agents/.+if os.getenv("AGENTS_ENABLED", "false").strip().lower() in ("1", "true", "yes", "on"):+ try:+ from app.agents.api.info import router as agents_info_router+ from app.agents.api.agents import router as agents_router+ from app.agents.api.connections import router as agents_connections_router+ from app.agents.api.conversations import router as agents_conversations_router+ from app.agents.api.chat import router as agents_chat_router+ from app.agents.api.knowledge import router as agents_knowledge_router++ # Mount literal-prefix routers (conversations, connections) BEFORE+ # the generic agents router so paths like /api/agents/connections+ # don't get captured by /api/agents/{agent_id}.+ app.include_router(agents_info_router)+ app.include_router(agents_connections_router)+ app.include_router(agents_conversations_router)+ app.include_router(agents_router)+ app.include_router(agents_chat_router)+ app.include_router(agents_knowledge_router)+ logger.info("Agents feature enabled — mounted /api/agents routes")+ except Exception:+ logger.exception("Agents feature flag is on but import failed; routes not mounted")@app.get("/api/health")diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 59625f18..4269f24a 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -74,6 +74,10 @@ async def get_transactions(sort_by: Optional[str] = None,sort_dir: str = "desc",transaction_ids: Optional[list[uuid.UUID]] = None,+ currency: Optional[str] = None,+ min_amount: Optional[float] = None,+ max_amount: Optional[float] = None,+ account_types: Optional[list[str]] = None,) -> tuple[list[Transaction], int]:# In "accrual" mode, bucket/order by effective_date so list filters# line up with the cash-flow view used by the dashboard and reports.@@ -191,6 +195,22 @@ async def get_transactions(base_query = base_query.where(Transaction.transfer_pair_id.is_(None))if txn_type:base_query = base_query.where(Transaction.type == txn_type)+ if currency:+ # Native-currency filter — match the column verbatim. Lets agents+ # answer "do I have any EUR transactions?" without text-searching+ # the description column.+ base_query = base_query.where(Transaction.currency == currency.upper())+ if min_amount is not None or max_amount is not None:+ # Amount filters operate on the primary-currency value when+ # available so cross-currency totals make sense; fall back to the+ # native amount on rows that haven't been stamped yet.+ amount_expr = func.coalesce(Transaction.amount_primary, Transaction.amount)+ if min_amount is not None:+ base_query = base_query.where(amount_expr >= min_amount)+ if max_amount is not None:+ base_query = base_query.where(amount_expr <= max_amount)+ if account_types:+ base_query = base_query.where(Account.type.in_(account_types))# Bill-driven filter: when the caller passes bill_id, include# (a) txs linked to this bill via Pluggy's billId mapping (handles# charges the bank rolled into a bill whose nominal range doesn't@@ -318,7 +338,15 @@ async def get_transactions(# statement ordering regardless of accounting mode.default_order_col = bill_view_date_col if in_bill_view else date_colsort_columns: dict[str, object] = {+ # `date` is the cycle/accrual-aware column the UI lists use so its+ # ordering matches the cash-flow & dashboard views."date": default_order_col,+ # `transaction_date` orders strictly by Transaction.date (purchase+ # date), regardless of effective_bill_date. Useful for "what's my+ # most recent transaction?" where credit-card bill projections+ # would otherwise float old purchases to the top because their+ # bill due date is in the future.+ "transaction_date": Transaction.date,"amount": Transaction.amount,"description": Transaction.description,"payee": Payee.name,@@ -326,6 +354,7 @@ async def get_transactions("account": Account.name,"type": Transaction.type,"status": Transaction.status,+ "created_at": Transaction.created_at,}chosen_col = sort_columns.get(sort_by) if sort_by else Noneif chosen_col is None:diff --git a/backend/app/worker.py b/backend/app/worker.pyindex 84176eb7..9dbbb00c 100644--- a/backend/app/worker.py+++ b/backend/app/worker.py@@ -54,4 +54,7 @@ celery_app.conf.include = ["app.tasks.recurring_tasks","app.tasks.asset_tasks","app.tasks.fx_rate_tasks",+ # Optional agents module — registering the import is harmless when+ # AGENTS_ENABLED=false (the task just won't be dispatched).+ "app.agents.tasks.ingest",]diff --git a/backend/mcp_server/__init__.py b/backend/mcp_server/__init__.pynew file mode 100644index 00000000..828efd9d--- /dev/null+++ b/backend/mcp_server/__init__.py@@ -0,0 +1,15 @@+"""Securo's built-in MCP (Model Context Protocol) server.++Runs as a separate container (`mcp-server` in docker-compose, gated by the+`agents` profile). Exposes Securo's read APIs as MCP tools over JSON-RPC 2.0.++The server reuses the backend's Python image — same SQLAlchemy models,+same services — but listens on its own port (8765). The agent runtime+mints a short-lived JWT scoped to (user_id, conversation_id) and passes+it as a Bearer token; the MCP server verifies it and runs each tool with+that user's identity.++Tools are read-only in v1. Mutations are returned as `propose_*` previews+that the agent surfaces to the user; the user confirms in the UI, which+then triggers the existing Securo write endpoint. This keeps MCP safe.+"""diff --git a/backend/mcp_server/auth.py b/backend/mcp_server/auth.pynew file mode 100644index 00000000..750c3c4f--- /dev/null+++ b/backend/mcp_server/auth.py@@ -0,0 +1,65 @@+"""JWT verification for MCP requests.++The agent runtime (in the backend) mints a short-lived JWT per call,+signed with `AGENTS_MCP_JWT_SECRET`. We verify here. Same secret on both+sides; mismatched secret = 401 every time.+"""+from __future__ import annotations++import uuid+from dataclasses import dataclass+from typing import Optional++from fastapi import HTTPException, Request, status+from jose import JWTError, jwt++from app.agents.config import get_agent_settings+++JWT_ISSUER = "securo-backend"+JWT_AUDIENCE = "securo-mcp"+JWT_ALGO = "HS256"+++@dataclass+class CallContext:+ user_id: uuid.UUID+ conversation_id: Optional[uuid.UUID] = None+ agent_id: Optional[uuid.UUID] = None+++def _settings():+ return get_agent_settings()+++def verify_request(request: Request) -> CallContext:+ auth = request.headers.get("authorization") or ""+ if not auth.lower().startswith("bearer "):+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="missing bearer token")+ token = auth.split(" ", 1)[1].strip()+ try:+ payload = jwt.decode(+ token,+ _settings().mcp_jwt_secret,+ algorithms=[JWT_ALGO],+ audience=JWT_AUDIENCE,+ issuer=JWT_ISSUER,+ )+ except JWTError as exc:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"invalid token: {exc}") from exc++ sub = payload.get("sub")+ if not sub:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="missing subject")+ try:+ user_id = uuid.UUID(sub)+ except ValueError as exc:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="bad subject") from exc++ conv_raw = payload.get("conv_id")+ agent_raw = payload.get("agent_id")+ return CallContext(+ user_id=user_id,+ conversation_id=uuid.UUID(conv_raw) if conv_raw else None,+ agent_id=uuid.UUID(agent_raw) if agent_raw else None,+ )diff --git a/backend/mcp_server/main.py b/backend/mcp_server/main.pynew file mode 100644index 00000000..5ce5b6a9--- /dev/null+++ b/backend/mcp_server/main.py@@ -0,0 +1,120 @@+"""MCP server FastAPI app. JSON-RPC 2.0 over HTTP POST /mcp.++Exposes Securo's built-in tools (read-only + propose-mutations) over the+Model Context Protocol. Runs as a separate container; gated by the+`agents` profile in docker-compose.+"""+from __future__ import annotations++import logging+from typing import Any++from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse++from app.core.database import async_session_maker+from mcp_server import tools as _tools_pkg # noqa: F401 triggers tool registration+from mcp_server.auth import verify_request+from mcp_server.registry import REGISTRY, call_tool, list_tools++logger = logging.getLogger(__name__)++app = FastAPI(title="Securo MCP Server", openapi_url=None, docs_url=None)+++SERVER_INFO = {+ "name": "securo-builtin",+ "version": "0.1.0",+}+PROTOCOL_VERSION = "2024-11-05"+++def _err(req_id: Any, code: int, message: str, data: Any = None) -> dict:+ err: dict = {"code": code, "message": message}+ if data is not None:+ err["data"] = data+ return {"jsonrpc": "2.0", "id": req_id, "error": err}+++def _ok(req_id: Any, result: Any) -> dict:+ return {"jsonrpc": "2.0", "id": req_id, "result": result}++[email protected]("/health")+async def health():+ return {"status": "ok", "tools": len(REGISTRY)}++[email protected]("/mcp")+async def mcp(request: Request) -> JSONResponse:+ # Auth first — never accept unauthenticated calls.+ try:+ ctx = verify_request(request)+ except Exception as exc: # HTTPException from verify_request+ status_code = getattr(exc, "status_code", 401)+ detail = getattr(exc, "detail", str(exc))+ return JSONResponse(+ status_code=status_code,+ content={"jsonrpc": "2.0", "id": None, "error": {"code": -32001, "message": str(detail)}},+ )++ try:+ body = await request.json()+ except Exception:+ return JSONResponse(status_code=400, content=_err(None, -32700, "parse error"))++ if not isinstance(body, dict):+ return JSONResponse(status_code=400, content=_err(None, -32600, "invalid request"))++ req_id = body.get("id")+ method = body.get("method")+ params = body.get("params") or {}++ if body.get("jsonrpc") != "2.0" or not isinstance(method, str):+ return JSONResponse(status_code=400, content=_err(req_id, -32600, "invalid request"))++ if method == "initialize":+ return JSONResponse(+ content=_ok(req_id, {+ "protocolVersion": PROTOCOL_VERSION,+ "capabilities": {"tools": {"listChanged": False}},+ "serverInfo": SERVER_INFO,+ })+ )++ if method == "tools/list":+ return JSONResponse(content=_ok(req_id, {"tools": list_tools()}))++ if method == "tools/call":+ name = params.get("name")+ arguments = params.get("arguments") or {}+ if not isinstance(name, str):+ return JSONResponse(content=_err(req_id, -32602, "tools/call requires 'name'"))+ try:+ async with async_session_maker() as session:+ result = await call_tool(session, ctx, name, arguments)+ # MCP wraps tool output in `content` blocks. Use the structured+ # variant — many clients (and our own runtime) prefer JSON.+ return JSONResponse(content=_ok(req_id, {+ "content": [{"type": "text", "text": _safe_json(result)}],+ "structuredContent": result,+ "isError": False,+ }))+ except KeyError as exc:+ return JSONResponse(content=_err(req_id, -32601, str(exc)))+ except Exception as exc: # noqa: BLE001+ logger.exception("MCP tool failure: %s", name)+ return JSONResponse(content=_ok(req_id, {+ "content": [{"type": "text", "text": f"Tool error: {exc}"}],+ "isError": True,+ }))++ return JSONResponse(content=_err(req_id, -32601, f"unknown method: {method}"))+++def _safe_json(obj: Any) -> str:+ import json+ try:+ return json.dumps(obj, default=str)+ except Exception:+ return str(obj)diff --git a/backend/mcp_server/registry.py b/backend/mcp_server/registry.pynew file mode 100644index 00000000..1c4c8bd0--- /dev/null+++ b/backend/mcp_server/registry.py@@ -0,0 +1,82 @@+"""Tool registry for the MCP server.++Each tool is a Python coroutine registered via the @tool decorator. The+registry holds (name → ToolSpec) for /mcp's `tools/list` and `tools/call`.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Awaitable, Callable++from sqlalchemy.ext.asyncio import AsyncSession++from mcp_server.auth import CallContext+++ToolHandler = Callable[..., Awaitable[Any]]+++@dataclass+class ToolSpec:+ name: str+ description: str+ parameters: dict[str, Any] # JSON Schema (object)+ handler: ToolHandler+ # Optional. When True, the tool produces a preview (no DB writes); the+ # frontend asks the user to confirm before applying. Drives UI hints.+ is_proposal: bool = False+ tags: list[str] = field(default_factory=list)+++REGISTRY: dict[str, ToolSpec] = {}+++def tool(+ name: str,+ *,+ description: str,+ parameters: dict[str, Any],+ is_proposal: bool = False,+ tags: list[str] | None = None,+) -> Callable[[ToolHandler], ToolHandler]:+ """Decorator. The handler must be an async function with signature+ `async def handler(session: AsyncSession, ctx: CallContext, **kwargs)`.+ """+ def deco(fn: ToolHandler) -> ToolHandler:+ if name in REGISTRY:+ raise RuntimeError(f"duplicate tool registration: {name}")+ REGISTRY[name] = ToolSpec(+ name=name,+ description=description,+ parameters=parameters,+ handler=fn,+ is_proposal=is_proposal,+ tags=list(tags or []),+ )+ return fn+ return deco+++def list_tools() -> list[dict[str, Any]]:+ """MCP-compatible tool list payload."""+ return [+ {+ "name": s.name,+ "description": s.description,+ "inputSchema": s.parameters,+ "_securo": {"is_proposal": s.is_proposal, "tags": s.tags},+ }+ for s in REGISTRY.values()+ ]+++async def call_tool(+ session: AsyncSession,+ ctx: CallContext,+ name: str,+ arguments: dict[str, Any] | None,+) -> Any:+ spec = REGISTRY.get(name)+ if spec is None:+ raise KeyError(f"unknown tool: {name}")+ return await spec.handler(session=session, ctx=ctx, **(arguments or {}))diff --git a/backend/mcp_server/tools/__init__.py b/backend/mcp_server/tools/__init__.pynew file mode 100644index 00000000..c7309a66--- /dev/null+++ b/backend/mcp_server/tools/__init__.py@@ -0,0 +1,17 @@+"""Auto-imports all tool modules so they register themselves into the+shared registry on startup.+"""+from mcp_server.tools import ( # noqa: F401+ transactions,+ accounts,+ categories,+ payees,+ budgets,+ reports,+ search,+ aggregate,+ proposals,+ knowledge,+ lifecycle,+ groups,+)diff --git a/backend/mcp_server/tools/_helpers.py b/backend/mcp_server/tools/_helpers.pynew file mode 100644index 00000000..f684eaa5--- /dev/null+++ b/backend/mcp_server/tools/_helpers.py@@ -0,0 +1,45 @@+"""Shared helpers for serializing model rows into LLM-friendly dicts.++Keep payloads small and stable: a transaction returned to the LLM should+have a small set of obviously-named fields, not the full SQLAlchemy row.+"""+from __future__ import annotations++import uuid+from datetime import date, datetime+from decimal import Decimal+from typing import Any, Optional+++def parse_date(v: Any) -> Optional[date]:+ if v is None or v == "":+ return None+ if isinstance(v, date) and not isinstance(v, datetime):+ return v+ if isinstance(v, datetime):+ return v.date()+ return date.fromisoformat(str(v))+++def parse_uuid(v: Any) -> Optional[uuid.UUID]:+ if v is None or v == "":+ return None+ if isinstance(v, uuid.UUID):+ return v+ return uuid.UUID(str(v))+++def parse_uuid_list(v: Any) -> Optional[list[uuid.UUID]]:+ if v is None:+ return None+ if isinstance(v, (list, tuple)):+ return [parse_uuid(x) for x in v if x] or None+ return [parse_uuid(v)]+++def num(x: Any) -> Optional[float]:+ if x is None:+ return None+ if isinstance(x, Decimal):+ return float(x)+ return float(x)diff --git a/backend/mcp_server/tools/accounts.py b/backend/mcp_server/tools/accounts.pynew file mode 100644index 00000000..9f0916a8--- /dev/null+++ b/backend/mcp_server/tools/accounts.py@@ -0,0 +1,91 @@+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import account_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_date, parse_uuid+++@tool(+ name="list_accounts",+ description=(+ "List the user's accounts (checking, savings, credit cards, wallets, etc.) "+ "with current balances. Closed accounts are excluded by default."+ ),+ parameters={+ "type": "object",+ "properties": {+ "include_closed": {"type": "boolean", "default": False},+ },+ "additionalProperties": False,+ },+ tags=["read", "accounts"],+)+async def list_accounts(+ *,+ session: AsyncSession,+ ctx: CallContext,+ include_closed: bool = False,+) -> dict[str, Any]:+ rows = await account_service.get_accounts(session, ctx.user_id, include_closed=include_closed)+ # rows is already a list of dicts (per service contract), but normalize keys.+ items: list[dict[str, Any]] = []+ for r in rows:+ items.append({+ "id": str(r.get("id")) if r.get("id") else None,+ "name": r.get("name"),+ "type": r.get("type"),+ "currency": r.get("currency"),+ "balance": num(r.get("balance")),+ "balance_primary": num(r.get("balance_primary")),+ "is_closed": bool(r.get("is_closed", False)),+ "institution": r.get("institution"),+ })+ return {"items": items, "total": len(items)}+++@tool(+ name="get_account_summary",+ description=(+ "Income, expenses, and net for a single account over a date range. "+ "Defaults to the current month if no range is provided."+ ),+ parameters={+ "type": "object",+ "properties": {+ "account_id": {"type": "string", "format": "uuid"},+ "from_date": {"type": "string", "format": "date"},+ "to_date": {"type": "string", "format": "date"},+ },+ "required": ["account_id"],+ "additionalProperties": False,+ },+ tags=["read", "accounts"],+)+async def get_account_summary(+ *,+ session: AsyncSession,+ ctx: CallContext,+ account_id: str,+ from_date: str | None = None,+ to_date: str | None = None,+) -> dict[str, Any]:+ summary = await account_service.get_account_summary(+ session,+ parse_uuid(account_id),+ ctx.user_id,+ date_from=parse_date(from_date),+ date_to=parse_date(to_date),+ )+ if summary is None:+ return {"error": "account not found"}+ # Normalize numeric fields.+ for k in list(summary.keys()):+ v = summary[k]+ if hasattr(v, "isoformat"):+ summary[k] = v.isoformat()+ return summarydiff --git a/backend/mcp_server/tools/aggregate.py b/backend/mcp_server/tools/aggregate.pynew file mode 100644index 00000000..b806cd3c--- /dev/null+++ b/backend/mcp_server/tools/aggregate.py@@ -0,0 +1,165 @@+from __future__ import annotations++from typing import Any++from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.transaction import Transaction+from app.models.category import Category+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_date, parse_uuid_list+++@tool(+ name="aggregate",+ description=(+ "Aggregate transactions without writing custom SQL. Choose a metric "+ "(sum|count|avg) and a group_by (category|month|account|payee|day). "+ "Returns a list of {bucket, value, count} rows. Amounts use the "+ "user's primary currency when available, falling back to native. "+ "By default counts only POSTED transactions (already settled) — "+ "set status='all' or 'pending' to include scheduled/recurring rows."+ ),+ parameters={+ "type": "object",+ "properties": {+ "metric": {"type": "string", "enum": ["sum", "count", "avg"], "default": "sum"},+ "group_by": {"type": "string", "enum": ["category", "month", "account", "payee", "day"], "default": "category"},+ "from_date": {"type": "string", "format": "date"},+ "to_date": {"type": "string", "format": "date"},+ "account_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}},+ "category_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}},+ "payee_id": {"type": "string", "format": "uuid", "description": "Restrict to a single payee — useful for 'how much did I spend at X?'"},+ "currency": {"type": "string", "description": "Restrict to one native currency (BRL, USD, EUR, ...)"},+ "tx_type": {"type": "string", "enum": ["expense", "income"], "description": "Filter to expenses or income only"},+ "description_contains": {"type": "string", "description": "Case-insensitive substring match against the transaction description — use this to scope to a merchant/keyword like 'uber', 'spotify', 'amigos do bem'."},+ "status": {"type": "string", "enum": ["posted", "pending", "all"], "default": "posted", "description": "Default 'posted' = only money that already moved. Use 'pending' for scheduled/recurring not yet settled, or 'all' to include both."},+ "exclude_transfers": {"type": "boolean", "default": True},+ "limit": {"type": "integer", "minimum": 1, "maximum": 50, "default": 25, "description": "Max bucket rows in the result. Capped at 50."},+ },+ "additionalProperties": False,+ },+ tags=["read", "aggregate"],+)+async def aggregate(+ *,+ session: AsyncSession,+ ctx: CallContext,+ metric: str = "sum",+ group_by: str = "category",+ from_date: str | None = None,+ to_date: str | None = None,+ account_ids: list[str] | None = None,+ category_ids: list[str] | None = None,+ payee_id: str | None = None,+ currency: str | None = None,+ tx_type: str | None = None,+ description_contains: str | None = None,+ status: str = "posted",+ exclude_transfers: bool = True,+ limit: int = 25,+) -> dict[str, Any]:+ # Hard cap regardless of LLM input — keeps payload small enough for+ # token-tight providers.+ limit = max(1, min(int(limit), 50))+ amount_col = func.coalesce(Transaction.amount_primary, Transaction.amount)++ # Group expression + label expression.+ if group_by == "category":+ bucket_id = Transaction.category_id+ label_q = select(Category.id, Category.name).where(Category.user_id == ctx.user_id)+ elif group_by == "account":+ bucket_id = Transaction.account_id+ label_q = None+ elif group_by == "payee":+ bucket_id = Transaction.payee_id+ label_q = None+ elif group_by == "month":+ bucket_id = func.to_char(Transaction.date, "YYYY-MM")+ label_q = None+ elif group_by == "day":+ bucket_id = func.to_char(Transaction.date, "YYYY-MM-DD")+ label_q = None+ else:+ return {"error": f"unknown group_by: {group_by}"}++ if metric == "sum":+ value_expr = func.sum(amount_col)+ elif metric == "avg":+ value_expr = func.avg(amount_col)+ else: # count+ value_expr = func.count(Transaction.id)++ q = (+ select(bucket_id.label("bucket"), value_expr.label("value"), func.count(Transaction.id).label("count"))+ .where(Transaction.user_id == ctx.user_id)+ )++ fd = parse_date(from_date)+ td = parse_date(to_date)+ if fd:+ q = q.where(Transaction.date >= fd)+ if td:+ q = q.where(Transaction.date <= td)++ accs = parse_uuid_list(account_ids)+ if accs:+ q = q.where(Transaction.account_id.in_(accs))+ cats = parse_uuid_list(category_ids)+ if cats:+ q = q.where(Transaction.category_id.in_(cats))+ if payee_id:+ # parse_uuid_list returns a list — single payee_id wrapped works too.+ pids = parse_uuid_list([payee_id])+ if pids:+ q = q.where(Transaction.payee_id == pids[0])+ if currency:+ q = q.where(Transaction.currency == currency.upper())+ if description_contains:+ q = q.where(Transaction.description.ilike(f"%{description_contains}%"))+ # Status: default to "posted" so totals reflect money that actually+ # moved. The model can opt into "pending" or "all" when the user+ # explicitly asks about scheduled/projected amounts.+ if status == "posted":+ q = q.where(Transaction.status == "posted")+ elif status == "pending":+ q = q.where(Transaction.status == "pending")+ # status == "all" → no filter++ # Securo convention: type='debit' = expense, type='credit' = income.+ # Amount sign isn't authoritative because some imports normalize it.+ if tx_type == "expense":+ q = q.where(Transaction.type == "debit")+ elif tx_type == "income":+ q = q.where(Transaction.type == "credit")++ if exclude_transfers:+ q = q.where(Transaction.transfer_pair_id.is_(None))++ q = q.group_by(bucket_id).order_by(value_expr.desc().nulls_last()).limit(int(limit))++ rows = (await session.execute(q)).all()+ label_map: dict[Any, str] = {}+ if label_q is not None:+ for cid, cname in (await session.execute(label_q)).all():+ label_map[cid] = cname++ items = [+ {+ "bucket": str(r.bucket) if r.bucket is not None else None,+ "label": label_map.get(r.bucket),+ "value": num(r.value),+ "count": int(r.count or 0),+ }+ for r in rows+ ]+ return {+ "metric": metric,+ "group_by": group_by,+ "from_date": fd.isoformat() if fd else None,+ "to_date": td.isoformat() if td else None,+ "items": items,+ "total": len(items),+ }diff --git a/backend/mcp_server/tools/budgets.py b/backend/mcp_server/tools/budgets.pynew file mode 100644index 00000000..58a51f3f--- /dev/null+++ b/backend/mcp_server/tools/budgets.py@@ -0,0 +1,49 @@+from __future__ import annotations++from datetime import date+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import budget_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_date+++@tool(+ name="get_budget_vs_actual",+ description=(+ "For each budgeted category in the given month, return budget amount, "+ "actual spending, and the variance. Defaults to the current month."+ ),+ parameters={+ "type": "object",+ "properties": {+ "month": {"type": "string", "format": "date", "description": "Any date inside the target month (YYYY-MM-DD)"},+ },+ "additionalProperties": False,+ },+ tags=["read", "budgets"],+)+async def get_budget_vs_actual(+ *,+ session: AsyncSession,+ ctx: CallContext,+ month: str | None = None,+) -> dict[str, Any]:+ target = parse_date(month) or date.today().replace(day=1)+ rows = await budget_service.get_budget_vs_actual(session, ctx.user_id, month=target)+ items = []+ for r in rows:+ # BudgetVsActual is a Pydantic model; serialize defensively.+ d = r.model_dump() if hasattr(r, "model_dump") else r.__dict__+ items.append({+ "category_id": str(d.get("category_id")) if d.get("category_id") else None,+ "category_name": d.get("category_name"),+ "budget_amount": num(d.get("budget_amount") or d.get("amount")),+ "actual_amount": num(d.get("actual_amount") or d.get("actual") or d.get("spent")),+ "remaining": num(d.get("remaining")),+ "currency": d.get("currency"),+ })+ return {"month": target.isoformat(), "items": items, "total": len(items)}diff --git a/backend/mcp_server/tools/categories.py b/backend/mcp_server/tools/categories.pynew file mode 100644index 00000000..a8058d9f--- /dev/null+++ b/backend/mcp_server/tools/categories.py@@ -0,0 +1,40 @@+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import category_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+++@tool(+ name="list_categories",+ description=(+ "List the user's categories. Each category has an id, name, optional "+ "group_id, icon, and color. Use the ids when filtering or proposing "+ "categorization."+ ),+ parameters={"type": "object", "properties": {}, "additionalProperties": False},+ tags=["read", "categories"],+)+async def list_categories(+ *,+ session: AsyncSession,+ ctx: CallContext,+) -> dict[str, Any]:+ cats = await category_service.get_categories(session, ctx.user_id)+ items = [+ {+ "id": str(c.id),+ "name": c.name,+ "group_id": str(c.group_id) if c.group_id else None,+ "icon": c.icon,+ "color": c.color,+ "is_system": bool(c.is_system),+ "treat_as_transfer": bool(getattr(c, "treat_as_transfer", False)),+ }+ for c in cats+ ]+ return {"items": items, "total": len(items)}diff --git a/backend/mcp_server/tools/groups.py b/backend/mcp_server/tools/groups.pynew file mode 100644index 00000000..e8f930bd--- /dev/null+++ b/backend/mcp_server/tools/groups.py@@ -0,0 +1,175 @@+"""Read-only group + member + balance + settlement exposure for the agent.++Splits are written through `propose_create_transaction` (with its+`group_id` + `splits` parameters) — there's no `propose_create_split`+tool because splits live attached to the parent transaction, not as+standalone rows.+"""+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import balance_service, group_service, settlement_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_uuid+++@tool(+ name="list_groups",+ description=(+ "List the user's expense-sharing groups (Splitwise-style: 'Amigos', "+ "'Roommates', etc.) along with their members. Returns each group "+ "with `members: [{id, name, is_self}]` so a single call gives the "+ "model everything it needs to propose a transaction with equal/"+ "exact/percent splits. The `is_self` flag marks the member that "+ "represents the user (used to compute who-owes-who balances)."+ ),+ parameters={+ "type": "object",+ "properties": {+ "include_archived": {"type": "boolean", "default": False},+ },+ "additionalProperties": False,+ },+ tags=["read", "groups"],+)+async def list_groups(+ *,+ session: AsyncSession,+ ctx: CallContext,+ include_archived: bool = False,+) -> dict[str, Any]:+ groups = await group_service.list_groups(session, ctx.user_id, include_archived=include_archived)+ return {+ "items": [+ {+ "id": str(g.id),+ "name": g.name,+ "kind": g.kind,+ "default_currency": g.default_currency,+ "is_archived": bool(g.is_archived),+ "members": [+ {+ "id": str(m.id),+ "name": m.name,+ "is_self": bool(m.is_self),+ }+ for m in (g.members or [])+ ],+ }+ for g in groups+ ],+ "total": len(groups),+ }+++@tool(+ name="get_group_balances",+ description=(+ "Compute the who-owes-who balance for one expense-sharing group. "+ "Returns lines per member: positive `amount` means the member "+ "OWES the user (self) that much in `currency`; negative means the "+ "user owes them. `amount_in_default_currency` is the value "+ "converted to the group's default currency for a single bottom "+ "line. Already accounts for past `group_settlements` (payments "+ "that closed previous balances). Use this for 'quem ainda me "+ "deve?', 'estamos quites?', 'qual o saldo do grupo Amigos?'."+ ),+ parameters={+ "type": "object",+ "properties": {+ "group_id": {"type": "string", "format": "uuid"},+ },+ "required": ["group_id"],+ "additionalProperties": False,+ },+ tags=["read", "groups"],+)+async def get_group_balances(+ *,+ session: AsyncSession,+ ctx: CallContext,+ group_id: str,+) -> dict[str, Any]:+ gid = parse_uuid(group_id)+ result = await balance_service.compute_balances(session, gid, ctx.user_id)+ if result is None:+ return {"error": "group not found or not visible to this user"}++ # Resolve member names so the agent doesn't need a second list_groups+ # call to humanize the output.+ from sqlalchemy import select+ from app.models.group import GroupMember+ rows = (await session.execute(+ select(GroupMember).where(GroupMember.group_id == gid)+ )).scalars().all()+ name_by_id = {m.id: m.name for m in rows}+ is_self_by_id = {m.id: bool(m.is_self) for m in rows}++ lines = []+ for ln in result.get("lines", []):+ mid = ln["member_id"]+ lines.append({+ "member_id": str(mid),+ "member_name": name_by_id.get(mid),+ "is_self": is_self_by_id.get(mid, False),+ "currency": ln["currency"],+ "amount": num(ln["amount"]),+ "amount_in_default_currency": num(ln.get("amount_in_default_currency")),+ })+ return {+ "group_id": str(result["group_id"]),+ "self_member_id": str(result["self_member_id"]) if result.get("self_member_id") else None,+ "default_currency": result.get("default_currency"),+ "lines": lines,+ }+++@tool(+ name="list_group_settlements",+ description=(+ "List the recorded settlements (payments between members that "+ "close out balances) for one group, newest first. Each row has "+ "{from_member_id, to_member_id, amount, currency, date, notes}. "+ "Pair with `get_group_balances` when the user asks 'quem já me "+ "pagou?' or 'qual o histórico de acertos?'."+ ),+ parameters={+ "type": "object",+ "properties": {+ "group_id": {"type": "string", "format": "uuid"},+ },+ "required": ["group_id"],+ "additionalProperties": False,+ },+ tags=["read", "groups"],+)+async def list_group_settlements(+ *,+ session: AsyncSession,+ ctx: CallContext,+ group_id: str,+) -> dict[str, Any]:+ gid = parse_uuid(group_id)+ rows = await settlement_service.list_settlements(session, gid, ctx.user_id)+ if rows is None:+ return {"error": "group not found or not visible to this user"}++ items = [+ {+ "id": str(s.id),+ "group_id": str(s.group_id),+ "from_member_id": str(s.from_member_id),+ "to_member_id": str(s.to_member_id),+ "amount": num(s.amount),+ "currency": s.currency,+ "date": s.date.isoformat() if s.date else None,+ "notes": getattr(s, "notes", None),+ "transaction_id": str(s.transaction_id) if getattr(s, "transaction_id", None) else None,+ }+ for s in rows+ ]+ return {"items": items, "total": len(items)}diff --git a/backend/mcp_server/tools/knowledge.py b/backend/mcp_server/tools/knowledge.pynew file mode 100644index 00000000..11fb5148--- /dev/null+++ b/backend/mcp_server/tools/knowledge.py@@ -0,0 +1,54 @@+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.services import knowledge_service+from app.agents.services.embedding import embed_one+from mcp_server.auth import CallContext+from mcp_server.registry import tool+++@tool(+ name="search_knowledge_base",+ description=(+ "Semantic search across the calling agent's uploaded documents "+ "(PDF, MD, TXT). Returns the top matching text chunks with their "+ "similarity score. Use this when the user asks about something the "+ "agent has been given knowledge about (tax laws, accounting rules, "+ "personal notes, etc.)."+ ),+ parameters={+ "type": "object",+ "properties": {+ "query": {"type": "string", "minLength": 1},+ "top_n": {"type": "integer", "minimum": 1, "maximum": 25, "default": 6},+ "similarity_threshold": {"type": "number", "minimum": 0.0, "maximum": 1.0, "default": 0.0},+ },+ "required": ["query"],+ "additionalProperties": False,+ },+ tags=["read", "knowledge"],+)+async def search_knowledge_base(+ *,+ session: AsyncSession,+ ctx: CallContext,+ query: str,+ top_n: int = 6,+ similarity_threshold: float = 0.0,+) -> dict[str, Any]:+ if not ctx.agent_id:+ return {"error": "agent_id required (this tool only works inside an agent conversation)"}+ vec = await embed_one(query)+ if vec is None:+ return {"items": [], "total": 0, "warning": "embedding failed"}+ hits = await knowledge_service.similarity_search(+ session,+ agent_id=ctx.agent_id,+ query_embedding=vec,+ top_n=int(top_n),+ similarity_threshold=float(similarity_threshold),+ )+ return {"items": hits, "total": len(hits)}diff --git a/backend/mcp_server/tools/lifecycle.py b/backend/mcp_server/tools/lifecycle.pynew file mode 100644index 00000000..7de84629--- /dev/null+++ b/backend/mcp_server/tools/lifecycle.py@@ -0,0 +1,161 @@+"""Lifecycle entities — recurring transactions, assets, goals, budgets.++These come up in 'do I have any subscriptions?' / 'how are my goals+going?' / 'list my investments' type questions. Surfacing them as+first-class tools keeps the agent from falling back to text search.+"""+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import asset_service, budget_service, goal_service, recurring_transaction_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_date+++@tool(+ name="list_recurring_transactions",+ description=(+ "List the user's recurring transactions / subscriptions. Each row "+ "has frequency (weekly/monthly/...), next_occurrence, amount, "+ "category, and account. Use this — not list_transactions search — "+ "to answer 'what subscriptions do I have?' or 'show my recurring "+ "expenses'."+ ),+ parameters={"type": "object", "properties": {}, "additionalProperties": False},+ tags=["read", "recurring"],+)+async def list_recurring_transactions(+ *, session: AsyncSession, ctx: CallContext+) -> dict[str, Any]:+ rows = await recurring_transaction_service.get_recurring_transactions(session, ctx.user_id)+ items = [+ {+ "id": str(r.id),+ "description": r.description,+ "amount": num(r.amount),+ "currency": r.currency,+ "type": r.type,+ "frequency": r.frequency,+ "interval": getattr(r, "interval", None),+ "next_occurrence": r.next_occurrence.isoformat() if getattr(r, "next_occurrence", None) else None,+ "start_date": r.start_date.isoformat() if getattr(r, "start_date", None) else None,+ "end_date": r.end_date.isoformat() if getattr(r, "end_date", None) else None,+ "is_active": bool(getattr(r, "is_active", True)),+ "category_id": str(r.category_id) if getattr(r, "category_id", None) else None,+ "account_id": str(r.account_id) if getattr(r, "account_id", None) else None,+ }+ for r in rows+ ]+ return {"items": items, "total": len(items)}+++@tool(+ name="list_assets",+ description=(+ "List the user's investments / assets (stocks, crypto, CDBs, real "+ "estate, etc.) with current value and grouping. Use for 'what "+ "investments do I have?' or 'show my portfolio'."+ ),+ parameters={+ "type": "object",+ "properties": {+ "include_archived": {"type": "boolean", "default": False},+ },+ "additionalProperties": False,+ },+ tags=["read", "assets"],+)+async def list_assets(+ *, session: AsyncSession, ctx: CallContext, include_archived: bool = False+) -> dict[str, Any]:+ rows = await asset_service.get_assets(session, ctx.user_id, include_archived=include_archived)+ items: list[dict[str, Any]] = []+ for r in rows:+ d = r.model_dump(mode="json") if hasattr(r, "model_dump") else dict(r.__dict__)+ items.append({+ "id": str(d.get("id")) if d.get("id") else None,+ "name": d.get("name"),+ "type": d.get("type"),+ "currency": d.get("currency"),+ "current_value": num(d.get("current_value")),+ "current_value_primary": num(d.get("current_value_primary")),+ "ticker": d.get("ticker"),+ "units": num(d.get("units")),+ "group_id": str(d.get("group_id")) if d.get("group_id") else None,+ "is_archived": bool(d.get("is_archived", False)),+ })+ return {"items": items, "total": len(items)}+++@tool(+ name="list_goals",+ description=(+ "List the user's savings / financial goals with target, current "+ "amount, deadline, and progress. Use for 'how are my goals "+ "going?' / 'am I on track?'."+ ),+ parameters={+ "type": "object",+ "properties": {+ "status": {"type": "string", "description": "Filter by status (e.g. 'active', 'completed')"},+ },+ "additionalProperties": False,+ },+ tags=["read", "goals"],+)+async def list_goals(+ *, session: AsyncSession, ctx: CallContext, status: str | None = None+) -> dict[str, Any]:+ rows = await goal_service.get_goals(session, ctx.user_id, status=status)+ items: list[dict[str, Any]] = []+ for r in rows:+ d = r.model_dump(mode="json") if hasattr(r, "model_dump") else dict(r.__dict__)+ items.append({+ "id": str(d.get("id")) if d.get("id") else None,+ "name": d.get("name"),+ "target_amount": num(d.get("target_amount")),+ "current_amount": num(d.get("current_amount")),+ "currency": d.get("currency"),+ "deadline": d.get("deadline"),+ "status": d.get("status"),+ "progress_pct": num(d.get("progress_pct")),+ "category_id": str(d.get("category_id")) if d.get("category_id") else None,+ })+ return {"items": items, "total": len(items)}+++@tool(+ name="list_budgets",+ description=(+ "List the raw budget rows (category + monthly amount). For "+ "spending vs budget comparison use get_budget_vs_actual instead."+ ),+ parameters={+ "type": "object",+ "properties": {+ "month": {"type": "string", "format": "date", "description": "Any date inside the target month; omit for all months"},+ },+ "additionalProperties": False,+ },+ tags=["read", "budgets"],+)+async def list_budgets(+ *, session: AsyncSession, ctx: CallContext, month: str | None = None+) -> dict[str, Any]:+ target = parse_date(month)+ rows = await budget_service.get_budgets(session, ctx.user_id, month=target)+ items = [+ {+ "id": str(b.id),+ "category_id": str(b.category_id) if b.category_id else None,+ "amount": num(b.amount),+ "month": b.month.isoformat() if getattr(b, "month", None) else None,+ "is_recurring": bool(getattr(b, "is_recurring", False)),+ }+ for b in rows+ ]+ return {"items": items, "total": len(items)}diff --git a/backend/mcp_server/tools/payees.py b/backend/mcp_server/tools/payees.pynew file mode 100644index 00000000..f451a4b8--- /dev/null+++ b/backend/mcp_server/tools/payees.py@@ -0,0 +1,32 @@+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import payee_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+++@tool(+ name="list_payees",+ description="List the user's payees (merchants/counterparties).",+ parameters={"type": "object", "properties": {}, "additionalProperties": False},+ tags=["read", "payees"],+)+async def list_payees(+ *,+ session: AsyncSession,+ ctx: CallContext,+) -> dict[str, Any]:+ payees = await payee_service.get_payees(session, ctx.user_id)+ items = [+ {+ "id": str(p.id),+ "name": p.name,+ "default_category_id": str(p.default_category_id) if getattr(p, "default_category_id", None) else None,+ }+ for p in payees+ ]+ return {"items": items, "total": len(items)}diff --git a/backend/mcp_server/tools/proposals.py b/backend/mcp_server/tools/proposals.pynew file mode 100644index 00000000..3f6b1dde--- /dev/null+++ b/backend/mcp_server/tools/proposals.py@@ -0,0 +1,703 @@+"""Propose-mutations.++These tools NEVER write to the DB. They return a structured proposal that+the agent surfaces to the user. The user confirms in the UI, which calls+the existing Securo write endpoint to do the real change. Keeps MCP safe+and gives the user a chance to review.+"""+from __future__ import annotations++from datetime import date+from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.category import Category+from app.models.group import Group, GroupMember+from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list+++# Repeated in EVERY propose_* tool description. The LLM reads these when+# deciding when to use a tool AND when describing the result to the user.+# The strong "REQUIRES USER CONFIRMATION" framing prevents the model from+# saying "Pronto! Criei…" / "Done! I added…" — the action is NOT executed+# by the tool call; it only takes effect when the user clicks Apply.+_PROPOSAL_PREFACE = (+ "[PROPOSAL — PREVIEW ONLY, NOT EXECUTED. The user MUST click Apply in "+ "the UI to confirm. Describe results as 'I prepared a proposal…' or "+ "'Here's a preview…' — NEVER as 'I created' / 'Done' / 'Ready'. The "+ "Apply button + diff card render automatically; do not duplicate the "+ "details in your reply.] "+)+++@tool(+ name="propose_categorize",+ description=_PROPOSAL_PREFACE + (+ "Build a preview for re-categorizing one or more transactions. "+ "Returns a summary of what would change and the resolved category."+ ),+ parameters={+ "type": "object",+ "properties": {+ "transaction_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}, "minItems": 1},+ "category_id": {"type": "string", "format": "uuid"},+ },+ "required": ["transaction_ids", "category_id"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "transactions"],+)+async def propose_categorize(+ *,+ session: AsyncSession,+ ctx: CallContext,+ transaction_ids: list[str],+ category_id: str,+) -> dict[str, Any]:+ cat_id = parse_uuid(category_id)+ cat = (await session.execute(+ select(Category).where(Category.id == cat_id, Category.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if cat is None:+ return {"error": "category not found"}++ tx_ids = parse_uuid_list(transaction_ids) or []+ txs = (await session.execute(+ select(Transaction).where(Transaction.id.in_(tx_ids), Transaction.user_id == ctx.user_id)+ )).scalars().all()++ affected = [+ {"id": str(t.id), "description": t.description, "amount": num(t.amount), "currency": t.currency,+ "current_category_id": str(t.category_id) if t.category_id else None}+ for t in txs+ ]+ return {+ "kind": "categorize",+ "target_category": {"id": str(cat.id), "name": cat.name},+ "affected_count": len(affected),+ "affected": affected,+ "missing_ids": [str(t) for t in tx_ids if str(t) not in {a["id"] for a in affected}],+ "apply_endpoint": "POST /api/transactions/categorize",+ }+++@tool(+ name="propose_create_category",+ description=_PROPOSAL_PREFACE + (+ "Preview the creation of a new category. Returns the proposed shape "+ "and any name collision detected."+ ),+ parameters={+ "type": "object",+ "properties": {+ "name": {"type": "string", "minLength": 1, "maxLength": 100},+ "group_id": {"type": "string", "format": "uuid"},+ "icon": {"type": "string"},+ "color": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"},+ },+ "required": ["name"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "categories"],+)+async def propose_create_category(+ *,+ session: AsyncSession,+ ctx: CallContext,+ name: str,+ group_id: str | None = None,+ icon: str | None = None,+ color: str | None = None,+) -> dict[str, Any]:+ existing = (await session.execute(+ select(Category.id, Category.name).where(+ Category.user_id == ctx.user_id,+ Category.name.ilike(name.strip()),+ )+ )).first()+ return {+ "kind": "create_category",+ "proposed": {+ "name": name.strip(),+ "group_id": str(parse_uuid(group_id)) if group_id else None,+ "icon": icon or "circle-help",+ "color": color or "#6B7280",+ },+ "name_collision": {"id": str(existing.id), "name": existing.name} if existing else None,+ "apply_endpoint": "POST /api/categories",+ }+++@tool(+ name="propose_create_budget",+ description=_PROPOSAL_PREFACE + (+ "Preview a budget creation for a category and month. Returns the "+ "proposal plus any existing budget for the same category/month. "+ "STRICT: if the user mentions a category that does NOT match an "+ "existing one (call list_categories first to verify), do not "+ "silently substitute a different category — instead, ask the user "+ "to confirm an alternative or call propose_create_category first "+ "to add the missing one."+ ),+ parameters={+ "type": "object",+ "properties": {+ "category_id": {"type": "string", "format": "uuid"},+ "month": {"type": "string", "format": "date"},+ "amount": {"type": "number", "exclusiveMinimum": 0},+ "currency": {"type": "string"},+ },+ "required": ["category_id", "month", "amount"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "budgets"],+)+async def propose_create_budget(+ *,+ session: AsyncSession,+ ctx: CallContext,+ category_id: str,+ month: str,+ amount: float,+ currency: str | None = None,+) -> dict[str, Any]:+ cat_id = parse_uuid(category_id)+ target_month = (parse_date(month) or date.today()).replace(day=1)++ cat = (await session.execute(+ select(Category).where(Category.id == cat_id, Category.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if cat is None:+ return {"error": "category not found"}++ return {+ "kind": "create_budget",+ "proposed": {+ "category_id": str(cat.id),+ "category_name": cat.name,+ "month": target_month.isoformat(),+ "amount": float(amount),+ "currency": currency,+ },+ "apply_endpoint": "POST /api/budgets",+ }+++@tool(+ name="propose_create_transaction",+ description=_PROPOSAL_PREFACE + (+ "Build a preview for adding a one-off transaction (e.g. 'add a "+ "R$50 lunch today'). Validates the account/category exist; "+ "leaves currency to the account's default when not provided.\n\n"+ "Group splits: pass `group_id` + `splits` to attach a Splitwise-"+ "style breakdown. `splits.share_type='equal'` divides the amount "+ "evenly across the listed `member_ids` — perfect for 'crie no "+ "grupo dos Amigos e divida igualmente'. Use `'exact'` with a "+ "`share_amount` per member, or `'percent'` with `share_pct` per "+ "member, for custom shares. All members must belong to the same "+ "group as `group_id`. Call `list_groups` first to fetch IDs."+ ),+ parameters={+ "type": "object",+ "properties": {+ "description": {"type": "string", "minLength": 1, "maxLength": 500},+ "amount": {"type": "number", "exclusiveMinimum": 0, "description": "Absolute value, always positive — direction comes from `type`"},+ "type": {"type": "string", "enum": ["debit", "credit"], "description": "debit = expense, credit = income"},+ "account_id": {"type": "string", "format": "uuid"},+ "category_id": {"type": "string", "format": "uuid"},+ "date": {"type": "string", "format": "date", "description": "Defaults to today"},+ "currency": {"type": "string", "description": "Defaults to the account's currency"},+ "notes": {"type": "string"},+ "group_id": {"type": "string", "format": "uuid", "description": "Optional: attach to an expense-sharing group"},+ "splits": {+ "type": "object",+ "description": "Required when `group_id` is set. Defines how the amount is split among group members.",+ "properties": {+ "share_type": {"type": "string", "enum": ["equal", "exact", "percent"]},+ "members": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "object",+ "properties": {+ "member_id": {"type": "string", "format": "uuid"},+ "share_amount": {"type": "number", "description": "Required for share_type='exact' (sum must equal `amount`)"},+ "share_pct": {"type": "number", "description": "Required for share_type='percent' (must sum to 100)"},+ },+ "required": ["member_id"],+ "additionalProperties": False,+ },+ },+ },+ "required": ["share_type", "members"],+ "additionalProperties": False,+ },+ },+ "required": ["description", "amount", "type", "account_id"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "transactions"],+)+async def propose_create_transaction(+ *,+ session: AsyncSession,+ ctx: CallContext,+ description: str,+ amount: float,+ type: str,+ account_id: str,+ category_id: str | None = None,+ date: str | None = None,+ currency: str | None = None,+ notes: str | None = None,+ group_id: str | None = None,+ splits: dict[str, Any] | None = None,+) -> dict[str, Any]:+ acc_id = parse_uuid(account_id)+ acc = (await session.execute(+ select(Account).where(Account.id == acc_id, Account.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if acc is None:+ return {"error": "account not found"}++ cat = None+ if category_id:+ cat = (await session.execute(+ select(Category).where(Category.id == parse_uuid(category_id), Category.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if cat is None:+ return {"error": "category not found"}++ # Validate group + splits (if any) so the preview is honest.+ splits_preview: list[dict[str, Any]] | None = None+ group_name: str | None = None+ if group_id or splits:+ if not (group_id and splits):+ return {"error": "group_id and splits must be provided together"}+ gid = parse_uuid(group_id)+ group = (await session.execute(+ select(Group).where(Group.id == gid, Group.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if group is None:+ return {"error": "group not found"}+ group_name = group.name++ share_type = splits.get("share_type")+ if share_type not in ("equal", "exact", "percent"):+ return {"error": f"invalid share_type: {share_type!r}"}+ members_in = splits.get("members") or []+ if not members_in:+ return {"error": "splits.members must not be empty"}+ member_ids = [parse_uuid(m["member_id"]) for m in members_in]+ rows = (await session.execute(+ select(GroupMember).where(GroupMember.id.in_(member_ids), GroupMember.group_id == gid)+ )).scalars().all()+ if len(rows) != len(set(member_ids)):+ return {"error": "one or more members do not belong to the given group"}+ name_by_id = {m.id: m.name for m in rows}++ # Materialize a preview for the UI/LLM. The actual write happens+ # via POST /api/transactions which re-runs the same math.+ n = len(members_in)+ amt = float(amount)+ if share_type == "equal":+ per = round(amt / n, 2)+ residual = round(amt - per * (n - 1), 2)+ splits_preview = [+ {+ "member_id": str(m["member_id"]),+ "member_name": name_by_id.get(parse_uuid(m["member_id"]), "?"),+ "share_amount": (residual if i == n - 1 else per),+ }+ for i, m in enumerate(members_in)+ ]+ elif share_type == "exact":+ total = round(sum((float(m.get("share_amount") or 0) for m in members_in), 0.0), 2)+ if abs(total - amt) > 0.01:+ return {"error": f"exact share amounts sum to {total}, expected {amt}"}+ splits_preview = [+ {+ "member_id": str(m["member_id"]),+ "member_name": name_by_id.get(parse_uuid(m["member_id"]), "?"),+ "share_amount": float(m.get("share_amount") or 0),+ }+ for m in members_in+ ]+ else: # percent+ pct_sum = round(sum((float(m.get("share_pct") or 0) for m in members_in), 0.0), 2)+ if abs(pct_sum - 100.0) > 0.01:+ return {"error": f"percent shares sum to {pct_sum}, expected 100"}+ running = 0.0+ splits_preview = []+ for i, m in enumerate(members_in):+ if i == n - 1:+ share = round(amt - running, 2)+ else:+ share = round(amt * float(m.get("share_pct") or 0) / 100.0, 2)+ running += share+ splits_preview.append({+ "member_id": str(m["member_id"]),+ "member_name": name_by_id.get(parse_uuid(m["member_id"]), "?"),+ "share_amount": share,+ "share_pct": float(m.get("share_pct") or 0),+ })++ target_date = parse_date(date) or _today()+ proposed: dict[str, Any] = {+ "description": description.strip(),+ "amount": float(amount),+ "currency": (currency or acc.currency or "USD").upper(),+ "type": type,+ "date": target_date.isoformat(),+ "account_id": str(acc.id),+ "account_name": acc.name,+ "category_id": str(cat.id) if cat else None,+ "category_name": cat.name if cat else None,+ "notes": (notes or None),+ }+ if splits_preview is not None:+ proposed["group_id"] = group_id+ proposed["group_name"] = group_name+ proposed["splits"] = {+ "share_type": splits["share_type"],+ "items": splits_preview,+ }+ return {+ "kind": "create_transaction",+ "proposed": proposed,+ "apply_endpoint": "POST /api/transactions",+ }+++@tool(+ name="propose_create_recurring_transaction",+ description=_PROPOSAL_PREFACE + (+ "Build a preview for adding a recurring transaction / subscription "+ "(e.g. 'Netflix R$55 every month on the 10th'). Frequency is one "+ "of weekly/monthly/yearly. For monthly use day_of_month (1-31)."+ ),+ parameters={+ "type": "object",+ "properties": {+ "description": {"type": "string", "minLength": 1, "maxLength": 500},+ "amount": {"type": "number", "exclusiveMinimum": 0},+ "type": {"type": "string", "enum": ["debit", "credit"]},+ "frequency": {"type": "string", "enum": ["weekly", "monthly", "yearly"]},+ "day_of_month": {"type": "integer", "minimum": 1, "maximum": 31, "description": "Required for monthly"},+ "start_date": {"type": "string", "format": "date", "description": "Defaults to today"},+ "end_date": {"type": "string", "format": "date"},+ "account_id": {"type": "string", "format": "uuid"},+ "category_id": {"type": "string", "format": "uuid"},+ "currency": {"type": "string"},+ },+ "required": ["description", "amount", "type", "frequency", "account_id"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "recurring"],+)+async def propose_create_recurring_transaction(+ *,+ session: AsyncSession,+ ctx: CallContext,+ description: str,+ amount: float,+ type: str,+ frequency: str,+ account_id: str,+ day_of_month: int | None = None,+ start_date: str | None = None,+ end_date: str | None = None,+ category_id: str | None = None,+ currency: str | None = None,+) -> dict[str, Any]:+ if frequency == "monthly" and not day_of_month:+ return {"error": "day_of_month is required for monthly frequency"}+ acc = (await session.execute(+ select(Account).where(Account.id == parse_uuid(account_id), Account.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if acc is None:+ return {"error": "account not found"}+ cat = None+ if category_id:+ cat = (await session.execute(+ select(Category).where(Category.id == parse_uuid(category_id), Category.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if cat is None:+ return {"error": "category not found"}++ return {+ "kind": "create_recurring_transaction",+ "proposed": {+ "description": description.strip(),+ "amount": float(amount),+ "currency": (currency or acc.currency or "USD").upper(),+ "type": type,+ "frequency": frequency,+ "day_of_month": int(day_of_month) if day_of_month else None,+ "start_date": (parse_date(start_date) or _today()).isoformat(),+ "end_date": parse_date(end_date).isoformat() if end_date else None,+ "account_id": str(acc.id),+ "account_name": acc.name,+ "category_id": str(cat.id) if cat else None,+ "category_name": cat.name if cat else None,+ },+ "apply_endpoint": "POST /api/recurring-transactions",+ }+++@tool(+ name="propose_update_recurring_transaction",+ description=_PROPOSAL_PREFACE + (+ "Build a preview for editing an existing recurring transaction "+ "(e.g. 'update my salary to R$8,000', 'change Netflix to R$60'). "+ "Pass the recurring_id and only the fields you want to change. "+ "Returns the current values alongside the proposed changes so the "+ "user can compare before confirming."+ ),+ parameters={+ "type": "object",+ "properties": {+ "recurring_id": {"type": "string", "format": "uuid"},+ "description": {"type": "string", "minLength": 1, "maxLength": 500},+ "amount": {"type": "number", "exclusiveMinimum": 0},+ "frequency": {"type": "string", "enum": ["weekly", "monthly", "yearly"]},+ "day_of_month": {"type": "integer", "minimum": 1, "maximum": 31},+ "end_date": {"type": "string", "format": "date"},+ "category_id": {"type": "string", "format": "uuid"},+ "is_active": {"type": "boolean"},+ },+ "required": ["recurring_id"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "recurring"],+)+async def propose_update_recurring_transaction(+ *,+ session: AsyncSession,+ ctx: CallContext,+ recurring_id: str,+ description: str | None = None,+ amount: float | None = None,+ frequency: str | None = None,+ day_of_month: int | None = None,+ end_date: str | None = None,+ category_id: str | None = None,+ is_active: bool | None = None,+) -> dict[str, Any]:+ rid = parse_uuid(recurring_id)+ rt = (await session.execute(+ select(RecurringTransaction).where(+ RecurringTransaction.id == rid, RecurringTransaction.user_id == ctx.user_id+ )+ )).scalar_one_or_none()+ if rt is None:+ return {"error": "recurring transaction not found"}++ cat = None+ if category_id:+ cat = (await session.execute(+ select(Category).where(Category.id == parse_uuid(category_id), Category.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if cat is None:+ return {"error": "category not found"}++ changes: dict[str, Any] = {}+ if description is not None:+ changes["description"] = description.strip()+ if amount is not None:+ changes["amount"] = float(amount)+ if frequency is not None:+ changes["frequency"] = frequency+ if day_of_month is not None:+ changes["day_of_month"] = int(day_of_month)+ if end_date is not None:+ changes["end_date"] = parse_date(end_date).isoformat() if end_date else None+ if cat is not None:+ changes["category_id"] = str(cat.id)+ if is_active is not None:+ changes["is_active"] = bool(is_active)++ if not changes:+ return {"error": "no changes provided"}++ return {+ "kind": "update_recurring_transaction",+ "target": {+ "id": str(rt.id),+ "description": rt.description,+ "amount": num(rt.amount),+ "currency": rt.currency,+ "frequency": rt.frequency,+ "day_of_month": rt.day_of_month,+ "is_active": bool(getattr(rt, "is_active", True)),+ },+ "changes": changes,+ "apply_endpoint": f"PATCH /api/recurring-transactions/{rt.id}",+ }+++@tool(+ name="propose_cancel_recurring_transaction",+ description=_PROPOSAL_PREFACE + (+ "Build a preview for cancelling a recurring transaction (e.g. "+ "'cancel that subscription'). Two modes: 'deactivate' keeps the "+ "history but stops future occurrences (recommended); 'delete' "+ "removes it entirely."+ ),+ parameters={+ "type": "object",+ "properties": {+ "recurring_id": {"type": "string", "format": "uuid"},+ "mode": {"type": "string", "enum": ["deactivate", "delete"], "default": "deactivate"},+ },+ "required": ["recurring_id"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "recurring"],+)+async def propose_cancel_recurring_transaction(+ *,+ session: AsyncSession,+ ctx: CallContext,+ recurring_id: str,+ mode: str = "deactivate",+) -> dict[str, Any]:+ rt = (await session.execute(+ select(RecurringTransaction).where(+ RecurringTransaction.id == parse_uuid(recurring_id),+ RecurringTransaction.user_id == ctx.user_id,+ )+ )).scalar_one_or_none()+ if rt is None:+ return {"error": "recurring transaction not found"}++ if mode == "delete":+ endpoint = f"DELETE /api/recurring-transactions/{rt.id}"+ else:+ endpoint = f"PATCH /api/recurring-transactions/{rt.id} body={{is_active: false}}"++ return {+ "kind": "cancel_recurring_transaction",+ "mode": mode,+ "target": {+ "id": str(rt.id),+ "description": rt.description,+ "amount": num(rt.amount),+ "currency": rt.currency,+ "frequency": rt.frequency,+ "is_active": bool(getattr(rt, "is_active", True)),+ },+ "apply_endpoint": endpoint,+ }+++@tool(+ name="propose_create_goal",+ description=_PROPOSAL_PREFACE + (+ "Build a preview for creating a savings/financial goal (e.g. "+ "'set a R$10k goal for travel')."+ ),+ parameters={+ "type": "object",+ "properties": {+ "name": {"type": "string", "minLength": 1, "maxLength": 255},+ "target_amount": {"type": "number", "exclusiveMinimum": 0},+ "currency": {"type": "string", "description": "Defaults to user's primary currency"},+ "deadline": {"type": "string", "format": "date"},+ "initial_amount": {"type": "number", "minimum": 0, "description": "How much you've already saved"},+ "icon": {"type": "string"},+ "color": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"},+ },+ "required": ["name", "target_amount"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "goals"],+)+async def propose_create_goal(+ *,+ session: AsyncSession,+ ctx: CallContext,+ name: str,+ target_amount: float,+ currency: str | None = None,+ deadline: str | None = None,+ initial_amount: float | None = None,+ icon: str | None = None,+ color: str | None = None,+) -> dict[str, Any]:+ return {+ "kind": "create_goal",+ "proposed": {+ "name": name.strip(),+ "target_amount": float(target_amount),+ "currency": (currency or "BRL").upper(),+ "deadline": parse_date(deadline).isoformat() if deadline else None,+ "initial_amount": float(initial_amount) if initial_amount is not None else 0.0,+ "icon": icon or "target",+ "color": color or "#3B82F6",+ },+ "apply_endpoint": "POST /api/goals",+ }+++def _today():+ from datetime import date as _d+ return _d.today()+++@tool(+ name="propose_create_payee_rule",+ description=_PROPOSAL_PREFACE + (+ "Preview a rule that auto-categorizes future transactions matching "+ "a description pattern. Returns the proposed rule shape."+ ),+ parameters={+ "type": "object",+ "properties": {+ "match_pattern": {"type": "string", "description": "Substring to match in transaction description (case-insensitive)"},+ "category_id": {"type": "string", "format": "uuid"},+ },+ "required": ["match_pattern", "category_id"],+ "additionalProperties": False,+ },+ is_proposal=True,+ tags=["propose", "rules"],+)+async def propose_create_payee_rule(+ *,+ session: AsyncSession,+ ctx: CallContext,+ match_pattern: str,+ category_id: str,+) -> dict[str, Any]:+ cat_id = parse_uuid(category_id)+ cat = (await session.execute(+ select(Category).where(Category.id == cat_id, Category.user_id == ctx.user_id)+ )).scalar_one_or_none()+ if cat is None:+ return {"error": "category not found"}++ return {+ "kind": "create_payee_rule",+ "proposed": {+ "match_pattern": match_pattern,+ "category_id": str(cat.id),+ "category_name": cat.name,+ },+ "apply_endpoint": "POST /api/rules",+ }diff --git a/backend/mcp_server/tools/reports.py b/backend/mcp_server/tools/reports.pynew file mode 100644index 00000000..100b8eb6--- /dev/null+++ b/backend/mcp_server/tools/reports.py@@ -0,0 +1,129 @@+from __future__ import annotations++from datetime import date+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import dashboard_service, report_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import parse_date+++def _pri_currency(ctx: CallContext) -> str:+ # The user model defaults to USD; reports reach into the DB for the+ # actual primary currency, so the value passed here is just the fallback.+ return "USD"+++def _serialize_report(r: Any) -> dict[str, Any]:+ if hasattr(r, "model_dump"):+ return r.model_dump(mode="json")+ return r if isinstance(r, dict) else {"value": str(r)}+++@tool(+ name="get_net_worth",+ description="Net worth time series over the last N months. Use to answer 'how is my net worth trending?'",+ parameters={+ "type": "object",+ "properties": {+ "months": {"type": "integer", "minimum": 1, "maximum": 60, "default": 12},+ "interval": {"type": "string", "enum": ["daily", "weekly", "monthly", "yearly"], "default": "monthly"},+ },+ "additionalProperties": False,+ },+ tags=["read", "reports"],+)+async def get_net_worth(+ *,+ session: AsyncSession,+ ctx: CallContext,+ months: int = 12,+ interval: str = "monthly",+) -> dict[str, Any]:+ rep = await report_service.get_net_worth_report(+ session, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx)+ )+ return _serialize_report(rep)+++@tool(+ name="get_income_expenses",+ description="Income vs expenses over the last N months. Use for budgeting questions.",+ parameters={+ "type": "object",+ "properties": {+ "months": {"type": "integer", "minimum": 1, "maximum": 60, "default": 12},+ "interval": {"type": "string", "enum": ["daily", "weekly", "monthly", "yearly"], "default": "monthly"},+ },+ "additionalProperties": False,+ },+ tags=["read", "reports"],+)+async def get_income_expenses(+ *,+ session: AsyncSession,+ ctx: CallContext,+ months: int = 12,+ interval: str = "monthly",+) -> dict[str, Any]:+ rep = await report_service.get_income_expenses_report(+ session, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx)+ )+ return _serialize_report(rep)+++@tool(+ name="get_cash_flow",+ description="Forward-looking cash flow projection — current balance plus future bookings and recurring transactions.",+ parameters={+ "type": "object",+ "properties": {+ "months": {"type": "integer", "minimum": 1, "maximum": 24, "default": 6},+ "interval": {"type": "string", "enum": ["daily", "weekly", "monthly"], "default": "daily"},+ },+ "additionalProperties": False,+ },+ tags=["read", "reports"],+)+async def get_cash_flow(+ *,+ session: AsyncSession,+ ctx: CallContext,+ months: int = 6,+ interval: str = "daily",+) -> dict[str, Any]:+ rep = await report_service.get_cash_flow_report(+ session, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx)+ )+ return _serialize_report(rep)+++@tool(+ name="get_dashboard_snapshot",+ description=(+ "One-call month snapshot: total income/expenses/savings, balances by "+ "currency, top categories. Defaults to the current month."+ ),+ parameters={+ "type": "object",+ "properties": {+ "month": {"type": "string", "format": "date", "description": "Any date inside the target month"},+ },+ "additionalProperties": False,+ },+ tags=["read", "dashboard"],+)+async def get_dashboard_snapshot(+ *,+ session: AsyncSession,+ ctx: CallContext,+ month: str | None = None,+) -> dict[str, Any]:+ target = parse_date(month) or date.today().replace(day=1)+ summary = await dashboard_service.get_summary(session, ctx.user_id, month=target)+ if hasattr(summary, "model_dump"):+ return summary.model_dump(mode="json")+ return {"value": str(summary)}diff --git a/backend/mcp_server/tools/search.py b/backend/mcp_server/tools/search.pynew file mode 100644index 00000000..08dccac5--- /dev/null+++ b/backend/mcp_server/tools/search.py@@ -0,0 +1,37 @@+from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from app.services import search_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+++@tool(+ name="search_all",+ description=(+ "Global text search across the user's entities (transactions, "+ "accounts, categories, payees, etc.). Returns up to N hits per type."+ ),+ parameters={+ "type": "object",+ "properties": {+ "query": {"type": "string", "minLength": 1},+ "per_type_limit": {"type": "integer", "minimum": 1, "maximum": 25, "default": 5},+ },+ "required": ["query"],+ "additionalProperties": False,+ },+ tags=["read", "search"],+)+async def search_all(+ *,+ session: AsyncSession,+ ctx: CallContext,+ query: str,+ per_type_limit: int = 5,+) -> dict[str, Any]:+ hits = await search_service.search_all(session, ctx.user_id, query, per_type_limit=int(per_type_limit))+ return {"items": hits, "total": len(hits)}diff --git a/backend/mcp_server/tools/transactions.py b/backend/mcp_server/tools/transactions.pynew file mode 100644index 00000000..04199986--- /dev/null+++ b/backend/mcp_server/tools/transactions.py@@ -0,0 +1,221 @@+from __future__ import annotations++from typing import Any++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.group import GroupMember+from app.services import transaction_service+from mcp_server.auth import CallContext+from mcp_server.registry import tool+from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list+++@tool(+ name="list_transactions",+ description=(+ "List the user's transactions with rich filters. Returns paginated "+ "items plus a `total` count of ALL matches (not just the page). "+ "If you only need a count (e.g. 'how many uncategorized?'), call "+ "with limit=1 and read `total` instead of paginating through "+ "everything. By default sorts by purchase date (most recent "+ "first) so 'what's my last transaction?' returns the actual "+ "newest one — change sort_by to 'date' for the credit-card-bill-"+ "aware ordering used by the dashboard. Each row carries its "+ "native currency in `currency` and the user's primary-currency "+ "view in `amount_primary`. To answer 'do I have any EUR/USD/etc "+ "transactions?' use the `currency` filter — don't text-search "+ "the description. Each row also carries a `splits` field: when "+ "non-null, the transaction is shared via a Splitwise-style "+ "group — `splits.group_id` ties it back to a row from "+ "`list_groups`, and `splits.members[]` shows each "+ "{member_id, member_name, is_self, share_amount, share_type, "+ "share_pct}. So 'is this transaction split?' is just `splits != "+ "null`; no extra tool call needed."+ ),+ parameters={+ "type": "object",+ "properties": {+ "account_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}, "description": "Filter to specific accounts (by id)"},+ "account_types": {+ "type": "array",+ "items": {"type": "string", "enum": ["checking", "savings", "credit_card", "wallet", "investment", "loan", "other"]},+ "description": "Filter by account type — e.g. ['credit_card'] for 'all my credit-card transactions'",+ },+ "category_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}, "description": "Filter to specific categories"},+ "payee_id": {"type": "string", "format": "uuid", "description": "Filter to a single payee"},+ "group_id": {"type": "string", "format": "uuid", "description": "Filter to transactions split with this expense-sharing group (Splitwise-style). The id comes from `list_groups`. Use this — NOT a `search:'group_id:...'` hack — to ask 'show all transactions in group X'."},+ "from_date": {"type": "string", "format": "date", "description": "Inclusive lower bound (YYYY-MM-DD)"},+ "to_date": {"type": "string", "format": "date", "description": "Inclusive upper bound (YYYY-MM-DD)"},+ "search": {"type": "string", "description": "Substring match against description or payee"},+ "currency": {+ "type": "string",+ "description": "ISO currency code (BRL, USD, EUR, GBP, ...). Matches each transaction's native currency exactly. Use this — not search — for currency questions.",+ },+ "min_amount": {+ "type": "number",+ "exclusiveMinimum": 0,+ "description": "Minimum absolute amount (in user's primary currency when available, else native). E.g. 100 = 'transactions of $100 or more'.",+ },+ "max_amount": {+ "type": "number",+ "exclusiveMinimum": 0,+ "description": "Maximum absolute amount (primary-currency view).",+ },+ "tx_type": {"type": "string", "enum": ["debit", "credit"], "description": "debit = expense, credit = income"},+ "uncategorized": {"type": "boolean", "default": False, "description": "Only transactions without a category"},+ "exclude_transfers": {"type": "boolean", "default": False, "description": "Exclude transfers between user's own accounts"},+ "tags": {"type": "array", "items": {"type": "string"}, "description": "Match any of these tags"},+ "sort_by": {+ "type": "string",+ "enum": ["transaction_date", "date", "amount", "description", "payee", "category", "account", "created_at"],+ "default": "transaction_date",+ "description": (+ "transaction_date = purchase date (default, intuitive 'latest'); "+ "date = cycle/accrual-aware (matches dashboard ordering, can put "+ "future-billed credit-card purchases on top); "+ "created_at = order rows were inserted into Securo (useful for "+ "freshly-synced data)."+ ),+ },+ "sort_dir": {"type": "string", "enum": ["desc", "asc"], "default": "desc"},+ "accounting_mode": {+ "type": "string",+ "enum": ["cash", "accrual"],+ "description": "Override the global accounting mode for this query. Affects how credit-card transactions are bucketed by date.",+ },+ "limit": {"type": "integer", "minimum": 1, "maximum": 50, "default": 25, "description": "Max rows per page. Capped at 50 — bigger pages blow up token budgets on small models. Use `total` for counts and pagination via `page` to walk longer lists."},+ "page": {"type": "integer", "minimum": 1, "default": 1},+ },+ "additionalProperties": False,+ },+ tags=["read", "transactions"],+)+async def list_transactions(+ *,+ session: AsyncSession,+ ctx: CallContext,+ account_ids: list[str] | None = None,+ account_types: list[str] | None = None,+ category_ids: list[str] | None = None,+ payee_id: str | None = None,+ group_id: str | None = None,+ from_date: str | None = None,+ to_date: str | None = None,+ search: str | None = None,+ currency: str | None = None,+ min_amount: float | None = None,+ max_amount: float | None = None,+ tx_type: str | None = None,+ uncategorized: bool = False,+ exclude_transfers: bool = False,+ tags: list[str] | None = None,+ sort_by: str = "transaction_date",+ sort_dir: str = "desc",+ accounting_mode: str | None = None,+ limit: int = 25,+ page: int = 1,+) -> dict[str, Any]:+ # Hard cap regardless of what the LLM asks — the schema says 50 but+ # not every provider enforces additionalProperties / maximum.+ limit = max(1, min(int(limit), 50))+ txs, total = await transaction_service.get_transactions(+ session,+ ctx.user_id,+ account_ids=parse_uuid_list(account_ids),+ account_types=account_types or None,+ category_ids=parse_uuid_list(category_ids),+ payee_id=parse_uuid(payee_id) if payee_id else None,+ group_id=parse_uuid(group_id) if group_id else None,+ from_date=parse_date(from_date),+ to_date=parse_date(to_date),+ search=search,+ currency=currency,+ min_amount=float(min_amount) if min_amount is not None else None,+ max_amount=float(max_amount) if max_amount is not None else None,+ txn_type=tx_type,+ uncategorized=uncategorized,+ exclude_transfers=exclude_transfers,+ tags=tags or None,+ sort_by=sort_by,+ sort_dir=sort_dir,+ accounting_mode=accounting_mode,+ limit=int(limit),+ page=int(page),+ )+ # Resolve group + member metadata for any transaction with splits, in+ # one batched query — without this the agent has no way to tell that+ # a transaction is split among a group's members ("is this Jantar a+ # solo expense?" → "no, split with Marcelo + Tereza in Amigos").+ member_ids: set[Any] = set()+ for t in txs:+ for s in (getattr(t, "splits", None) or []):+ member_ids.add(s.group_member_id)+ member_lookup: dict[Any, GroupMember] = {}+ if member_ids:+ rows = (await session.execute(+ select(GroupMember).where(GroupMember.id.in_(member_ids))+ )).scalars().all()+ member_lookup = {m.id: m for m in rows}++ def _splits_summary(t: Any) -> dict[str, Any] | None:+ splits = getattr(t, "splits", None) or []+ if not splits:+ return None+ # Splits all belong to the same group by invariant — surface the+ # group id from any one of them so the model can correlate with+ # `list_groups` without a second tool call.+ group_id = None+ items = []+ for s in splits:+ mem = member_lookup.get(s.group_member_id)+ if mem is not None and group_id is None:+ group_id = str(mem.group_id)+ items.append({+ "member_id": str(s.group_member_id),+ "member_name": mem.name if mem else None,+ "is_self": bool(getattr(mem, "is_self", False)) if mem else False,+ "share_amount": num(s.share_amount),+ "share_type": s.share_type,+ "share_pct": num(s.share_pct),+ })+ return {+ "is_split": True,+ "group_id": group_id,+ "share_type": splits[0].share_type if splits else None,+ "members": items,+ }++ items = [+ {+ "id": str(t.id),+ "date": t.date.isoformat() if t.date else None,+ "effective_date": t.effective_date.isoformat() if getattr(t, "effective_date", None) else None,+ "description": t.description,+ "amount": num(t.amount),+ "currency": t.currency,+ "amount_primary": num(getattr(t, "amount_primary", None)),+ "type": t.type,+ "status": getattr(t, "status", None),+ "category_id": str(t.category_id) if t.category_id else None,+ "category_name": t.category.name if getattr(t, "category", None) else None,+ "account_id": str(t.account_id) if t.account_id else None,+ "account_name": t.account.name if getattr(t, "account", None) else None,+ "payee_id": str(t.payee_id) if getattr(t, "payee_id", None) else None,+ "payee_name": t.payee_entity.name if getattr(t, "payee_entity", None) else None,+ "tags": getattr(t, "tags", None),+ "is_transfer": bool(getattr(t, "transfer_pair_id", None)),+ "notes": getattr(t, "notes", None),+ "splits": _splits_summary(t),+ }+ for t in txs+ ]+ return {+ "items": items,+ "total": int(total),+ "page": int(page),+ "limit": int(limit),+ "sort_by": sort_by,+ "sort_dir": sort_dir,+ }diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex 0d5284f2..dba50c51 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -12,6 +12,7 @@ dependencies = ["pydantic>=2.5.0","pydantic-settings>=2.1.0","python-jose[cryptography]>=3.3.0",+ "cryptography==46.0.7","passlib[bcrypt]>=1.7.4","fastapi-users[sqlalchemy]>=13.0.0","httpx>=0.26.0",@@ -22,6 +23,14 @@ dependencies = ["redis[hiredis]>=5.0.0","pyotp>=2.9.0","yfinance>=1.3.0",+ "pgvector>=0.3.0",+ "pypdf>=5.0.0",+ # Bundled multilingual embedder — only imported on demand by the+ # agents knowledge-base path. ONNX runtime, ~120 MB model downloaded+ # on first use to /app/data/embedding_models. Users not on the+ # agents feature pay zero cost (the package is installed but never+ # imported).+ "fastembed>=0.4.0",][project.optional-dependencies]diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex 55e10566..a2af7008 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -1,33 +1,77 @@import asyncio+import osimport uuidfrom datetime import date, datetime, timezonefrom decimal import Decimalfrom typing import AsyncGeneratorfrom unittest.mock import AsyncMock, patch-import pytest-import pytest_asyncio-from httpx import ASGITransport, AsyncClient-from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker--from app.core.database import Base, get_async_session-from app.main import app-from app.models.user import User-from app.models.category import Category-from app.models.bank_connection import BankConnection-from app.models.account import Account-from app.models.transaction import Transaction-from app.models.rule import Rule-from app.models.asset import Asset # noqa: F401-from app.models.asset_value import AssetValue # noqa: F401-from app.models.transaction_attachment import TransactionAttachment # noqa: F401-from app.models.payee import Payee, PayeeMapping # noqa: F401-from app.models.app_settings import AppSetting # noqa: F401-from app.models.goal import Goal # noqa: F401-from app.models.credit_card_bill import CreditCardBill # noqa: F401-from app.models.group import Group, GroupMember # noqa: F401-from app.models.transaction_split import TransactionSplit # noqa: F401-from app.models.group_settlement import GroupSettlement # noqa: F401+# --- Agents test setup (must run BEFORE app.main is imported) ---------------+# Force the optional agents feature on for the test process so the routes+# are mounted and the agent models are reachable. Provide deterministic+# JWT/MCP secrets so test fixtures can mint tokens.+os.environ.setdefault("AGENTS_ENABLED", "true")+os.environ.setdefault("AGENTS_MCP_JWT_SECRET", "test-secret-not-for-production")+os.environ.setdefault("AGENTS_BUILTIN_MCP_URL", "http://test-mcp:8765/mcp")++# pgvector's Vector type only compiles on PostgreSQL. Tests use SQLite, so+# we shim it with JSON before any model module imports it. Production runs+# pgvector unchanged.+import sqlalchemy.types # noqa: E402+import pgvector.sqlalchemy as _pgv # noqa: E402+++class _VectorJSON(sqlalchemy.types.JSON):+ """JSON-backed stand-in for pgvector's Vector type, for SQLite tests."""++ cache_ok = True++ def __init__(self, dim=None, *args, **kwargs):+ super().__init__(*args, **kwargs)++ def cosine_distance(self, other): # type: ignore[override]+ # Tests for similarity_search are exercised against the real Postgres;+ # the SQLite path just needs a valid SQL fragment.+ from sqlalchemy import literal+ return literal(0.5)+++_pgv.Vector = _VectorJSON # type: ignore[attr-defined]+# ---------------------------------------------------------------------------++import pytest # noqa: E402+import pytest_asyncio # noqa: E402+from httpx import ASGITransport, AsyncClient # noqa: E402+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker # noqa: E402++from app.core.database import Base, get_async_session # noqa: E402+from app.main import app # noqa: E402+from app.models.user import User # noqa: E402+from app.models.category import Category # noqa: E402+from app.models.bank_connection import BankConnection # noqa: E402+from app.models.account import Account # noqa: E402+from app.models.transaction import Transaction # noqa: E402+from app.models.rule import Rule # noqa: E402+from app.models.asset import Asset # noqa: E402,F401+from app.models.asset_value import AssetValue # noqa: E402,F401+from app.models.transaction_attachment import TransactionAttachment # noqa: E402,F401+from app.models.payee import Payee, PayeeMapping # noqa: E402,F401+from app.models.app_settings import AppSetting # noqa: E402,F401+from app.models.goal import Goal # noqa: E402,F401+from app.models.credit_card_bill import CreditCardBill # noqa: E402,F401+from app.models.group import Group, GroupMember # noqa: E402,F401+from app.models.transaction_split import TransactionSplit # noqa: E402,F401+from app.models.group_settlement import GroupSettlement # noqa: E402,F401+# Agent models — gated by AGENTS_ENABLED above so tests always cover them.+from app.agents.models import ( # noqa: E402,F401+ Agent,+ AgentTool,+ Conversation,+ Message,+ KnowledgeDoc,+ KnowledgeChunk,+ LlmUsage,+)# Use SQLite for tests — fast, no external dependencyTEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"@@ -334,6 +378,39 @@ async def test_rules(return rules+@pytest_asyncio.fixture+async def test_agent(session: AsyncSession, test_user: User) -> Agent:+ """A baseline agent for tests."""+ agent = Agent(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Test Agent",+ description="A test agent",+ system_prompt="You are a helpful assistant.",+ provider="openai",+ model="gpt-4o-mini",+ temperature=0.4,+ )+ session.add(agent)+ await session.commit()+ await session.refresh(agent)+ return agent+++@pytest_asyncio.fixture+async def test_conversation(session: AsyncSession, test_user: User, test_agent: Agent) -> Conversation:+ conv = Conversation(+ id=uuid.uuid4(),+ user_id=test_user.id,+ agent_id=test_agent.id,+ channel="web",+ )+ session.add(conv)+ await session.commit()+ await session.refresh(conv)+ return conv++@pytest_asyncio.fixtureasync def test_user_with_2fa(session: AsyncSession, clean_db) -> User:"""Create a test user with 2FA enabled."""diff --git a/backend/tests/test_agents_api.py b/backend/tests/test_agents_api.pynew file mode 100644index 00000000..affa97fd--- /dev/null+++ b/backend/tests/test_agents_api.py@@ -0,0 +1,407 @@+"""Agent + conversation CRUD via HTTP. Verifies auth, multi-tenant scoping,+and field handling. Does not exercise the LLM (see test_agents_executor.py).+"""+import uuid+from unittest.mock import patch++import bcrypt as _bcrypt+import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.user import User+++pytestmark = pytest.mark.asyncio+++# Patch MCPRegistry.discover so /api/agents/{id}/tools doesn't try to hit a+# real MCP server during HTTP tests. Returns an empty tool list.[email protected](autouse=True)+def _mock_mcp_discover():+ async def _empty_discover(self, *, user_id, conversation_id=None):+ return []+ with patch("app.agents.api.agents.MCPRegistry.discover", new=_empty_discover):+ yield+++@pytest_asyncio.fixture+async def other_user(session: AsyncSession) -> User:+ """A second user in the same DB to verify cross-tenant isolation."""+ hashed = _bcrypt.hashpw(b"otherpass123", _bcrypt.gensalt()).decode()+ user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=hashed,+ is_active=True,+ is_superuser=False,+ is_verified=True,+ preferences={"language": "en", "currency_display": "USD"},+ )+ session.add(user)+ await session.commit()+ await session.refresh(user)+ return user+++@pytest_asyncio.fixture+async def other_auth_headers(client: AsyncClient, other_user: User) -> dict:+ resp = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "otherpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert resp.status_code == 200+ return {"Authorization": f"Bearer {resp.json()['access_token']}"}+++# --- Info endpoints --------------------------------------------------------++async def test_app_info_reports_agents_enabled(client: AsyncClient):+ r = await client.get("/api/info")+ assert r.status_code == 200+ assert r.json()["features"]["agents"] is True+++async def test_agents_info_lists_providers(client: AsyncClient, auth_headers: dict):+ r = await client.get("/api/agents/info", headers=auth_headers)+ assert r.status_code == 200+ body = r.json()+ assert body["enabled"] is True+ assert set(body["providers"]) >= {"openai", "anthropic", "ollama", "openai_compatible"}+++# --- Agent CRUD ------------------------------------------------------------++async def test_unauthenticated_agents_list_rejected(client: AsyncClient):+ r = await client.get("/api/agents")+ assert r.status_code == 401+++async def test_create_list_get_update_delete(client: AsyncClient, auth_headers: dict):+ # Empty by default+ r = await client.get("/api/agents", headers=auth_headers)+ assert r.status_code == 200+ assert r.json() == []++ # Create+ payload = {+ "name": "Brazilian Tax Advisor",+ "description": "Helps with PT-BR tax questions",+ "system_prompt": "You are a tax advisor.",+ "provider": "openai",+ "model": "gpt-4o-mini",+ "temperature": 0.3,+ }+ r = await client.post("/api/agents", json=payload, headers=auth_headers)+ assert r.status_code == 201, r.text+ created = r.json()+ assert created["name"] == "Brazilian Tax Advisor"+ assert created["provider"] == "openai"+ assert created["temperature"] == 0.3++ aid = created["id"]++ # List shows the new agent+ r = await client.get("/api/agents", headers=auth_headers)+ assert len(r.json()) == 1+ assert r.json()[0]["id"] == aid++ # Get by id+ r = await client.get(f"/api/agents/{aid}", headers=auth_headers)+ assert r.status_code == 200+ assert r.json()["id"] == aid++ # Update+ r = await client.patch(f"/api/agents/{aid}", json={"description": "New desc", "temperature": 0.7}, headers=auth_headers)+ assert r.status_code == 200+ assert r.json()["description"] == "New desc"+ assert r.json()["temperature"] == 0.7++ # Delete+ r = await client.delete(f"/api/agents/{aid}", headers=auth_headers)+ assert r.status_code == 204++ # Gone+ r = await client.get(f"/api/agents/{aid}", headers=auth_headers)+ assert r.status_code == 404+++async def test_multi_tenant_scoping(client: AsyncClient, auth_headers: dict, other_auth_headers: dict):+ """User A's agent is invisible to user B."""+ r = await client.post("/api/agents", json={"name": "Mine"}, headers=auth_headers)+ assert r.status_code == 201+ aid = r.json()["id"]++ # Other user lists their own agents — empty.+ r = await client.get("/api/agents", headers=other_auth_headers)+ assert r.status_code == 200+ assert r.json() == []++ # Other user can't read it directly.+ r = await client.get(f"/api/agents/{aid}", headers=other_auth_headers)+ assert r.status_code == 404++ # Or update.+ r = await client.patch(f"/api/agents/{aid}", json={"name": "hijack"}, headers=other_auth_headers)+ assert r.status_code == 404++ # Or delete.+ r = await client.delete(f"/api/agents/{aid}", headers=other_auth_headers)+ assert r.status_code == 404+++async def test_create_validation_rejects_missing_name(client: AsyncClient, auth_headers: dict):+ r = await client.post("/api/agents", json={}, headers=auth_headers)+ assert r.status_code == 422+++async def test_temperature_clamp(client: AsyncClient, auth_headers: dict):+ # Pydantic schema enforces 0..2+ r = await client.post("/api/agents", json={"name": "x", "temperature": 5.0}, headers=auth_headers)+ assert r.status_code == 422+++# --- Conversations & messages ---------------------------------------------++async def test_conversations_empty(client: AsyncClient, auth_headers: dict):+ r = await client.get("/api/agents/conversations", headers=auth_headers)+ assert r.status_code == 200+ assert r.json() == []+++async def test_conversation_filtered_by_agent(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ """Insert a conversation directly and verify the filter works."""+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ a1 = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A1")+ a2 = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A2")+ session.add_all([a1, a2])+ await session.commit()++ c1 = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=a1.id, channel="web", title="hello")+ c2 = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=a2.id, channel="web", title="other")+ session.add_all([c1, c2])+ await session.commit()++ r = await client.get(f"/api/agents/conversations?agent_id={a1.id}", headers=auth_headers)+ assert r.status_code == 200+ body = r.json()+ assert len(body) == 1+ assert body[0]["title"] == "hello"+++async def test_rename_conversation(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web", title="old")+ session.add_all([agent, conv])+ await session.commit()++ r = await client.patch(f"/api/agents/conversations/{conv.id}", json={"title": "renamed!"}, headers=auth_headers)+ assert r.status_code == 200, r.text+ assert r.json()["title"] == "renamed!"++ r = await client.get(f"/api/agents/conversations/{conv.id}", headers=auth_headers)+ assert r.json()["title"] == "renamed!"+++async def test_rename_conversation_validates_empty(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web", title="old")+ session.add_all([agent, conv])+ await session.commit()++ r = await client.patch(f"/api/agents/conversations/{conv.id}", json={"title": ""}, headers=auth_headers)+ assert r.status_code == 422+++async def test_rename_conversation_404_other_user(+ client: AsyncClient, auth_headers: dict, other_auth_headers: dict, session: AsyncSession, test_user: User+):+ """auth_headers must come BEFORE other_auth_headers so test_user's+ clean_db setup runs first — otherwise it wipes the other user that+ other_auth_headers already created."""+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web", title="old")+ session.add_all([agent, conv])+ await session.commit()++ r = await client.patch(+ f"/api/agents/conversations/{conv.id}", json={"title": "hijack"}, headers=other_auth_headers+ )+ assert r.status_code == 404+++async def test_delete_conversation(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web")+ session.add_all([agent, conv])+ await session.commit()++ r = await client.delete(f"/api/agents/conversations/{conv.id}", headers=auth_headers)+ assert r.status_code == 204++ r = await client.get(f"/api/agents/conversations/{conv.id}", headers=auth_headers)+ assert r.status_code == 404+++async def test_generate_title_uses_llm(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ """The endpoint asks the agent's LLM provider for a short summary+ and persists it. We patch _provider_and_model_for so no real LLM+ call is made."""+ from unittest.mock import patch+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation, Message+ from app.agents.providers.base import (+ ChatResponse,+ LLMProvider,+ Usage,+ )++ class _Scripted(LLMProvider):+ name = "openai"++ async def chat_stream(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ # not used for title (we call .chat() which goes through .chat_stream)+ yield # pragma: no cover+ return # pragma: no cover++ async def chat(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ return ChatResponse(content="Brazilian Cuisine Picks", usage=Usage(2, 4))++ async def embed(self, texts, *, model):+ return []++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A", provider="openai", model="gpt-4o-mini")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web", title="name three brazilian foods")+ session.add_all([agent, conv])+ await session.commit()++ session.add_all([+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=1, role="user", content="name three brazilian foods"),+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=2, role="assistant", content="Feijoada, Coxinha, Pão de Queijo"),+ ])+ await session.commit()++ with patch(+ "app.agents.runtime.executor._provider_and_model_for",+ return_value=(_Scripted(), "gpt-4o-mini"),+ ):+ r = await client.post(+ f"/api/agents/conversations/{conv.id}/generate-title",+ headers=auth_headers,+ )+ assert r.status_code == 200, r.text+ assert r.json()["title"] == "Brazilian Cuisine Picks"+++async def test_generate_title_strips_reasoning_tags(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ """Local reasoning models often emit `<think>...</think>` before the+ answer. The endpoint must strip that and use only the title."""+ from unittest.mock import patch+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation, Message+ from app.agents.providers.base import ChatResponse, LLMProvider, Usage++ class _Scripted(LLMProvider):+ name = "openai_compatible"++ async def chat_stream(self, *a, **kw):+ yield # pragma: no cover++ async def chat(self, *a, **kw):+ return ChatResponse(+ content="<think>Let me summarize…</think>\nQuick Math Question",+ usage=Usage(0, 0),+ )++ async def embed(self, *a, **kw):+ return []++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A", model="local")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web", title="2+2")+ session.add_all([agent, conv])+ await session.commit()+ session.add_all([+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=1, role="user", content="2+2"),+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=2, role="assistant", content="4"),+ ])+ await session.commit()++ with patch(+ "app.agents.runtime.executor._provider_and_model_for",+ return_value=(_Scripted(), "local"),+ ):+ r = await client.post(+ f"/api/agents/conversations/{conv.id}/generate-title",+ headers=auth_headers,+ )+ assert r.status_code == 200+ # Just the title — the <think> block is gone.+ assert r.json()["title"] == "Quick Math Question"+++# --- Tools endpoint --------------------------------------------------------++async def test_tools_endpoint_returns_empty_when_no_mcp(client: AsyncClient, auth_headers: dict):+ r = await client.post("/api/agents", json={"name": "T"}, headers=auth_headers)+ aid = r.json()["id"]++ r = await client.get(f"/api/agents/{aid}/tools", headers=auth_headers)+ assert r.status_code == 200+ body = r.json()+ assert body["tools"] == []+++async def test_put_tools_persists_selection(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User+):+ """Even without a live MCP server, the user can pre-stage a whitelist."""+ from app.agents.models.agent import Agent++ a = Agent(id=uuid.uuid4(), user_id=test_user.id, name="X")+ session.add(a)+ await session.commit()++ r = await client.put(+ f"/api/agents/{a.id}/tools",+ json=[+ {"server": "securo", "tool_name": "list_transactions", "enabled": True},+ {"server": "securo", "tool_name": "propose_categorize", "enabled": False},+ ],+ headers=auth_headers,+ )+ assert r.status_code == 200, r.text+ assert r.json()["updated"] == 2++ # Verify rows actually exist via the service.+ from app.agents.services import agent_service++ pairs = await agent_service.allowed_tool_pairs(session, a.id)+ assert pairs == {("securo", "list_transactions")}diff --git a/backend/tests/test_agents_chunking.py b/backend/tests/test_agents_chunking.pynew file mode 100644index 00000000..400ff6ee--- /dev/null+++ b/backend/tests/test_agents_chunking.py@@ -0,0 +1,74 @@+"""Chunking helper.++Tests cover:+ - empty / whitespace input → no chunks+ - text below target → single chunk+ - paragraph-aware splits stay close to the target size+ - overlap text appears at the start of subsequent chunks+ - very long single-paragraph fallback (hard split)+ - PDF / TXT mime extraction selection+"""++from app.agents.services.chunking import (+ TARGET_CHARS,+ chunk_text,+ chunks_from_upload,+ extract_text,+)+++def test_empty_input_yields_nothing():+ assert chunk_text("") == []+ assert chunk_text(" \n\n \n") == []+++def test_short_text_single_chunk():+ out = chunk_text("hello world")+ assert out == ["hello world"]+++def test_paragraphs_grouped_within_target():+ paras = "\n\n".join(["para " + str(i) + " " + ("x" * 200) for i in range(20)])+ chunks = chunk_text(paras, target=1000, overlap=50)+ assert len(chunks) >= 4+ # No chunk should be too far above the target after the overlap-adjusted split.+ for c in chunks:+ assert len(c) <= TARGET_CHARS * 1.5 + 50+++def test_overlap_carries_tail_into_next_chunk():+ p1 = "AAAA " * 200 # ~1000 chars+ p2 = "BBBB " * 200+ chunks = chunk_text(f"{p1}\n\n{p2}", target=900, overlap=100)+ assert len(chunks) >= 2+ # The overlap is the last ~OVERLAP_CHARS of chunk 0 prepended to chunk 1.+ # Stripping whitespace handles the space/newline noise around the join.+ tail = chunks[0][-100:].strip()+ head = chunks[1][:300]+ assert tail and tail in head, f"expected overlap tail in next chunk; got head={head[:120]!r}"+++def test_huge_single_paragraph_hard_split():+ huge = "Z" * 8000+ chunks = chunk_text(huge, target=2000, overlap=0)+ assert len(chunks) >= 4+ for c in chunks:+ assert len(c) <= 2000+++def test_extract_text_handles_txt_and_md():+ payload = "# Title\n\nbody text".encode("utf-8")+ assert "body text" in extract_text(payload, mime="text/markdown", filename="x.md")+ assert "body text" in extract_text(payload, mime="text/plain", filename="x.txt")+++def test_extract_text_falls_back_for_unknown_mime():+ payload = b"opaque bytes that are still utf8"+ out = extract_text(payload, mime="application/octet-stream", filename="thing.bin")+ assert "opaque" in out+++def test_chunks_from_upload_returns_iterable():+ payload = ("para one. " * 200 + "\n\n" + "para two. " * 200).encode("utf-8")+ chunks = list(chunks_from_upload(payload, mime="text/plain", filename="x.txt"))+ assert len(chunks) >= 1diff --git a/backend/tests/test_agents_connection_service.py b/backend/tests/test_agents_connection_service.pynew file mode 100644index 00000000..3c809baf--- /dev/null+++ b/backend/tests/test_agents_connection_service.py@@ -0,0 +1,303 @@+"""Coverage for app/agents/services/connection_service.++The CRUD paths use the real test SQLite session. test_connection() is+the largest function in the module — we drive it through a fake+httpx.AsyncClient so each provider branch is exercised without real+network calls.+"""+from __future__ import annotations++import uuid++import pytest++import app.agents.services.connection_service as cs+++# --------------------------------------------------------------------- CRUD++async def test_create_connection_rejects_unknown_kind(session, test_user):+ with pytest.raises(ValueError, match="unknown kind"):+ await cs.create_connection(session, test_user.id, name="x", kind="bogus")+++async def test_create_connection_requires_base_url_for_openai_compatible(session, test_user):+ with pytest.raises(ValueError, match="openai_compatible requires base_url"):+ await cs.create_connection(session, test_user.id, name="x", kind="openai_compatible")+++async def test_create_and_get_and_list(session, test_user):+ conn = await cs.create_connection(+ session, test_user.id,+ name="My OpenAI", kind="openai", api_key="sk-secret",+ default_model="gpt-4o-mini",+ )+ assert conn.id is not None+ # API key is stored encrypted, NOT plaintext.+ assert conn.api_key_encrypted != b"sk-secret"+ assert conn.api_key_encrypted++ fetched = await cs.get_connection(session, conn.id, test_user.id)+ assert fetched is not None and fetched.id == conn.id++ # Wrong user → invisible.+ other = uuid.uuid4()+ assert await cs.get_connection(session, conn.id, other) is None++ listed = await cs.list_connections(session, test_user.id)+ assert any(c.id == conn.id for c in listed)+++async def test_default_is_unique_per_user(session, test_user):+ a = await cs.create_connection(+ session, test_user.id, name="a", kind="openai", is_default=True,+ )+ b = await cs.create_connection(+ session, test_user.id, name="b", kind="openai", is_default=True,+ )+ # Re-fetch a — its default flag should be cleared.+ refreshed_a = await cs.get_connection(session, a.id, test_user.id)+ await session.refresh(refreshed_a)+ assert refreshed_a.is_default is False+ refreshed_b = await cs.get_connection(session, b.id, test_user.id)+ await session.refresh(refreshed_b)+ assert refreshed_b.is_default is True++ # get_default_connection returns b+ default = await cs.get_default_connection(session, test_user.id)+ assert default is not None and default.id == b.id+++async def test_update_connection_handles_partial_and_default_swap(session, test_user):+ a = await cs.create_connection(session, test_user.id, name="a", kind="openai", is_default=True)+ b = await cs.create_connection(session, test_user.id, name="b", kind="openai")++ updated = await cs.update_connection(+ session, b.id, test_user.id,+ name="renamed", api_key="new-key", default_model="gpt-4o",+ extra={"note": "yo"}, is_default=True,+ )+ assert updated is not None+ assert updated.name == "renamed"+ assert updated.default_model == "gpt-4o"+ assert updated.extra == {"note": "yo"}+ assert updated.is_default is True++ # a should be demoted.+ refreshed_a = await cs.get_connection(session, a.id, test_user.id)+ await session.refresh(refreshed_a)+ assert refreshed_a.is_default is False++ # Setting is_default=False explicitly clears it.+ cleared = await cs.update_connection(session, b.id, test_user.id, is_default=False)+ assert cleared is not None and cleared.is_default is False+++async def test_update_connection_returns_none_for_unknown(session, test_user):+ out = await cs.update_connection(session, uuid.uuid4(), test_user.id, name="x")+ assert out is None+++async def test_update_connection_can_clear_api_key(session, test_user):+ """Passing api_key='' should null out the stored encrypted key."""+ conn = await cs.create_connection(+ session, test_user.id, name="x", kind="openai", api_key="sk-old",+ )+ assert conn.api_key_encrypted is not None++ out = await cs.update_connection(session, conn.id, test_user.id, api_key="")+ assert out.api_key_encrypted is None+++async def test_delete_connection(session, test_user):+ conn = await cs.create_connection(session, test_user.id, name="x", kind="openai")+ assert await cs.delete_connection(session, conn.id, test_user.id) is True+ assert await cs.get_connection(session, conn.id, test_user.id) is None+ assert await cs.delete_connection(session, uuid.uuid4(), test_user.id) is False+++def test_build_provider_for_connection(session):+ """The connection should yield a provider instance whose attrs come+ from the row. Smoke-test via openai kind."""+ from app.agents.models.connection import LlmConnection++ conn = LlmConnection(+ id=uuid.uuid4(), user_id=uuid.uuid4(),+ name="x", kind="openai",+ base_url="https://api.openai.com/v1",+ api_key_encrypted=None,+ default_model="gpt-4o-mini",+ extra={},+ )+ provider = cs.build_provider_for_connection(conn)+ assert provider.name == "openai"+++# --------------------------------------------------------------------- test_connection (probe)++class _FakeResp:+ def __init__(self, *, status_code=200, json_body=None, text=""):+ self.status_code = status_code+ self._json = json_body+ self.text = text++ def raise_for_status(self):+ if self.status_code >= 400:+ import httpx+ raise httpx.HTTPError(f"HTTP {self.status_code}")++ def json(self):+ if isinstance(self._json, Exception):+ raise self._json+ return self._json+++class _FakeAsyncClient:+ queue: list[_FakeResp] = []+ calls: list[tuple[str, dict]] = []++ def __init__(self, *_, **__):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ async def get(self, url, *, headers=None):+ type(self).calls.append((url, headers or {}))+ return type(self).queue.pop(0)+++def fake_httpx(monkeypatch):+ _FakeAsyncClient.queue = []+ _FakeAsyncClient.calls = []+ import httpx+ monkeypatch.setattr(httpx, "AsyncClient", _FakeAsyncClient)+ yield _FakeAsyncClient+++def _conn(**overrides):+ from app.agents.models.connection import LlmConnection+ defaults = dict(+ id=uuid.uuid4(), user_id=uuid.uuid4(),+ name="x", kind="openai",+ base_url=None, api_key_encrypted=None,+ default_model=None, extra={},+ )+ defaults.update(overrides)+ return LlmConnection(**defaults)+++async def test_probe_ollama_returns_model_count(fake_httpx):+ fake_httpx.queue.append(_FakeResp(json_body={+ "models": [{"name": "llama3"}, {"name": "nomic"}],+ }))+ out = await cs.test_connection(_conn(kind="ollama"))+ assert out["ok"] is True+ assert "2 models" in out["detail"]+ assert out["models"] == ["llama3", "nomic"]+++async def test_probe_openai_returns_models_on_success(fake_httpx):+ fake_httpx.queue.append(_FakeResp(json_body={+ "data": [{"id": "gpt-4o-mini"}, {"id": "gpt-4o"}],+ }))+ out = await cs.test_connection(_conn(kind="openai"))+ assert out["ok"] is True+ assert "2 models" in out["detail"]+++async def test_probe_openai_auth_rejected(fake_httpx):+ fake_httpx.queue.append(_FakeResp(status_code=401))+ out = await cs.test_connection(_conn(kind="openai"))+ assert out["ok"] is False+ assert "auth rejected" in out["detail"]+++async def test_probe_openai_returns_http_error_text(fake_httpx):+ fake_httpx.queue.append(_FakeResp(status_code=500, text="oops"))+ out = await cs.test_connection(_conn(kind="openai"))+ assert out["ok"] is False+ assert "HTTP 500" in out["detail"]+++async def test_probe_openai_compatible_warns_when_no_models(fake_httpx):+ fake_httpx.queue.append(_FakeResp(json_body={"data": []}))+ out = await cs.test_connection(_conn(+ kind="openai_compatible", base_url="http://lmstudio:1234/v1",+ ))+ assert out["ok"] is False+ assert "no models" in out["detail"]+++async def test_probe_openai_compatible_warns_when_bad_json(fake_httpx):+ fake_httpx.queue.append(_FakeResp(json_body=ValueError("not json")))+ out = await cs.test_connection(_conn(+ kind="openai_compatible", base_url="http://lmstudio:1234/v1",+ ))+ assert out["ok"] is False+ assert "did not return JSON" in out["detail"]+++async def test_probe_anthropic_success(fake_httpx):+ fake_httpx.queue.append(_FakeResp(json_body={+ "data": [{"id": "claude-3-5-sonnet"}],+ }))+ out = await cs.test_connection(_conn(kind="anthropic"))+ assert out["ok"] is True+ assert "1 models" in out["detail"]+++async def test_probe_anthropic_auth_failure(fake_httpx):+ fake_httpx.queue.append(_FakeResp(status_code=403))+ out = await cs.test_connection(_conn(kind="anthropic"))+ assert out["ok"] is False+ assert "auth rejected" in out["detail"]+++async def test_probe_unknown_kind(fake_httpx):+ out = await cs.test_connection(_conn(kind="something-else"))+ assert out["ok"] is False+ assert "unknown kind" in out["detail"]+++async def test_probe_swallows_httpx_errors(monkeypatch):+ """If the AsyncClient itself raises (network down), we should return+ a structured 'unreachable' response, not propagate."""+ import httpx++ class _BlowsUp:+ def __init__(self, *_, **__):+ pass++ async def __aenter__(self):+ raise httpx.ConnectError("dns fail")++ async def __aexit__(self, *exc):+ return False++ monkeypatch.setattr(httpx, "AsyncClient", _BlowsUp)+ out = await cs.test_connection(_conn(kind="ollama"))+ assert out["ok"] is False+ assert "unreachable" in out["detail"]diff --git a/backend/tests/test_agents_connections.py b/backend/tests/test_agents_connections.pynew file mode 100644index 00000000..63f8d019--- /dev/null+++ b/backend/tests/test_agents_connections.py@@ -0,0 +1,312 @@+"""LLM connections — encryption, CRUD via HTTP, executor wiring."""+import uuid+from unittest.mock import patch, AsyncMock++import bcrypt as _bcrypt+import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.agents.services import connection_service+from app.agents.services.crypto import decrypt, encrypt+from app.models.user import User+++pytestmark = pytest.mark.asyncio+++# --- Encryption ------------------------------------------------------------++def test_encrypt_decrypt_roundtrip():+ secret = "sk-ant-totally-secret-12345"+ enc = encrypt(secret)+ assert enc != secret+ assert enc and len(enc) > 40 # Fernet tokens are noticeably longer than the input+ assert decrypt(enc) == secret+++def test_encrypt_none_passes_through():+ assert encrypt(None) is None+ assert encrypt("") is None+ assert decrypt(None) is None+ assert decrypt("") is None+++def test_decrypt_corrupt_returns_none():+ """Rotated secret / corrupt ciphertext must not crash; returns None."""+ assert decrypt("not-a-real-fernet-token") is None+++# --- Service layer --------------------------------------------------------++async def test_create_connection_with_encryption(session: AsyncSession, test_user: User):+ conn = await connection_service.create_connection(+ session, test_user.id,+ name="Local Ollama",+ kind="ollama",+ base_url="http://host.docker.internal:11434",+ api_key=None,+ default_model="llama3.1:8b",+ )+ assert conn.id is not None+ assert conn.api_key_encrypted is None # ollama doesn't need a key++ conn2 = await connection_service.create_connection(+ session, test_user.id,+ name="My Anthropic",+ kind="anthropic",+ api_key="sk-ant-real-key",+ default_model="claude-haiku-4-5",+ )+ assert conn2.api_key_encrypted is not None+ assert conn2.api_key_encrypted != "sk-ant-real-key"+ assert decrypt(conn2.api_key_encrypted) == "sk-ant-real-key"+++async def test_create_connection_rejects_unknown_kind(session: AsyncSession, test_user: User):+ with pytest.raises(ValueError):+ await connection_service.create_connection(+ session, test_user.id, name="x", kind="bogus",+ )+++async def test_openai_compatible_requires_base_url(session: AsyncSession, test_user: User):+ with pytest.raises(ValueError):+ await connection_service.create_connection(+ session, test_user.id, name="x", kind="openai_compatible",+ )+++async def test_only_one_default_per_user(session: AsyncSession, test_user: User):+ a = await connection_service.create_connection(+ session, test_user.id, name="A", kind="ollama", is_default=True,+ )+ b = await connection_service.create_connection(+ session, test_user.id, name="B", kind="ollama", is_default=True,+ )+ # Re-fetch a — should no longer be default.+ a_after = await connection_service.get_connection(session, a.id, test_user.id)+ assert a_after.is_default is False+ assert b.is_default is True+++async def test_update_keeps_existing_key_when_api_key_omitted(session: AsyncSession, test_user: User):+ conn = await connection_service.create_connection(+ session, test_user.id, name="x", kind="openai", api_key="sk-original",+ )+ enc_before = conn.api_key_encrypted++ # Update without touching api_key.+ updated = await connection_service.update_connection(+ session, conn.id, test_user.id, name="renamed",+ )+ assert updated.api_key_encrypted == enc_before+ assert decrypt(updated.api_key_encrypted) == "sk-original"+++async def test_update_clears_key_with_empty_string(session: AsyncSession, test_user: User):+ conn = await connection_service.create_connection(+ session, test_user.id, name="x", kind="openai", api_key="sk-original",+ )+ updated = await connection_service.update_connection(+ session, conn.id, test_user.id, api_key="",+ )+ assert updated.api_key_encrypted is None+++# --- HTTP CRUD -------------------------------------------------------------++async def test_unauthenticated_connections_list_rejected(client: AsyncClient):+ r = await client.get("/api/agents/connections")+ assert r.status_code == 401+++async def test_create_then_list_via_http(client: AsyncClient, auth_headers: dict):+ r = await client.post(+ "/api/agents/connections",+ json={+ "name": "Local Ollama",+ "kind": "ollama",+ "base_url": "http://host.docker.internal:11434",+ "default_model": "llama3.1:8b",+ },+ headers=auth_headers,+ )+ assert r.status_code == 201, r.text+ body = r.json()+ assert body["name"] == "Local Ollama"+ assert body["has_api_key"] is False+ assert "api_key" not in body # never expose key++ r = await client.get("/api/agents/connections", headers=auth_headers)+ assert r.status_code == 200+ assert len(r.json()) == 1+++async def test_api_key_never_returned(client: AsyncClient, auth_headers: dict):+ r = await client.post(+ "/api/agents/connections",+ json={"name": "secret", "kind": "openai", "api_key": "sk-real-and-private"},+ headers=auth_headers,+ )+ assert r.status_code == 201+ cid = r.json()["id"]+ assert "api_key" not in r.json()+ assert r.json()["has_api_key"] is True++ r = await client.get(f"/api/agents/connections/{cid}", headers=auth_headers)+ body = r.json()+ assert "api_key" not in body+ # The plaintext should not appear anywhere in the response.+ assert "sk-real-and-private" not in r.text+++@pytest_asyncio.fixture+async def other_auth_headers_conn(client: AsyncClient, session: AsyncSession) -> dict:+ """Second user just for tenant-isolation tests in this file."""+ hashed = _bcrypt.hashpw(b"otherpass123", _bcrypt.gensalt()).decode()+ user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=hashed,+ is_active=True, is_superuser=False, is_verified=True,+ preferences={"language": "en", "currency_display": "USD"},+ )+ session.add(user)+ await session.commit()+ resp = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "otherpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ return {"Authorization": f"Bearer {resp.json()['access_token']}"}+++async def test_connections_are_per_user(client: AsyncClient, auth_headers: dict, other_auth_headers_conn: dict):+ r = await client.post(+ "/api/agents/connections",+ json={"name": "mine", "kind": "ollama"},+ headers=auth_headers,+ )+ cid = r.json()["id"]++ r = await client.get("/api/agents/connections", headers=other_auth_headers_conn)+ assert r.json() == []++ r = await client.get(f"/api/agents/connections/{cid}", headers=other_auth_headers_conn)+ assert r.status_code == 404+++# --- Test endpoint (mocked HTTP probe) ------------------------------------++async def test_test_endpoint_mocked_ok(client: AsyncClient, auth_headers: dict):+ r = await client.post(+ "/api/agents/connections",+ json={"name": "x", "kind": "ollama", "base_url": "http://fake:11434"},+ headers=auth_headers,+ )+ cid = r.json()["id"]++ fake_resp = AsyncMock()+ fake_resp.raise_for_status = lambda: None+ fake_resp.json = lambda: {"models": [{"name": "llama3.1:8b"}]}++ fake_client = AsyncMock()+ fake_client.__aenter__.return_value = fake_client+ fake_client.__aexit__.return_value = None+ fake_client.get = AsyncMock(return_value=fake_resp)++ # `httpx` is imported lazily inside test_connection(); patch the global.+ with patch("httpx.AsyncClient", return_value=fake_client):+ r = await client.post(f"/api/agents/connections/{cid}/test", headers=auth_headers)+ assert r.status_code == 200+ body = r.json()+ assert body["ok"] is True+ assert body["models"] == ["llama3.1:8b"]+++async def test_test_endpoint_404_for_unknown(client: AsyncClient, auth_headers: dict):+ r = await client.post(f"/api/agents/connections/{uuid.uuid4()}/test", headers=auth_headers)+ assert r.status_code == 404+++# --- Executor uses the connection ------------------------------------------++async def test_executor_resolves_provider_from_connection(+ session: AsyncSession, test_user: User+):+ """Agent with connection_id → executor builds provider via the connection,+ inheriting its base_url and decrypted api_key. The connection's+ default_model is used when the agent doesn't override."""+ from app.agents.runtime.executor import _provider_and_model_for+ from app.agents.models.agent import Agent++ conn = await connection_service.create_connection(+ session, test_user.id,+ name="my-llm", kind="openai_compatible",+ base_url="http://my-server:8000/v1",+ api_key="sk-some-key",+ default_model="my-custom-model",+ )++ agent = Agent(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="A",+ connection_id=conn.id,+ model=None, # falls back to connection.default_model+ )+ session.add(agent)+ await session.commit()++ provider, model = await _provider_and_model_for(session, agent)+ assert provider.name == "openai_compatible"+ assert provider.base_url == "http://my-server:8000/v1"+ assert provider.api_key == "sk-some-key"+ assert model == "my-custom-model"+++async def test_executor_falls_back_to_user_default_connection(+ session: AsyncSession, test_user: User+):+ """No connection_id on agent, but user has a default connection — use it."""+ from app.agents.runtime.executor import _provider_and_model_for+ from app.agents.models.agent import Agent++ await connection_service.create_connection(+ session, test_user.id,+ name="default-anthropic", kind="anthropic",+ api_key="sk-ant-x", default_model="claude-haiku-4-5",+ is_default=True,+ )++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A", connection_id=None, model=None)+ session.add(agent)+ await session.commit()++ provider, model = await _provider_and_model_for(session, agent)+ assert provider.name == "anthropic"+ assert provider.api_key == "sk-ant-x"+ assert model == "claude-haiku-4-5"+++async def test_executor_agent_model_overrides_connection_default(+ session: AsyncSession, test_user: User+):+ from app.agents.runtime.executor import _provider_and_model_for+ from app.agents.models.agent import Agent++ conn = await connection_service.create_connection(+ session, test_user.id,+ name="x", kind="openai", api_key="sk", default_model="gpt-4o-mini",+ )+ agent = Agent(+ id=uuid.uuid4(), user_id=test_user.id, name="A",+ connection_id=conn.id, model="gpt-4o", # explicit override+ )+ session.add(agent)+ await session.commit()++ _provider, model = await _provider_and_model_for(session, agent)+ assert model == "gpt-4o"diff --git a/backend/tests/test_agents_connections_api.py b/backend/tests/test_agents_connections_api.pynew file mode 100644index 00000000..e310ae4a--- /dev/null+++ b/backend/tests/test_agents_connections_api.py@@ -0,0 +1,154 @@+"""HTTP coverage for /api/agents/connections — LLM connection CRUD plus+the /test probe endpoint."""+from __future__ import annotations++import uuid+from unittest.mock import patch++import pytest+++async def test_list_connections_empty(client, auth_headers, test_user):+ r = await client.get("/api/agents/connections", headers=auth_headers)+ assert r.status_code == 200+ assert r.json() == []+++async def test_create_connection_persists_and_hides_api_key(client, auth_headers, test_user):+ payload = {+ "name": "My OpenAI",+ "kind": "openai",+ "api_key": "sk-secret-123",+ "default_model": "gpt-4o-mini",+ }+ r = await client.post("/api/agents/connections", json=payload, headers=auth_headers)+ assert r.status_code == 201, r.text+ body = r.json()+ # has_api_key reflects presence; the literal key never round-trips.+ assert body["has_api_key"] is True+ assert "api_key" not in body+ assert body["default_model"] == "gpt-4o-mini"+++async def test_create_connection_400_for_unknown_kind(client, auth_headers, test_user):+ r = await client.post(+ "/api/agents/connections",+ json={"name": "x", "kind": "bogus"},+ headers=auth_headers,+ )+ assert r.status_code == 400+ assert "unknown kind" in r.json()["detail"]+++async def test_create_connection_400_for_openai_compat_without_base_url(client, auth_headers, test_user):+ r = await client.post(+ "/api/agents/connections",+ json={"name": "x", "kind": "openai_compatible"},+ headers=auth_headers,+ )+ assert r.status_code == 400+++async def test_get_update_delete_connection(client, auth_headers, test_user):+ r = await client.post(+ "/api/agents/connections",+ json={"name": "A", "kind": "openai"},+ headers=auth_headers,+ )+ cid = r.json()["id"]++ # GET+ r = await client.get(f"/api/agents/connections/{cid}", headers=auth_headers)+ assert r.status_code == 200+ assert r.json()["name"] == "A"++ # PATCH+ r = await client.patch(+ f"/api/agents/connections/{cid}",+ json={"name": "Renamed", "is_default": True},+ headers=auth_headers,+ )+ assert r.status_code == 200+ assert r.json()["name"] == "Renamed"+ assert r.json()["is_default"] is True++ # DELETE+ r = await client.delete(f"/api/agents/connections/{cid}", headers=auth_headers)+ assert r.status_code == 204++ # 404 after delete+ r = await client.get(f"/api/agents/connections/{cid}", headers=auth_headers)+ assert r.status_code == 404+++async def test_get_connection_404(client, auth_headers, test_user):+ r = await client.get(+ f"/api/agents/connections/{uuid.uuid4()}", headers=auth_headers+ )+ assert r.status_code == 404+++async def test_update_connection_404(client, auth_headers, test_user):+ r = await client.patch(+ f"/api/agents/connections/{uuid.uuid4()}",+ json={"name": "x"},+ headers=auth_headers,+ )+ assert r.status_code == 404+++async def test_delete_connection_404(client, auth_headers, test_user):+ r = await client.delete(+ f"/api/agents/connections/{uuid.uuid4()}", headers=auth_headers+ )+ assert r.status_code == 404+++async def test_test_connection_uses_service_probe(client, auth_headers, test_user):+ """The /test endpoint should delegate to connection_service.test_connection+ and return its structured result."""+ r = await client.post(+ "/api/agents/connections",+ json={"name": "A", "kind": "ollama"},+ headers=auth_headers,+ )+ cid = r.json()["id"]++ async def fake_probe(conn):+ return {"ok": True, "detail": "fake reachable", "models": ["llama3"]}++ with patch(+ "app.agents.api.connections.connection_service.test_connection",+ side_effect=fake_probe,+ ):+ r = await client.post(+ f"/api/agents/connections/{cid}/test", headers=auth_headers+ )+ assert r.status_code == 200, r.text+ body = r.json()+ assert body["ok"] is True+ assert body["detail"] == "fake reachable"+ assert body["models"] == ["llama3"]+++async def test_test_connection_404_for_unknown(client, auth_headers, test_user):+ r = await client.post(+ f"/api/agents/connections/{uuid.uuid4()}/test", headers=auth_headers+ )+ assert r.status_code == 404+++async def test_unauthenticated_connections_rejected(client):+ r = await client.get("/api/agents/connections")+ assert r.status_code == 401diff --git a/backend/tests/test_agents_conversation_service.py b/backend/tests/test_agents_conversation_service.pynew file mode 100644index 00000000..7baa17cf--- /dev/null+++ b/backend/tests/test_agents_conversation_service.py@@ -0,0 +1,160 @@+"""Direct unit tests for app/agents/services/conversation_service. The+HTTP layer covers most paths in test_agents_api.py — this fills in the+service-only utilities (append_message ordinal generation,+update_title_if_empty, etc.) that don't ride a route."""+from __future__ import annotations++import uuid++import pytest++from app.agents.services import conversation_service as svc+++async def test_create_conversation_persists_with_defaults(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ assert conv.id is not None+ assert conv.user_id == test_user.id+ assert conv.agent_id == test_agent.id+ assert conv.channel == "web" # default+ assert conv.title is None+++async def test_list_conversations_filters_by_agent_and_user(session, test_user, test_agent):+ a = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id, title="A",+ )+ # Conversation for a different agent → should be filtered out.+ other_agent_id = uuid.uuid4()+ from app.agents.models.agent import Agent+ other_agent = Agent(id=other_agent_id, user_id=test_user.id, name="Other")+ session.add(other_agent)+ await session.commit()+ b = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=other_agent_id, title="B",+ )++ rows_a = await svc.list_conversations(session, test_user.id, agent_id=test_agent.id)+ assert {c.id for c in rows_a} == {a.id}++ # All of test_user's convs.+ rows_all = await svc.list_conversations(session, test_user.id)+ assert {a.id, b.id} <= {c.id for c in rows_all}++ # Foreign user → empty.+ foreign = uuid.uuid4()+ assert await svc.list_conversations(session, foreign) == []+++async def test_append_message_assigns_monotonic_ordinals(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ a = await svc.append_message(session, conversation_id=conv.id, role="user", content="one")+ b = await svc.append_message(session, conversation_id=conv.id, role="assistant", content="two")+ c = await svc.append_message(session, conversation_id=conv.id, role="user", content="three")+ assert (a.ordinal, b.ordinal, c.ordinal) == (1, 2, 3)+++async def test_list_messages_ordered_by_ordinal(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ await svc.append_message(session, conversation_id=conv.id, role="user", content="one")+ await svc.append_message(session, conversation_id=conv.id, role="assistant", content="two")+ msgs = await svc.list_messages(session, conv.id)+ assert [m.content for m in msgs] == ["one", "two"]+++async def test_append_message_persists_tool_payloads(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ msg = await svc.append_message(+ session,+ conversation_id=conv.id,+ role="assistant",+ content=None,+ tool_calls=[{"id": "tc1", "name": "list_accounts", "arguments": "{}"}],+ tool_result={"items": [{"id": "x"}]},+ citations=[{"doc_id": "d", "score": 0.9}],+ input_tokens=12,+ output_tokens=34,+ )+ assert msg.tool_calls == [{"id": "tc1", "name": "list_accounts", "arguments": "{}"}]+ assert msg.tool_result == {"items": [{"id": "x"}]}+ assert msg.citations == [{"doc_id": "d", "score": 0.9}]+ assert msg.input_tokens == 12+ assert msg.output_tokens == 34+++async def test_update_title_if_empty_only_writes_when_blank(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ # First call: title is None → should fill in.+ await svc.update_title_if_empty(session, conv.id, "Auto generated")+ refreshed = await svc.get_conversation(session, conv.id, test_user.id)+ await session.refresh(refreshed)+ assert refreshed.title == "Auto generated"++ # Second call: title already set → should NOT overwrite.+ await svc.update_title_if_empty(session, conv.id, "Different title")+ refreshed = await svc.get_conversation(session, conv.id, test_user.id)+ await session.refresh(refreshed)+ assert refreshed.title == "Auto generated"+++async def test_update_title_if_empty_silent_on_missing_conv(session):+ # No exception when the conv doesn't exist — used by streaming code.+ await svc.update_title_if_empty(session, uuid.uuid4(), "x")+++async def test_update_title_truncates_to_200_chars(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ long_title = "x" * 500+ out = await svc.update_title(session, conv.id, test_user.id, long_title)+ assert out is not None+ assert len(out.title) == 200+++async def test_update_title_returns_none_on_missing(session, test_user):+ out = await svc.update_title(session, uuid.uuid4(), test_user.id, "x")+ assert out is None+++async def test_update_title_blank_clears_to_none(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id, title="Existing",+ )+ out = await svc.update_title(session, conv.id, test_user.id, " ")+ assert out is not None+ assert out.title is None+++async def test_delete_conversation_returns_false_on_missing(session, test_user):+ assert await svc.delete_conversation(session, uuid.uuid4(), test_user.id) is False+++async def test_delete_conversation_removes_row(session, test_user, test_agent):+ conv = await svc.create_conversation(+ session, user_id=test_user.id, agent_id=test_agent.id,+ )+ assert await svc.delete_conversation(session, conv.id, test_user.id) is True+ assert await svc.get_conversation(session, conv.id, test_user.id) is Nonediff --git a/backend/tests/test_agents_coverage_gaps.py b/backend/tests/test_agents_coverage_gaps.pynew file mode 100644index 00000000..a9006f8e--- /dev/null+++ b/backend/tests/test_agents_coverage_gaps.py@@ -0,0 +1,318 @@+"""Supplemental tests targeting specific uncovered branches in+app/agents/services/agent_service and app/agents/api/{agents,conversations}.+The existing test_agents_api.py covers happy paths; this file fills in+the unhit branches (is_default toggling, count aggregation, tools+discovery, generate-title, delete fallbacks)."""+from __future__ import annotations++import uuid+from unittest.mock import patch++import pytest++from app.agents.services import agent_service+++# --------------------------------------------------------------------- agent_service.list_agents conv+kb count aggregation++async def test_list_agents_populates_conversation_and_knowledge_counts(+ session, test_user, test_agent+):+ """Ensures the GROUP BY count queries (lines 23-43) run."""+ from app.agents.models.conversation import Conversation+ from app.agents.models.knowledge import KnowledgeDoc++ # Add 2 conversations and 1 KB doc to the agent.+ session.add_all([+ Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=test_agent.id, channel="web"),+ Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=test_agent.id, channel="web"),+ KnowledgeDoc(+ id=uuid.uuid4(), agent_id=test_agent.id, user_id=test_user.id,+ title="t", source="t", mime="text/plain", size_bytes=1, status="ready",+ ),+ ])+ await session.commit()++ rows = await agent_service.list_agents(session, test_user.id)+ assert len(rows) == 1+ assert rows[0].conversation_count == 2 # type: ignore[attr-defined]+ assert rows[0].knowledge_count == 1 # type: ignore[attr-defined]+++# --------------------------------------------------------------------- agent_service.set_tool_enabled++async def test_set_tool_enabled_inserts_then_updates_existing_row(session, test_agent):+ # Insert path+ row = await agent_service.set_tool_enabled(+ session, test_agent.id, "securo", "list_accounts", True+ )+ assert row.enabled is True+ # Same (server, tool) pair → updates the existing row, no second insert.+ row2 = await agent_service.set_tool_enabled(+ session, test_agent.id, "securo", "list_accounts", False+ )+ # Composite primary key: same (agent_id, server, tool_name) tuple.+ assert (row2.agent_id, row2.server, row2.tool_name) == (row.agent_id, row.server, row.tool_name)+ assert row2.enabled is False++ # And allowed_tool_pairs reflects it.+ pairs = await agent_service.allowed_tool_pairs(session, test_agent.id)+ assert pairs == set() # disabled → not in allowed set+++async def test_allowed_tool_pairs_returns_none_when_no_rows(session, test_agent):+ """No explicit AgentTool rows → returns None ('allow all')."""+ out = await agent_service.allowed_tool_pairs(session, test_agent.id)+ assert out is None+++# --------------------------------------------------------------------- agents API: /default + /tools++async def test_get_default_agent_endpoint_returns_explicit_default(+ client, auth_headers, test_user+):+ await client.post("/api/agents", json={"name": "A"}, headers=auth_headers)+ b = (await client.post("/api/agents", json={"name": "B"}, headers=auth_headers)).json()+ # Mark B explicit default.+ await client.patch(f"/api/agents/{b['id']}", json={"is_default": True}, headers=auth_headers)++ r = await client.get("/api/agents/default", headers=auth_headers)+ assert r.status_code == 200+ assert r.json()["id"] == b["id"]+++async def test_get_default_agent_endpoint_404_when_no_agents(client, auth_headers, test_user):+ r = await client.get("/api/agents/default", headers=auth_headers)+ assert r.status_code == 404+++async def test_get_default_falls_back_to_most_recent_when_no_explicit(+ client, auth_headers, test_user+):+ a = (await client.post("/api/agents", json={"name": "A"}, headers=auth_headers)).json()+ b = (await client.post("/api/agents", json={"name": "B"}, headers=auth_headers)).json()+ r = await client.get("/api/agents/default", headers=auth_headers)+ assert r.status_code == 200+ # The newest agent wins as fallback.+ assert r.json()["id"] in {a["id"], b["id"]}+++async def test_marking_second_agent_default_clears_first(+ client, auth_headers, test_user+):+ a = (await client.post("/api/agents", json={"name": "A"}, headers=auth_headers)).json()+ b = (await client.post("/api/agents", json={"name": "B"}, headers=auth_headers)).json()++ await client.patch(f"/api/agents/{a['id']}", json={"is_default": True}, headers=auth_headers)+ await client.patch(f"/api/agents/{b['id']}", json={"is_default": True}, headers=auth_headers)++ r = await client.get(f"/api/agents/{a['id']}", headers=auth_headers)+ assert r.json()["is_default"] is False+ r = await client.get(f"/api/agents/{b['id']}", headers=auth_headers)+ assert r.json()["is_default"] is True+++async def test_get_agent_tools_returns_merged_state(+ client, auth_headers, test_user+):+ """Mock MCPRegistry.discover so we can exercise the merge logic+ in api/agents.py without a live MCP server."""+ from app.agents.mcp.client import ToolHandle++ async def fake_discover(self, *, user_id, conversation_id=None, agent_id=None):+ return [+ ToolHandle(server="securo", name="list_accounts", description="d", parameters={}),+ ToolHandle(server="securo", name="propose_x", description="d", parameters={}, is_proposal=True),+ ]++ with patch("app.agents.api.agents.MCPRegistry.discover", new=fake_discover), \+ patch("app.agents.api.agents.MCPRegistry.server_names", lambda self: ["securo"]):+ a = (await client.post("/api/agents", json={"name": "A"}, headers=auth_headers)).json()+ r = await client.get(f"/api/agents/{a['id']}/tools", headers=auth_headers)+ assert r.status_code == 200+ body = r.json()+ assert body["servers"] == [{"name": "securo"}]+ by_name = {t["name"]: t for t in body["tools"]}+ # First-run with no AgentTool rows yet → enabled defaults to True.+ assert by_name["list_accounts"]["enabled"] is True+ assert by_name["propose_x"]["is_proposal"] is True+++async def test_get_agent_tools_404_for_unknown_agent(client, auth_headers, test_user):+ r = await client.get(f"/api/agents/{uuid.uuid4()}/tools", headers=auth_headers)+ assert r.status_code == 404+++async def test_put_agent_tools_persists_explicit_selection(+ client, auth_headers, test_user+):+ a = (await client.post("/api/agents", json={"name": "A"}, headers=auth_headers)).json()+ r = await client.put(+ f"/api/agents/{a['id']}/tools",+ json=[+ {"server": "securo", "tool_name": "list_accounts", "enabled": True},+ {"server": "securo", "tool_name": "create_payee", "enabled": False},+ ],+ headers=auth_headers,+ )+ assert r.status_code == 200+ assert r.json() == {"updated": 2}+++async def test_put_agent_tools_404_for_unknown_agent(client, auth_headers, test_user):+ r = await client.put(+ f"/api/agents/{uuid.uuid4()}/tools",+ json=[],+ headers=auth_headers,+ )+ assert r.status_code == 404+++# --------------------------------------------------------------------- conversations API: generate-title quirks++async def test_generate_title_returns_unchanged_when_no_messages(+ client, auth_headers, test_user, session+):+ """generate-title shortcuts to the existing row when transcript is+ empty — covers the early-return branch."""+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A")+ conv = Conversation(+ id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id,+ channel="web", title="original",+ )+ session.add_all([agent, conv])+ await session.commit()++ r = await client.post(+ f"/api/agents/conversations/{conv.id}/generate-title", headers=auth_headers,+ )+ assert r.status_code == 200+ assert r.json()["title"] == "original"+++async def test_generate_title_silently_swallows_llm_errors(+ client, auth_headers, test_user, session+):+ """If the provider raises, the existing title is preserved and a 200+ is still returned."""+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation, Message+ from app.agents.providers.base import LLMProvider++ class _Boom(LLMProvider):+ name = "openai"+ async def chat_stream(self, *a, **kw): yield # pragma: no cover+ async def chat(self, *a, **kw):+ raise RuntimeError("provider down")+ async def embed(self, *a, **kw): return []++ agent = Agent(+ id=uuid.uuid4(), user_id=test_user.id, name="A",+ provider="openai", model="gpt-4o-mini",+ )+ conv = Conversation(+ id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id,+ channel="web", title="kept",+ )+ session.add_all([agent, conv])+ await session.commit()+ session.add_all([+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=1, role="user", content="hi"),+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=2, role="assistant", content="hello"),+ ])+ await session.commit()++ with patch(+ "app.agents.runtime.executor._provider_and_model_for",+ return_value=(_Boom(), "gpt-4o-mini"),+ ):+ r = await client.post(+ f"/api/agents/conversations/{conv.id}/generate-title", headers=auth_headers,+ )+ assert r.status_code == 200+ assert r.json()["title"] == "kept"+++async def test_generate_title_404_for_unknown_conversation(client, auth_headers, test_user):+ r = await client.post(+ f"/api/agents/conversations/{uuid.uuid4()}/generate-title", headers=auth_headers,+ )+ assert r.status_code == 404+++# --------------------------------------------------------------------- conversations API: 404 paths++async def test_get_conversation_404(client, auth_headers, test_user):+ r = await client.get(+ f"/api/agents/conversations/{uuid.uuid4()}", headers=auth_headers,+ )+ assert r.status_code == 404+++async def test_list_messages_404_for_unknown_conversation(client, auth_headers, test_user):+ r = await client.get(+ f"/api/agents/conversations/{uuid.uuid4()}/messages", headers=auth_headers,+ )+ assert r.status_code == 404+++async def test_list_messages_returns_messages_for_owned_conversation(+ client, auth_headers, test_user, session+):+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation, Message++ agent = Agent(id=uuid.uuid4(), user_id=test_user.id, name="A")+ conv = Conversation(id=uuid.uuid4(), user_id=test_user.id, agent_id=agent.id, channel="web")+ session.add_all([agent, conv])+ await session.commit()+ session.add_all([+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=1, role="user", content="hi"),+ Message(id=uuid.uuid4(), conversation_id=conv.id, ordinal=2, role="assistant", content="hello"),+ ])+ await session.commit()++ r = await client.get(+ f"/api/agents/conversations/{conv.id}/messages", headers=auth_headers,+ )+ assert r.status_code == 200+ body = r.json()+ assert [m["content"] for m in body] == ["hi", "hello"]+++async def test_delete_conversation_404(client, auth_headers, test_user):+ r = await client.delete(+ f"/api/agents/conversations/{uuid.uuid4()}", headers=auth_headers,+ )+ assert r.status_code == 404+++async def test_rename_conversation_404(client, auth_headers, test_user):+ r = await client.patch(+ f"/api/agents/conversations/{uuid.uuid4()}",+ json={"title": "x"},+ headers=auth_headers,+ )+ assert r.status_code == 404diff --git a/backend/tests/test_agents_embedding.py b/backend/tests/test_agents_embedding.pynew file mode 100644index 00000000..e94fccac--- /dev/null+++ b/backend/tests/test_agents_embedding.py@@ -0,0 +1,96 @@+"""Native embedder dispatch tests.++We do NOT actually download or run fastembed in CI — these tests stub+the underlying _get_native_embedder factory so the dispatch logic can+be exercised without the 120MB model download.+"""+from __future__ import annotations++from unittest.mock import patch++import pytest+++pytestmark = pytest.mark.asyncio+++async def test_native_embedder_is_lazy_imported_only_on_call():+ """Importing the embedding module must NOT pull in fastembed. Only+ the actual _embed_native call should. This protects users who don't+ use the agents feature from paying the import + memory cost."""+ import sys++ # Reset any prior fastembed import to test cleanly.+ if "fastembed" in sys.modules:+ del sys.modules["fastembed"]++ # Importing the embedding module by itself must not load fastembed.+ from app.agents.services import embedding # noqa: F401++ assert "fastembed" not in sys.modules, (+ "fastembed must not be eagerly imported — wrap the import inside the function body"+ )+++async def test_native_dispatch_calls_lazy_factory():+ """When provider=native, embed_texts must route to _embed_native and+ receive the dimension-adjusted vectors. We stub the factory."""+ from app.agents.services import embedding++ class _FakeEmbedder:+ def embed(self, texts):+ for _ in texts:+ yield [0.1, 0.2, 0.3, 0.4] # 4-dim — far below target 1536++ with patch.object(embedding, "_get_native_embedder", return_value=_FakeEmbedder()), \+ patch.object(embedding.get_agent_settings(), "embedding_provider", "native"):+ # The lru_cache on _get_native_embedder caches the FAKE for the+ # rest of this session — fine because it's a fresh fake each test.+ embedding._get_native_embedder.cache_clear()+ with patch.object(embedding, "_get_native_embedder", return_value=_FakeEmbedder()):+ vecs, label = await embedding.embed_texts(["hello", "world"])++ assert len(vecs) == 2+ assert label.startswith("native:")+ # Each vector dimension-adjusted to AGENTS_EMBEDDING_DIM (1536).+ for v in vecs:+ assert len(v) == 1536+ # First 4 dims are the fake values; the rest are zero-padded.+ assert v[:4] == [0.1, 0.2, 0.3, 0.4]+ assert all(x == 0.0 for x in v[4:])+++async def test_remote_dispatch_when_provider_is_not_native():+ """provider=ollama (or openai/openai_compatible) routes to the LLM+ provider abstraction's embed() method — not the native path."""+ from unittest.mock import AsyncMock+ from app.agents.services import embedding++ fake_provider = AsyncMock()+ fake_provider.embed = AsyncMock(return_value=[[1.0] * 768])++ with patch.object(embedding, "_build_remote_provider", return_value=fake_provider), \+ patch.object(embedding.get_agent_settings(), "embedding_provider", "ollama"):+ vecs, label = await embedding.embed_texts(["hi"])++ assert len(vecs) == 1+ assert len(vecs[0]) == 1536 # padded+ assert label.startswith("ollama:")+ fake_provider.embed.assert_awaited_once()+++async def test_empty_input_short_circuits():+ """No texts → no work, no provider import, no remote call."""+ from app.agents.services import embedding+ vecs, _ = await embedding.embed_texts([])+ assert vecs == []+++async def test_dimension_padding_preserves_signal():+ """Padding with zeros must not destroy the front of the vector — it+ just rounds out to the target dim. Cosine similarity is unaffected+ because zero dims contribute nothing to the dot product."""+ from app.agents.services.embedding import _adjust_dim+ assert _adjust_dim([0.5, -0.3], 4) == [0.5, -0.3, 0.0, 0.0]+ assert _adjust_dim([0.1] * 1600, 1536) == [0.1] * 1536 # truncated+ assert _adjust_dim([1.0, 2.0, 3.0], 3) == [1.0, 2.0, 3.0]diff --git a/backend/tests/test_agents_executor.py b/backend/tests/test_agents_executor.pynew file mode 100644index 00000000..b3b16965--- /dev/null+++ b/backend/tests/test_agents_executor.py@@ -0,0 +1,533 @@+"""End-to-end-style executor tests with a scripted LLM and a fake MCP.++These exercise the full agent runtime — turn loop, tool dispatch, message+persistence, usage logging, error classification — without ever hitting a+real LLM or MCP server.++Pattern:+ - `_ScriptedProvider` yields a predetermined sequence of ChatChunks.+ - `_FakeMCP` exposes one synthetic tool and records calls.+ - We patch `_provider_for` and pass our fake MCP into AgentExecutor.+"""+import uuid+from typing import AsyncIterator+from unittest.mock import patch++import pytest+from sqlalchemy import select++from app.agents.mcp.client import MCPRegistry, ToolHandle+from app.agents.models.agent import Agent+from app.agents.models.conversation import Conversation, Message+from app.agents.models.usage import LlmUsage+from app.agents.providers.base import (+ ChatChunk,+ LLMAuthError,+ LLMProvider,+ Usage,+)+from app.agents.runtime.executor import AgentExecutor, ExecutorEvent+++pytestmark = pytest.mark.asyncio+++# --- Fakes -----------------------------------------------------------------+++class _ScriptedProvider(LLMProvider):+ """Yields chunks from a list of "turns". Each turn is a list of chunks+ that simulate one model round. The provider iterates turns across+ successive chat_stream() calls."""++ name = "openai" # match cost-table key for usage tests++ def __init__(self, turns: list[list[ChatChunk]]):+ super().__init__(api_key="x")+ self._turns = list(turns)++ async def chat_stream( # type: ignore[override]+ self, messages, *, model, tools=None, temperature=0.4, max_tokens=None+ ) -> AsyncIterator[ChatChunk]:+ if not self._turns:+ # No more scripted turns — emit a generic finish.+ yield ChatChunk(type="finish", finish_reason="stop")+ return+ turn = self._turns.pop(0)+ for c in turn:+ yield c++ async def embed(self, texts, *, model):+ return [[0.0] * 4 for _ in texts]+++class _FakeMCP(MCPRegistry):+ """In-process MCPRegistry that doesn't open any sockets. Discovers a+ single tool and records every call() invocation."""++ def __init__(self, *, tools: list[ToolHandle], canned_result: dict | None = None):+ # Skip parent __init__ so we don't try to construct real clients.+ self._tools = tools+ self._canned = canned_result or {"ok": True, "data": {"items": [{"hello": "world"}]}, "text": "ok"}+ self.calls: list[tuple[str, dict]] = []++ def server_names(self):+ return ["securo"]++ async def discover(self, *, user_id, conversation_id=None, agent_id=None):+ return list(self._tools)++ async def call(self, *, wire_name, arguments, user_id, conversation_id=None, agent_id=None):+ self.calls.append((wire_name, arguments))+ return self._canned+++# --- Helpers --------------------------------------------------------------+++def _patch_provider(p: LLMProvider):+ return patch("app.agents.runtime.executor._provider_for", return_value=p)+++async def _drain(executor: AgentExecutor, **kwargs) -> list[ExecutorEvent]:+ return [ev async for ev in executor.run(**kwargs)]+++# --- Tests ----------------------------------------------------------------+++async def test_simple_text_response_no_tools(session, test_user, test_agent: Agent, test_conversation: Conversation):+ """LLM returns a plain answer; no tool calls."""+ provider = _ScriptedProvider([[+ ChatChunk(type="text_delta", text="Hello "),+ ChatChunk(type="text_delta", text="world!"),+ ChatChunk(type="usage", usage=Usage(input_tokens=10, output_tokens=4)),+ ChatChunk(type="finish", finish_reason="stop"),+ ]])++ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ with _patch_provider(provider):+ events = await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )++ text_events = [e for e in events if e.type == "text_delta"]+ assert "".join(e.text or "" for e in text_events) == "Hello world!"+ assert events[-1].type == "done"+ assert events[-1].finish_reason == "stop"++ # Persisted: user msg + assistant msg.+ msgs = (await session.execute(+ select(Message).where(Message.conversation_id == test_conversation.id).order_by(Message.ordinal)+ )).scalars().all()+ roles = [m.role for m in msgs]+ assert roles == ["user", "assistant"]+ assert msgs[1].content == "Hello world!"+ assert msgs[1].input_tokens == 10+ assert msgs[1].output_tokens == 4+++async def test_usage_row_recorded(session, test_user, test_agent, test_conversation):+ provider = _ScriptedProvider([[+ ChatChunk(type="text_delta", text="ok"),+ ChatChunk(type="usage", usage=Usage(input_tokens=100, output_tokens=20)),+ ChatChunk(type="finish", finish_reason="stop"),+ ]])+ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ with _patch_provider(provider):+ await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )+ rows = (await session.execute(+ select(LlmUsage).where(LlmUsage.conversation_id == test_conversation.id)+ )).scalars().all()+ assert len(rows) == 1+ assert rows[0].input_tokens == 100+ assert rows[0].output_tokens == 20+ assert rows[0].provider == "openai"+ # gpt-4o-mini rates: (0.15, 0.60) per 1M.+ assert rows[0].cost_usd is not None+ assert float(rows[0].cost_usd) > 0+++async def test_tool_call_dispatch_and_result_persisted(session, test_user, test_agent, test_conversation):+ """LLM emits a tool call; executor runs it via fake MCP and feeds the+ result back; second turn returns a plain answer."""+ tools = [ToolHandle(server="securo", name="list_accounts", description="d", parameters={"type": "object"})]+ fake_mcp = _FakeMCP(tools=tools, canned_result={+ "ok": True, "data": {"items": [{"id": "a1", "name": "Checking"}]}, "text": "1 account",+ })++ provider = _ScriptedProvider([+ # Turn 1: emit a tool call.+ [+ ChatChunk(type="tool_call_start", tool_call_id="t1", tool_name="securo__list_accounts"),+ ChatChunk(type="tool_call_args_delta", tool_call_id="t1", args_delta="{}"),+ ChatChunk(type="tool_call_end", tool_call_id="t1"),+ ChatChunk(type="usage", usage=Usage(input_tokens=20, output_tokens=5)),+ ChatChunk(type="finish", finish_reason="tool_calls"),+ ],+ # Turn 2: respond with the result.+ [+ ChatChunk(type="text_delta", text="You have 1 account."),+ ChatChunk(type="usage", usage=Usage(input_tokens=30, output_tokens=8)),+ ChatChunk(type="finish", finish_reason="stop"),+ ],+ ])++ executor = AgentExecutor(mcp=fake_mcp)+ with _patch_provider(provider):+ events = await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="how many accounts?",+ )++ # Event stream: tool_call → tool_result → text_delta → done.+ types = [e.type for e in events]+ assert "tool_call" in types+ assert "tool_result" in types+ assert types[-1] == "done"++ # MCP got called with the right wire name.+ assert fake_mcp.calls == [("securo__list_accounts", {})]++ # DB state: user, assistant(turn1, with tool_calls), tool, assistant(turn2, with text).+ msgs = (await session.execute(+ select(Message).where(Message.conversation_id == test_conversation.id).order_by(Message.ordinal)+ )).scalars().all()+ roles = [m.role for m in msgs]+ assert roles == ["user", "assistant", "tool", "assistant"]+ assert msgs[1].tool_calls and msgs[1].tool_calls[0]["name"] == "securo__list_accounts"+ assert msgs[3].content == "You have 1 account."++ # Two usage rows, one per provider call.+ usage_rows = (await session.execute(+ select(LlmUsage).where(LlmUsage.conversation_id == test_conversation.id)+ )).scalars().all()+ assert len(usage_rows) == 2+++async def test_provider_auth_error_surfaced_as_friendly_message(+ session, test_user, test_agent, test_conversation+):+ """An LLMAuthError becomes an error event with code=auth, not a 500."""++ class _BoomProvider(LLMProvider):+ name = "openai"++ async def chat_stream(self, *args, **kwargs): # type: ignore[override]+ raise LLMAuthError("missing key")+ yield # unreachable, makes this a generator++ async def embed(self, texts, *, model):+ return []++ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ with _patch_provider(_BoomProvider()):+ events = await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )++ err = next((e for e in events if e.type == "error"), None)+ assert err is not None+ assert err.error_code == "auth"+ done = next((e for e in events if e.type == "done"), None)+ assert done is not None and done.finish_reason == "error"+++async def test_no_model_configured_yields_config_error(session, test_user, test_conversation):+ """An agent without model and without AGENTS_DEFAULT_MODEL should bail+ early with a config error rather than calling the provider."""+ bare_agent = Agent(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Bare",+ provider="openai",+ model=None, # the missing piece+ )+ session.add(bare_agent)+ await session.commit()++ # Reuse the existing conversation but switch its agent to the bare one.+ test_conversation.agent_id = bare_agent.id+ await session.commit()++ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ # Provider doesn't matter here — should never be called.+ provider = _ScriptedProvider([])+ with _patch_provider(provider), patch.dict("os.environ", {"AGENTS_DEFAULT_MODEL": ""}, clear=False):+ events = await _drain(+ executor,+ session=session,+ agent=bare_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )+ err = next((e for e in events if e.type == "error"), None)+ assert err is not None and err.error_code == "config"+++async def test_per_agent_tool_whitelist_filters_discovery(+ session, test_user, test_agent, test_conversation+):+ """If the agent has explicit tool whitelist rows, the executor only+ sends the enabled ones to the LLM."""+ from app.agents.services import agent_service++ # Discover 2 tools, but only enable one.+ tools = [+ ToolHandle(server="securo", name="list_accounts", description="", parameters={"type": "object"}),+ ToolHandle(server="securo", name="list_categories", description="", parameters={"type": "object"}),+ ]+ fake_mcp = _FakeMCP(tools=tools)+ await agent_service.replace_tool_enablement(+ session, test_agent.id,+ [("securo", "list_accounts", True), ("securo", "list_categories", False)],+ )++ captured_tool_names: list[str] = []++ class _Capture(_ScriptedProvider):+ async def chat_stream(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ captured_tool_names.extend([t.name for t in (tools or [])])+ async for c in super().chat_stream(messages, model=model, tools=tools, temperature=temperature, max_tokens=max_tokens):+ yield c++ provider = _Capture([[+ ChatChunk(type="text_delta", text="ok"),+ ChatChunk(type="finish", finish_reason="stop"),+ ]])++ executor = AgentExecutor(mcp=fake_mcp)+ with _patch_provider(provider):+ await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )++ assert captured_tool_names == ["securo__list_accounts"]+++async def test_tool_result_passed_to_llm_in_full(session, test_user, test_agent, test_conversation):+ """Regression: the executor used to truncate the tool result text to+ 1500 chars before feeding it back to the model, causing the LLM to+ report "truncated" rows for any list response over a few items.+ The LLM must see the full structured payload."""+ big_items = [{"id": f"id-{i}", "description": f"Transaction number {i}", "amount": i * 10} for i in range(20)]+ fake_mcp = _FakeMCP(+ tools=[ToolHandle(server="securo", name="list_transactions", description="d", parameters={"type": "object"})],+ canned_result={+ "ok": True,+ "data": {"items": big_items, "total": 20},+ "text": "long unused text",+ },+ )++ captured_tool_messages: list[str] = []++ class _Capture(_ScriptedProvider):+ async def chat_stream(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ captured_tool_messages.extend([m.content for m in messages if m.role == "tool"])+ async for c in super().chat_stream(messages, model=model, tools=tools, temperature=temperature, max_tokens=max_tokens):+ yield c++ provider = _Capture([+ # Turn 1: emit a tool call.+ [+ ChatChunk(type="tool_call_start", tool_call_id="t1", tool_name="securo__list_transactions"),+ ChatChunk(type="tool_call_args_delta", tool_call_id="t1", args_delta="{}"),+ ChatChunk(type="tool_call_end", tool_call_id="t1"),+ ChatChunk(type="finish", finish_reason="tool_calls"),+ ],+ # Turn 2: text reply.+ [+ ChatChunk(type="text_delta", text="ok"),+ ChatChunk(type="finish", finish_reason="stop"),+ ],+ ])++ executor = AgentExecutor(mcp=fake_mcp)+ with _patch_provider(provider):+ await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="list me everything",+ )++ assert captured_tool_messages, "executor should have fed a tool message into turn 2"+ last = captured_tool_messages[-1]+ # Every item must appear in the LLM-facing content — no silent truncation.+ for i in range(20):+ assert f"Transaction number {i}" in last, (+ f"item {i} missing from tool message of length {len(last)} — likely truncation regression"+ )+++async def test_auto_context_primer_prepended_when_enabled(session, test_user, test_agent, test_conversation, test_account):+ """Captures the system messages the provider sees and verifies the+ primer is the first one when auto_context=True (default), with the+ agent's own system_prompt right after."""+ captured: dict[str, list] = {"system": []}++ class _Capture(_ScriptedProvider):+ async def chat_stream(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ captured["system"] = [m.content for m in messages if m.role == "system"]+ async for c in super().chat_stream(messages, model=model, tools=tools, temperature=temperature, max_tokens=max_tokens):+ yield c++ provider = _Capture([[+ ChatChunk(type="text_delta", text="ok"),+ ChatChunk(type="finish", finish_reason="stop"),+ ]])+ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ test_agent.auto_context = True+ test_agent.system_prompt = "You are helpful."+ await session.commit()++ with _patch_provider(provider):+ await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )+ sys_msgs = captured["system"]+ # Stack: guardrail [0] + identity primer [1] + agent system_prompt [2] + auto-context [3].+ assert len(sys_msgs) == 4, f"expected guardrail + identity + agent prompt + auto-context, got {len(sys_msgs)}"+ assert "Runtime rules" in sys_msgs[0]+ assert "propose_" in sys_msgs[0]+ assert "Securo" in sys_msgs[1] # identity primer mentions the product+ assert sys_msgs[2] == "You are helpful."+ assert "Context for this conversation" in sys_msgs[3]+ assert "[email protected]" in sys_msgs[3] # uses test_user fixture's email+ assert "Conta Corrente" in sys_msgs[3] # account name from fixture+++async def test_auto_context_primer_skipped_when_disabled(session, test_user, test_agent, test_conversation):+ captured: dict[str, list] = {"system": []}++ class _Capture(_ScriptedProvider):+ async def chat_stream(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ captured["system"] = [m.content for m in messages if m.role == "system"]+ async for c in super().chat_stream(messages, model=model, tools=tools, temperature=temperature, max_tokens=max_tokens):+ yield c++ provider = _Capture([[+ ChatChunk(type="text_delta", text="ok"),+ ChatChunk(type="finish", finish_reason="stop"),+ ]])+ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ test_agent.auto_context = False+ test_agent.system_prompt = "Just the agent prompt."+ await session.commit()++ with _patch_provider(provider):+ await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="hi",+ )+ sys_msgs = captured["system"]+ # Guardrail [0] + identity [1] + agent prompt [2]; no auto-context primer.+ assert len(sys_msgs) == 3+ assert "Runtime rules" in sys_msgs[0]+ assert "Securo" in sys_msgs[1]+ assert sys_msgs[2] == "Just the agent prompt."+++async def test_runtime_guardrail_always_present_even_with_no_agent_prompt(session, test_user, test_agent, test_conversation):+ """Even when the user gave their agent no system_prompt and disabled+ auto_context, the runtime guardrail must still be there."""+ captured: dict[str, list] = {"system": []}++ class _Capture(_ScriptedProvider):+ async def chat_stream(self, messages, *, model, tools=None, temperature=0.4, max_tokens=None):+ captured["system"] = [m.content for m in messages if m.role == "system"]+ async for c in super().chat_stream(messages, model=model, tools=tools, temperature=temperature, max_tokens=max_tokens):+ yield c++ provider = _Capture([[ChatChunk(type="text_delta", text="ok"), ChatChunk(type="finish", finish_reason="stop")]])+ executor = AgentExecutor(mcp=_FakeMCP(tools=[]))+ test_agent.auto_context = False+ test_agent.system_prompt = ""+ await session.commit()++ with _patch_provider(provider):+ await _drain(+ executor, session=session, agent=test_agent,+ user_id=test_user.id, conversation_id=test_conversation.id,+ user_message="hi",+ )+ sys_msgs = captured["system"]+ # Guardrail [0] + identity primer [1] are the irreducible minimum —+ # both are always present even when the user gave no system_prompt+ # and turned auto-context off.+ assert len(sys_msgs) == 2+ assert "Runtime rules" in sys_msgs[0]+ assert "propose_" in sys_msgs[0]+ assert "Securo" in sys_msgs[1]+++async def test_max_iterations_terminates_runaway_agent(session, test_user, test_agent, test_conversation):+ """If the LLM keeps emitting tool calls forever, executor stops at+ MAX_ITERS and emits a max_iterations error."""+ tools = [ToolHandle(server="securo", name="loop_tool", description="", parameters={"type": "object"})]+ fake_mcp = _FakeMCP(tools=tools)++ # Same tool-call turn repeated indefinitely.+ def _looping_turn():+ return [+ ChatChunk(type="tool_call_start", tool_call_id=f"t{uuid.uuid4().hex[:6]}", tool_name="securo__loop_tool"),+ ChatChunk(type="tool_call_args_delta", tool_call_id="t1", args_delta="{}"),+ ChatChunk(type="tool_call_end", tool_call_id="t1"),+ ChatChunk(type="finish", finish_reason="tool_calls"),+ ]++ provider = _ScriptedProvider([_looping_turn() for _ in range(20)])+ executor = AgentExecutor(mcp=fake_mcp)+ with _patch_provider(provider):+ events = await _drain(+ executor,+ session=session,+ agent=test_agent,+ user_id=test_user.id,+ conversation_id=test_conversation.id,+ user_message="loop forever",+ )++ err = next((e for e in events if e.type == "error"), None)+ done = next((e for e in events if e.type == "done"), None)+ assert err is not None and err.error_code == "max_iterations"+ assert done is not None and done.finish_reason == "max_iterations"diff --git a/backend/tests/test_agents_ingest.py b/backend/tests/test_agents_ingest.pynew file mode 100644index 00000000..e2be9572--- /dev/null+++ b/backend/tests/test_agents_ingest.py@@ -0,0 +1,161 @@+"""Cover app/agents/tasks/ingest._do_ingest, bypassing the Celery layer.++We drive the async helper directly with our SQLite test session_maker+plus a monkeypatched embed_texts (so we don't pull ONNX / fastembed+into the test env). The KnowledgeChunk.embedding column is shimmed to+JSON in conftest, so writing a Python list works on SQLite.+"""+from __future__ import annotations++import tempfile+import uuid++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker++from app.agents.services import knowledge_service+from app.agents.tasks.ingest import _do_ingest++[email protected](autouse=True)+def _storage_in_tmpdir(monkeypatch):+ """Redirect AGENTS_KNOWLEDGE_STORAGE_PATH to a per-test tmpdir. The+ default `/app/data/agent_knowledge` is not writable in CI."""+ tmp = tempfile.mkdtemp(prefix="kb-ingest-")+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "knowledge_storage_path", tmp)+ yield tmp+++def _session_maker_from(session):+ """Build a session_maker that points at the same SQLite engine the+ test session already uses. _do_ingest opens its own session inside,+ which is exactly the contract we want to test."""+ return async_sessionmaker(session.bind, expire_on_commit=False)+++async def test_do_ingest_happy_path_writes_chunks_and_marks_ready(+ session, test_agent, test_user, monkeypatch+):+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="ok.txt",+ mime="text/plain",+ payload=b"one two three four",+ )++ monkeypatch.setattr(+ "app.agents.services.chunking.chunks_from_upload",+ lambda payload, mime, title: ["chunk-a", "chunk-b"],+ )++ async def fake_embed(chunks):+ # 1536-dim vector full of zeros — matches embedding_dim, harmless on SQLite.+ return [[0.0] * 1536 for _ in chunks], "fake-model"++ monkeypatch.setattr("app.agents.services.embedding.embed_texts", fake_embed)++ result = await _do_ingest(_session_maker_from(session), doc.id, test_agent.id)++ assert result == {"ok": True, "chunks": 2}+ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ # The session_maker inside _do_ingest commits — we need a fresh read.+ await session.refresh(refreshed)+ assert refreshed.status == "ready"+ assert refreshed.chunk_count == 2+ assert refreshed.error is None+++async def test_do_ingest_missing_doc_returns_reason(session, test_agent):+ """A doc_id that doesn't exist should short-circuit, not crash."""+ result = await _do_ingest(_session_maker_from(session), uuid.uuid4(), test_agent.id)+ assert result == {"ok": False, "reason": "doc missing"}+++async def test_do_ingest_marks_failed_when_storage_unreadable(+ session, test_agent, test_user, monkeypatch+):+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="x.txt",+ mime="text/plain",+ payload=b"x",+ )+ # Point storage_path at a non-existent file — Path.read_bytes raises.+ doc.storage_path = "/tmp/this-file-really-shouldnt-exist-12345.bin"+ await session.commit()++ result = await _do_ingest(_session_maker_from(session), doc.id, test_agent.id)+ assert result == {"ok": False, "reason": "read failed"}++ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ await session.refresh(refreshed)+ assert refreshed.status == "failed"+ assert "read failed" in (refreshed.error or "")+++async def test_do_ingest_marks_failed_when_no_extractable_text(+ session, test_agent, test_user, monkeypatch+):+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="empty.txt",+ mime="text/plain",+ payload=b"",+ )+ monkeypatch.setattr(+ "app.agents.services.chunking.chunks_from_upload",+ lambda payload, mime, title: [],+ )++ result = await _do_ingest(_session_maker_from(session), doc.id, test_agent.id)+ assert result == {"ok": False, "reason": "no text"}++ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ await session.refresh(refreshed)+ assert refreshed.status == "failed"+ assert "no extractable text" in (refreshed.error or "")+ assert refreshed.chunk_count == 0+++async def test_do_ingest_marks_failed_when_embedding_fails(+ session, test_agent, test_user, monkeypatch+):+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="boom.txt",+ mime="text/plain",+ payload=b"some text",+ )+ monkeypatch.setattr(+ "app.agents.services.chunking.chunks_from_upload",+ lambda payload, mime, title: ["a chunk"],+ )++ async def boom(chunks):+ raise RuntimeError("provider 503")++ monkeypatch.setattr("app.agents.services.embedding.embed_texts", boom)++ result = await _do_ingest(_session_maker_from(session), doc.id, test_agent.id)+ assert result == {"ok": False, "reason": "embed failed"}++ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ await session.refresh(refreshed)+ assert refreshed.status == "failed"+ assert "embed failed" in (refreshed.error or "")+ assert "provider 503" in (refreshed.error or "")diff --git a/backend/tests/test_agents_jwt.py b/backend/tests/test_agents_jwt.pynew file mode 100644index 00000000..1b70e9f0--- /dev/null+++ b/backend/tests/test_agents_jwt.py@@ -0,0 +1,125 @@+"""JWT mint/verify roundtrip between the backend and the MCP server.++Both sides share AGENTS_MCP_JWT_SECRET. We test that:+ - A token minted by the backend verifies cleanly on the MCP side.+ - Tokens with the wrong secret are rejected.+ - Expired tokens are rejected.+ - Missing audience / issuer is rejected.+"""+import time+import uuid++import pytest+from jose import jwt++from app.agents.config import get_agent_settings+from app.agents.mcp.auth import JWT_ALGO, JWT_AUDIENCE, JWT_ISSUER, mint_token+++def test_mint_then_verify_roundtrip():+ from mcp_server.auth import verify_request++ user_id = uuid.uuid4()+ conv_id = uuid.uuid4()+ agent_id = uuid.uuid4()+ token = mint_token(user_id=user_id, conversation_id=conv_id, agent_id=agent_id)++ # Stub Request just enough for verify_request — it only reads the header.+ class _Req:+ headers = {"authorization": f"Bearer {token}"}++ ctx = verify_request(_Req()) # type: ignore[arg-type]+ assert ctx.user_id == user_id+ assert ctx.conversation_id == conv_id+ assert ctx.agent_id == agent_id+++def test_missing_authorization_rejected():+ from fastapi import HTTPException+ from mcp_server.auth import verify_request++ class _Req:+ headers: dict[str, str] = {}++ with pytest.raises(HTTPException) as exc:+ verify_request(_Req()) # type: ignore[arg-type]+ assert exc.value.status_code == 401+++def test_wrong_secret_rejected():+ from fastapi import HTTPException+ from mcp_server.auth import verify_request++ user_id = uuid.uuid4()+ bogus = jwt.encode(+ {+ "sub": str(user_id),+ "iss": JWT_ISSUER,+ "aud": JWT_AUDIENCE,+ "iat": int(time.time()),+ "exp": int(time.time()) + 60,+ },+ "totally-different-secret",+ algorithm=JWT_ALGO,+ )++ class _Req:+ headers = {"authorization": f"Bearer {bogus}"}++ with pytest.raises(HTTPException) as exc:+ verify_request(_Req()) # type: ignore[arg-type]+ assert exc.value.status_code == 401+++def test_expired_token_rejected():+ from fastapi import HTTPException+ from mcp_server.auth import verify_request++ s = get_agent_settings()+ user_id = uuid.uuid4()+ expired = jwt.encode(+ {+ "sub": str(user_id),+ "iss": JWT_ISSUER,+ "aud": JWT_AUDIENCE,+ "iat": int(time.time()) - 7200,+ "exp": int(time.time()) - 3600,+ },+ s.mcp_jwt_secret,+ algorithm=JWT_ALGO,+ )++ class _Req:+ headers = {"authorization": f"Bearer {expired}"}++ with pytest.raises(HTTPException) as exc:+ verify_request(_Req()) # type: ignore[arg-type]+ assert exc.value.status_code == 401+++def test_short_ttl_respected():+ """Mint with ttl_seconds=1, sleep 2, verify rejection."""+ from fastapi import HTTPException+ from mcp_server.auth import verify_request++ token = mint_token(user_id=uuid.uuid4(), ttl_seconds=1)+ time.sleep(2.1)++ class _Req:+ headers = {"authorization": f"Bearer {token}"}++ with pytest.raises(HTTPException):+ verify_request(_Req()) # type: ignore[arg-type]+++def test_optional_conv_id_is_truly_optional():+ from mcp_server.auth import verify_request++ token = mint_token(user_id=uuid.uuid4())++ class _Req:+ headers = {"authorization": f"Bearer {token}"}++ ctx = verify_request(_Req()) # type: ignore[arg-type]+ assert ctx.conversation_id is None+ assert ctx.agent_id is Nonediff --git a/backend/tests/test_agents_knowledge_api.py b/backend/tests/test_agents_knowledge_api.pynew file mode 100644index 00000000..88f768dd--- /dev/null+++ b/backend/tests/test_agents_knowledge_api.py@@ -0,0 +1,169 @@+"""HTTP-level coverage for /api/agents/{id}/knowledge.++Goes through the FastAPI router with the conftest `client` and+`auth_headers` fixtures so we exercise auth + route + service in one+trip. Celery dispatch is mocked because we don't run a worker in tests.+"""+from __future__ import annotations++import io+import tempfile+import uuid+from unittest.mock import patch++import pytest++[email protected](autouse=True)+def _storage_in_tmpdir(monkeypatch):+ tmp = tempfile.mkdtemp(prefix="kb-api-")+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "knowledge_storage_path", tmp)+ yield tmp++[email protected](autouse=True)+def _stub_celery_dispatch():+ """Knowledge upload does send_task → we don't want it to actually+ enqueue anything during tests. Returning a sentinel keeps the upload+ happy."""+ with patch("app.worker.celery_app.send_task", return_value=None) as m:+ yield m+++async def _make_agent(client, auth_headers, name="KB Agent") -> str:+ r = await client.post("/api/agents", json={"name": name}, headers=auth_headers)+ assert r.status_code == 201, r.text+ return r.json()["id"]+++async def test_list_knowledge_404_for_unknown_agent(client, auth_headers, test_user):+ r = await client.get(f"/api/agents/{uuid.uuid4()}/knowledge", headers=auth_headers)+ assert r.status_code == 404+++async def test_list_knowledge_returns_empty_for_new_agent(client, auth_headers, test_user):+ aid = await _make_agent(client, auth_headers)+ r = await client.get(f"/api/agents/{aid}/knowledge", headers=auth_headers)+ assert r.status_code == 200+ assert r.json() == {"items": [], "total": 0}+++async def test_upload_knowledge_persists_doc_and_dispatches_celery(+ client, auth_headers, test_user, _stub_celery_dispatch+):+ aid = await _make_agent(client, auth_headers)+ files = {"file": ("notes.md", io.BytesIO(b"# Title\nbody"), "text/markdown")}+ r = await client.post(+ f"/api/agents/{aid}/knowledge",+ files=files,+ data={"pinned": "false"},+ headers=auth_headers,+ )+ assert r.status_code == 201, r.text+ body = r.json()+ assert body["title"] == "notes.md"+ assert body["mime"] == "text/markdown"+ assert body["status"] == "pending"+ assert body["pinned"] is False+ assert body["size_bytes"] == len(b"# Title\nbody")+ # Celery was asked to schedule the ingest task once.+ _stub_celery_dispatch.assert_called_once()+ args, _ = _stub_celery_dispatch.call_args+ assert args[0] == "app.agents.tasks.ingest.ingest_doc"++ # And it shows up in list_knowledge.+ r = await client.get(f"/api/agents/{aid}/knowledge", headers=auth_headers)+ assert r.json()["total"] == 1+++async def test_upload_knowledge_404_for_unknown_agent(client, auth_headers, test_user):+ r = await client.post(+ f"/api/agents/{uuid.uuid4()}/knowledge",+ files={"file": ("x.txt", io.BytesIO(b"x"), "text/plain")},+ headers=auth_headers,+ )+ assert r.status_code == 404+++async def test_upload_knowledge_returns_413_when_too_large(+ client, auth_headers, test_user, monkeypatch+):+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "knowledge_max_file_size_mb", 1)+ aid = await _make_agent(client, auth_headers)+ big = b"x" * (1024 * 1024 + 1)+ r = await client.post(+ f"/api/agents/{aid}/knowledge",+ files={"file": ("big.bin", io.BytesIO(big), "application/octet-stream")},+ headers=auth_headers,+ )+ assert r.status_code == 413+ assert "exceeds" in r.json()["detail"]+++async def test_toggle_pin_flips_flag(client, auth_headers, test_user):+ aid = await _make_agent(client, auth_headers)+ r = await client.post(+ f"/api/agents/{aid}/knowledge",+ files={"file": ("p.txt", io.BytesIO(b"p"), "text/plain")},+ headers=auth_headers,+ )+ doc_id = r.json()["id"]++ # Pin+ r = await client.patch(+ f"/api/agents/{aid}/knowledge/{doc_id}/pin?pinned=true", headers=auth_headers+ )+ assert r.status_code == 200+ assert r.json()["pinned"] is True++ # Unpin+ r = await client.patch(+ f"/api/agents/{aid}/knowledge/{doc_id}/pin?pinned=false", headers=auth_headers+ )+ assert r.status_code == 200+ assert r.json()["pinned"] is False+++async def test_toggle_pin_404_for_unknown_doc(client, auth_headers, test_user):+ aid = await _make_agent(client, auth_headers)+ r = await client.patch(+ f"/api/agents/{aid}/knowledge/{uuid.uuid4()}/pin?pinned=true", headers=auth_headers+ )+ assert r.status_code == 404+++async def test_delete_knowledge_removes_doc(client, auth_headers, test_user):+ aid = await _make_agent(client, auth_headers)+ r = await client.post(+ f"/api/agents/{aid}/knowledge",+ files={"file": ("d.txt", io.BytesIO(b"d"), "text/plain")},+ headers=auth_headers,+ )+ doc_id = r.json()["id"]++ r = await client.delete(f"/api/agents/{aid}/knowledge/{doc_id}", headers=auth_headers)+ assert r.status_code == 204++ docs = (await client.get(f"/api/agents/{aid}/knowledge", headers=auth_headers)).json()+ assert docs["total"] == 0+++async def test_delete_knowledge_404_for_unknown_doc(client, auth_headers, test_user):+ aid = await _make_agent(client, auth_headers)+ r = await client.delete(+ f"/api/agents/{aid}/knowledge/{uuid.uuid4()}", headers=auth_headers+ )+ assert r.status_code == 404diff --git a/backend/tests/test_agents_knowledge_service.py b/backend/tests/test_agents_knowledge_service.pynew file mode 100644index 00000000..f7963a17--- /dev/null+++ b/backend/tests/test_agents_knowledge_service.py@@ -0,0 +1,222 @@+"""Cover the doc-metadata paths of app/agents/services/knowledge_service.++Skipping similarity_search / replace_chunks / list_pinned_chunks: those+hit a pgvector column type that doesn't exist on SQLite. The rest of the+file (upload, list, get, delete, set_pinned, mark_status, hash_payload,+file_size_limit_mb) is platform-agnostic.+"""+from __future__ import annotations++import os+import tempfile+import uuid++import pytest++from app.agents.services import knowledge_service++[email protected](autouse=True)+def _storage_in_tmpdir(monkeypatch):+ """Redirect AGENTS_KNOWLEDGE_STORAGE_PATH to a per-test tmpdir so+ uploads don't leak into other tests or pollute /app/data."""+ tmp = tempfile.mkdtemp(prefix="kb-test-")+ from app.agents.config import get_agent_settings++ # Settings is @lru_cache'd — monkeypatch the attribute on the+ # cached instance.+ s = get_agent_settings()+ monkeypatch.setattr(s, "knowledge_storage_path", tmp)+ yield tmp+++async def test_upload_doc_writes_file_and_persists_metadata(session, test_agent, test_user):+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="note.md",+ mime="text/markdown",+ payload=b"# Hello",+ )+ assert doc.id is not None+ assert doc.status == "pending"+ assert doc.size_bytes == len(b"# Hello")+ assert doc.storage_path+ # The file is actually on disk.+ assert os.path.exists(doc.storage_path)+ with open(doc.storage_path, "rb") as fh:+ assert fh.read() == b"# Hello"+++async def test_upload_doc_rejects_oversized_payload(session, test_agent, test_user, monkeypatch):+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "knowledge_max_file_size_mb", 1)+ too_big = b"x" * (1024 * 1024 + 1)+ with pytest.raises(ValueError, match="exceeds"):+ await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="big.bin",+ mime="application/octet-stream",+ payload=too_big,+ )+++async def test_upload_doc_sanitizes_disk_filename(session, test_agent, test_user):+ # Slashes / ../ would normally let an attacker escape the storage+ # root. _disk_path replaces them with underscores and clips to 80+ # chars. We verify by checking the resulting file lives directly in+ # storage_path's basename without any path traversal.+ doc = await knowledge_service.upload_doc(+ session,+ agent_id=test_agent.id,+ user_id=test_user.id,+ filename="../etc/passwd",+ mime="text/plain",+ payload=b"x",+ )+ assert "../" not in doc.storage_path.split("/", 5)[-1] # no traversal in stored basename+ assert os.path.dirname(doc.storage_path) == os.path.abspath(os.path.dirname(doc.storage_path))+++async def test_list_docs_returns_all_docs_for_agent(session, test_agent, test_user):+ a = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="a.txt", mime="text/plain", payload=b"a",+ )+ b = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="b.txt", mime="text/plain", payload=b"b",+ )+ rows = await knowledge_service.list_docs(session, test_agent.id)+ # Ordering is `created_at DESC` in code, but on fast-running test envs+ # the two uploads can share a timestamp, so we just assert membership.+ assert {a.id, b.id} <= {d.id for d in rows}+++async def test_get_doc_scopes_by_user(session, test_agent, test_user):+ doc = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="x.txt", mime="text/plain", payload=b"x",+ )+ # Wrong user → None.+ other = uuid.uuid4()+ assert await knowledge_service.get_doc(session, doc.id, other) is None+ # Right user → returns the row.+ found = await knowledge_service.get_doc(session, doc.id, test_user.id)+ assert found is not None+ assert found.id == doc.id+++async def test_delete_doc_returns_false_when_missing(session, test_user):+ assert await knowledge_service.delete_doc(session, uuid.uuid4(), test_user.id) is False+++async def test_delete_doc_removes_row_and_file(session, test_agent, test_user):+ doc = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="delete-me.txt", mime="text/plain", payload=b"hi",+ )+ path = doc.storage_path+ assert os.path.exists(path)+ ok = await knowledge_service.delete_doc(session, doc.id, test_user.id)+ assert ok is True+ assert not os.path.exists(path)+ assert await knowledge_service.get_doc(session, doc.id, test_user.id) is None+++async def test_delete_doc_swallows_missing_file_on_disk(session, test_agent, test_user):+ """If someone removes the file under us, the DB row should still+ delete cleanly."""+ doc = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="ghost.txt", mime="text/plain", payload=b"x",+ )+ os.remove(doc.storage_path)+ assert await knowledge_service.delete_doc(session, doc.id, test_user.id) is True+++async def test_set_pinned_toggles_flag(session, test_agent, test_user):+ doc = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="pin.txt", mime="text/plain", payload=b"x",+ )+ pinned = await knowledge_service.set_pinned(session, doc.id, test_user.id, True)+ assert pinned is not None+ assert pinned.pinned is True+ unpinned = await knowledge_service.set_pinned(session, doc.id, test_user.id, False)+ assert unpinned is not None+ assert unpinned.pinned is False+++async def test_set_pinned_returns_none_when_missing(session, test_user):+ out = await knowledge_service.set_pinned(session, uuid.uuid4(), test_user.id, True)+ assert out is None+++async def test_mark_status_ready_clears_prior_error(session, test_agent, test_user):+ doc = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="s.txt", mime="text/plain", payload=b"x",+ )+ # Initial failure → error message stored.+ await knowledge_service.mark_status(session, doc.id, status="failed", error="embed failed: 500")+ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ assert refreshed.status == "failed"+ assert "embed failed" in (refreshed.error or "")+ # Subsequent success → status flips AND prior error cleared.+ await knowledge_service.mark_status(session, doc.id, status="ready", chunk_count=4)+ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ assert refreshed.status == "ready"+ assert refreshed.error is None+ assert refreshed.chunk_count == 4+++async def test_mark_status_failed_preserves_prior_status_metadata(session, test_agent, test_user):+ doc = await knowledge_service.upload_doc(+ session, agent_id=test_agent.id, user_id=test_user.id,+ filename="fail.txt", mime="text/plain", payload=b"x",+ )+ await knowledge_service.mark_status(session, doc.id, status="processing")+ await knowledge_service.mark_status(session, doc.id, status="failed", error="parse failed")+ refreshed = await knowledge_service.get_doc(session, doc.id, test_user.id)+ assert refreshed.status == "failed"+ assert "parse failed" in (refreshed.error or "")+++async def test_mark_status_unknown_doc_is_silent_noop(session):+ # No exception even when the doc doesn't exist — used by the+ # Celery task to avoid crashing on a missing row.+ await knowledge_service.mark_status(session, uuid.uuid4(), status="failed", error="x")+++def test_hash_payload_is_stable_and_unique():+ a = knowledge_service.hash_payload(b"hello")+ b = knowledge_service.hash_payload(b"hello")+ c = knowledge_service.hash_payload(b"world")+ assert a == b+ assert a != c+ assert len(a) == 64 # SHA-256 hex digest length+++def test_file_size_limit_mb_returns_settings_value(monkeypatch):+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "knowledge_max_file_size_mb", 42)+ assert knowledge_service.file_size_limit_mb() == 42diff --git a/backend/tests/test_agents_mcp_client.py b/backend/tests/test_agents_mcp_client.pynew file mode 100644index 00000000..41ad80b9--- /dev/null+++ b/backend/tests/test_agents_mcp_client.py@@ -0,0 +1,328 @@+"""Cover app/agents/mcp/client.py — the JSON-RPC client used by the+agents runtime to talk to MCP servers.++Strategy: replace httpx.AsyncClient with a thin fake driven by a queue+of canned responses so each test can shape the wire protocol without+the test process opening real sockets.+"""+from __future__ import annotations++import uuid+from typing import Any++import pytest++import app.agents.mcp.client as mcp_client_module+from app.agents.mcp.client import (+ MCPClient,+ MCPRegistry,+ ToolHandle,+ _join_text,+ _parse_servers,+)+++# --------------------------------------------------------------------- helpers++class _FakeResponse:+ def __init__(self, *, status_code: int = 200, json_body: Any = None):+ self.status_code = status_code+ self._body = json_body or {}++ def raise_for_status(self) -> None:+ if self.status_code >= 400:+ # Discover swallows Exception, so the type doesn't matter here.+ raise RuntimeError(f"HTTP {self.status_code}")++ def json(self) -> Any:+ return self._body+++class _FakeAsyncClient:+ """Records calls, returns queued responses. Implements just enough+ of httpx.AsyncClient for MCPClient._post to be happy."""++ def __init__(self, *_, **__): # accept (timeout=...) kw+ pass++ queue: list[_FakeResponse] = []+ calls: list[tuple[str, dict, dict]] = []++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ async def post(self, url, *, json=None, headers=None): # noqa: A002+ type(self).calls.append((url, json, headers))+ if not type(self).queue:+ return _FakeResponse(status_code=200, json_body={"jsonrpc": "2.0", "id": 1, "result": {}})+ return type(self).queue.pop(0)++[email protected](autouse=True)+def _fake_httpx(monkeypatch):+ _FakeAsyncClient.queue = []+ _FakeAsyncClient.calls = []+ monkeypatch.setattr(mcp_client_module.httpx, "AsyncClient", _FakeAsyncClient)+ yield+++# --------------------------------------------------------------------- _join_text++def test_join_text_concatenates_text_parts():+ out = _join_text([{"type": "text", "text": "hi"}, {"type": "text", "text": "there"}])+ assert out == "hi\nthere"+++def test_join_text_ignores_non_text_and_non_list():+ assert _join_text(None) == ""+ assert _join_text("not a list") == ""+ assert _join_text([{"type": "image", "url": "x"}]) == ""+ # Mixed: only text parts survive.+ assert _join_text([{"type": "text", "text": "a"}, {"type": "image"}]) == "a"+++# --------------------------------------------------------------------- _parse_servers++def test_parse_servers_includes_builtin_only_by_default(monkeypatch):+ from app.agents.config import get_agent_settings++ s = get_agent_settings()+ monkeypatch.setattr(s, "extra_mcp_servers", "")+ out = _parse_servers()+ assert [sp.name for sp in out] == ["securo"]+++def test_parse_servers_handles_extra_with_and_without_alias(monkeypatch):+ from app.agents.config import get_agent_settings++ s = get_agent_settings()+ monkeypatch.setattr(s, "extra_mcp_servers", "http://a:9000/mcp|alpha, http://b:9001/mcp, , http://c:9002/mcp|gamma")+ out = _parse_servers()+ names = [sp.name for sp in out]+ urls = {sp.name: sp.url for sp in out}+ # securo + 3 extras (empty entry is skipped)+ assert names == ["securo", "alpha", "http://b:9001/mcp", "gamma"]+ assert urls["alpha"] == "http://a:9000/mcp"+ assert urls["gamma"] == "http://c:9002/mcp"+++# --------------------------------------------------------------------- MCPClient.list_tools++async def test_list_tools_parses_securo_extras_and_defaults_schema():+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "tools": [+ {+ "name": "list_accounts",+ "description": "List accounts",+ "inputSchema": {"type": "object", "properties": {}},+ },+ {+ "name": "create_payee",+ "description": "Create a payee",+ # no inputSchema — should default+ "_securo": {"is_proposal": True},+ },+ ]+ },+ }))++ client = MCPClient(name="securo", url="http://mcp.test/mcp")+ handles = await client.list_tools(token="fake")++ assert len(handles) == 2+ assert {h.name for h in handles} == {"list_accounts", "create_payee"}+ by_name = {h.name: h for h in handles}+ assert by_name["create_payee"].is_proposal is True+ assert by_name["create_payee"].parameters == {"type": "object", "properties": {}}+ # Bearer header is propagated.+ _, _, headers = _FakeAsyncClient.calls[0]+ assert headers["Authorization"] == "Bearer fake"+++async def test_list_tools_handles_missing_tools_array():+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0", "id": 1, "result": None,+ }))+ client = MCPClient(name="securo", url="http://mcp.test/mcp")+ assert await client.list_tools(token="fake") == []+++# --------------------------------------------------------------------- MCPClient._post error paths++async def test_post_raises_runtime_error_when_rpc_error_present():+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0",+ "id": 1,+ "error": {"code": -32601, "message": "method not found"},+ }))+ client = MCPClient(name="securo", url="http://mcp.test/mcp")+ with pytest.raises(RuntimeError, match="method not found"):+ await client.list_tools(token="fake")+++# --------------------------------------------------------------------- MCPClient.call_tool++async def test_call_tool_unpacks_structured_content_and_text():+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "isError": False,+ "structuredContent": {"items": [1, 2, 3]},+ "content": [{"type": "text", "text": "ok"}],+ },+ }))+ client = MCPClient(name="securo", url="http://mcp.test/mcp")+ out = await client.call_tool(name="list_accounts", arguments={}, token="fake")+ assert out == {"ok": True, "data": {"items": [1, 2, 3]}, "text": "ok"}+++async def test_call_tool_marks_error_when_is_error_true():+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "isError": True,+ "structuredContent": {"error": "bad input"},+ "content": [{"type": "text", "text": "bad input"}],+ },+ }))+ client = MCPClient(name="securo", url="http://mcp.test/mcp")+ out = await client.call_tool(name="x", arguments={}, token="fake")+ assert out["ok"] is False+ assert out["data"] == {"error": "bad input"}+++async def test_call_tool_falls_back_when_no_structured_content():+ """Servers that don't emit structuredContent still get a sensible+ response shape — `data` is the raw result, ok defaults from isError."""+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0",+ "id": 1,+ "result": {"content": [{"type": "text", "text": "raw"}], "isError": False},+ }))+ client = MCPClient(name="securo", url="http://mcp.test/mcp")+ out = await client.call_tool(name="x", arguments={}, token="fake")+ assert out["ok"] is True+ assert out["text"] == ""+ # data is the raw dict, no structuredContent unpacking.+ assert out["data"] == {"content": [{"type": "text", "text": "raw"}], "isError": False}+++# --------------------------------------------------------------------- MCPRegistry++def test_to_provider_tools_namespaces_and_filters():+ handles = [+ ToolHandle(server="securo", name="list_accounts", description="d1", parameters={"type": "object"}),+ ToolHandle(server="securo", name="create_payee", description="d2", parameters={}),+ ToolHandle(server="extra", name="list_accounts", description="d3", parameters={}),+ ]+ # No filter → all three.+ all_tools = MCPRegistry.to_provider_tools(handles, allowed=None)+ assert {t.name for t in all_tools} == {"securo__list_accounts", "securo__create_payee", "extra__list_accounts"}++ # Filter by (server, name) pair.+ filtered = MCPRegistry.to_provider_tools(handles, allowed={("securo", "list_accounts")})+ assert [t.name for t in filtered] == ["securo__list_accounts"]+ # Defaults a missing parameters schema to an empty object schema.+ handle_no_schema = ToolHandle(server="x", name="y", description="d", parameters=None) # type: ignore[arg-type]+ out = MCPRegistry.to_provider_tools([handle_no_schema], allowed=None)+ assert out[0].parameters == {"type": "object", "properties": {}}+++async def test_registry_discover_aggregates_across_servers(monkeypatch):+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "extra_mcp_servers", "http://extra:9000/mcp|extra")++ # Two list_tools responses — one per registered server.+ _FakeAsyncClient.queue.extend([+ _FakeResponse(json_body={"jsonrpc": "2.0", "id": 1, "result": {"tools": [+ {"name": "a", "description": "", "inputSchema": {}}]}}),+ _FakeResponse(json_body={"jsonrpc": "2.0", "id": 1, "result": {"tools": [+ {"name": "b", "description": "", "inputSchema": {}}]}}),+ ])++ reg = MCPRegistry()+ handles = await reg.discover(user_id=uuid.uuid4())+ names = {(h.server, h.name) for h in handles}+ assert ("securo", "a") in names+ assert ("extra", "b") in names+++async def test_registry_discover_swallows_per_server_errors(monkeypatch):+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "extra_mcp_servers", "http://down:9000/mcp|down")++ # First server returns tools, second errors out — discover should+ # surface only the successful one.+ _FakeAsyncClient.queue.extend([+ _FakeResponse(json_body={"jsonrpc": "2.0", "id": 1, "result": {"tools": [+ {"name": "a", "description": "", "inputSchema": {}}]}}),+ _FakeResponse(status_code=500, json_body={}),+ ])++ reg = MCPRegistry()+ handles = await reg.discover(user_id=uuid.uuid4())+ assert {h.name for h in handles} == {"a"}+++async def test_registry_call_routes_via_namespaced_name():+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0", "id": 1, "result": {"isError": False, "structuredContent": {"hello": "world"}, "content": []},+ }))+ reg = MCPRegistry()+ out = await reg.call(wire_name="securo__list_accounts", arguments={}, user_id=uuid.uuid4())+ assert out["ok"] is True+ assert out["data"] == {"hello": "world"}+++async def test_registry_call_falls_back_to_bare_name(monkeypatch):+ """If the LLM drops the namespace prefix, registry must scan servers+ and route to whoever exposes that tool."""+ # The registry will call list_tools (to find the tool), then call_tool.+ _FakeAsyncClient.queue.extend([+ _FakeResponse(json_body={"jsonrpc": "2.0", "id": 1, "result": {"tools": [+ {"name": "list_accounts", "description": "", "inputSchema": {}}]}}),+ _FakeResponse(json_body={"jsonrpc": "2.0", "id": 2, "result": {+ "isError": False, "structuredContent": {"items": []}, "content": []}}),+ ])+ reg = MCPRegistry()+ out = await reg.call(wire_name="list_accounts", arguments={}, user_id=uuid.uuid4())+ assert out["ok"] is True+++async def test_registry_call_raises_on_unknown_tool():+ # list_tools on the only server (securo) returns no tools → unknown.+ _FakeAsyncClient.queue.append(_FakeResponse(json_body={+ "jsonrpc": "2.0", "id": 1, "result": {"tools": []},+ }))+ reg = MCPRegistry()+ with pytest.raises(ValueError, match="unknown tool"):+ await reg.call(wire_name="ghost_tool", arguments={}, user_id=uuid.uuid4())+++def test_registry_exposes_server_names(monkeypatch):+ from app.agents.config import get_agent_settings++ monkeypatch.setattr(get_agent_settings(), "extra_mcp_servers", "http://b:9001/mcp|beta")+ reg = MCPRegistry()+ assert set(reg.server_names()) == {"securo", "beta"}diff --git a/backend/tests/test_agents_mcp_tools.py b/backend/tests/test_agents_mcp_tools.pynew file mode 100644index 00000000..39045d93--- /dev/null+++ b/backend/tests/test_agents_mcp_tools.py@@ -0,0 +1,586 @@+"""MCP tool wrappers — call them directly with seeded data and a fake+CallContext (skipping HTTP/JWT, which is covered by test_agents_jwt.py).++Tools that depend on services Securo already tests heavily (reports,+dashboard) just check that the wrapper returns a serializable shape, not+the full numeric correctness of those services.+"""+import uuid++import pytest+import pytest_asyncio+from sqlalchemy.ext.asyncio import AsyncSession++# Importing this package registers all tools into mcp_server.registry.REGISTRY.+import mcp_server.tools # noqa: F401+from mcp_server.auth import CallContext+from mcp_server.registry import REGISTRY+++pytestmark = pytest.mark.asyncio+++@pytest_asyncio.fixture+def ctx(test_user) -> CallContext:+ return CallContext(user_id=test_user.id, conversation_id=uuid.uuid4())+++# --- Registry shape --------------------------------------------------------++def test_registry_contains_v1_tools():+ """We promised these in the design — keep the contract."""+ expected = {+ "list_transactions",+ "list_accounts",+ "get_account_summary",+ "list_categories",+ "list_payees",+ "get_budget_vs_actual",+ "list_budgets",+ "get_net_worth",+ "get_income_expenses",+ "get_cash_flow",+ "get_dashboard_snapshot",+ "search_all",+ "aggregate",+ "propose_categorize",+ "propose_create_category",+ "propose_create_budget",+ "propose_create_payee_rule",+ "propose_create_transaction",+ "propose_create_recurring_transaction",+ "propose_update_recurring_transaction",+ "propose_cancel_recurring_transaction",+ "propose_create_goal",+ "search_knowledge_base",+ "list_recurring_transactions",+ "list_assets",+ "list_goals",+ }+ assert expected.issubset(set(REGISTRY.keys())), (+ f"missing: {expected - set(REGISTRY.keys())}"+ )+++def test_proposal_tools_marked_is_proposal():+ for name in ("propose_categorize", "propose_create_category", "propose_create_budget", "propose_create_payee_rule"):+ spec = REGISTRY[name]+ assert spec.is_proposal, f"{name} should have is_proposal=True"+++def test_each_tool_has_input_schema():+ for name, spec in REGISTRY.items():+ assert spec.parameters.get("type") == "object", f"{name} schema must be object"+ assert "properties" in spec.parameters+++# --- Read tools (with real seeded data) -----------------------------------++async def test_list_transactions_returns_seeded_data(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["list_transactions"].handler+ result = await handler(session=session, ctx=ctx)+ assert isinstance(result, dict)+ assert "items" in result and "total" in result+ assert result["total"] >= len(test_transactions)+ sample = result["items"][0]+ for k in ("id", "date", "description", "amount", "currency"):+ assert k in sample+++async def test_list_transactions_with_search_filter(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["list_transactions"].handler+ result = await handler(session=session, ctx=ctx, search="UBER")+ assert all("UBER" in x["description"] for x in result["items"])+++async def test_list_transactions_default_sort_is_purchase_date_desc(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ """Regression: the default sort must be by purchase date desc so+ 'what's my last transaction?' returns the most recent one.+ Previously we sorted by COALESCE(effective_bill_date, date), which+ floats credit-card transactions whose bill is due in the future to+ the top — pushing the actual latest transaction down."""+ handler = REGISTRY["list_transactions"].handler+ result = await handler(session=session, ctx=ctx, limit=5)+ items = result["items"]+ assert items, "fixture has transactions; default query must return them"+ # Each item's date >= the next item's date (desc).+ dates = [x["date"] for x in items if x["date"]]+ assert dates == sorted(dates, reverse=True), f"not sorted desc by purchase date: {dates}"+ assert result["sort_by"] == "transaction_date"+++async def test_list_transactions_exposes_extra_fields(+ session: AsyncSession, ctx: CallContext, test_transactions, test_account, test_categories+):+ """Make sure the LLM gets enough context per row — names, not just+ ids — so it can answer "from which account?" without a second call."""+ handler = REGISTRY["list_transactions"].handler+ result = await handler(session=session, ctx=ctx, limit=5)+ sample = result["items"][0]+ for key in ("id", "date", "description", "amount", "currency", "type", "account_id", "account_name"):+ assert key in sample, f"missing key {key} in row"+ # account_name should resolve when category/account are seeded.+ assert any(x.get("account_name") == "Conta Corrente" for x in result["items"])+++async def test_list_transactions_tx_type_filter(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["list_transactions"].handler+ debits = await handler(session=session, ctx=ctx, tx_type="debit")+ credits = await handler(session=session, ctx=ctx, tx_type="credit")+ assert all(x["type"] == "debit" for x in debits["items"])+ assert all(x["type"] == "credit" for x in credits["items"])+ assert debits["total"] + credits["total"] >= len(debits["items"]) # sanity+++async def test_list_transactions_currency_filter_matches_native(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ """The Transaction.currency column defaults to USD in the fixture+ (independent of the account's BRL currency), so 'USD' should return+ everything and any narrower filter returns ≤ that count."""+ handler = REGISTRY["list_transactions"].handler+ usd = await handler(session=session, ctx=ctx, currency="USD")+ assert usd["total"] >= 1+ assert all(x["currency"] == "USD" for x in usd["items"])+++async def test_list_transactions_currency_filter_returns_zero_for_unused(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ """Regression for the 'do I have any EUR transactions?' bug — the+ answer should be a clean 0, not a 0 from text-searching 'EUR' in+ descriptions."""+ handler = REGISTRY["list_transactions"].handler+ eur = await handler(session=session, ctx=ctx, currency="EUR")+ assert eur["total"] == 0+ assert eur["items"] == []+++async def test_list_transactions_currency_filter_is_case_insensitive(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["list_transactions"].handler+ a = await handler(session=session, ctx=ctx, currency="usd")+ b = await handler(session=session, ctx=ctx, currency="USD")+ assert a["total"] == b["total"]+++async def test_list_transactions_min_amount_filter(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["list_transactions"].handler+ big = await handler(session=session, ctx=ctx, min_amount=100)+ # Fixture has transactions of 25.50, 45.00, 8000.00, 150.00, 39.90+ # Primary-currency stamping isn't computed in tests so this falls back+ # to native amount. Three rows >= 100: 8000, 150 (and zero with stamping+ # rules in our test setup we keep this lenient).+ assert big["total"] >= 1+ for it in big["items"]:+ # All returned amounts must be >= 100 (in their primary view).+ amt = it.get("amount_primary") or it.get("amount") or 0+ assert amt >= 100, f"row {it} slipped under min_amount"+++async def test_list_transactions_max_amount_filter(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["list_transactions"].handler+ small = await handler(session=session, ctx=ctx, max_amount=50)+ for it in small["items"]:+ amt = it.get("amount_primary") or it.get("amount") or 0+ assert amt <= 50+++async def test_list_recurring_transactions_returns_empty_dict_with_no_data(+ session: AsyncSession, ctx: CallContext+):+ """When there are no recurring transactions the tool must still return+ a stable {items, total} shape, not raise."""+ handler = REGISTRY["list_recurring_transactions"].handler+ r = await handler(session=session, ctx=ctx)+ assert r == {"items": [], "total": 0}+++async def test_list_assets_empty(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["list_assets"].handler+ r = await handler(session=session, ctx=ctx)+ assert r["total"] == 0+++async def test_list_goals_empty(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["list_goals"].handler+ r = await handler(session=session, ctx=ctx)+ assert r["total"] == 0+++async def test_list_budgets_empty(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["list_budgets"].handler+ r = await handler(session=session, ctx=ctx)+ assert r == {"items": [], "total": 0}+++async def test_aggregate_payee_filter(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ """The new payee_id filter on aggregate makes 'how much did I spend at X?'+ a single tool call instead of the agent's old 4-call dance."""+ handler = REGISTRY["aggregate"].handler+ r = await handler(session=session, ctx=ctx, payee_id=str(uuid.uuid4()))+ # Filtering by a non-existent payee returns no buckets — but the call+ # should still succeed (no error key).+ assert "error" not in r+ assert r["items"] == []+++async def test_aggregate_currency_filter(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["aggregate"].handler+ usd = await handler(session=session, ctx=ctx, currency="USD", group_by="category")+ assert "error" not in usd+ eur = await handler(session=session, ctx=ctx, currency="EUR", group_by="category")+ assert "error" not in eur and eur["items"] == []+++async def test_list_transactions_account_types_filter(+ session: AsyncSession, ctx: CallContext, test_transactions, test_account+):+ """fixture's test_account is 'checking' — filtering on 'credit_card' returns nothing."""+ handler = REGISTRY["list_transactions"].handler+ cc = await handler(session=session, ctx=ctx, account_types=["credit_card"])+ assert cc["total"] == 0+ checking = await handler(session=session, ctx=ctx, account_types=["checking"])+ assert checking["total"] >= 1+++async def test_list_accounts(session: AsyncSession, ctx: CallContext, test_account):+ handler = REGISTRY["list_accounts"].handler+ result = await handler(session=session, ctx=ctx)+ assert result["total"] >= 1+ found = next((a for a in result["items"] if a["id"] == str(test_account.id)), None)+ assert found is not None+ assert found["currency"] == "BRL"+++async def test_get_account_summary(session: AsyncSession, ctx: CallContext, test_account, test_transactions):+ handler = REGISTRY["get_account_summary"].handler+ result = await handler(session=session, ctx=ctx, account_id=str(test_account.id))+ # Real service returns a dict with income/expense/etc. We just verify it's not an error.+ assert isinstance(result, dict)+ assert "error" not in result or result.get("error") is None+++async def test_get_account_summary_unknown_account(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["get_account_summary"].handler+ result = await handler(session=session, ctx=ctx, account_id=str(uuid.uuid4()))+ assert result.get("error") == "account not found"+++async def test_list_categories(session: AsyncSession, ctx: CallContext, test_categories):+ handler = REGISTRY["list_categories"].handler+ result = await handler(session=session, ctx=ctx)+ names = {c["name"] for c in result["items"]}+ assert "Alimentação" in names+ # Check the IDs round-trip as strings (LLM consumes via JSON).+ for c in result["items"]:+ uuid.UUID(c["id"]) # raises if not a UUID+++async def test_list_payees_empty(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["list_payees"].handler+ result = await handler(session=session, ctx=ctx)+ assert result["total"] == 0+ assert result["items"] == []+++async def test_get_dashboard_snapshot(session: AsyncSession, ctx: CallContext, test_transactions):+ handler = REGISTRY["get_dashboard_snapshot"].handler+ result = await handler(session=session, ctx=ctx)+ assert isinstance(result, dict)+ # Snapshot is a Pydantic model dumped to dict — at minimum should be non-empty.+ assert result+++# --- aggregate -------------------------------------------------------------++async def test_aggregate_by_category(+ session: AsyncSession, ctx: CallContext, test_transactions, test_categories+):+ handler = REGISTRY["aggregate"].handler+ result = await handler(+ session=session, ctx=ctx,+ metric="sum", group_by="category", tx_type="expense",+ )+ assert "items" in result+ # We have UBER (Transporte) and IFOOD (Alimentação) as expenses.+ labels = {item.get("label") for item in result["items"]}+ assert "Transporte" in labels or "Alimentação" in labels++[email protected](reason="aggregate by month uses PostgreSQL to_char, not portable to SQLite test DB")+async def test_aggregate_by_month(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["aggregate"].handler+ result = await handler(session=session, ctx=ctx, metric="count", group_by="month")+ assert "items" in result+ for item in result["items"]:+ if item["bucket"]:+ assert len(item["bucket"]) == 7 and item["bucket"][4] == "-"+++async def test_aggregate_unknown_group_by(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["aggregate"].handler+ result = await handler(session=session, ctx=ctx, group_by="bogus")+ assert "error" in result+++# --- search_all ------------------------------------------------------------++async def test_search_all(session: AsyncSession, ctx: CallContext, test_transactions):+ handler = REGISTRY["search_all"].handler+ result = await handler(session=session, ctx=ctx, query="UBER")+ assert result["total"] >= 1+++# --- Proposal tools (no DB writes) ----------------------------------------++async def test_propose_categorize_returns_preview(+ session: AsyncSession, ctx: CallContext, test_transactions, test_categories+):+ handler = REGISTRY["propose_categorize"].handler+ target_cat = test_categories[0] # Alimentação+ tx_ids = [str(t.id) for t in test_transactions[:2]]+ result = await handler(+ session=session, ctx=ctx,+ transaction_ids=tx_ids,+ category_id=str(target_cat.id),+ )+ assert result["kind"] == "categorize"+ assert result["target_category"]["id"] == str(target_cat.id)+ assert result["affected_count"] == 2+ assert "apply_endpoint" in result+++async def test_propose_categorize_unknown_category(+ session: AsyncSession, ctx: CallContext, test_transactions+):+ handler = REGISTRY["propose_categorize"].handler+ result = await handler(+ session=session, ctx=ctx,+ transaction_ids=[str(test_transactions[0].id)],+ category_id=str(uuid.uuid4()),+ )+ assert result["error"] == "category not found"+++async def test_propose_create_category_detects_collision(+ session: AsyncSession, ctx: CallContext, test_categories+):+ handler = REGISTRY["propose_create_category"].handler+ # Use the same name as an existing category — should flag collision.+ result = await handler(session=session, ctx=ctx, name=test_categories[0].name)+ assert result["kind"] == "create_category"+ assert result["name_collision"] is not None+ assert result["name_collision"]["name"] == test_categories[0].name+++async def test_propose_create_category_no_collision(+ session: AsyncSession, ctx: CallContext, test_categories+):+ handler = REGISTRY["propose_create_category"].handler+ result = await handler(session=session, ctx=ctx, name="UniqueNewCategoryX9Z")+ assert result["name_collision"] is None+ assert result["proposed"]["name"] == "UniqueNewCategoryX9Z"+++async def test_propose_create_budget(+ session: AsyncSession, ctx: CallContext, test_categories+):+ handler = REGISTRY["propose_create_budget"].handler+ result = await handler(+ session=session, ctx=ctx,+ category_id=str(test_categories[0].id),+ month="2026-05-15",+ amount=500.0,+ currency="BRL",+ )+ assert result["kind"] == "create_budget"+ assert result["proposed"]["amount"] == 500.0+ assert result["proposed"]["month"] == "2026-05-01" # snapped to month start+++async def test_propose_create_transaction_full(+ session: AsyncSession, ctx: CallContext, test_account, test_categories+):+ handler = REGISTRY["propose_create_transaction"].handler+ r = await handler(+ session=session, ctx=ctx,+ description="Almoço",+ amount=50.0,+ type="debit",+ account_id=str(test_account.id),+ category_id=str(test_categories[0].id),+ )+ assert r["kind"] == "create_transaction"+ p = r["proposed"]+ assert p["description"] == "Almoço"+ assert p["amount"] == 50.0+ assert p["type"] == "debit"+ assert p["account_id"] == str(test_account.id)+ assert p["category_name"] == test_categories[0].name+ assert p["currency"] == "BRL" # inherited from account+ assert p["date"] # default to today+++async def test_propose_create_transaction_unknown_account(+ session: AsyncSession, ctx: CallContext+):+ handler = REGISTRY["propose_create_transaction"].handler+ r = await handler(+ session=session, ctx=ctx,+ description="x", amount=1.0, type="debit", account_id=str(uuid.uuid4()),+ )+ assert r["error"] == "account not found"+++async def test_propose_create_recurring_monthly_requires_day(+ session: AsyncSession, ctx: CallContext, test_account+):+ handler = REGISTRY["propose_create_recurring_transaction"].handler+ r = await handler(+ session=session, ctx=ctx,+ description="Netflix", amount=55.0, type="debit",+ frequency="monthly", account_id=str(test_account.id),+ )+ assert "day_of_month" in r.get("error", "")+++async def test_propose_create_recurring_monthly_full(+ session: AsyncSession, ctx: CallContext, test_account+):+ handler = REGISTRY["propose_create_recurring_transaction"].handler+ r = await handler(+ session=session, ctx=ctx,+ description="Netflix", amount=55.0, type="debit",+ frequency="monthly", day_of_month=10,+ account_id=str(test_account.id),+ )+ assert r["kind"] == "create_recurring_transaction"+ assert r["proposed"]["day_of_month"] == 10+ assert r["proposed"]["frequency"] == "monthly"+++async def test_propose_update_recurring_no_changes(+ session: AsyncSession, ctx: CallContext, test_user+):+ """If the LLM calls without any change fields, the tool should refuse+ with a clear error rather than build an empty 'changes' object."""+ from app.models.recurring_transaction import RecurringTransaction+ from decimal import Decimal+ from datetime import date++ rt = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id,+ description="Salary", amount=Decimal("4000"), currency="BRL",+ type="credit", frequency="monthly", day_of_month=1,+ start_date=date(2026, 1, 1), next_occurrence=date(2026, 5, 1), is_active=True,+ )+ session.add(rt)+ await session.commit()++ handler = REGISTRY["propose_update_recurring_transaction"].handler+ r = await handler(session=session, ctx=ctx, recurring_id=str(rt.id))+ assert r["error"] == "no changes provided"+++async def test_propose_update_recurring_amount_change(+ session: AsyncSession, ctx: CallContext, test_user+):+ """'Update my salary to R$8,000' — change amount only, current values+ are echoed back so the user sees the diff."""+ from app.models.recurring_transaction import RecurringTransaction+ from decimal import Decimal+ from datetime import date++ rt = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id,+ description="Salary", amount=Decimal("4000"), currency="BRL",+ type="credit", frequency="monthly", day_of_month=1,+ start_date=date(2026, 1, 1), next_occurrence=date(2026, 5, 1), is_active=True,+ )+ session.add(rt)+ await session.commit()++ handler = REGISTRY["propose_update_recurring_transaction"].handler+ r = await handler(session=session, ctx=ctx, recurring_id=str(rt.id), amount=8000)+ assert r["kind"] == "update_recurring_transaction"+ assert r["target"]["amount"] == 4000.0 # current value visible+ assert r["changes"] == {"amount": 8000.0}+++async def test_propose_cancel_recurring_default_mode_is_deactivate(+ session: AsyncSession, ctx: CallContext, test_user+):+ from app.models.recurring_transaction import RecurringTransaction+ from decimal import Decimal+ from datetime import date++ rt = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id,+ description="Spotify", amount=Decimal("23.90"), currency="BRL",+ type="debit", frequency="monthly", day_of_month=15,+ start_date=date(2026, 1, 1), next_occurrence=date(2026, 5, 15), is_active=True,+ )+ session.add(rt)+ await session.commit()++ handler = REGISTRY["propose_cancel_recurring_transaction"].handler+ r = await handler(session=session, ctx=ctx, recurring_id=str(rt.id))+ assert r["mode"] == "deactivate"+ assert r["target"]["description"] == "Spotify"+++async def test_propose_create_goal(session: AsyncSession, ctx: CallContext):+ handler = REGISTRY["propose_create_goal"].handler+ r = await handler(+ session=session, ctx=ctx,+ name="Viagem para o Japão", target_amount=10000, deadline="2026-12-31",+ )+ assert r["kind"] == "create_goal"+ assert r["proposed"]["target_amount"] == 10000.0+ assert r["proposed"]["deadline"] == "2026-12-31"+ assert r["proposed"]["initial_amount"] == 0.0+++async def test_propose_create_payee_rule_unknown_category(+ session: AsyncSession, ctx: CallContext+):+ handler = REGISTRY["propose_create_payee_rule"].handler+ result = await handler(+ session=session, ctx=ctx,+ match_pattern="UBER",+ category_id=str(uuid.uuid4()),+ )+ assert result["error"] == "category not found"+++# --- search_knowledge_base ------------------------------------------------++async def test_search_knowledge_base_requires_agent_id(+ session: AsyncSession, test_user+):+ """Without agent_id in context, the tool refuses (covers a misconfigured caller)."""+ handler = REGISTRY["search_knowledge_base"].handler+ bare_ctx = CallContext(user_id=test_user.id) # no agent_id+ result = await handler(session=session, ctx=bare_ctx, query="anything")+ assert "error" in result+ assert "agent_id" in result["error"]diff --git a/backend/tests/test_agents_providers.py b/backend/tests/test_agents_providers.pynew file mode 100644index 00000000..c772a373--- /dev/null+++ b/backend/tests/test_agents_providers.py@@ -0,0 +1,234 @@+"""Provider abstraction tests.++We don't talk to real LLM providers in unit tests. Instead:+ - Test the wire serializers (messages, tools) for OpenAI and Anthropic.+ - Test the registry's build_provider dispatch.+ - Test the high-level chat() helper assembles streaming chunks correctly.+"""+import json+from typing import AsyncIterator++import pytest++from app.agents.providers import build_provider, list_providers+from app.agents.providers.anthropic import (+ _serialize_messages as anthropic_serialize,+ _serialize_tools as anthropic_tools,+ _split_system,+)+from app.agents.providers.base import (+ ChatChunk,+ ChatMessage,+ ChatResponse,+ LLMProvider,+ ToolCall,+ ToolDefinition,+ Usage,+)+from app.agents.providers.openai import (+ _serialize_messages as openai_serialize,+ _serialize_tools as openai_tools,+ normalize_openai_base_url,+)+++pytestmark = pytest.mark.asyncio+++def test_registry_lists_all_four_providers():+ assert set(list_providers()) == {"ollama", "openai", "anthropic", "openai_compatible"}+++def test_registry_unknown_raises():+ with pytest.raises(ValueError):+ build_provider("does_not_exist")+++def test_registry_build_openai_compat_requires_base_url():+ # build_provider strips falsy base_url so the constructor's required+ # kwarg is missing → TypeError. If supplied as empty string directly,+ # the constructor raises ValueError. Either is acceptable as a refusal.+ with pytest.raises((ValueError, TypeError)):+ build_provider("openai_compatible", base_url="")+++def test_openai_serialization_basic_message():+ out = openai_serialize([ChatMessage(role="user", content="hi")])+ assert out == [{"role": "user", "content": "hi"}]+++def test_openai_serialization_assistant_with_tool_calls():+ msg = ChatMessage(+ role="assistant",+ content=None,+ tool_calls=[ToolCall(id="t1", name="list_accounts", arguments={"x": 1})],+ )+ out = openai_serialize([msg])+ assert out[0]["tool_calls"][0]["id"] == "t1"+ assert out[0]["tool_calls"][0]["function"]["name"] == "list_accounts"+ args = json.loads(out[0]["tool_calls"][0]["function"]["arguments"])+ assert args == {"x": 1}+++def test_openai_serialization_tool_result():+ msg = ChatMessage(role="tool", content="42 transactions", tool_call_id="t1")+ out = openai_serialize([msg])+ assert out[0]["role"] == "tool"+ assert out[0]["tool_call_id"] == "t1"+++def test_openai_tools_payload_shape():+ defs = [ToolDefinition(name="list_accounts", description="d", parameters={"type": "object"})]+ out = openai_tools(defs)+ assert out and out[0]["type"] == "function"+ assert out[0]["function"]["name"] == "list_accounts"+++def test_anthropic_split_system_extracts_system_messages():+ sys, rest = _split_system([+ ChatMessage(role="system", content="primary instructions"),+ ChatMessage(role="user", content="hello"),+ ])+ assert sys == "primary instructions"+ assert len(rest) == 1+ assert rest[0].role == "user"+++def test_anthropic_serializes_tool_use_blocks():+ msg = ChatMessage(+ role="assistant",+ content="thinking",+ tool_calls=[ToolCall(id="toolu_1", name="get_dashboard_snapshot", arguments={})],+ )+ out = anthropic_serialize([msg])+ blocks = out[0]["content"]+ kinds = [b["type"] for b in blocks]+ assert "text" in kinds and "tool_use" in kinds+ tu = next(b for b in blocks if b["type"] == "tool_use")+ assert tu["id"] == "toolu_1" and tu["name"] == "get_dashboard_snapshot"+++def test_anthropic_tool_result_block():+ msg = ChatMessage(role="tool", content="ok", tool_call_id="toolu_1")+ out = anthropic_serialize([msg])+ blk = out[0]["content"][0]+ assert blk["type"] == "tool_result"+ assert blk["tool_use_id"] == "toolu_1"++[email protected]("raw,expected", [+ ("http://192.168.1.142:1234", "http://192.168.1.142:1234/v1"),+ ("http://lmstudio:1234/", "http://lmstudio:1234/v1"),+ ("http://lmstudio:1234/v1", "http://lmstudio:1234/v1"),+ ("http://lmstudio:1234/v1/", "http://lmstudio:1234/v1"),+ ("https://api.openai.com/v1", "https://api.openai.com/v1"),+ ("https://api.groq.com/openai/v1", "https://api.groq.com/openai/v1"),+ ("https://api.example.com/v2", "https://api.example.com/v2"),+ ("https://api.example.com/beta", "https://api.example.com/beta"),+ ("https://api.example.com/", "https://api.example.com/v1"),+ ("", ""),+])+def test_normalize_openai_base_url(raw, expected):+ assert normalize_openai_base_url(raw) == expected+++def test_openai_provider_normalizes_base_url_at_construction():+ from app.agents.providers.openai import OpenAIProvider++ p = OpenAIProvider(api_key="x", base_url="http://lmstudio:1234")+ assert p.base_url == "http://lmstudio:1234/v1"+++def test_anthropic_tools_payload_shape():+ defs = [ToolDefinition(name="search_all", description="d", parameters={"type": "object"})]+ out = anthropic_tools(defs)+ assert out and out[0]["name"] == "search_all"+ assert out[0]["input_schema"] == {"type": "object"}+++async def test_openai_parser_handles_index_keyed_tool_call_chunks():+ """Regression: OpenAI streams tool calls with `id` and `name` only in+ the FIRST chunk for an `index`; subsequent chunks have just args.+ Earlier code keyed by id (falling back to `_idx_N` when missing),+ creating phantom entries with empty names — dispatch then failed with+ `unknown tool: `."""+ from unittest.mock import patch+ from app.agents.providers.base import ChatMessage+ from app.agents.providers.openai import OpenAIProvider++ sse_chunks = [+ b'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_abc","function":{"name":"propose_categorize","arguments":""}}]}}]}\n',+ b'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"transaction_ids\\":"}}]}}]}\n',+ b'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"[\\"abc\\"],\\"category_id\\":\\"def\\"}"}}]}}]}\n',+ b'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":12,"completion_tokens":34}}\n',+ b'data: [DONE]\n',+ ]++ class _StreamResp:+ status_code = 200+ async def __aenter__(self): return self+ async def __aexit__(self, *_a): pass+ async def aiter_lines(self):+ for line in sse_chunks:+ yield line.decode().rstrip("\n")++ class _Client:+ async def __aenter__(self): return self+ async def __aexit__(self, *_a): pass+ def stream(self, *_a, **_kw): return _StreamResp()++ p = OpenAIProvider(api_key="x", base_url="http://lmstudio:1234")+ chunks = []+ with patch("httpx.AsyncClient", return_value=_Client()):+ async for c in p.chat_stream([ChatMessage(role="user", content="hi")], model="m"):+ chunks.append(c)++ starts = [c for c in chunks if c.type == "tool_call_start"]+ assert len(starts) == 1, "should emit exactly one tool_call_start per index"+ assert starts[0].tool_name == "propose_categorize"+ assert starts[0].tool_call_id == "call_abc"++ arg_deltas = [c.args_delta for c in chunks if c.type == "tool_call_args_delta"]+ assert "".join(arg_deltas) == '{"transaction_ids":["abc"],"category_id":"def"}'++ ends = [c for c in chunks if c.type == "tool_call_end"]+ assert len(ends) == 1 and ends[0].tool_call_id == "call_abc"+++# --- chat() helper assembly -------------------------------------------------++class _ScriptedProvider(LLMProvider):+ name = "scripted"++ def __init__(self, chunks: list[ChatChunk]):+ super().__init__()+ self._chunks = chunks++ async def chat_stream( # type: ignore[override]+ self, messages, *, model, tools=None, temperature=0.4, max_tokens=None+ ) -> AsyncIterator[ChatChunk]:+ for c in self._chunks:+ yield c++ async def embed(self, texts, *, model):+ return [[0.1] * 4 for _ in texts]+++async def test_chat_helper_aggregates_text_and_tool_calls():+ p = _ScriptedProvider([+ ChatChunk(type="text_delta", text="Hello "),+ ChatChunk(type="text_delta", text="world"),+ ChatChunk(type="tool_call_start", tool_call_id="t1", tool_name="list_accounts"),+ ChatChunk(type="tool_call_args_delta", tool_call_id="t1", args_delta='{"x": 1}'),+ ChatChunk(type="tool_call_end", tool_call_id="t1"),+ ChatChunk(type="usage", usage=Usage(input_tokens=12, output_tokens=4)),+ ChatChunk(type="finish", finish_reason="tool_calls"),+ ])+ res = await p.chat([ChatMessage(role="user", content="hi")], model="m")+ assert isinstance(res, ChatResponse)+ assert res.content == "Hello world"+ assert res.finish_reason == "tool_calls"+ assert res.usage.input_tokens == 12+ assert len(res.tool_calls) == 1+ assert res.tool_calls[0].name == "list_accounts"+ assert res.tool_calls[0].arguments == {"x": 1}diff --git a/backend/tests/test_agents_providers_streaming.py b/backend/tests/test_agents_providers_streaming.pynew file mode 100644index 00000000..0bb9ef42--- /dev/null+++ b/backend/tests/test_agents_providers_streaming.py@@ -0,0 +1,311 @@+"""Coverage for the streaming chat + embed paths in+app/agents/providers/{ollama,anthropic}.py. Both providers open+httpx.AsyncClient.stream(...) inline, so we replace AsyncClient with a+fake whose stream() yields a pre-baked SSE/JSONL response.+"""+from __future__ import annotations++import json+from contextlib import asynccontextmanager+from typing import Iterable++import pytest++import app.agents.providers.anthropic as anthropic_module+import app.agents.providers.ollama as ollama_module+from app.agents.providers.anthropic import AnthropicProvider+from app.agents.providers.base import (+ ChatMessage,+ LLMAuthError,+ LLMNotSupportedError,+ LLMRateLimitError,+ LLMUnavailableError,+ ToolDefinition,+)+from app.agents.providers.ollama import OllamaProvider+++# --------------------------------------------------------------------- httpx fake++class _FakeStreamResponse:+ """Stand-in for the response object yielded from `client.stream(...)`."""++ def __init__(self, *, status_code: int, lines: Iterable[str], body: bytes = b""):+ self.status_code = status_code+ self._lines = list(lines)+ self._body = body++ async def aiter_lines(self):+ for ln in self._lines:+ yield ln++ async def aread(self) -> bytes:+ return self._body+++class _FakeResponse:+ """Stand-in for a plain (non-streaming) response."""++ def __init__(self, *, status_code: int, json_body=None, text: str = ""):+ self.status_code = status_code+ self._body = json_body+ self.text = text++ def json(self):+ return self._body+++class _FakeAsyncClient:+ queue_stream: list[_FakeStreamResponse] = []+ queue_post: list[_FakeResponse] = []+ posted: list[tuple[str, dict]] = []++ def __init__(self, *_, **__): # accept (timeout=...) kw+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ @asynccontextmanager+ async def stream(self, method, url, *, json=None, headers=None): # noqa: A002+ type(self).posted.append((url, json or {}))+ yield type(self).queue_stream.pop(0)++ async def post(self, url, *, json=None, headers=None): # noqa: A002+ type(self).posted.append((url, json or {}))+ return type(self).queue_post.pop(0)++[email protected](autouse=True)+def _fake_httpx(monkeypatch):+ _FakeAsyncClient.queue_stream = []+ _FakeAsyncClient.queue_post = []+ _FakeAsyncClient.posted = []+ monkeypatch.setattr(ollama_module.httpx, "AsyncClient", _FakeAsyncClient)+ monkeypatch.setattr(anthropic_module.httpx, "AsyncClient", _FakeAsyncClient)+ yield+++# --------------------------------------------------------------------- Ollama: chat_stream++async def test_ollama_chat_stream_yields_text_and_finish():+ """Two JSONL deltas + a final done frame should produce text deltas+ plus usage + finish chunks."""+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(status_code=200, lines=[+ json.dumps({"message": {"content": "Hel"}}),+ json.dumps({"message": {"content": "lo"}}),+ json.dumps({+ "message": {"content": ""},+ "done": True, "done_reason": "stop",+ "prompt_eval_count": 7, "eval_count": 4,+ }),+ "", # blank line — should be skipped+ ]))++ provider = OllamaProvider(base_url="http://ollama:11434")+ chunks = []+ async for chunk in provider.chat_stream(+ [ChatMessage(role="user", content="hi")], model="llama3", temperature=0.1, max_tokens=64,+ ):+ chunks.append(chunk)++ text = "".join(c.text or "" for c in chunks if c.type == "text_delta")+ assert text == "Hello"+ assert any(c.type == "usage" and c.usage and c.usage.input_tokens == 7 for c in chunks)+ assert any(c.type == "finish" and c.finish_reason == "stop" for c in chunks)++ # Verify the request payload picked up our temperature + num_predict.+ _, payload = _FakeAsyncClient.posted[-1]+ assert payload["options"]["temperature"] == 0.1+ assert payload["options"]["num_predict"] == 64+++async def test_ollama_chat_stream_emits_tool_call_events():+ """A streaming tool_calls payload should produce start/args/end chunks."""+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(status_code=200, lines=[+ json.dumps({+ "message": {+ "content": "",+ "tool_calls": [+ {"function": {"name": "list_accounts", "arguments": {"limit": 5}}},+ ],+ },+ }),+ json.dumps({"message": {"content": ""}, "done": True, "done_reason": "tool_calls"}),+ ]))++ provider = OllamaProvider()+ types = []+ async for c in provider.chat_stream([ChatMessage(role="user", content="x")], model="llama3"):+ types.append(c.type)+ assert "tool_call_start" in types+ assert "tool_call_args_delta" in types+ assert "tool_call_end" in types+++async def test_ollama_chat_stream_raises_on_http_error():+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(+ status_code=503, lines=[], body=b"unavailable",+ ))+ provider = OllamaProvider()+ with pytest.raises(LLMUnavailableError):+ async for _ in provider.chat_stream(+ [ChatMessage(role="user", content="x")], model="llama3",+ ):+ pass+++async def test_ollama_chat_stream_includes_tools_in_payload():+ """When tools are passed, they must show up in the request body."""+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(status_code=200, lines=[+ json.dumps({"message": {"content": ""}, "done": True, "done_reason": "stop"}),+ ]))+ provider = OllamaProvider()+ tools = [ToolDefinition(name="t", description="d", parameters={"type": "object"})]+ async for _ in provider.chat_stream(+ [ChatMessage(role="user", content="x")], model="llama3", tools=tools,+ ):+ pass+ _, payload = _FakeAsyncClient.posted[-1]+ assert payload["tools"][0]["function"]["name"] == "t"+++# --------------------------------------------------------------------- Ollama: embed++async def test_ollama_embed_returns_vectors_per_input():+ _FakeAsyncClient.queue_post.append(_FakeResponse(status_code=200, json_body={+ "embeddings": [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],+ }))+ provider = OllamaProvider()+ out = await provider.embed(["a", "b"], model="nomic-embed-text")+ assert out == [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]+++async def test_ollama_embed_handles_missing_embeddings_array():+ """If the server returns an unexpected shape, we should yield [] rather than crash."""+ _FakeAsyncClient.queue_post.append(_FakeResponse(status_code=200, json_body={"unexpected": True}))+ provider = OllamaProvider()+ out = await provider.embed(["a"], model="nomic-embed-text")+ assert out == []+++async def test_ollama_embed_raises_on_http_error():+ _FakeAsyncClient.queue_post.append(_FakeResponse(status_code=500, text="boom"))+ provider = OllamaProvider()+ with pytest.raises(LLMUnavailableError):+ await provider.embed(["a"], model="nomic-embed-text")+++# --------------------------------------------------------------------- Anthropic: chat_stream++async def test_anthropic_chat_stream_parses_text_block_sequence():+ sse = [+ f"data: {json.dumps({'type': 'message_start', 'message': {'usage': {'input_tokens': 5, 'output_tokens': 0}}})}",+ f"data: {json.dumps({'type': 'content_block_start', 'index': 0, 'content_block': {'type': 'text'}})}",+ f"data: {json.dumps({'type': 'content_block_delta', 'index': 0, 'delta': {'type': 'text_delta', 'text': 'Hi'}})}",+ f"data: {json.dumps({'type': 'content_block_delta', 'index': 0, 'delta': {'type': 'text_delta', 'text': '!'}})}",+ f"data: {json.dumps({'type': 'content_block_stop', 'index': 0})}",+ f"data: {json.dumps({'type': 'message_delta', 'delta': {'stop_reason': 'end_turn'}, 'usage': {'output_tokens': 2}})}",+ "", # blank — skipped+ "non-sse line — should be ignored", # not 'data:' prefixed+ ]+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(status_code=200, lines=sse))++ provider = AnthropicProvider(api_key="sk-test")+ chunks = []+ async for c in provider.chat_stream([ChatMessage(role="user", content="hi")], model="claude-x"):+ chunks.append(c)++ text = "".join(c.text or "" for c in chunks if c.type == "text_delta")+ assert text == "Hi!"+ assert any(c.type == "usage" and c.usage.output_tokens == 2 for c in chunks)+ assert any(c.type == "finish" and c.finish_reason == "end_turn" for c in chunks)+++async def test_anthropic_chat_stream_parses_tool_use_block():+ # Build SSE lines via explicit json.dumps payloads — avoids backslash+ # escapes inside f-strings, which Python 3.11 doesn't allow.+ events = [+ {"type": "content_block_start", "index": 0,+ "content_block": {"type": "tool_use", "id": "toolu_1", "name": "list_accounts"}},+ {"type": "content_block_delta", "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": '{"limit":'}},+ {"type": "content_block_delta", "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": "5}"}},+ {"type": "content_block_stop", "index": 0},+ {"type": "message_delta",+ "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 1}},+ ]+ sse = ["data: " + json.dumps(e) for e in events]+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(status_code=200, lines=sse))++ provider = AnthropicProvider(api_key="sk-test")+ chunks = []+ async for c in provider.chat_stream([ChatMessage(role="user", content="x")], model="claude-x"):+ chunks.append(c)++ starts = [c for c in chunks if c.type == "tool_call_start"]+ args = [c for c in chunks if c.type == "tool_call_args_delta"]+ ends = [c for c in chunks if c.type == "tool_call_end"]+ assert starts and starts[0].tool_name == "list_accounts"+ assert "".join(c.args_delta or "" for c in args) == '{"limit":5}'+ assert ends and ends[0].tool_call_id == "toolu_1"+++async def test_anthropic_includes_system_and_tools_in_payload():+ sse = [f"data: {json.dumps({'type': 'message_delta', 'delta': {'stop_reason': 'end_turn'}, 'usage': {}})}"]+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(status_code=200, lines=sse))+ provider = AnthropicProvider(api_key="sk-test")+ tools = [ToolDefinition(name="t", description="d", parameters={"type": "object"})]+ msgs = [+ ChatMessage(role="system", content="part1"),+ ChatMessage(role="system", content="part2"),+ ChatMessage(role="user", content="hi"),+ ]+ async for _ in provider.chat_stream(msgs, model="claude-x", tools=tools, max_tokens=200):+ pass+ _, payload = _FakeAsyncClient.posted[-1]+ assert payload["system"] == "part1\n\npart2"+ assert payload["max_tokens"] == 200+ assert payload["tools"][0]["name"] == "t"+++# --------------------------------------------------------------------- Anthropic: HTTP errors → typed exceptions+[email protected]("status,exc_type", [+ (401, LLMAuthError),+ (403, LLMAuthError),+ (429, LLMRateLimitError),+ (500, LLMUnavailableError),+ (502, LLMUnavailableError),+ (400, LLMUnavailableError),+])+async def test_anthropic_http_errors_map_to_typed_exceptions(status, exc_type):+ _FakeAsyncClient.queue_stream.append(_FakeStreamResponse(+ status_code=status, lines=[], body=b'{"error":{"message":"x"}}',+ ))+ provider = AnthropicProvider(api_key="sk-test")+ with pytest.raises(exc_type):+ async for _ in provider.chat_stream([ChatMessage(role="user", content="x")], model="claude-x"):+ pass+++async def test_anthropic_embed_raises_not_supported():+ provider = AnthropicProvider(api_key="sk-test")+ with pytest.raises(LLMNotSupportedError):+ await provider.embed(["a"], model="x")diff --git a/backend/tests/test_mcp_server_groups.py b/backend/tests/test_mcp_server_groups.pynew file mode 100644index 00000000..423e9f89--- /dev/null+++ b/backend/tests/test_mcp_server_groups.py@@ -0,0 +1,229 @@+"""Cover mcp_server/tools/groups.py — the three group/balance/settlement+tools exposed to the agent. Service-layer behaviour is already covered+in tests/test_groups.py; here we focus on the MCP serialization layer:+name resolution, error pass-through, decimal coercion, etc.+"""+from __future__ import annotations++import uuid+from datetime import date+from decimal import Decimal+from types import SimpleNamespace++import pytest++import mcp_server.tools.groups as groups_tool+from mcp_server.auth import CallContext+++def _ctx(user_id):+ return CallContext(user_id=user_id)+++# --------------------------------------------------------------------- list_groups++async def test_list_groups_serializes_group_with_members(session, test_user, monkeypatch):+ gid = uuid.uuid4()+ mid1 = uuid.uuid4()+ mid2 = uuid.uuid4()+ fake_group = SimpleNamespace(+ id=gid,+ name="Amigos",+ kind="expense",+ default_currency="BRL",+ is_archived=False,+ members=[+ SimpleNamespace(id=mid1, name="Tássio", is_self=True),+ SimpleNamespace(id=mid2, name="Bia", is_self=False),+ ],+ )++ async def fake_list_groups(s, uid, *, include_archived):+ assert uid == test_user.id+ assert include_archived is True+ return [fake_group]++ monkeypatch.setattr(groups_tool.group_service, "list_groups", fake_list_groups)++ result = await groups_tool.list_groups(+ session=session, ctx=_ctx(test_user.id), include_archived=True+ )+ assert result["total"] == 1+ g = result["items"][0]+ assert g["id"] == str(gid)+ assert g["name"] == "Amigos"+ assert g["kind"] == "expense"+ assert g["default_currency"] == "BRL"+ assert g["is_archived"] is False+ assert len(g["members"]) == 2+ assert {m["name"] for m in g["members"]} == {"Tássio", "Bia"}+ assert next(m for m in g["members"] if m["name"] == "Tássio")["is_self"] is True+++async def test_list_groups_handles_missing_members(session, test_user, monkeypatch):+ """If a group has no members (or None), the tool must not crash."""+ fake_group = SimpleNamespace(+ id=uuid.uuid4(),+ name="Solo",+ kind="expense",+ default_currency="USD",+ is_archived=True,+ members=None,+ )++ async def fake(s, uid, *, include_archived):+ return [fake_group]++ monkeypatch.setattr(groups_tool.group_service, "list_groups", fake)+ result = await groups_tool.list_groups(session=session, ctx=_ctx(test_user.id))+ assert result["items"][0]["members"] == []+++async def test_list_groups_defaults_include_archived_false(session, test_user, monkeypatch):+ captured = {}++ async def fake(s, uid, *, include_archived):+ captured["include_archived"] = include_archived+ return []++ monkeypatch.setattr(groups_tool.group_service, "list_groups", fake)+ await groups_tool.list_groups(session=session, ctx=_ctx(test_user.id))+ assert captured["include_archived"] is False+++# --------------------------------------------------------------------- get_group_balances++async def test_get_group_balances_returns_error_when_group_missing(session, test_user, monkeypatch):+ async def fake_compute(s, gid, uid):+ return None # service signals not-visible/not-found via None+ monkeypatch.setattr(groups_tool.balance_service, "compute_balances", fake_compute)++ result = await groups_tool.get_group_balances(+ session=session, ctx=_ctx(test_user.id), group_id=str(uuid.uuid4())+ )+ assert "error" in result+++async def test_get_group_balances_resolves_member_names(session, test_user, monkeypatch):+ """Happy path: compute_balances returns raw lines; the tool resolves+ member names and is_self flags from the GroupMember table."""+ from app.models.group import Group, GroupMember++ g = Group(+ id=uuid.uuid4(), user_id=test_user.id, name="Roomies",+ kind="expense", default_currency="USD", is_archived=False,+ )+ me = GroupMember(id=uuid.uuid4(), group_id=g.id, name="Me", is_self=True)+ them = GroupMember(id=uuid.uuid4(), group_id=g.id, name="Alex", is_self=False)+ session.add_all([g, me, them])+ await session.commit()++ async def fake_compute(s, gid, uid):+ assert gid == g.id+ return {+ "group_id": g.id,+ "self_member_id": me.id,+ "default_currency": "USD",+ "lines": [+ {"member_id": them.id, "currency": "USD", "amount": Decimal("12.50"),+ "amount_in_default_currency": Decimal("12.50")},+ ],+ }++ monkeypatch.setattr(groups_tool.balance_service, "compute_balances", fake_compute)++ result = await groups_tool.get_group_balances(+ session=session, ctx=_ctx(test_user.id), group_id=str(g.id)+ )+ assert result["group_id"] == str(g.id)+ assert result["self_member_id"] == str(me.id)+ assert result["default_currency"] == "USD"+ assert len(result["lines"]) == 1+ ln = result["lines"][0]+ assert ln["member_id"] == str(them.id)+ assert ln["member_name"] == "Alex"+ assert ln["is_self"] is False+ assert ln["amount"] == 12.5+ assert ln["amount_in_default_currency"] == 12.5+++async def test_get_group_balances_handles_none_self_member(session, test_user, monkeypatch):+ """If the user isn't a member, self_member_id comes back None — we+ must serialize that as null, not crash."""+ gid = uuid.uuid4()++ async def fake_compute(s, g, u):+ return {+ "group_id": gid, "self_member_id": None, "default_currency": "BRL",+ "lines": [],+ }+ monkeypatch.setattr(groups_tool.balance_service, "compute_balances", fake_compute)+ result = await groups_tool.get_group_balances(+ session=session, ctx=_ctx(test_user.id), group_id=str(gid)+ )+ assert result["self_member_id"] is None+++# --------------------------------------------------------------------- list_group_settlements++async def test_list_group_settlements_returns_error_when_group_missing(session, test_user, monkeypatch):+ async def fake_list(s, gid, uid):+ return None+ monkeypatch.setattr(groups_tool.settlement_service, "list_settlements", fake_list)++ result = await groups_tool.list_group_settlements(+ session=session, ctx=_ctx(test_user.id), group_id=str(uuid.uuid4())+ )+ assert "error" in result+++async def test_list_group_settlements_serializes_rows(session, test_user, monkeypatch):+ s1 = SimpleNamespace(+ id=uuid.uuid4(),+ group_id=uuid.uuid4(),+ from_member_id=uuid.uuid4(),+ to_member_id=uuid.uuid4(),+ amount=Decimal("99.95"),+ currency="EUR",+ date=date(2026, 5, 1),+ notes="brunch",+ transaction_id=uuid.uuid4(),+ )+ s2 = SimpleNamespace(+ id=uuid.uuid4(),+ group_id=s1.group_id,+ from_member_id=uuid.uuid4(),+ to_member_id=uuid.uuid4(),+ amount=Decimal("10.00"),+ currency="EUR",+ date=None, # exercise the None-date branch+ notes=None,+ transaction_id=None, # exercise the None-txn branch+ )++ async def fake(s, gid, uid):+ return [s1, s2]+ monkeypatch.setattr(groups_tool.settlement_service, "list_settlements", fake)++ result = await groups_tool.list_group_settlements(+ session=session, ctx=_ctx(test_user.id), group_id=str(s1.group_id)+ )+ assert result["total"] == 2+ first, second = result["items"]+ assert first["id"] == str(s1.id)+ assert first["amount"] == 99.95+ assert first["currency"] == "EUR"+ assert first["date"] == "2026-05-01"+ assert first["notes"] == "brunch"+ assert first["transaction_id"] == str(s1.transaction_id)+ assert second["date"] is None+ assert second["transaction_id"] is None+ assert second["amount"] == 10.0diff --git a/backend/tests/test_mcp_server_main.py b/backend/tests/test_mcp_server_main.pynew file mode 100644index 00000000..40ccf87b--- /dev/null+++ b/backend/tests/test_mcp_server_main.py@@ -0,0 +1,203 @@+"""Cover the MCP server's HTTP surface (mcp_server/main.py).++Strategy: drive the FastAPI app directly with httpx.ASGITransport so we+exercise auth + JSON-RPC routing without needing the agents backend+running. Tool calls go against the SQLite test DB and are limited to+read-only paths (avoid pgvector-dependent tools).+"""+from __future__ import annotations++import json++import httpx+import pytest++from app.agents.mcp.auth import mint_token+++def _client():+ # Import here so the import counts toward coverage and the test DB+ # is already configured by conftest before mcp_server.main loads.+ from mcp_server.main import app++ transport = httpx.ASGITransport(app=app)+ return httpx.AsyncClient(transport=transport, base_url="http://mcp.test")+++def _auth_headers(user_id) -> dict[str, str]:+ return {"Authorization": f"Bearer {mint_token(user_id=user_id)}"}+++async def test_health_endpoint_lists_registered_tool_count(test_user):+ async with _client() as cli:+ r = await cli.get("/health")+ assert r.status_code == 200+ body = r.json()+ assert body["status"] == "ok"+ assert body["tools"] > 0+++async def test_mcp_rejects_unauthenticated():+ async with _client() as cli:+ r = await cli.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"})+ assert r.status_code == 401+ assert r.json()["error"]["code"] == -32001+++async def test_mcp_rejects_bad_token():+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ headers={"Authorization": "Bearer not.a.real.token"},+ )+ assert r.status_code == 401+++async def test_mcp_rejects_malformed_body(test_user):+ async with _client() as cli:+ r = await cli.post("/mcp", content="not json", headers=_auth_headers(test_user.id))+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32700+++async def test_mcp_rejects_non_object_body(test_user):+ async with _client() as cli:+ r = await cli.post("/mcp", json=[1, 2, 3], headers=_auth_headers(test_user.id))+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32600+++async def test_mcp_rejects_wrong_jsonrpc_version(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "1.0", "id": 7, "method": "tools/list"},+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 400+ assert r.json()["error"]["code"] == -32600+++async def test_mcp_rejects_non_string_method(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 7, "method": 42},+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 400+++async def test_mcp_initialize_returns_protocol_handshake(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 200+ result = r.json()["result"]+ assert result["protocolVersion"] == "2024-11-05"+ assert result["serverInfo"]["name"] == "securo-builtin"+ assert "tools" in result["capabilities"]+++async def test_mcp_tools_list(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 200+ tools = r.json()["result"]["tools"]+ names = {t["name"] for t in tools}+ # A representative sampling — these all live in mcp_server/tools/.+ assert {"list_accounts", "list_categories", "list_payees", "aggregate", "list_groups"} <= names+++async def test_mcp_tools_call_missing_name(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {}},+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 200+ assert r.json()["error"]["code"] == -32602+++async def test_mcp_tools_call_unknown_tool(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {"name": "does_not_exist", "arguments": {}},+ },+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 200+ assert r.json()["error"]["code"] == -32601+++async def test_mcp_unknown_method(test_user):+ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "resources/list"},+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 200+ assert r.json()["error"]["code"] == -32601+++async def test_mcp_tools_call_runs_real_tool(test_user, monkeypatch):+ """End-to-end happy path: auth → tools/call → real tool → structured+ JSON response. Uses list_categories because it has no pgvector+ dependency and is safe on SQLite.++ Routes the mcp_server's `async_session_maker` to the conftest test+ DB; otherwise CI's mcp_server points at the real Postgres which has+ no schema in the test environment and the tool raises."""+ from tests.conftest import TestSessionLocal+ import mcp_server.main as mcp_main++ monkeypatch.setattr(mcp_main, "async_session_maker", TestSessionLocal)++ async with _client() as cli:+ r = await cli.post(+ "/mcp",+ json={+ "jsonrpc": "2.0",+ "id": 9,+ "method": "tools/call",+ "params": {"name": "list_categories", "arguments": {}},+ },+ headers=_auth_headers(test_user.id),+ )+ assert r.status_code == 200+ body = r.json()+ result = body["result"]+ assert result["isError"] is False+ # `structuredContent` mirrors the tool's dict return value.+ assert "items" in result["structuredContent"]+ # `content[0].text` is JSON-encoded for clients that prefer text.+ parsed = json.loads(result["content"][0]["text"])+ assert "items" in parseddiff --git a/docker-compose.yml b/docker-compose.ymlindex 82d23792..0b9379d5 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -12,6 +12,26 @@ x-backend-env: &backend-envOPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}STORAGE_LOCAL_PATH: /app/data/attachments+ AGENTS_KNOWLEDGE_STORAGE_PATH: /app/data/agent_knowledge+ # Agents/LLM feature — opt-in. Off by default so existing users pay+ # zero cost. Run `docker compose --profile agents up` after enabling.+ AGENTS_ENABLED: ${AGENTS_ENABLED:-false}+ AGENTS_BUILTIN_MCP_URL: ${AGENTS_BUILTIN_MCP_URL:-http://mcp-server:8765/mcp}+ AGENTS_EXTRA_MCP_SERVERS: ${AGENTS_EXTRA_MCP_SERVERS:-}+ AGENTS_MCP_JWT_SECRET: ${AGENTS_MCP_JWT_SECRET:-dev-mcp-secret-change-in-production}+ # LLM provider config — only the provider you actually use needs setting.+ AGENTS_DEFAULT_PROVIDER: ${AGENTS_DEFAULT_PROVIDER:-ollama}+ AGENTS_DEFAULT_MODEL: ${AGENTS_DEFAULT_MODEL:-}+ AGENTS_OLLAMA_BASE_URL: ${AGENTS_OLLAMA_BASE_URL:-http://ollama:11434}+ AGENTS_OPENAI_API_KEY: ${AGENTS_OPENAI_API_KEY:-}+ AGENTS_ANTHROPIC_API_KEY: ${AGENTS_ANTHROPIC_API_KEY:-}+ AGENTS_OPENAI_COMPAT_BASE_URL: ${AGENTS_OPENAI_COMPAT_BASE_URL:-}+ AGENTS_OPENAI_COMPAT_API_KEY: ${AGENTS_OPENAI_COMPAT_API_KEY:-}+ # Knowledge-base embeddings. `native` (default) uses fastembed with a+ # bundled multilingual model — zero external setup. Override with+ # ollama/openai/openai_compatible for better quality.+ AGENTS_EMBEDDING_PROVIDER: ${AGENTS_EMBEDDING_PROVIDER:-native}+ AGENTS_EMBEDDING_MODEL: ${AGENTS_EMBEDDING_MODEL:-sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2}x-backend-base: &backend-basebuild: ./backend@@ -22,6 +42,8 @@ x-backend-base: &backend-basevolumes:- ./backend:/app- attachments:/app/data/attachments+ - agent_knowledge:/app/data/agent_knowledge+ - agent_embedding_models:/app/data/embedding_modelsrestart: unless-stoppedservices:@@ -34,7 +56,10 @@ services:retries: 5db:- image: postgres:16-alpine+ # pgvector/pgvector:pg16 is a drop-in replacement for postgres:16+ # that ships the `vector` extension. Required for the agents+ # knowledge base; harmless when AGENTS_ENABLED=false.+ image: ${DB_IMAGE:-pgvector/pgvector:pg16}environment:POSTGRES_USER: postgresPOSTGRES_PASSWORD: postgres@@ -81,6 +106,19 @@ services:<<: *backend-basecommand: celery -A app.worker beat --loglevel=info+ # Optional: Securo built-in MCP server. Only starts under the `agents`+ # profile (`docker compose --profile agents up`). Reuses the backend+ # image, just runs a different uvicorn entry point. Modular by design —+ # users not using the agents feature pay zero cost.+ mcp-server:+ <<: *backend-base+ profiles: [agents]+ command: uvicorn mcp_server.main:app --host 0.0.0.0 --port 8765+ expose:+ - "8765"+volumes:pgdata:attachments:+ agent_knowledge:+ agent_embedding_models:diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 2178dc66..c39f1fc7 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -26,9 +26,11 @@"react-dom": "^19.2.0","react-hook-form": "^7.71.2","react-i18next": "^16.5.4",+ "react-markdown": "^10.1.0","react-pluggy-connect": "^2.10.2","react-router-dom": "^7.13.1","recharts": "^3.7.0",+ "remark-gfm": "^4.0.1","sonner": "^2.0.7","tailwind-merge": "^3.5.0","zod": "^4.3.6"@@ -4399,13 +4401,39 @@"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==","license": "MIT"},+ "node_modules/@types/debug": {+ "version": "4.1.13",+ "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",+ "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==",+ "license": "MIT",+ "dependencies": {+ "@types/ms": "*"+ }+ },"node_modules/@types/estree": {"version": "1.0.8","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz","integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",- "dev": true,"license": "MIT"},+ "node_modules/@types/estree-jsx": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/@types/estree-jsx/-/estree-jsx-1.0.5.tgz",+ "integrity": "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "*"+ }+ },+ "node_modules/@types/hast": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },"node_modules/@types/json-schema": {"version": "7.0.15","resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",@@ -4413,6 +4441,21 @@"dev": true,"license": "MIT"},+ "node_modules/@types/mdast": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",+ "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "*"+ }+ },+ "node_modules/@types/ms": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",+ "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",+ "license": "MIT"+ },"node_modules/@types/node": {"version": "24.10.13","resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.13.tgz",@@ -4427,7 +4470,6 @@"version": "19.2.14","resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz","integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",- "devOptional": true,"license": "MIT","dependencies": {"csstype": "^3.2.2"@@ -4450,6 +4492,12 @@"dev": true,"license": "MIT"},+ "node_modules/@types/unist": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",+ "license": "MIT"+ },"node_modules/@types/use-sync-external-store": {"version": "0.0.6","resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",@@ -4758,6 +4806,12 @@"url": "https://opencollective.com/eslint"}},+ "node_modules/@ungap/structured-clone": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz",+ "integrity": "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==",+ "license": "ISC"+ },"node_modules/@vitejs/plugin-react": {"version": "5.1.4","resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.1.4.tgz",@@ -5000,6 +5054,16 @@"proxy-from-env": "^1.1.0"}},+ "node_modules/bail": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",+ "integrity": "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/balanced-match": {"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",@@ -5201,6 +5265,16 @@],"license": "CC-BY-4.0"},+ "node_modules/ccount": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",+ "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/chalk": {"version": "4.1.2","resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",@@ -5218,6 +5292,46 @@"url": "https://github.com/chalk/chalk?sponsor=1"}},+ "node_modules/character-entities": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-html4": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz",+ "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-entities-legacy": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/character-reference-invalid": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/class-variance-authority": {"version": "0.7.1","resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",@@ -5411,6 +5525,16 @@"node": ">= 0.8"}},+ "node_modules/comma-separated-tokens": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/commander": {"version": "14.0.3","resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz",@@ -5575,7 +5699,6 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "devOptional": true,"license": "MIT"},"node_modules/d3-array": {@@ -5723,7 +5846,6 @@"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",- "dev": true,"license": "MIT","dependencies": {"ms": "^2.1.3"@@ -5743,6 +5865,19 @@"integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==","license": "MIT"},+ "node_modules/decode-named-character-reference": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",+ "license": "MIT",+ "dependencies": {+ "character-entities": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/dedent": {"version": "1.7.1","resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.1.tgz",@@ -5837,6 +5972,15 @@"node": ">= 0.8"}},+ "node_modules/dequal": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",@@ -5853,6 +5997,19 @@"integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==","license": "MIT"},+ "node_modules/devlop": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz",+ "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/diff": {"version": "8.0.3","resolved": "https://registry.npmjs.org/diff/-/diff-8.0.3.tgz",@@ -6288,6 +6445,16 @@"node": ">=4.0"}},+ "node_modules/estree-util-is-identifier-name": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz",+ "integrity": "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/esutils": {"version": "2.0.3","resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",@@ -6464,6 +6631,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },"node_modules/fast-deep-equal": {"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",@@ -7021,6 +7194,46 @@"node": ">= 0.4"}},+ "node_modules/hast-util-to-jsx-runtime": {+ "version": "2.3.6",+ "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",+ "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "comma-separated-tokens": "^2.0.0",+ "devlop": "^1.0.0",+ "estree-util-is-identifier-name": "^3.0.0",+ "hast-util-whitespace": "^3.0.0",+ "mdast-util-mdx-expression": "^2.0.0",+ "mdast-util-mdx-jsx": "^3.0.0",+ "mdast-util-mdxjs-esm": "^2.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "style-to-js": "^1.0.0",+ "unist-util-position": "^5.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/hast-util-whitespace": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz",+ "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/headers-polyfill": {"version": "4.0.3","resolved": "https://registry.npmjs.org/headers-polyfill/-/headers-polyfill-4.0.3.tgz",@@ -7064,6 +7277,16 @@"void-elements": "3.1.0"}},+ "node_modules/html-url-attributes": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/http-errors": {"version": "2.0.1","resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",@@ -7220,6 +7443,12 @@"dev": true,"license": "ISC"},+ "node_modules/inline-style-parser": {+ "version": "0.2.7",+ "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",+ "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==",+ "license": "MIT"+ },"node_modules/internmap": {"version": "2.0.3","resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",@@ -7249,6 +7478,30 @@"node": ">= 0.10"}},+ "node_modules/is-alphabetical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/is-alphanumerical": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",+ "license": "MIT",+ "dependencies": {+ "is-alphabetical": "^2.0.0",+ "is-decimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/is-arrayish": {"version": "0.2.1","resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",@@ -7256,6 +7509,16 @@"dev": true,"license": "MIT"},+ "node_modules/is-decimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/is-docker": {"version": "3.0.0","resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz",@@ -7305,6 +7568,16 @@"node": ">=0.10.0"}},+ "node_modules/is-hexadecimal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/is-in-ssh": {"version": "1.0.0","resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz",@@ -7384,7 +7657,6 @@"version": "4.1.0","resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz","integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",- "dev": true,"license": "MIT","engines": {"node": ">=12"@@ -7944,6 +8216,16 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/longest-streak": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz",+ "integrity": "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/lru-cache": {"version": "5.1.1","resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",@@ -7973,6 +8255,16 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/markdown-table": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/math-intrinsics": {"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",@@ -7982,101 +8274,946 @@"node": ">= 0.4"}},- "node_modules/media-typer": {- "version": "1.1.0",- "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",- "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",- "dev": true,+ "node_modules/mdast-util-find-and-replace": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz",+ "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==","license": "MIT",- "engines": {- "node": ">= 0.8"+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "escape-string-regexp": "^5.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"}},- "node_modules/merge-descriptors": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",- "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",- "dev": true,+ "node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==","license": "MIT","engines": {- "node": ">=18"+ "node": ">=12"},"funding": {"url": "https://github.com/sponsors/sindresorhus"}},- "node_modules/merge-stream": {- "version": "2.0.0",- "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",- "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",- "dev": true,- "license": "MIT"- },- "node_modules/merge2": {- "version": "1.4.1",- "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",- "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",- "dev": true,+ "node_modules/mdast-util-from-markdown": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz",+ "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==","license": "MIT",- "engines": {- "node": ">= 8"+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark": "^4.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"}},- "node_modules/micromatch": {- "version": "4.0.8",- "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",- "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",- "dev": true,+ "node_modules/mdast-util-gfm": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==","license": "MIT","dependencies": {- "braces": "^3.0.3",- "picomatch": "^2.3.1"+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-gfm-autolink-literal": "^2.0.0",+ "mdast-util-gfm-footnote": "^2.0.0",+ "mdast-util-gfm-strikethrough": "^2.0.0",+ "mdast-util-gfm-table": "^2.0.0",+ "mdast-util-gfm-task-list-item": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"},- "engines": {- "node": ">=8.6"+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"}},- "node_modules/micromatch/node_modules/picomatch": {- "version": "2.3.1",- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",- "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",- "dev": true,+ "node_modules/mdast-util-gfm-autolink-literal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==","license": "MIT",- "engines": {- "node": ">=8.6"+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.0.0",+ "mdast-util-find-and-replace": "^3.0.0",+ "micromark-util-character": "^2.0.0"},"funding": {- "url": "https://github.com/sponsors/jonschlinkert"+ "type": "opencollective",+ "url": "https://opencollective.com/unified"}},- "node_modules/mime-db": {- "version": "1.52.0",- "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",- "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "node_modules/mdast-util-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==","license": "MIT",- "engines": {- "node": ">= 0.6"+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"}},- "node_modules/mime-types": {- "version": "2.1.35",- "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",- "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "node_modules/mdast-util-gfm-strikethrough": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz",+ "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==","license": "MIT","dependencies": {- "mime-db": "1.52.0"+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"},- "engines": {- "node": ">= 0.6"+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"}},- "node_modules/mimic-fn": {- "version": "2.1.0",- "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",- "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",- "dev": true,+ "node_modules/mdast-util-gfm-table": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==","license": "MIT",- "engines": {+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "markdown-table": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-task-list-item": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-expression": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",+ "integrity": "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdx-jsx": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz",+ "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "parse-entities": "^4.0.0",+ "stringify-entities": "^4.0.0",+ "unist-util-stringify-position": "^4.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-mdxjs-esm": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-mdxjs-esm/-/mdast-util-mdxjs-esm-2.0.1.tgz",+ "integrity": "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==",+ "license": "MIT",+ "dependencies": {+ "@types/estree-jsx": "^1.0.0",+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-phrasing": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-phrasing/-/mdast-util-phrasing-4.1.0.tgz",+ "integrity": "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-hast": {+ "version": "13.2.1",+ "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",+ "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "@ungap/structured-clone": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "trim-lines": "^3.0.0",+ "unist-util-position": "^5.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-markdown": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz",+ "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "@types/unist": "^3.0.0",+ "longest-streak": "^3.0.0",+ "mdast-util-phrasing": "^4.0.0",+ "mdast-util-to-string": "^4.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-decode-string": "^2.0.0",+ "unist-util-visit": "^5.0.0",+ "zwitch": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-to-string": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-4.0.0.tgz",+ "integrity": "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/media-typer": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/merge-stream": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",+ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/merge2": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",+ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/micromark": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",+ "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@types/debug": "^4.0.0",+ "debug": "^4.0.0",+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-core-commonmark": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz",+ "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "devlop": "^1.0.0",+ "micromark-factory-destination": "^2.0.0",+ "micromark-factory-label": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-factory-title": "^2.0.0",+ "micromark-factory-whitespace": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-html-tag-name": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-subtokenize": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-extension-gfm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",+ "license": "MIT",+ "dependencies": {+ "micromark-extension-gfm-autolink-literal": "^2.0.0",+ "micromark-extension-gfm-footnote": "^2.0.0",+ "micromark-extension-gfm-strikethrough": "^2.0.0",+ "micromark-extension-gfm-table": "^2.0.0",+ "micromark-extension-gfm-tagfilter": "^2.0.0",+ "micromark-extension-gfm-task-list-item": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-autolink-literal": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-strikethrough": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-table": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.1.tgz",+ "integrity": "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-tagfilter": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-task-list-item": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-factory-destination": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",+ "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-label": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz",+ "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-space": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz",+ "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-title": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz",+ "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-factory-whitespace": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz",+ "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-character": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz",+ "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-chunked": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz",+ "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-classify-character": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz",+ "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-combine-extensions": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz",+ "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-numeric-character-reference": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz",+ "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-decode-string": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-2.0.1.tgz",+ "integrity": "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "decode-named-character-reference": "^1.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-decode-numeric-character-reference": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-encode": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz",+ "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-html-tag-name": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz",+ "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-normalize-identifier": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz",+ "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-resolve-all": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz",+ "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-sanitize-uri": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz",+ "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-encode": "^2.0.0",+ "micromark-util-symbol": "^2.0.0"+ }+ },+ "node_modules/micromark-util-subtokenize": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz",+ "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ }+ },+ "node_modules/micromark-util-symbol": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz",+ "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromark-util-types": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz",+ "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==",+ "funding": [+ {+ "type": "GitHub Sponsors",+ "url": "https://github.com/sponsors/unifiedjs"+ },+ {+ "type": "OpenCollective",+ "url": "https://opencollective.com/unified"+ }+ ],+ "license": "MIT"+ },+ "node_modules/micromatch": {+ "version": "4.0.8",+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "braces": "^3.0.3",+ "picomatch": "^2.3.1"+ },+ "engines": {+ "node": ">=8.6"+ }+ },+ "node_modules/micromatch/node_modules/picomatch": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",+ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=8.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mimic-fn": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",+ "dev": true,+ "license": "MIT",+ "engines": {"node": ">=6"}},@@ -8120,7 +9257,6 @@"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",- "dev": true,"license": "MIT"},"node_modules/msw": {@@ -8515,6 +9651,31 @@"node": ">=6"}},+ "node_modules/parse-entities": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^2.0.0",+ "character-entities-legacy": "^3.0.0",+ "character-reference-invalid": "^2.0.0",+ "decode-named-character-reference": "^1.0.0",+ "is-alphanumerical": "^2.0.0",+ "is-decimal": "^2.0.0",+ "is-hexadecimal": "^2.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/parse-entities/node_modules/@types/unist": {+ "version": "2.0.11",+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",+ "license": "MIT"+ },"node_modules/parse-json": {"version": "5.2.0","resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",@@ -8769,6 +9930,16 @@"node": ">=6"}},+ "node_modules/property-information": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/proxy-addr": {"version": "2.0.7","resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",@@ -9019,6 +10190,33 @@"license": "MIT","peer": true},+ "node_modules/react-markdown": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "hast-util-to-jsx-runtime": "^2.0.0",+ "html-url-attributes": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.0.0",+ "unified": "^11.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "@types/react": ">=18",+ "react": ">=18"+ }+ },"node_modules/react-pluggy-connect": {"version": "2.12.0","resolved": "https://registry.npmjs.org/react-pluggy-connect/-/react-pluggy-connect-2.12.0.tgz",@@ -9240,6 +10438,72 @@"redux": "^5.0.0"}},+ "node_modules/remark-gfm": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-gfm": "^3.0.0",+ "micromark-extension-gfm": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-parse": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",+ "integrity": "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "micromark-util-types": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-rehype": {+ "version": "11.1.2",+ "resolved": "https://registry.npmjs.org/remark-rehype/-/remark-rehype-11.1.2.tgz",+ "integrity": "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "unified": "^11.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/remark-stringify": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/require-directory": {"version": "2.1.1","resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",@@ -9737,6 +11001,16 @@"node": ">=0.10.0"}},+ "node_modules/space-separated-tokens": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/statuses": {"version": "2.0.2","resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",@@ -9785,6 +11059,20 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/stringify-entities": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",+ "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==",+ "license": "MIT",+ "dependencies": {+ "character-entities-html4": "^2.0.0",+ "character-entities-legacy": "^3.0.0"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/stringify-object": {"version": "5.0.0","resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-5.0.0.tgz",@@ -9855,6 +11143,24 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/style-to-js": {+ "version": "1.1.21",+ "resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",+ "integrity": "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==",+ "license": "MIT",+ "dependencies": {+ "style-to-object": "1.0.14"+ }+ },+ "node_modules/style-to-object": {+ "version": "1.0.14",+ "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz",+ "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==",+ "license": "MIT",+ "dependencies": {+ "inline-style-parser": "0.2.7"+ }+ },"node_modules/supports-color": {"version": "7.2.0","resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",@@ -10001,6 +11307,26 @@"node": ">=16"}},+ "node_modules/trim-lines": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",+ "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },+ "node_modules/trough": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/trough/-/trough-2.2.0.tgz",+ "integrity": "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/ts-api-utils": {"version": "2.4.0","resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz",@@ -10185,6 +11511,93 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/unified": {+ "version": "11.0.5",+ "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",+ "integrity": "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "bail": "^2.0.0",+ "devlop": "^1.0.0",+ "extend": "^3.0.0",+ "is-plain-obj": "^4.0.0",+ "trough": "^2.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-is": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz",+ "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-position": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz",+ "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-stringify-position": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz",+ "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit": {+ "version": "5.1.0",+ "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz",+ "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/unist-util-visit-parents": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz",+ "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/universal-serialize": {"version": "1.0.10","resolved": "https://registry.npmjs.org/universal-serialize/-/universal-serialize-1.0.10.tgz",@@ -10340,6 +11753,34 @@"node": ">= 0.8"}},+ "node_modules/vfile": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",+ "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "vfile-message": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/vfile-message": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz",+ "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-stringify-position": "^4.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/victory-vendor": {"version": "37.3.6","resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz",@@ -10743,6 +12184,16 @@"post-robot": "^10","zalgo-promise": "^1.0.45"}+ },+ "node_modules/zwitch": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",+ "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }}}}diff --git a/frontend/package.json b/frontend/package.jsonindex 9342cdaf..385fd12c 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -29,9 +29,11 @@"react-dom": "^19.2.0","react-hook-form": "^7.71.2","react-i18next": "^16.5.4",+ "react-markdown": "^10.1.0","react-pluggy-connect": "^2.10.2","react-router-dom": "^7.13.1","recharts": "^3.7.0",+ "remark-gfm": "^4.0.1","sonner": "^2.0.7","tailwind-merge": "^3.5.0","zod": "^4.3.6"diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex de39b638..3be06da1 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -6,6 +6,7 @@ import { ThemeProvider } from '@/components/theme-provider'import { AuthProvider } from '@/contexts/auth-context'import { ProtectedRoute } from '@/components/protected-route'import { AdminRoute } from '@/components/admin-route'+import { AgentsRoute } from '@/components/agents-route'import { AppLayout } from '@/components/app-layout'const SetupPage = lazy(() => import('@/pages/setup'))@@ -27,6 +28,9 @@ const PayeesPage = lazy(() => import('@/pages/payees'))const GroupsPage = lazy(() => import('@/pages/groups'))const GroupDetailPage = lazy(() => import('@/pages/group-detail'))const AdminSettingsPage = lazy(() => import('@/pages/admin/settings'))+const AgentsListPage = lazy(() => import('@/pages/agents-list'))+const AgentDetailPage = lazy(() => import('@/pages/agent-detail'))+const AgentConnectionsPage = lazy(() => import('@/pages/agent-connections'))const queryClient = new QueryClient({defaultOptions: {@@ -79,6 +83,9 @@ function App() {<Route path="/groups" element={<GroupsPage />} /><Route path="/groups/:id" element={<GroupDetailPage />} /><Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} />+ <Route path="/agents" element={<AgentsRoute><AgentsListPage /></AgentsRoute>} />+ <Route path="/agents/connections" element={<AgentsRoute><AgentConnectionsPage /></AgentsRoute>} />+ <Route path="/agents/:id" element={<AgentsRoute><AgentDetailPage /></AgentsRoute>} /></Route></Routes></Suspense>diff --git a/frontend/src/components/agents-route.tsx b/frontend/src/components/agents-route.tsxnew file mode 100644index 00000000..39f82f46--- /dev/null+++ b/frontend/src/components/agents-route.tsx@@ -0,0 +1,19 @@+import { Navigate } from 'react-router-dom'+import { useFeatureFlags } from '@/hooks/use-feature-flags'++/** Wraps every /agents/* page so navigating directly to the URL when+ * AGENTS_ENABLED is false on the server kicks the user back to home+ * instead of rendering a broken management page that would 404 on+ * every API call. Mirrors AdminRoute's pattern. */+export function AgentsRoute({ children }: { children: React.ReactNode }) {+ const { agentsEnabled, isLoading } = useFeatureFlags()+ if (isLoading) {+ return (+ <div className="flex items-center justify-center min-h-screen">+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />+ </div>+ )+ }+ if (!agentsEnabled) return <Navigate to="/" replace />+ return <>{children}</>+}diff --git a/frontend/src/components/agents/agent-chart.tsx b/frontend/src/components/agents/agent-chart.tsxnew file mode 100644index 00000000..49d681d0--- /dev/null+++ b/frontend/src/components/agents/agent-chart.tsx@@ -0,0 +1,283 @@+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import {+ Area,+ AreaChart,+ Bar,+ BarChart,+ CartesianGrid,+ Cell,+ Legend,+ Line,+ LineChart,+ Pie,+ PieChart,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from 'recharts'+import { formatCurrency } from '@/lib/format'++/**+ * In-chat chart, rendered when an assistant message contains a fenced+ * code block tagged `securo-chart`. The body is JSON in this shape:+ *+ * { type: "line"|"bar"|"area"|"pie", title?, currency?, data, series? }+ *+ * Multi-series example:+ * {+ * "type": "line",+ * "title": "Income vs expenses",+ * "currency": "BRL",+ * "data": [{"x":"Jan","income":3000,"expense":1800}, ...],+ * "series": [+ * {"key":"income","name":"Income","color":"#10B981"},+ * {"key":"expense","name":"Expense","color":"#F43F5E"}+ * ]+ * }+ *+ * Single-series shorthand (no `series` array, default key is `y`):+ * { "type":"bar", "data":[{"x":"Food","y":500},{"x":"Rent","y":1200}] }+ *+ * Pie:+ * { "type":"pie", "data":[{"name":"Food","value":500},{"name":"Rent","value":1200}] }+ */++// Same palette as reports.tsx so chats look like the rest of the app.+const PALETTE = [+ '#6366F1', // indigo+ '#10B981', // emerald+ '#F59E0B', // amber+ '#F43F5E', // rose+ '#8B5CF6', // violet+ '#06B6D4', // cyan+ '#EC4899', // pink+ '#84CC16', // lime+]++type ChartType = 'line' | 'bar' | 'area' | 'pie'++interface SeriesSpec {+ key: string+ name?: string+ color?: string+}++export interface ChartSpec {+ type: ChartType+ title?: string+ subtitle?: string+ currency?: string+ x_label?: string+ y_label?: string+ data: Record<string, unknown>[]+ series?: SeriesSpec[]+}++interface Props {+ spec: ChartSpec+}++const tooltipStyle: React.CSSProperties = {+ backgroundColor: 'var(--popover)',+ color: 'var(--popover-foreground)',+ border: '1px solid var(--border)',+ borderRadius: 6,+ fontSize: 12,+}++function formatY(v: number | string | undefined | null, currency?: string): string {+ if (v == null) return ''+ if (typeof v === 'string') return v+ if (currency) return formatCurrency(v, currency, undefined)+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(v)+}++/**+ * Compact axis labels — "R$100K", "R$1.2M", "12K" — so big numbers+ * actually fit in the axis gutter. Tooltips still get the full+ * precision via formatY().+ */+function formatYAxis(v: number | string | undefined | null, currency?: string): string {+ if (v == null) return ''+ if (typeof v === 'string') return v+ if (Math.abs(v) < 1000) {+ if (currency) {+ try {+ return new Intl.NumberFormat(undefined, {+ style: 'currency',+ currency,+ minimumFractionDigits: 0,+ maximumFractionDigits: 0,+ }).format(v)+ } catch {+ return `${currency} ${v.toFixed(0)}`+ }+ }+ return new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(v)+ }+ if (currency) {+ try {+ return new Intl.NumberFormat(undefined, {+ style: 'currency',+ currency,+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(v)+ } catch {+ return `${currency} ${v}`+ }+ }+ return new Intl.NumberFormat(undefined, {+ notation: 'compact',+ maximumFractionDigits: 1,+ }).format(v)+}++function AgentChartImpl({ spec }: Props) {+ const { t } = useTranslation()+ if (!spec || !Array.isArray(spec.data) || spec.data.length === 0) {+ return (+ <div className="my-3 rounded-md border border-dashed border-border px-3 py-4 text-xs text-muted-foreground text-center">+ {t('agents.chart.noData')}+ </div>+ )+ }++ const series: SeriesSpec[] =+ spec.series && spec.series.length > 0+ ? spec.series+ : [{ key: 'y' }]++ const seriesWithColor = series.map((s, i) => ({ ...s, color: s.color || PALETTE[i % PALETTE.length] }))++ return (+ <figure className="my-3 rounded-lg border border-border bg-card overflow-hidden">+ {(spec.title || spec.subtitle) && (+ <figcaption className="px-3 py-2 border-b border-border">+ {spec.title && <div className="text-sm font-semibold">{spec.title}</div>}+ {spec.subtitle && <div className="text-xs text-muted-foreground mt-0.5">{spec.subtitle}</div>}+ </figcaption>+ )}+ <div className="h-[260px] px-2 pt-3 pb-2">+ <ResponsiveContainer width="100%" height="100%">+ {renderChart(spec.type, spec.data, seriesWithColor, spec.currency)}+ </ResponsiveContainer>+ </div>+ </figure>+ )+}++type ResolvedSeries = { key: string; name?: string; color: string }++function renderChart(+ type: ChartType,+ data: Record<string, unknown>[],+ series: ResolvedSeries[],+ currency?: string,+) {+ if (type === 'pie') {+ // Pie expects { name, value } shape. Map a friendly fallback.+ const items = data.map((d, i) => ({+ name: String(d.name ?? d.x ?? d.label ?? `Slice ${i + 1}`),+ value: Number(d.value ?? d.y ?? 0),+ }))+ return (+ <PieChart>+ <Pie+ data={items}+ dataKey="value"+ nameKey="name"+ outerRadius={90}+ innerRadius={48}+ paddingAngle={1}+ stroke="var(--background)"+ strokeWidth={1.5}+ >+ {items.map((_, i) => (+ <Cell key={i} fill={PALETTE[i % PALETTE.length]} />+ ))}+ </Pie>+ <Tooltip+ contentStyle={tooltipStyle}+ formatter={(v) => formatY(v as number | string | undefined, currency)}+ />+ <Legend wrapperStyle={{ fontSize: 11 }} />+ </PieChart>+ )+ }++ const ChartCmp = type === 'bar' ? BarChart : type === 'area' ? AreaChart : LineChart++ return (+ <ChartCmp data={data} margin={{ top: 4, right: 12, left: 0, bottom: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />+ <XAxis+ dataKey="x"+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}+ axisLine={false}+ tickLine={false}+ interval="preserveStartEnd"+ />+ <YAxis+ tickFormatter={(v) => formatYAxis(v, currency)}+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}+ axisLine={false}+ tickLine={false}+ width={56}+ tickCount={5}+ />+ <Tooltip+ contentStyle={tooltipStyle}+ formatter={(v, name) => [formatY(v as number | string | undefined, currency), String(name ?? '')]}+ />+ {series.length > 1 && <Legend wrapperStyle={{ fontSize: 11 }} />}+ {series.map((s) => {+ const common = {+ key: s.key,+ dataKey: s.key,+ name: s.name || s.key,+ stroke: s.color,+ }+ if (type === 'bar') {+ return <Bar key={s.key} dataKey={s.key} name={s.name || s.key} fill={s.color} radius={[4, 4, 0, 0]} />+ }+ if (type === 'area') {+ return (+ <Area+ {...common}+ type="monotone"+ fill={s.color}+ fillOpacity={0.18}+ strokeWidth={2}+ dot={false}+ activeDot={{ r: 3 }}+ />+ )+ }+ // line+ return (+ <Line+ {...common}+ type="monotone"+ strokeWidth={2}+ dot={false}+ activeDot={{ r: 3 }}+ />+ )+ })}+ </ChartCmp>+ )+}++/** Memoized export. The whole reason this exists: every keystroke in+ * the chat textarea triggers a parent re-render, and Recharts treats+ * any new prop reference as new data — reanimating slices and bars.+ * We compare specs by serialized string (cheap; specs are tiny JSON+ * blobs the LLM emitted once) so a re-render with the same spec is a+ * no-op. */+export const AgentChart = memo(+ AgentChartImpl,+ (prev, next) => JSON.stringify(prev.spec) === JSON.stringify(next.spec),+)diff --git a/frontend/src/components/agents/agent-form-dialog.tsx b/frontend/src/components/agents/agent-form-dialog.tsxnew file mode 100644index 00000000..1e8ea3d5--- /dev/null+++ b/frontend/src/components/agents/agent-form-dialog.tsx@@ -0,0 +1,271 @@+import { useEffect, useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { Link } from 'react-router-dom'+import { ArrowRight, Plug, Settings2 } from 'lucide-react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { Switch } from '@/components/ui/switch'+import { agents } from '@/lib/api'+import type { Agent } from '@/lib/api'++interface Props {+ open: boolean+ onOpenChange: (open: boolean) => void+ agent?: Agent | null+ providers: string[]+}++export function AgentFormDialog({ open, onOpenChange, agent }: Props) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const isEdit = !!agent+ const [name, setName] = useState('')+ const [description, setDescription] = useState('')+ const [systemPrompt, setSystemPrompt] = useState('')+ // Empty string = nothing picked yet. Required to submit; we no+ // longer support an "instance default" sentinel because there is no+ // such thing — a connection is what tells the agent how to reach an+ // LLM.+ const [connectionId, setConnectionId] = useState<string>('')+ const [model, setModel] = useState('')+ const [temperature, setTemperature] = useState('0.4')+ const [autoContext, setAutoContext] = useState(true)+ const [isDefault, setIsDefault] = useState(false)++ const { data: connections } = useQuery({+ queryKey: ['agent-connections'],+ queryFn: () => agents.connections.list(),+ enabled: open,+ })++ useEffect(() => {+ if (agent) {+ setName(agent.name)+ setDescription(agent.description ?? '')+ setSystemPrompt(agent.system_prompt ?? '')+ setConnectionId(agent.connection_id ?? '')+ setModel(agent.model ?? '')+ setTemperature(String(agent.temperature ?? 0.4))+ setAutoContext(agent.auto_context ?? true)+ setIsDefault(agent.is_default ?? false)+ } else {+ setName('')+ setDescription('')+ setSystemPrompt('')+ // Pre-select the user's default connection (or the only one,+ // if there's just one) so the form is one click closer to done.+ setConnectionId('')+ setModel('')+ setTemperature('0.4')+ setAutoContext(true)+ setIsDefault(false)+ }+ }, [agent, open])++ // When connections load (or the dialog opens), pre-select the most+ // sensible default: the user-flagged default connection, or the only+ // one if there's a single connection.+ useEffect(() => {+ if (!open || isEdit || connectionId) return+ if (!connections || connections.length === 0) return+ const def = connections.find((c) => c.is_default)+ setConnectionId(def?.id ?? connections[0].id)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, connections])++ const selectedConnection = connections?.find((c) => c.id === connectionId)++ const saveMut = useMutation({+ mutationFn: (payload: Partial<Agent> & { name: string }) =>+ isEdit && agent ? agents.update(agent.id, payload) : agents.create(payload),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agents'] })+ onOpenChange(false)+ toast.success(isEdit ? t('agents.form.updated') : t('agents.form.created'))+ },+ onError: (err: unknown) => {+ const message = (err as { message?: string })?.message ?? t('agents.form.saveFailed')+ toast.error(message)+ },+ })++ const submit = () => {+ if (!name.trim()) {+ toast.error(t('agents.form.nameRequired'))+ return+ }+ if (!connectionId) {+ toast.error(t('agents.form.connectionRequired', 'Pick a connection — agents need one to talk to an LLM.'))+ return+ }+ saveMut.mutate({+ name: name.trim(),+ description: description.trim() || null,+ system_prompt: systemPrompt,+ connection_id: connectionId,+ model: model.trim() || null,+ temperature: Number(temperature) || 0.4,+ auto_context: autoContext,+ is_default: isDefault,+ })+ }++ const noConnections = connections !== undefined && connections.length === 0++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-xl">+ <DialogHeader>+ <DialogTitle>{isEdit ? t('agents.form.editTitle') : t('agents.form.createTitle')}</DialogTitle>+ </DialogHeader>+ <div className="grid gap-4 py-2">+ <div className="grid gap-2">+ <Label htmlFor="agent-name">{t('agents.form.name')}</Label>+ <Input id="agent-name" value={name} onChange={(e) => setName(e.target.value)} placeholder={t('agents.form.namePlaceholder')} />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="agent-desc">{t('agents.form.description')}</Label>+ <Input+ id="agent-desc"+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ placeholder={t('agents.form.descriptionPlaceholder')}+ />+ </div>+ <div className="grid gap-2">+ <Label htmlFor="agent-prompt">{t('agents.form.systemPrompt')}</Label>+ <textarea+ id="agent-prompt"+ value={systemPrompt}+ onChange={(e) => setSystemPrompt(e.target.value)}+ rows={6}+ className="rounded-md border bg-background px-3 py-2 text-sm font-mono"+ placeholder={t('agents.form.systemPromptPlaceholder')}+ />+ </div>+ {noConnections ? (+ // No connections at all → block the create flow with a+ // useful CTA. Otherwise the user fills out the form and+ // gets a confusing error when they hit "create".+ <div className="rounded-md border border-dashed p-4 flex items-start gap-3">+ <Plug className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="text-sm font-medium">+ {t('agents.form.needConnectionTitle', 'Add an LLM connection first')}+ </div>+ <p className="text-xs text-muted-foreground mt-0.5">+ {t(+ 'agents.form.needConnectionHint',+ 'An agent needs a connection (OpenAI, Anthropic, Ollama, …) to talk to a model. Set one up, then come back here.',+ )}+ </p>+ <Link+ to="/agents/connections"+ onClick={() => onOpenChange(false)}+ className="inline-flex items-center gap-1 mt-2 text-xs font-medium text-primary hover:underline"+ >+ {t('agents.form.goToConnections', 'Go to connections')}+ <ArrowRight className="h-3 w-3" />+ </Link>+ </div>+ </div>+ ) : (+ <div className="grid grid-cols-[1fr_1fr] gap-3">+ <div className="grid gap-2">+ <div className="flex items-center justify-between">+ <Label>{t('agents.form.connection')}</Label>+ <Link+ to="/agents/connections"+ className="text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1"+ onClick={() => onOpenChange(false)}+ >+ <Settings2 className="h-3 w-3" />+ {t('agents.form.manageConnections')}+ </Link>+ </div>+ <Select value={connectionId} onValueChange={setConnectionId}>+ <SelectTrigger>+ <SelectValue placeholder={t('agents.form.connectionPlaceholder', 'Pick a connection')} />+ </SelectTrigger>+ <SelectContent>+ {(connections ?? []).map((c) => (+ <SelectItem key={c.id} value={c.id}>+ {c.name} <span className="text-muted-foreground ml-1">({c.kind})</span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="grid gap-2">+ <Label htmlFor="agent-model">{t('agents.form.model')}</Label>+ <Input+ id="agent-model"+ value={model}+ onChange={(e) => setModel(e.target.value)}+ placeholder={selectedConnection?.default_model || t('agents.form.modelPlaceholder')}+ />+ {!model && selectedConnection?.default_model && (+ <p className="text-xs text-muted-foreground">{t('agents.form.willUseConnectionDefault', { model: selectedConnection.default_model })}</p>+ )}+ </div>+ </div>+ )}+ <div className="grid gap-2 max-w-[160px]">+ <Label htmlFor="agent-temp">{t('agents.form.temperature')}</Label>+ <Input+ id="agent-temp"+ type="number"+ step="0.05"+ min="0"+ max="2"+ value={temperature}+ onChange={(e) => setTemperature(e.target.value)}+ />+ </div>+ <div className="rounded-md border p-3 flex items-start gap-3">+ <Switch checked={autoContext} onCheckedChange={(v) => setAutoContext(!!v)} />+ <div className="min-w-0 flex-1">+ <Label className="cursor-pointer" onClick={() => setAutoContext(!autoContext)}>+ {t('agents.form.autoContext')}+ </Label>+ <p className="text-xs text-muted-foreground mt-0.5">{t('agents.form.autoContextHint')}</p>+ </div>+ </div>+ <div className="rounded-md border p-3 flex items-start gap-3">+ <Switch checked={isDefault} onCheckedChange={(v) => setIsDefault(!!v)} />+ <div className="min-w-0 flex-1">+ <Label className="cursor-pointer" onClick={() => setIsDefault(!isDefault)}>+ {t('agents.form.isDefault', 'Default agent')}+ </Label>+ <p className="text-xs text-muted-foreground mt-0.5">+ {t(+ 'agents.form.isDefaultHint',+ 'Used by the global slide-over chat (⌘J). Only one agent can be the default — turning this on clears it on others.',+ )}+ </p>+ </div>+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('agents.form.cancel')}+ </Button>+ <Button onClick={submit} disabled={saveMut.isPending || noConnections || !connectionId}>+ {saveMut.isPending ? t('agents.form.saving') : isEdit ? t('agents.form.save') : t('agents.form.create')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/components/agents/chat-panel.tsx b/frontend/src/components/agents/chat-panel.tsxnew file mode 100644index 00000000..f34caa17--- /dev/null+++ b/frontend/src/components/agents/chat-panel.tsx@@ -0,0 +1,500 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { ShellLogo } from '@/components/shell-logo'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { Loader2, Send, Sparkles, AlertCircle } from 'lucide-react'+import { Button } from '@/components/ui/button'+import { agents } from '@/lib/api'+import type { Agent, AgentMessage } from '@/lib/api'+import { streamChat, type AgentStreamEvent } from '@/lib/agents-stream'+import { Markdown } from '@/components/agents/markdown'+import { ToolDebugChip } from '@/components/agents/tool-debug-chip'+import { ProposalCard, isProposalData, isProposalToolName } from '@/components/agents/proposal-card'++interface Props {+ agent: Agent+ conversationId: string | null+ onConversationCreated: (id: string) => void+ // Bumped by the parent on every sidebar interaction (new + select an+ // already-active conversation). Lets the chat input refocus even when+ // conversationId itself doesn't change.+ focusSignal?: number+ // Optional snapshot of the current page (route, label, filters,+ // selection). Forwarded as `page_context` on every streamChat call so+ // the agent can reason about "this row" / "the filters above".+ // Re-read on each send so we always pick up the latest state.+ getPageContext?: () => Record<string, unknown> | null+}++interface DraftMessage {+ id: string+ role: 'user' | 'assistant'+ text: string+ tools: { name: string; args: Record<string, unknown>; result?: { ok?: boolean; data?: unknown; text?: string | null } }[]+ error?: string+ pending?: boolean+}++export function ChatPanel({ agent, conversationId, onConversationCreated, focusSignal, getPageContext }: Props) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const [input, setInput] = useState('')+ const [streaming, setStreaming] = useState(false)+ const [draft, setDraft] = useState<DraftMessage | null>(null) // assistant turn currently being streamed+ const [pendingUser, setPendingUser] = useState<DraftMessage | null>(null) // user msg shown immediately+ // Last error from a chat round, kept after streaming ends so the user+ // can actually see what went wrong. Cleared when they send a new message.+ const [lastError, setLastError] = useState<string | null>(null)+ const scrollRef = useRef<HTMLDivElement>(null)+ const inputRef = useRef<HTMLTextAreaElement>(null)+ // Whether the user is "pinned" to the bottom of the scroll area. We+ // only auto-scroll while pinned — if the user scrolls up to read,+ // streaming deltas no longer yank them back down.+ const isAtBottomRef = useRef(true)++ const { data: history } = useQuery({+ queryKey: ['agent-conv-messages', conversationId],+ queryFn: () => (conversationId ? agents.conversations.messages(conversationId) : Promise.resolve([])),+ enabled: !!conversationId,+ staleTime: 1000 * 5,+ })++ // Snap to bottom when the conversation switches (it should look fresh)+ // and move keyboard focus to the input — covers both "+" (null) and+ // selecting an existing conversation. focusSignal also triggers focus+ // when the user clicks "+" while already on a null conversation.+ useEffect(() => {+ if (scrollRef.current) {+ isAtBottomRef.current = true+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight+ }+ inputRef.current?.focus()+ }, [conversationId, focusSignal])++ // Clear any stale optimistic draft when the conversation prop changes+ // for a reason OTHER than the in-flight stream getting its id assigned+ // (i.e. user picked a different thread from history, or hit "+"). We+ // detect "stream is mid-flight" via the `streaming` flag — during that+ // window the conversationId may legitimately go from null → real, and+ // we don't want to wipe the loading bubble. Once the stream finishes,+ // the existing finally{} clears the draft anyway.+ useEffect(() => {+ if (!streaming) {+ setDraft(null)+ setPendingUser(null)+ setLastError(null)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [conversationId])++ // Reset the textarea's inline height when the input is cleared (after+ // send, on conversation change, etc.) — onChange's auto-grow leaves+ // an explicit `style.height` behind that won't shrink on its own.+ useEffect(() => {+ if (input === '' && inputRef.current) {+ inputRef.current.style.height = ''+ }+ }, [input])++ // While streaming or new content arrives, only follow if pinned.+ useEffect(() => {+ if (!scrollRef.current) return+ if (isAtBottomRef.current) {+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight+ }+ }, [history, draft, pendingUser])++ const handleScroll = () => {+ const el = scrollRef.current+ if (!el) return+ // 80px tolerance — close enough to count as "at the bottom".+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight+ isAtBottomRef.current = distance < 80+ }++ const send = async () => {+ const trimmed = input.trim()+ if (!trimmed || streaming) return+ setInput('')+ setLastError(null)+ setStreaming(true)+ // User just took an action — they want to see the response.+ isAtBottomRef.current = true+ let errorThisTurn: string | null = null+ // Track the active conversation id locally — the React state for it+ // updates asynchronously, so a closure over `conversationId` still+ // sees the value at the start of send() and would invalidate the+ // wrong query key on a brand-new conversation.+ let activeConvId = conversationId+ // Remember whether this round started a fresh conversation, so we+ // can ask the backend to generate a real title from the LLM after+ // streaming completes successfully.+ const startedFresh = !conversationId+ const localId = crypto.randomUUID()+ setPendingUser({ id: 'pending-user-' + localId, role: 'user', text: trimmed, tools: [] })+ setDraft({ id: 'draft-' + localId, role: 'assistant', text: '', tools: [], pending: true })+ try {+ await streamChat({+ agentId: agent.id,+ content: trimmed,+ conversationId,+ pageContext: getPageContext?.() ?? null,+ onEvent: (ev: AgentStreamEvent) => {+ if (ev.kind === 'conversation') {+ activeConvId = ev.conversation_id+ if (!conversationId) onConversationCreated(ev.conversation_id)+ return+ }+ if (ev.kind === 'text_delta') {+ setDraft((d) => (d ? { ...d, text: d.text + ev.text } : d))+ } else if (ev.kind === 'tool_call') {+ setDraft((d) => (d ? { ...d, tools: [...d.tools, { name: ev.tool_name, args: ev.tool_args }] } : d))+ } else if (ev.kind === 'tool_result') {+ setDraft((d) => {+ if (!d) return d+ const idx = d.tools.findIndex((t) => t.name === ev.tool_name && !t.result)+ if (idx === -1) return d+ const copy = [...d.tools]+ copy[idx] = { ...copy[idx], result: ev.tool_result }+ return { ...d, tools: copy }+ })+ } else if (ev.kind === 'error') {+ errorThisTurn = `${ev.error_code || 'error'}: ${ev.error_message || ''}`+ setDraft((d) => (d ? { ...d, error: errorThisTurn || undefined } : d))+ } else if (ev.kind === 'done') {+ setDraft((d) => (d ? { ...d, pending: false } : d))+ }+ },+ })+ } catch (err) {+ errorThisTurn = String(err)+ setDraft((d) => (d ? { ...d, error: String(err) } : d))+ } finally {+ setStreaming(false)+ // Pull the persisted turn for the conversation we actually wrote+ // to. refetchQueries waits for the data to come back; only THEN do+ // we clear the optimistic draft so the user never sees a blank gap.+ if (activeConvId) {+ try {+ await qc.refetchQueries({ queryKey: ['agent-conv-messages', activeConvId] })+ } catch {+ // ignore — we still want to clear the draft below+ }+ }+ qc.invalidateQueries({ queryKey: ['agent-conversations'] })+ setPendingUser(null)+ setDraft(null)+ if (errorThisTurn) setLastError(errorThisTurn)+ // After the very first round of a brand-new conversation, ask the+ // backend to summarize the exchange into a short title via the+ // LLM. Fire-and-forget — the conversations list will refetch when+ // it lands.+ if (!errorThisTurn && startedFresh && activeConvId) {+ agents.conversations+ .generateTitle(activeConvId)+ .then(() => qc.invalidateQueries({ queryKey: ['agent-conversations'] }))+ .catch(() => {})+ }+ }+ }++ return (+ // min-h-0 is required so the inner flex-1 messages area can scroll+ // instead of pushing the input footer past the bottom of the viewport.+ <div className="flex flex-col h-full min-h-0">+ <div ref={scrollRef} onScroll={handleScroll} className="flex-1 min-h-0 overflow-y-auto px-4 py-3 space-y-4">+ {/* Empty state for a fresh conversation: brand mark + a few+ randomized suggestion chips so the user has something to+ click instead of staring at a blank panel. Hidden once any+ history / pending bubble / draft exists. */}+ {(history ?? []).length === 0 && !pendingUser && !draft && (+ <ChatEmptyState+ agent={agent}+ onPick={(text) => {+ setInput(text)+ // Defer focus so the textarea picks up the new value+ // before we drop the caret into it.+ requestAnimationFrame(() => inputRef.current?.focus())+ }}+ />+ )}+ <HistoryView agent={agent} history={history ?? []} />+ {/* `pendingUser` is the optimistic bubble shown the instant the+ user hits send. As soon as the SSE `conversation` event fires+ for a brand-new chat, the parent updates conversationId and+ the history query refetches — at which point the persisted+ user message lands in `history` while the optimistic bubble+ is still mounted, briefly duplicating the message. Suppress+ the optimistic bubble once history already contains a+ matching user message. */}+ {pendingUser &&+ !(history ?? []).some(+ (m) => m.role === 'user' && (m.content ?? '').trim() === pendingUser.text.trim(),+ ) && (+ <div className="flex justify-end">+ <div className="max-w-[80%] rounded-lg px-3 py-2 bg-primary text-primary-foreground">+ <div className="whitespace-pre-wrap text-sm">{pendingUser.text}</div>+ </div>+ </div>+ )}+ {draft && (+ <div className="space-y-2">+ {draft.tools.map((tool, i) => {+ const isProposal = isProposalToolName(tool.name) && tool.result?.data && isProposalData(tool.result.data)+ if (isProposal) {+ // Stable id for the localStorage "applied" marker — the+ // draft uses an in-flight uuid so we suffix with the index.+ return (+ <ProposalCard+ key={i}+ toolCallId={`draft-${draft.id}-${i}`}+ data={tool.result!.data as Record<string, unknown>}+ />+ )+ }+ return (+ <ToolDebugChip+ key={i}+ name={tool.name}+ args={tool.args}+ result={tool.result || null}+ pending={!tool.result}+ />+ )+ })}+ {(draft.text || draft.pending) && (+ <div className="rounded-lg px-3 py-2 bg-muted">+ <div className="text-xs uppercase tracking-wider text-muted-foreground mb-1 flex items-center gap-1.5">+ <Sparkles className="h-3 w-3" /> {agent.name}+ </div>+ {draft.text ? (+ <Markdown>{draft.text + (draft.pending ? ' ▍' : '')}</Markdown>+ ) : (+ <Loader2 className="inline h-3.5 w-3.5 animate-spin text-muted-foreground" />+ )}+ </div>+ )}+ {draft.error && (+ <div className="rounded-lg px-3 py-2 bg-rose-50 dark:bg-rose-950/30 text-rose-700 dark:text-rose-200 text-sm flex items-center gap-2">+ <AlertCircle className="h-4 w-4" />+ {draft.error}+ </div>+ )}+ </div>+ )}+ {!draft && lastError && (+ <div className="rounded-lg px-3 py-2 bg-rose-50 dark:bg-rose-950/30 text-rose-700 dark:text-rose-200 text-sm flex items-start gap-2">+ <AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />+ <div className="min-w-0 flex-1 break-words">{lastError}</div>+ <button+ type="button"+ onClick={() => setLastError(null)}+ className="text-xs uppercase tracking-wider text-rose-600/70 hover:text-rose-700 dark:text-rose-400/70 dark:hover:text-rose-200"+ >+ ✕+ </button>+ </div>+ )}+ </div>+ <div className="shrink-0 border-t p-3 flex items-end gap-2 bg-background">+ <textarea+ ref={inputRef}+ value={input}+ onChange={(e) => {+ setInput(e.target.value)+ // Auto-grow: reset then size to content. Capped via maxHeight.+ const el = e.target+ el.style.height = 'auto'+ el.style.height = `${Math.min(el.scrollHeight, 200)}px`+ }}+ rows={1}+ placeholder={t('agents.chat.placeholder', { name: agent.name })}+ // h-10 matches the default Button height so the input + send+ // button line up when empty. Auto-grow above lifts it as the+ // user types more lines.+ className="flex-1 h-10 max-h-[200px] rounded-md border bg-background px-3 py-2 text-sm resize-none leading-5 overflow-y-auto"+ onKeyDown={(e) => {+ // Enter sends; Shift+Enter inserts a newline. IME composition+ // (e.g. accented chars on Mac, CJK input) must not be hijacked.+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault()+ send()+ }+ }}+ />+ <Button onClick={send} disabled={streaming || !input.trim()} className="shrink-0">+ {streaming ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}+ </Button>+ </div>+ </div>+ )+}++/**+ * Persisted history. Pairs each assistant tool_call with its matching+ * `tool` message (looked up by tool_call_id) so the call and its result+ * render together in a single expandable chip — same UX as the live+ * streaming draft.+ */+function HistoryView({ agent, history }: { agent: Agent; history: AgentMessage[] }) {+ const resultsById = useMemo(() => {+ const map: Record<string, AgentMessage> = {}+ for (const m of history) {+ if (m.role === 'tool') {+ const id = m.tool_result?.tool_call_id+ if (id) map[id] = m+ }+ }+ return map+ }, [history])++ return (+ <>+ {history+ .filter((m) => m.role !== 'tool') // tool messages render under their assistant call+ .map((m) => {+ if (m.role === 'user') {+ return (+ <div key={m.id} className="flex justify-end">+ <div className="max-w-[80%] rounded-lg px-3 py-2 bg-primary text-primary-foreground">+ <div className="whitespace-pre-wrap text-sm">{m.content}</div>+ </div>+ </div>+ )+ }+ if (m.role === 'assistant') {+ return (+ <div key={m.id} className="space-y-2">+ {m.tool_calls?.map((tc) => {+ const tres = resultsById[tc.id]+ const data = tres?.tool_result?.data+ if (isProposalToolName(tc.name) && data && isProposalData(data)) {+ // Persisted tool_call_id is stable across reloads —+ // perfect localStorage key for the "applied" marker.+ return <ProposalCard key={tc.id} toolCallId={tc.id} data={data as Record<string, unknown>} />+ }+ return (+ <ToolDebugChip+ key={tc.id}+ name={tc.name}+ args={tc.arguments}+ result={+ tres+ ? {+ ok: tres.tool_result?.ok ?? false,+ data: tres.tool_result?.data,+ text: tres.content,+ }+ : null+ }+ pending={!tres}+ />+ )+ })}+ {m.content && (+ <div className="rounded-lg px-3 py-2 bg-muted">+ <div className="text-xs uppercase tracking-wider text-muted-foreground mb-1 flex items-center gap-1.5">+ <Sparkles className="h-3 w-3" /> {agent.name}+ </div>+ <Markdown>{m.content}</Markdown>+ </div>+ )}+ </div>+ )+ }+ return null+ })}+ </>+ )+}+++/** Shown in a fresh conversation (no history, no draft). Centers the+ * Securo mark + agent name and surfaces ~6 randomized example prompts+ * pulled from i18n. Picking one fills the textarea and focuses it+ * (cheaper than auto-sending — gives the user a chance to tweak). */+function ChatEmptyState({ agent, onPick }: { agent: Agent; onPick: (text: string) => void }) {+ const { t } = useTranslation()++ // Resolve the LLM connector tied to this agent so the empty state+ // can show "Connected via X" — useful trust signal: the user knows+ // which provider/key/model is going to handle the next message.+ // Falls back gracefully when the agent has no connection_id (uses+ // raw provider/model fields or instance default).+ const { data: connections } = useQuery({+ queryKey: ['agent-connections'],+ queryFn: () => agents.connections.list(),+ staleTime: 1000 * 60,+ })+ const connectorLabel = useMemo<string | null>(() => {+ if (agent.connection_id) {+ const conn = connections?.find((c) => c.id === agent.connection_id)+ if (conn) {+ const model = agent.model || conn.default_model+ return model ? `${conn.name} · ${model}` : conn.name+ }+ }+ if (agent.provider) {+ return agent.model ? `${agent.provider} · ${agent.model}` : agent.provider+ }+ return null+ }, [agent.connection_id, agent.provider, agent.model, connections])++ // Pull the localized prompt pool. Each locale ships ~10 short tips;+ // we shuffle and take the first 6 so reopening a fresh chat doesn't+ // always show the same chips.+ const allPrompts = useMemo<string[]>(() => {+ const raw = t('agents.emptyState.suggestions', { returnObjects: true })+ return Array.isArray(raw) ? (raw as string[]) : []+ // Re-randomize each time the agent changes so switching agents+ // refreshes the suggestion set too.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [t, agent.id])++ const picks = useMemo(() => {+ const pool = [...allPrompts]+ for (let i = pool.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1))+ ;[pool[i], pool[j]] = [pool[j], pool[i]]+ }+ return pool.slice(0, 3)+ }, [allPrompts])++ return (+ <div className="flex flex-col items-center justify-center text-center gap-5 py-12 min-h-[65vh]">+ {/* Brand mark — uses the primary indigo so it reads as Securo, not+ as the agent's accent color. Transparent background. */}+ <ShellLogo size={56} className="text-primary opacity-90" />+ <div className="space-y-1 px-6">+ <div className="text-base font-semibold">{agent.name}</div>+ {agent.description && (+ <p className="text-xs text-muted-foreground line-clamp-2">{agent.description}</p>+ )}+ {connectorLabel && (+ <div className="text-[11px] text-muted-foreground/80 mt-1.5">+ {t('agents.emptyState.connectedVia', 'via')} <span className="font-mono">{connectorLabel}</span>+ </div>+ )}+ </div>+ {picks.length > 0 && (+ <div className="w-full px-3 mt-1">+ <div className="text-[11px] uppercase tracking-wider text-muted-foreground/80 mb-2 text-center">+ {t('agents.emptyState.tryAsking', 'Try asking')}+ </div>+ <div className="flex flex-col gap-1.5">+ {picks.map((p) => (+ <button+ key={p}+ type="button"+ onClick={() => onPick(p)}+ className="text-left text-sm px-3 py-2 rounded-md border border-border bg-background/40 hover:bg-muted transition-colors"+ >+ {p}+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/agents/connection-form-dialog.tsx b/frontend/src/components/agents/connection-form-dialog.tsxnew file mode 100644index 00000000..1c3e04f0--- /dev/null+++ b/frontend/src/components/agents/connection-form-dialog.tsx@@ -0,0 +1,225 @@+import { useEffect, useState } from 'react'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { Switch } from '@/components/ui/switch'+import { agents } from '@/lib/api'+import type { LlmConnection, LlmConnectionKind } from '@/lib/api'++interface Props {+ open: boolean+ onOpenChange: (open: boolean) => void+ connection?: LlmConnection | null+}++const KIND_LABELS: Record<LlmConnectionKind, { label: string; needsBaseUrl: boolean; needsKey: boolean; modelHint: string; urlHint: string; defaultModel?: string }> = {+ ollama: { label: 'Ollama', needsBaseUrl: false, needsKey: false, modelHint: 'llama3.1:8b', urlHint: 'http://host.docker.internal:11434' },+ // OpenAI + Anthropic ship a sensible default model so non-tech users+ // don't need to know which id to type. Self-hosted kinds (Ollama,+ // OpenAI-compatible) intentionally have NO default — the right model+ // depends on what the user actually has installed/loaded.+ openai: { label: 'OpenAI', needsBaseUrl: false, needsKey: true, modelHint: 'gpt-4o-mini', urlHint: '', defaultModel: 'gpt-4o-mini' },+ anthropic: { label: 'Anthropic', needsBaseUrl: false, needsKey: true, modelHint: 'claude-haiku-4-5', urlHint: '', defaultModel: 'claude-haiku-4-5' },+ openai_compatible: { label: 'OpenAI-compatible (LM Studio, vLLM, Groq, Together, …)', needsBaseUrl: true, needsKey: false, modelHint: 'llama3.1-70b', urlHint: 'http://192.168.1.142:1234' },+}++export function ConnectionFormDialog({ open, onOpenChange, connection }: Props) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const isEdit = !!connection++ const [name, setName] = useState('')+ const [kind, setKind] = useState<LlmConnectionKind>('ollama')+ const [baseUrl, setBaseUrl] = useState('')+ const [apiKey, setApiKey] = useState('')+ const [keyTouched, setKeyTouched] = useState(false)+ const [defaultModel, setDefaultModel] = useState('')+ // Track whether the user typed in the model field. If they didn't,+ // switching kinds re-seeds the field with the new kind's default+ // model (where one exists). Once they type, we never overwrite.+ const [modelTouched, setModelTouched] = useState(false)+ const [isDefault, setIsDefault] = useState(false)++ /** Switch the connector kind and, when the user is in the create+ * flow and hasn't customized the model field, auto-fill the new+ * kind's preset (only OpenAI + Anthropic ship one). */+ const handleKindChange = (newKind: LlmConnectionKind) => {+ setKind(newKind)+ if (isEdit) return+ if (modelTouched) return+ setDefaultModel(KIND_LABELS[newKind].defaultModel ?? '')+ }++ useEffect(() => {+ if (connection) {+ setName(connection.name)+ setKind(connection.kind)+ setBaseUrl(connection.base_url ?? '')+ setApiKey('')+ setKeyTouched(false)+ setDefaultModel(connection.default_model ?? '')+ // Editing a saved connection — treat the field as already+ // user-touched so kind swaps don't clobber what's stored.+ setModelTouched(true)+ setIsDefault(connection.is_default)+ } else {+ setName('')+ setKind('ollama')+ setBaseUrl('')+ setApiKey('')+ setKeyTouched(false)+ // Seed the model field with the initial kind's default (none+ // for ollama). Switching kinds inside the form will re-seed via+ // handleKindChange.+ setDefaultModel(KIND_LABELS['ollama'].defaultModel ?? '')+ setModelTouched(false)+ setIsDefault(false)+ }+ }, [connection, open])++ const meta = KIND_LABELS[kind]++ const saveMut = useMutation({+ mutationFn: async () => {+ const payload: Parameters<typeof agents.connections.create>[0] = {+ name: name.trim(),+ kind,+ base_url: meta.needsBaseUrl ? baseUrl.trim() || null : baseUrl.trim() || null,+ default_model: defaultModel.trim() || null,+ is_default: isDefault,+ }+ // Only include api_key in the payload if user actually typed one. This+ // preserves the existing key on edits where the user didn't touch the field.+ if (!isEdit || keyTouched) {+ payload.api_key = apiKey || null+ }+ if (isEdit && connection) return agents.connections.update(connection.id, payload)+ return agents.connections.create(payload)+ },+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agent-connections'] })+ onOpenChange(false)+ toast.success(isEdit ? t('agents.connections.updated') : t('agents.connections.created'))+ },+ onError: (err: unknown) => {+ const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail+ toast.error(detail || t('agents.connections.saveFailed'))+ },+ })++ const submit = () => {+ if (!name.trim()) {+ toast.error(t('agents.connections.nameRequired'))+ return+ }+ if (meta.needsBaseUrl && !baseUrl.trim()) {+ toast.error(t('agents.connections.baseUrlRequired'))+ return+ }+ saveMut.mutate()+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-xl">+ <DialogHeader>+ <DialogTitle>{isEdit ? t('agents.connections.editTitle') : t('agents.connections.createTitle')}</DialogTitle>+ </DialogHeader>+ <div className="grid gap-4 py-2">+ <div className="grid gap-2">+ <Label>{t('agents.connections.name')}</Label>+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder={t('agents.connections.namePlaceholder')} />+ </div>+ <div className="grid gap-2">+ <Label>{t('agents.connections.kind')}</Label>+ <Select value={kind} onValueChange={(v) => handleKindChange(v as LlmConnectionKind)} disabled={isEdit}>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(Object.keys(KIND_LABELS) as LlmConnectionKind[]).map((k) => (+ <SelectItem key={k} value={k}>+ {KIND_LABELS[k].label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="grid gap-2">+ <Label>+ {t('agents.connections.baseUrl')}+ {!meta.needsBaseUrl && <span className="text-xs text-muted-foreground ml-1">({t('agents.connections.optional')})</span>}+ </Label>+ <Input+ value={baseUrl}+ onChange={(e) => setBaseUrl(e.target.value)}+ placeholder={meta.urlHint || t('agents.connections.baseUrlPlaceholder')}+ />+ {kind === 'ollama' && (+ <p className="text-xs text-muted-foreground">+ {t('agents.connections.ollamaHint')}+ </p>+ )}+ {kind === 'openai_compatible' && (+ <p className="text-xs text-muted-foreground">+ {t('agents.connections.openaiCompatHint')}+ </p>+ )}+ </div>+ <div className="grid gap-2">+ <Label>+ {t('agents.connections.apiKey')}+ {!meta.needsKey && <span className="text-xs text-muted-foreground ml-1">({t('agents.connections.optional')})</span>}+ </Label>+ <Input+ type="password"+ value={apiKey}+ onChange={(e) => {+ setApiKey(e.target.value)+ setKeyTouched(true)+ }}+ placeholder={isEdit && connection?.has_api_key ? t('agents.connections.apiKeyPlaceholderEdit') : t('agents.connections.apiKeyPlaceholder')}+ />+ <p className="text-xs text-muted-foreground">{t('agents.connections.apiKeyHint')}</p>+ </div>+ <div className="grid gap-2">+ <Label>{t('agents.connections.defaultModel')}</Label>+ <Input+ value={defaultModel}+ onChange={(e) => {+ setDefaultModel(e.target.value)+ setModelTouched(true)+ }}+ placeholder={meta.modelHint}+ />+ </div>+ <div className="flex items-center gap-2">+ <Switch checked={isDefault} onCheckedChange={(v) => setIsDefault(!!v)} />+ <Label className="cursor-pointer" onClick={() => setIsDefault(!isDefault)}>+ {t('agents.connections.setAsDefault')}+ </Label>+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('agents.connections.cancel')}+ </Button>+ <Button onClick={submit} disabled={saveMut.isPending}>+ {saveMut.isPending ? t('agents.connections.saving') : isEdit ? t('agents.connections.save') : t('agents.connections.create')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/components/agents/conversation-row.tsx b/frontend/src/components/agents/conversation-row.tsxnew file mode 100644index 00000000..58042322--- /dev/null+++ b/frontend/src/components/agents/conversation-row.tsx@@ -0,0 +1,156 @@+import { useEffect, useRef, useState } from 'react'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { Check, MessageSquare, Pencil, Trash2, X } from 'lucide-react'+import { toast } from 'sonner'+import { agents } from '@/lib/api'+import type { AgentConversation } from '@/lib/api'+import { formatRelative } from '@/lib/relative-time'+import { cn } from '@/lib/utils'++interface Props {+ conv: AgentConversation+ agentId: string+ active: boolean+ onPick: () => void+ onDeleted: () => void+}++export function ConversationRow({ conv, agentId, active, onPick, onDeleted }: Props) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const [editing, setEditing] = useState(false)+ const [draft, setDraft] = useState(conv.title || '')+ const inputRef = useRef<HTMLInputElement>(null)++ useEffect(() => {+ if (editing) {+ inputRef.current?.focus()+ inputRef.current?.select()+ }+ }, [editing])++ const renameMut = useMutation({+ mutationFn: (title: string) => agents.conversations.rename(conv.id, title),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agent-conversations', agentId] })+ setEditing(false)+ },+ onError: () => toast.error(t('agents.conversation.renameFailed')),+ })++ const deleteMut = useMutation({+ mutationFn: () => agents.conversations.remove(conv.id),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agent-conversations', agentId] })+ qc.removeQueries({ queryKey: ['agent-conv-messages', conv.id] })+ onDeleted()+ toast.success(t('agents.conversation.deleted'))+ },+ onError: () => toast.error(t('agents.conversation.deleteFailed')),+ })++ const submitRename = () => {+ const value = draft.trim()+ if (!value) {+ setDraft(conv.title || '')+ setEditing(false)+ return+ }+ if (value === conv.title) {+ setEditing(false)+ return+ }+ renameMut.mutate(value)+ }++ if (editing) {+ return (+ <div className={cn('flex items-center gap-1 px-2 py-1.5', active && 'bg-muted')}>+ <MessageSquare className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <input+ ref={inputRef}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault()+ submitRename()+ } else if (e.key === 'Escape') {+ setDraft(conv.title || '')+ setEditing(false)+ }+ }}+ className="flex-1 min-w-0 rounded-sm border bg-background px-1.5 py-0.5 text-sm"+ />+ <button+ type="button"+ onClick={submitRename}+ className="p-1 rounded hover:bg-background text-emerald-600"+ title={t('agents.conversation.save')}+ >+ <Check className="h-3.5 w-3.5" />+ </button>+ <button+ type="button"+ onClick={() => {+ setDraft(conv.title || '')+ setEditing(false)+ }}+ className="p-1 rounded hover:bg-background text-muted-foreground"+ title={t('agents.conversation.cancel')}+ >+ <X className="h-3.5 w-3.5" />+ </button>+ </div>+ )+ }++ return (+ <div+ className={cn(+ 'group flex items-center px-3 py-2 text-sm hover:bg-muted',+ active && 'bg-muted',+ )}+ >+ <button+ type="button"+ onClick={onPick}+ className="flex-1 min-w-0 flex items-center gap-2 text-left"+ >+ <MessageSquare className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="flex-1 min-w-0 truncate">{conv.title || t('agents.detail.untitled')}</span>+ <span className="text-[11px] text-muted-foreground shrink-0 tabular-nums group-hover:opacity-0 transition-opacity">+ {formatRelative(conv.updated_at)}+ </span>+ </button>+ <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation()+ setEditing(true)+ }}+ className="p-1 rounded hover:bg-background text-muted-foreground"+ title={t('agents.conversation.rename')}+ >+ <Pencil className="h-3 w-3" />+ </button>+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation()+ if (confirm(t('agents.conversation.deleteConfirm', { name: conv.title || t('agents.detail.untitled') }))) {+ deleteMut.mutate()+ }+ }}+ className="p-1 rounded hover:bg-background text-rose-500"+ title={t('agents.conversation.delete')}+ disabled={deleteMut.isPending}+ >+ <Trash2 className="h-3 w-3" />+ </button>+ </div>+ </div>+ )+}diff --git a/frontend/src/components/agents/knowledge-section.tsx b/frontend/src/components/agents/knowledge-section.tsxnew file mode 100644index 00000000..dfab185b--- /dev/null+++ b/frontend/src/components/agents/knowledge-section.tsx@@ -0,0 +1,128 @@+import { useRef } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { Pin, PinOff, Trash2, Upload as UploadIcon, FileText, AlertCircle, Loader2, CheckCircle2 } from 'lucide-react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { agents } from '@/lib/api'+import type { KnowledgeDoc } from '@/lib/api'++function StatusBadge({ d }: { d: KnowledgeDoc }) {+ const { t } = useTranslation()+ if (d.status === 'ready')+ return (+ <span className="inline-flex items-center gap-1 text-xs text-emerald-600 dark:text-emerald-400">+ <CheckCircle2 className="h-3.5 w-3.5" /> {t('agents.knowledge.ready')} · {t('agents.knowledge.chunks', { count: d.chunk_count })}+ </span>+ )+ if (d.status === 'failed')+ return (+ <span className="inline-flex items-center gap-1 text-xs text-rose-600 dark:text-rose-400" title={d.error || ''}>+ <AlertCircle className="h-3.5 w-3.5" /> {t('agents.knowledge.failed')}+ </span>+ )+ return (+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" /> {d.status}+ </span>+ )+}++export function KnowledgeSection({ agentId }: { agentId: string }) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const fileRef = useRef<HTMLInputElement>(null)++ const { data, isLoading } = useQuery({+ queryKey: ['agent-knowledge', agentId],+ queryFn: () => agents.knowledge.list(agentId),+ refetchInterval: (q) => {+ const items = q.state.data?.items || []+ return items.some((d) => d.status !== 'ready' && d.status !== 'failed') ? 3000 : false+ },+ })++ const upload = useMutation({+ mutationFn: (file: File) => agents.knowledge.upload(agentId, file, false),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agent-knowledge', agentId] })+ toast.success(t('agents.knowledge.uploaded'))+ },+ onError: (err: unknown) => {+ const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail+ toast.error(detail || t('agents.knowledge.uploadFailed'))+ },+ })++ const pin = useMutation({+ mutationFn: ({ id, pinned }: { id: string; pinned: boolean }) => agents.knowledge.pin(agentId, id, pinned),+ onSuccess: () => qc.invalidateQueries({ queryKey: ['agent-knowledge', agentId] }),+ })++ const remove = useMutation({+ mutationFn: (id: string) => agents.knowledge.remove(agentId, id),+ onSuccess: () => qc.invalidateQueries({ queryKey: ['agent-knowledge', agentId] }),+ })++ const items = data?.items ?? []++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-sm font-semibold">{t('agents.knowledge.title')}</h3>+ <p className="text-xs text-muted-foreground">{t('agents.knowledge.subtitle')}</p>+ </div>+ <input+ ref={fileRef}+ type="file"+ accept=".pdf,.md,.markdown,.txt,.rst"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0]+ if (f) upload.mutate(f)+ if (fileRef.current) fileRef.current.value = ''+ }}+ />+ <Button size="sm" onClick={() => fileRef.current?.click()} disabled={upload.isPending}>+ <UploadIcon className="h-4 w-4 mr-1.5" />+ {upload.isPending ? t('agents.knowledge.uploading') : t('agents.knowledge.upload')}+ </Button>+ </div>++ {isLoading ? (+ <div className="text-sm text-muted-foreground">{t('agents.knowledge.loading')}</div>+ ) : items.length === 0 ? (+ <div className="rounded-lg border border-dashed p-6 text-sm text-muted-foreground text-center">+ {t('agents.knowledge.empty')}+ </div>+ ) : (+ <div className="rounded-lg border divide-y">+ {items.map((d) => (+ <div key={d.id} className="flex items-center gap-3 px-3 py-2.5">+ <FileText className="h-4 w-4 text-muted-foreground shrink-0" />+ <div className="min-w-0 flex-1">+ <div className="text-sm truncate">{d.title}</div>+ <div className="flex items-center gap-3">+ <StatusBadge d={d} />+ <span className="text-xs text-muted-foreground">{(d.size_bytes / 1024).toFixed(0)} KB</span>+ </div>+ </div>+ <Button+ size="icon"+ variant="ghost"+ title={d.pinned ? t('agents.knowledge.unpinTitle') : t('agents.knowledge.pinTitle')}+ onClick={() => pin.mutate({ id: d.id, pinned: !d.pinned })}+ >+ {d.pinned ? <Pin className="h-4 w-4 text-amber-500" /> : <PinOff className="h-4 w-4" />}+ </Button>+ <Button size="icon" variant="ghost" onClick={() => remove.mutate(d.id)}>+ <Trash2 className="h-4 w-4 text-rose-500" />+ </Button>+ </div>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/agents/markdown.tsx b/frontend/src/components/agents/markdown.tsxnew file mode 100644index 00000000..9ec191b3--- /dev/null+++ b/frontend/src/components/agents/markdown.tsx@@ -0,0 +1,169 @@+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'+import { cn } from '@/lib/utils'+import { Component, memo, type ReactNode } from 'react'+import { AgentChart, type ChartSpec } from '@/components/agents/agent-chart'++type NodeProps = { children?: ReactNode }++interface Props {+ children: string+ className?: string+}++/**+ * Tailwind-styled GFM markdown for chat messages.+ *+ * Deliberately conservative: no raw HTML, no images, links open in a new+ * tab with rel=noopener. Sized to feel right inside the chat bubble — not+ * a documentation page.+ *+ * Wrapped in React.memo at the bottom so static assistant messages+ * (including embedded `securo-chart` blocks) don't re-render on every+ * keystroke in the chat input — they were causing Recharts to fully+ * reanimate per character typed.+ */+function _Markdown({ children, className }: Props) {+ return (+ <div className={cn('text-sm leading-relaxed [&>:first-child]:mt-0 [&>:last-child]:mb-0', className)}>+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ components={{+ p: ({ children }: NodeProps) => <p className="my-2 whitespace-pre-wrap">{children}</p>,+ ul: ({ children }: NodeProps) => <ul className="my-2 list-disc pl-5 space-y-0.5">{children}</ul>,+ ol: ({ children }: NodeProps) => <ol className="my-2 list-decimal pl-5 space-y-0.5">{children}</ol>,+ li: ({ children }: NodeProps) => <li className="marker:text-muted-foreground/70">{children}</li>,+ h1: ({ children }: NodeProps) => <h1 className="text-base font-bold mt-3 mb-1.5">{children}</h1>,+ h2: ({ children }: NodeProps) => <h2 className="text-[15px] font-semibold mt-3 mb-1.5">{children}</h2>,+ h3: ({ children }: NodeProps) => <h3 className="text-sm font-semibold mt-2.5 mb-1">{children}</h3>,+ h4: ({ children }: NodeProps) => <h4 className="text-sm font-semibold mt-2 mb-1">{children}</h4>,+ strong: ({ children }: NodeProps) => <strong className="font-semibold">{children}</strong>,+ em: ({ children }: NodeProps) => <em className="italic">{children}</em>,+ del: ({ children }: NodeProps) => <del className="opacity-70">{children}</del>,+ blockquote: ({ children }: NodeProps) => (+ <blockquote className="border-l-2 border-border pl-3 italic text-muted-foreground my-2">+ {children}+ </blockquote>+ ),+ a: ({ href, children }: NodeProps & { href?: string }) => (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ className="text-primary underline underline-offset-2 hover:opacity-80"+ >+ {children}+ </a>+ ),+ hr: () => <hr className="my-3 border-border" />,+ table: ({ children }: NodeProps) => (+ <div className="my-2 overflow-x-auto">+ <table className="border-collapse text-xs">{children}</table>+ </div>+ ),+ thead: ({ children }: NodeProps) => <thead className="bg-muted/60">{children}</thead>,+ th: ({ children }: NodeProps) => (+ <th className="border border-border px-2 py-1 text-left font-semibold">{children}</th>+ ),+ td: ({ children }: NodeProps) => <td className="border border-border px-2 py-1 align-top">{children}</td>,+ code: ({ className, children, ...props }: NodeProps & { className?: string }) => {+ const isFenced = typeof className === 'string' && className.startsWith('language-')+ // Special-case our agent chart code-fence: parse the JSON+ // body and render an inline recharts figure instead of a+ // code block. Falls back to a plain pre/code on parse error+ // so the user can still see what the model emitted.+ if (className === 'language-securo-chart') {+ const raw = String(children ?? '').trim()+ try {+ const spec = JSON.parse(raw) as ChartSpec+ return (+ <ChartErrorBoundary raw={raw}>+ <AgentChart spec={spec} />+ </ChartErrorBoundary>+ )+ } catch {+ // fall through to plain code rendering+ }+ }+ if (isFenced) {+ return (+ <code className={cn('font-mono text-xs', className)} {...props}>+ {children}+ </code>+ )+ }+ return (+ <code+ className="rounded border border-border/60 bg-background/60 px-1.5 py-0.5 text-[11.5px] font-mono"+ {...props}+ >+ {children}+ </code>+ )+ },+ pre: ({ children }: NodeProps) => (+ <pre className="my-2 overflow-x-auto rounded-md border bg-background/60 p-3 text-xs leading-snug">+ {children}+ </pre>+ ),+ input: ({ checked, type }: { checked?: boolean; type?: string }) => {+ // GFM task lists.+ if (type === 'checkbox') {+ return (+ <input+ type="checkbox"+ checked={!!checked}+ readOnly+ className="mr-1.5 align-middle accent-primary"+ />+ )+ }+ return null+ },+ }}+ >+ {children}+ </ReactMarkdown>+ </div>+ )+}++/** Memoized export — keystrokes in the chat input force the parent to+ * re-render, but assistant messages don't change, so we skip rendering+ * them entirely when `children`/`className` are referentially the+ * same. Critical for chats that contain a recharts figure (Recharts+ * treats new prop refs as new data and re-runs its enter animations). */+export const Markdown = memo(_Markdown, (prev, next) =>+ prev.children === next.children && prev.className === next.className,+)+++interface ChartBoundaryProps {+ children: ReactNode+ raw: string+}++interface ChartBoundaryState {+ hasError: boolean+}++/** Recharts can throw inside its layout effects (e.g. legend dispatcher+ * hitting "Maximum update depth exceeded" in tight panel widths). A+ * thrown error in a chart should NOT take the whole chat down — degrade+ * to a code block so the user still sees the JSON the model produced. */+class ChartErrorBoundary extends Component<ChartBoundaryProps, ChartBoundaryState> {+ state: ChartBoundaryState = { hasError: false }++ static getDerivedStateFromError(): ChartBoundaryState {+ return { hasError: true }+ }++ render() {+ if (!this.state.hasError) return this.props.children+ return (+ <pre className="my-3 rounded-md border border-border bg-muted/40 p-3 text-[11px] leading-snug font-mono overflow-x-auto whitespace-pre-wrap">+ {this.props.raw}+ </pre>+ )+ }+}diff --git a/frontend/src/components/agents/proposal-card.tsx b/frontend/src/components/agents/proposal-card.tsxnew file mode 100644index 00000000..f7fb5d71--- /dev/null+++ b/frontend/src/components/agents/proposal-card.tsx@@ -0,0 +1,430 @@+import { useState } from 'react'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { AlertCircle, Check, ChevronDown, ChevronRight, Loader2, Sparkles } from 'lucide-react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'+import {+ budgets,+ categories,+ goals,+ recurring,+ rules,+ transactions,+} from '@/lib/api'++type ProposalKind =+ | 'categorize'+ | 'create_category'+ | 'create_budget'+ | 'create_payee_rule'+ | 'create_transaction'+ | 'create_recurring_transaction'+ | 'update_recurring_transaction'+ | 'cancel_recurring_transaction'+ | 'create_goal'++interface ProposalData {+ kind?: ProposalKind+ proposed?: Record<string, unknown>+ target?: Record<string, unknown>+ changes?: Record<string, unknown>+ affected?: { id: string; description?: string; amount?: number; currency?: string }[]+ affected_count?: number+ target_category?: { id: string; name: string }+ name_collision?: { id: string; name: string }+ mode?: 'deactivate' | 'delete'+ apply_endpoint?: string+ error?: string+}++interface Props {+ toolCallId: string+ data: ProposalData+}++const APPLIED_KEY = 'securo:agent-proposal-applied'++function loadApplied(): Record<string, { ts: number; ref?: string }> {+ try {+ return JSON.parse(localStorage.getItem(APPLIED_KEY) || '{}')+ } catch {+ return {}+ }+}++function persistApplied(toolCallId: string, ref?: string) {+ const all = loadApplied()+ all[toolCallId] = { ts: Date.now(), ref }+ localStorage.setItem(APPLIED_KEY, JSON.stringify(all))+}++export function ProposalCard({ toolCallId, data }: Props) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const initiallyApplied = loadApplied()[toolCallId]+ const [appliedAt, setAppliedAt] = useState<number | null>(initiallyApplied?.ts ?? null)+ const [showJson, setShowJson] = useState(false)++ const apply = useMutation({+ mutationFn: () => applyProposal(data),+ onSuccess: (ref) => {+ persistApplied(toolCallId, typeof ref === 'string' ? ref : undefined)+ setAppliedAt(Date.now())+ toast.success(t('agents.proposal.applied'))+ // Invalidate the broad surface that proposals may have changed.+ ;[+ 'transactions',+ 'accounts',+ 'categories',+ 'category-groups',+ 'recurring-transactions',+ 'budgets',+ 'rules',+ 'goals',+ 'dashboard',+ ].forEach((key) => qc.invalidateQueries({ queryKey: [key] }))+ },+ onError: (err: unknown) => {+ const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail+ toast.error(detail || t('agents.proposal.applyFailed'))+ },+ })++ // Backend already short-circuits with {error: "..."} on bad input.+ if (data.error) {+ return (+ <div className="rounded-md border border-rose-300/50 bg-rose-50/40 dark:bg-rose-950/15 px-3 py-2 text-sm flex items-center gap-2 text-rose-700 dark:text-rose-200">+ <AlertCircle className="h-4 w-4 shrink-0" />+ <span className="truncate">{data.error}</span>+ </div>+ )+ }++ if (!data.kind) return null++ const kind = data.kind+ const summary = renderSummary(kind, data, t)+ const isApplied = appliedAt !== null++ return (+ <div+ className={cn(+ 'rounded-md border text-sm overflow-hidden',+ isApplied+ ? 'border-emerald-300/40 bg-emerald-50/30 dark:bg-emerald-950/15'+ : 'border-amber-300/50 bg-amber-50/40 dark:bg-amber-950/15',+ )}+ >+ <div className="px-3 py-2.5 flex items-start gap-3">+ <div className="shrink-0 mt-0.5">+ {isApplied ? (+ <Check className="h-4 w-4 text-emerald-600" />+ ) : (+ <Sparkles className="h-4 w-4 text-amber-600" />+ )}+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="font-semibold">{kindTitle(kind, t)}</span>+ <span+ className={cn(+ 'text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded',+ isApplied+ ? 'bg-emerald-200/70 text-emerald-900 dark:bg-emerald-900/40 dark:text-emerald-200'+ : 'bg-amber-200/70 text-amber-900 dark:bg-amber-900/40 dark:text-amber-200',+ )}+ >+ {isApplied ? t('agents.proposal.applied') : t('agents.proposal.label')}+ </span>+ </div>+ <div className="mt-1 text-muted-foreground text-[13px] leading-snug">{summary}</div>+ <SplitPreview proposed={data.proposed} />+ </div>+ <div className="shrink-0 flex items-center gap-1.5">+ {isApplied ? (+ <span className="text-xs text-emerald-700 dark:text-emerald-300 inline-flex items-center gap-1">+ <Check className="h-3.5 w-3.5" />+ {t('agents.proposal.applied')}+ </span>+ ) : (+ <Button size="sm" onClick={() => apply.mutate()} disabled={apply.isPending}>+ {apply.isPending ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin mr-1.5" />+ ) : (+ <Check className="h-3.5 w-3.5 mr-1.5" />+ )}+ {t('agents.proposal.apply')}+ </Button>+ )}+ </div>+ </div>+ <button+ type="button"+ onClick={() => setShowJson((v) => !v)}+ className="w-full text-[11px] uppercase tracking-wider text-muted-foreground hover:text-foreground border-t px-3 py-1.5 flex items-center gap-1.5"+ >+ {showJson ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}+ {t('agents.proposal.showRaw')}+ </button>+ {showJson && (+ <pre className="border-t px-3 py-2 text-[11px] leading-snug font-mono bg-background/60 overflow-x-auto">+ {safeStringify(data)}+ </pre>+ )}+ </div>+ )+}++function kindTitle(kind: ProposalKind, t: ReturnType<typeof useTranslation>['t']): string {+ return t(`agents.proposal.kind.${kind}`)+}++function renderSummary(kind: ProposalKind, d: ProposalData, t: ReturnType<typeof useTranslation>['t']): string {+ const p = (d.proposed || {}) as Record<string, unknown>+ const tgt = (d.target || {}) as Record<string, unknown>+ switch (kind) {+ case 'categorize':+ return t('agents.proposal.summary.categorize', {+ count: d.affected_count ?? d.affected?.length ?? 0,+ category: d.target_category?.name ?? '?',+ })+ case 'create_category':+ return t('agents.proposal.summary.createCategory', {+ name: String(p.name ?? '?'),+ }) + (d.name_collision ? ` — ${t('agents.proposal.collision', { name: d.name_collision.name })}` : '')+ case 'create_budget':+ return t('agents.proposal.summary.createBudget', {+ category: String((p.category_name as string) ?? p.category_id ?? '?'),+ amount: fmt(p.amount, p.currency),+ month: String(p.month ?? '?'),+ })+ case 'create_payee_rule':+ return t('agents.proposal.summary.createPayeeRule', {+ pattern: String(p.match_pattern ?? '?'),+ category: String((p.category_name as string) ?? p.category_id ?? '?'),+ })+ case 'create_transaction':+ return t('agents.proposal.summary.createTransaction', {+ description: String(p.description ?? '?'),+ amount: fmt(p.amount, p.currency),+ type: String(p.type ?? '?'),+ date: String(p.date ?? ''),+ account: String((p.account_name as string) ?? '?'),+ })+ case 'create_recurring_transaction':+ return t('agents.proposal.summary.createRecurring', {+ description: String(p.description ?? '?'),+ amount: fmt(p.amount, p.currency),+ frequency: String(p.frequency ?? '?'),+ day: p.day_of_month ? `${p.day_of_month}` : '?',+ account: String((p.account_name as string) ?? '?'),+ })+ case 'update_recurring_transaction': {+ const changes = (d.changes || {}) as Record<string, unknown>+ const lines = Object.entries(changes).map(([k, v]) => {+ const before = tgt[k]+ return `${k}: ${String(before ?? '∅')} → ${String(v ?? '∅')}`+ })+ return t('agents.proposal.summary.updateRecurring', {+ description: String(tgt.description ?? '?'),+ changes: lines.join(', ') || '—',+ })+ }+ case 'cancel_recurring_transaction':+ return t(d.mode === 'delete' ? 'agents.proposal.summary.deleteRecurring' : 'agents.proposal.summary.deactivateRecurring', {+ description: String(tgt.description ?? '?'),+ })+ case 'create_goal':+ return t('agents.proposal.summary.createGoal', {+ name: String(p.name ?? '?'),+ target: fmt(p.target_amount, p.currency),+ deadline: p.deadline ? String(p.deadline) : '—',+ })+ default:+ return ''+ }+}++function fmt(amount: unknown, currency: unknown): string {+ if (amount == null) return '?'+ const n = typeof amount === 'number' ? amount : Number(amount) || 0+ const c = typeof currency === 'string' ? currency : 'BRL'+ try {+ return new Intl.NumberFormat(undefined, { style: 'currency', currency: c }).format(n)+ } catch {+ return `${c} ${n.toFixed(2)}`+ }+}++function safeStringify(o: unknown): string {+ try {+ return JSON.stringify(o, null, 2)+ } catch {+ return String(o)+ }+}++function SplitPreview({ proposed }: { proposed?: Record<string, unknown> }) {+ const p = proposed || {}+ const splits = p.splits as { share_type?: string; items?: Array<Record<string, unknown>> } | undefined+ if (!splits || !Array.isArray(splits.items) || splits.items.length === 0) return null+ const groupName = (p.group_name as string) || ''+ const currency = typeof p.currency === 'string' ? p.currency : 'BRL'+ const shareType = splits.share_type || 'equal'+ return (+ <div className="mt-1.5 text-[12px] border rounded px-2 py-1.5 bg-background/40">+ <div className="text-muted-foreground mb-1">+ {groupName ? `${groupName} · ` : ''}{shareType}+ </div>+ <ul className="space-y-0.5">+ {splits.items.map((s, i) => (+ <li key={i} className="flex justify-between gap-3">+ <span>{String(s.member_name ?? s.member_id ?? '?')}</span>+ <span className="tabular-nums">+ {fmt(s.share_amount, currency)}+ {s.share_pct != null ? ` (${Number(s.share_pct)}%)` : ''}+ </span>+ </li>+ ))}+ </ul>+ </div>+ )+}++// Each kind maps to one Securo endpoint already exposed via lib/api.ts.+// Returns a string ref (id of the new entity) when available — used as a+// breadcrumb in the localStorage record so a future "view created entity"+// affordance can deep-link to it.+async function applyProposal(data: ProposalData): Promise<string | void> {+ const p = (data.proposed || {}) as Record<string, unknown>+ switch (data.kind) {+ case 'categorize': {+ const ids = (data.affected || []).map((a) => a.id)+ const res = await transactions.bulkCategorize(ids, data.target_category!.id)+ return `${res.updated} updated`+ }+ case 'create_category': {+ const c = await categories.create({+ name: String(p.name),+ group_id: (p.group_id as string) || undefined,+ icon: (p.icon as string) || undefined,+ color: (p.color as string) || undefined,+ })+ return c.id+ }+ case 'create_budget': {+ const b = await budgets.create({+ category_id: String(p.category_id),+ amount: Number(p.amount),+ month: String(p.month),+ })+ return b.id+ }+ case 'create_payee_rule': {+ const r = await rules.create({+ name: `Rule: ${String(p.match_pattern).slice(0, 60)}`,+ conditions_op: 'and',+ conditions: [+ { field: 'description', op: 'contains', value: String(p.match_pattern) },+ ],+ actions: [{ op: 'set_category', value: String(p.category_id) }],+ priority: 10,+ is_active: true,+ })+ return r.id+ }+ case 'create_transaction': {+ // If the proposal includes group splits, translate the agent's+ // {member_id, share_amount, share_pct} preview into the API's+ // {group_member_id, share_amount, share_pct} schema. The backend+ // service re-runs the math in `equal` mode so passing the per-+ // member amounts back is not required, but we keep them so an+ // exact/percent split round-trips identically to the preview.+ const splitsBlock = p.splits as { share_type?: string; items?: Array<Record<string, unknown>> } | undefined+ const splitsPayload = splitsBlock && Array.isArray(splitsBlock.items) && splitsBlock.items.length > 0+ ? {+ share_type: String(splitsBlock.share_type || 'equal'),+ splits: splitsBlock.items.map((it) => ({+ group_member_id: String(it.member_id),+ ...(it.share_amount != null ? { share_amount: Number(it.share_amount) } : {}),+ ...(it.share_pct != null ? { share_pct: Number(it.share_pct) } : {}),+ })),+ }+ : undefined+ const t = await transactions.create({+ description: String(p.description),+ amount: Number(p.amount),+ currency: (p.currency as string) || undefined,+ type: (p.type as string) || undefined,+ date: (p.date as string) || undefined,+ account_id: (p.account_id as string) || undefined,+ category_id: (p.category_id as string) || undefined,+ notes: (p.notes as string) || undefined,+ ...(splitsPayload ? { splits: splitsPayload } : {}),+ } as Parameters<typeof transactions.create>[0])+ return t.id+ }+ case 'create_recurring_transaction': {+ const rt = await recurring.create({+ description: String(p.description),+ amount: Number(p.amount),+ currency: (p.currency as string) || undefined,+ type: (p.type as string) || undefined,+ frequency: (p.frequency as string) || undefined,+ day_of_month: (p.day_of_month as number) ?? undefined,+ start_date: (p.start_date as string) || undefined,+ end_date: (p.end_date as string) || undefined,+ account_id: (p.account_id as string) || undefined,+ category_id: (p.category_id as string) || undefined,+ } as Parameters<typeof recurring.create>[0])+ return rt.id+ }+ case 'update_recurring_transaction': {+ const id = String((data.target as Record<string, unknown>).id)+ await recurring.update(id, (data.changes || {}) as Parameters<typeof recurring.update>[1])+ return id+ }+ case 'cancel_recurring_transaction': {+ const id = String((data.target as Record<string, unknown>).id)+ if (data.mode === 'delete') {+ await recurring.delete(id)+ } else {+ await recurring.update(id, { is_active: false } as Parameters<typeof recurring.update>[1])+ }+ return id+ }+ case 'create_goal': {+ const g = await goals.create({+ name: String(p.name),+ target_amount: Number(p.target_amount),+ currency: (p.currency as string) || undefined,+ deadline: (p.deadline as string) || undefined,+ initial_amount: (p.initial_amount as number) ?? undefined,+ icon: (p.icon as string) || undefined,+ color: (p.color as string) || undefined,+ } as Parameters<typeof goals.create>[0])+ return g.id+ }+ }+}++/** Heuristic: a tool result is a proposal if its data has a known kind. */+export function isProposalData(data: unknown): data is ProposalData {+ if (!data || typeof data !== 'object') return false+ const k = (data as { kind?: unknown }).kind+ return typeof k === 'string' && [+ 'categorize', 'create_category', 'create_budget', 'create_payee_rule',+ 'create_transaction', 'create_recurring_transaction',+ 'update_recurring_transaction', 'cancel_recurring_transaction',+ 'create_goal',+ ].includes(k)+}++/** Treat the data as a proposal even when only `error` is present, since+ * a proposal that failed validation should still render a small error card+ * instead of a generic tool-debug chip. */+export function isProposalToolName(name: string): boolean {+ return name.includes('propose_')+}diff --git a/frontend/src/components/agents/tool-debug-chip.tsx b/frontend/src/components/agents/tool-debug-chip.tsxnew file mode 100644index 00000000..9b593a89--- /dev/null+++ b/frontend/src/components/agents/tool-debug-chip.tsx@@ -0,0 +1,99 @@+import { useState } from 'react'+import { ChevronDown, ChevronRight, Loader2, Wrench } from 'lucide-react'+import { cn } from '@/lib/utils'++interface Props {+ name: string+ args?: Record<string, unknown> | null+ result?: { ok?: boolean; data?: unknown; text?: string | null } | null+ pending?: boolean+ defaultOpen?: boolean+}++/**+ * Expandable tool-call inspector. Compact by default (status, name, brief+ * summary). Clicking reveals the raw JSON arguments and result — same+ * "show your work" affordance anything-llm uses for agent skills.+ */+export function ToolDebugChip({ name, args, result, pending, defaultOpen = false }: Props) {+ const [open, setOpen] = useState(defaultOpen)+ const status = pending ? 'pending' : result?.ok === false ? 'error' : result ? 'ok' : 'pending'+ const summary = result?.text || (result?.data && typeof result.data === 'object'+ ? summarizeData(result.data as Record<string, unknown>)+ : null)++ return (+ <div className={cn(+ 'rounded-md border text-xs',+ status === 'error' ? 'border-rose-300/50 bg-rose-50/40 dark:bg-rose-950/20'+ : status === 'pending' ? 'border-border bg-muted/40'+ : 'border-emerald-300/40 bg-emerald-50/30 dark:bg-emerald-950/15'+ )}>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="w-full flex items-center gap-2 px-2.5 py-1.5 text-left"+ >+ {status === 'pending' ? (+ <Loader2 className="h-3 w-3 animate-spin text-muted-foreground shrink-0" />+ ) : status === 'error' ? (+ <span className="text-rose-600 font-mono text-[11px] shrink-0">✗</span>+ ) : (+ <span className="text-emerald-600 font-mono text-[11px] shrink-0">✓</span>+ )}+ <Wrench className="h-3 w-3 text-muted-foreground shrink-0" />+ <span className="font-mono truncate">{name}</span>+ {summary && (+ <span className="text-muted-foreground truncate flex-1 min-w-0">— {summary}</span>+ )}+ {open ? (+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground/70 shrink-0" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5 text-muted-foreground/70 shrink-0" />+ )}+ </button>+ {open && (+ <div className="border-t px-2.5 py-2 space-y-2">+ <Block label="Arguments" payload={args ?? {}} />+ {result && <Block label="Result" payload={result.data} fallback={result.text} />}+ </div>+ )}+ </div>+ )+}++function Block({ label, payload, fallback }: { label: string; payload: unknown; fallback?: string | null }) {+ const json = (() => {+ if (payload === undefined || payload === null) {+ return fallback || '(empty)'+ }+ try {+ return JSON.stringify(payload, null, 2)+ } catch {+ return String(payload)+ }+ })()+ return (+ <div>+ <div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-1">{label}</div>+ <pre className="rounded bg-background/70 border border-border/60 p-2 overflow-x-auto text-[11px] leading-snug font-mono">+ {json}+ </pre>+ </div>+ )+}++function summarizeData(data: Record<string, unknown>): string | null {+ if (Array.isArray((data as { items?: unknown[] }).items)) {+ const n = ((data as { items: unknown[] }).items).length+ const total = (data as { total?: number }).total+ return `${total ?? n} item${(total ?? n) === 1 ? '' : 's'}`+ }+ if ('error' in data) {+ return String((data as { error: unknown }).error)+ }+ if ('kind' in data) {+ return String((data as { kind: unknown }).kind)+ }+ return null+}diff --git a/frontend/src/components/agents/tools-section.tsx b/frontend/src/components/agents/tools-section.tsxnew file mode 100644index 00000000..addfc5ce--- /dev/null+++ b/frontend/src/components/agents/tools-section.tsx@@ -0,0 +1,91 @@+import { useEffect, useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Switch } from '@/components/ui/switch'+import { agents } from '@/lib/api'+import type { AgentToolHandle } from '@/lib/api'++export function ToolsSection({ agentId }: { agentId: string }) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const { data, isLoading } = useQuery({+ queryKey: ['agent-tools', agentId],+ queryFn: () => agents.tools(agentId),+ })++ const [draft, setDraft] = useState<AgentToolHandle[]>([])+ useEffect(() => {+ setDraft(data?.tools ?? [])+ }, [data?.tools])++ const save = useMutation({+ mutationFn: () => agents.setTools(agentId, draft.map((t) => ({ server: t.server, tool_name: t.name, enabled: t.enabled }))),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agent-tools', agentId] })+ toast.success(t('agents.tools.saved'))+ },+ onError: () => toast.error(t('agents.tools.saveFailed')),+ })++ if (isLoading) return <div className="text-sm text-muted-foreground">{t('agents.tools.loading')}</div>++ const grouped = draft.reduce<Record<string, AgentToolHandle[]>>((acc, tool) => {+ ;(acc[tool.server] ||= []).push(tool)+ return acc+ }, {})++ const dirty = draft.some((tool, i) => (data?.tools[i]?.enabled ?? true) !== tool.enabled)++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div>+ <h3 className="text-sm font-semibold">{t('agents.tools.title')}</h3>+ <p className="text-xs text-muted-foreground">{t('agents.tools.subtitle')}</p>+ </div>+ <Button size="sm" disabled={!dirty || save.isPending} onClick={() => save.mutate()}>+ {save.isPending ? t('agents.tools.saving') : t('agents.tools.save')}+ </Button>+ </div>++ {Object.keys(grouped).length === 0 ? (+ <div className="rounded-lg border border-dashed p-6 text-sm text-muted-foreground text-center">+ {t('agents.tools.empty')}+ </div>+ ) : (+ <div className="space-y-5">+ {Object.entries(grouped).map(([server, items]) => (+ <div key={server}>+ <div className="text-xs uppercase tracking-wider text-muted-foreground mb-2">{server}</div>+ <div className="rounded-lg border divide-y">+ {items.map((tool) => (+ <div key={`${tool.server}.${tool.name}`} className="flex items-center gap-3 px-3 py-2.5">+ <div className="min-w-0 flex-1">+ <div className="text-sm font-medium flex items-center gap-2">+ {tool.name}+ {tool.is_proposal && (+ <span className="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200">+ {t('agents.tools.proposeBadge')}+ </span>+ )}+ </div>+ <div className="text-xs text-muted-foreground line-clamp-2">{tool.description}</div>+ </div>+ <Switch+ checked={tool.enabled}+ onCheckedChange={(v) => {+ setDraft((d) => d.map((x) => (x.server === tool.server && x.name === tool.name ? { ...x, enabled: !!v } : x)))+ }}+ />+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 260c8bd7..534e6a06 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -1,4 +1,4 @@-import { useState, useCallback } from 'react'+import { useState, useCallback, useEffect } from 'react'import { getAccountName } from '@/lib/account-utils'import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'@@ -29,7 +29,6 @@ import { ShellLogo } from '@/components/shell-logo'import { UpdateAvailableBanner } from '@/components/update-available-banner'import { UpdateAvailableDialog } from '@/components/update-available-dialog'import {- LayoutDashboard,ArrowLeftRight,Building2,SlidersHorizontal,@@ -62,21 +61,21 @@ import { ChangePasswordDialog } from '@/components/change-password-dialog'import { TwoFactorSetup } from '@/components/two-factor-setup'import { CommandPalette } from '@/components/command-palette'import { useCommandPaletteHotkey } from '@/hooks/use-command-palette-hotkey'-import { Search } from 'lucide-react'+import { GlobalChatPanel } from '@/components/global-chat-panel'+import { useFeatureFlags } from '@/hooks/use-feature-flags'+import { Bot, Search, Sparkles } from 'lucide-react'type NavItem =| { type: 'link'; key: string; path: string; icon: React.ElementType }| { type: 'separator'; labelKey: string }const navItems: NavItem[] = [- { type: 'link', key: 'dashboard', path: '/', icon: LayoutDashboard },- {- type: 'link',- key: 'transactions',- path: '/transactions',- icon: ArrowLeftRight,- },+ // The dashboard ("Painel") is now reachable by clicking the Securo+ // logo + name in the sidebar header — no dedicated menu item to keep+ // the sidebar focused on the main destinations. Transactions sits+ // inside the ACCOUNTS section since it's account-scoped data.{ type: 'separator', labelKey: 'nav.groupAccounts' },+ { type: 'link', key: 'transactions', path: '/transactions', icon: ArrowLeftRight },{ type: 'link', key: 'accounts', path: '/accounts', icon: Building2 },{ type: 'link', key: 'import', path: '/import', icon: Upload },{ type: 'separator', labelKey: 'nav.groupAnalysis' },@@ -114,8 +113,31 @@ export function AppLayout() {const [twoFactorOpen, setTwoFactorOpen] = useState(false)const [backingUp, setBackingUp] = useState(false)const [paletteOpen, setPaletteOpen] = useState(false)+ const [chatOpen, setChatOpen] = useState(false)const [updateDialogOpen, setUpdateDialogOpen] = useState(false)useCommandPaletteHotkey(setPaletteOpen)+ const { agentsEnabled } = useFeatureFlags()+ // ⌘J / Ctrl+J toggles the global slide-over chat from anywhere.+ // Distinct from ⌘K (command palette) so users can have both open.+ // Gated on agentsEnabled so the hotkey is a no-op when the feature is+ // off — keeps ⌘J free for browsers/other tools.+ useEffect(() => {+ if (!agentsEnabled) return+ const handler = (e: KeyboardEvent) => {+ const isMod = e.metaKey || e.ctrlKey+ if (isMod && (e.key === 'j' || e.key === 'J')) {+ e.preventDefault()+ setChatOpen((prev) => !prev)+ }+ }+ document.addEventListener('keydown', handler)+ return () => document.removeEventListener('keydown', handler)+ }, [agentsEnabled])+ // The "Agents" management page used to live in the sidebar, but it's+ // a configuration surface (KB upload, providers, default selection),+ // not a daily destination. Moved to the user menu (Change password,+ // 2FA, Backups, AI agents).+ const finalNavItems: NavItem[] = navItemsconst isMac =typeof navigator !== 'undefined' &&/Mac|iPhone|iPad|iPod/.test(navigator.platform)@@ -170,12 +192,17 @@ export function AppLayout() {><Menu size={20} /></button>- <div className="flex items-center gap-2">+ <Link+ to="/"+ className="flex items-center gap-2 -mx-1 px-1 py-1 rounded-md hover:bg-sidebar-accent transition-colors"+ aria-label={t('app.name')}+ title={t('nav.dashboard')}+ ><ShellLogo size={22} className="text-primary shrink-0" /><span className="font-bold text-sidebar-foreground">{t('app.name')}</span>- </div>+ </Link><div className="ml-auto flex items-center gap-2"><buttononClick={() => setPaletteOpen(true)}@@ -202,11 +229,25 @@ export function AppLayout() {>{isDark ? <Sun size={18} /> : <Moon size={18} />}</button>+ {/* AI chat — opens the global slide-over (also reachable via+ ⌘J). Sits next to the theme toggle so the icon is always+ within thumb reach on mobile too. */}+ {agentsEnabled && (+ <button+ onClick={() => setChatOpen(true)}+ className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1"+ title={`${t('agents.globalChat.title', 'Chat')} (${isMac ? '⌘J' : 'Ctrl+J'})`}+ aria-label={t('agents.globalChat.openHint', 'Open chat (⌘J)')}+ >+ <Bot size={18} />+ </button>+ )}<UserMenuuserInitial={userInitial}logout={logout}onChangePassword={() => setChangePasswordOpen(true)}onTwoFactor={() => setTwoFactorOpen(true)}+ agentsEnabled={agentsEnabled}backingUp={backingUp}onBackup={async () => {setBackingUp(true)@@ -241,14 +282,22 @@ export function AppLayout() {sidebarOpen ? 'translate-x-0' : '-translate-x-full',)}>- {/* Logo */}+ {/* Logo — clickable link to the dashboard. Replaces the+ dedicated 'Painel' nav item so the sidebar stays focused+ on the main destinations. */}<div className="flex h-16 min-h-16 items-center justify-between px-5 border-b border-sidebar-border shrink-0">- <div className="flex items-center gap-2.5">+ <Link+ to="/"+ className="flex items-center gap-2.5 -mx-1 px-1 py-1 rounded-md hover:bg-sidebar-accent transition-colors"+ onClick={() => setSidebarOpen(false)}+ aria-label={t('app.name')}+ title={t('nav.dashboard')}+ ><ShellLogo size={24} className="text-primary shrink-0" /><span className="font-bold text-lg text-sidebar-foreground tracking-tight">{t('app.name')}</span>- </div>+ </Link><div className="flex items-center gap-0.5"><buttononClick={togglePrivacyMode}@@ -258,6 +307,19 @@ export function AppLayout() {>{privacyMode ? <EyeOff size={16} /> : <Eye size={16} />}</button>+ {/* AI chat — same trigger as the mobile bar, ⌘J also+ works. Lives in the sidebar header so the entry point+ is visible even on first load (no floating button). */}+ {agentsEnabled && (+ <button+ onClick={() => setChatOpen(true)}+ className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1 rounded-md hover:bg-sidebar-accent"+ title={`${t('agents.globalChat.title', 'Chat')} (${isMac ? '⌘J' : 'Ctrl+J'})`}+ aria-label={t('agents.globalChat.openHint', 'Open chat (⌘J)')}+ >+ <Bot size={16} />+ </button>+ )}<buttononClick={toggleTheme}className="text-sidebar-muted hover:text-sidebar-foreground transition-colors p-1 rounded-md hover:bg-sidebar-accent"@@ -295,11 +357,16 @@ export function AppLayout() {<div className="flex-1 min-h-0 overflow-y-auto">{/* Nav */}- <nav className="flex flex-col gap-0.5 p-3" data-tour="sidebar">- {navItems.map((item, idx) => {+ <nav className="flex flex-col gap-0.5 px-3 pt-1 pb-3" data-tour="sidebar">+ {finalNavItems.map((item, idx) => {if (item.type === 'separator') {+ // The first separator sits right below the search bar+ // — without trimming the top padding it leaves a wide+ // gap that makes the section header feel disconnected+ // from the search trigger.+ const isFirstSep = idx === 0return (- <div key={`sep-${idx}`} className="pt-3 pb-1 px-3">+ <div key={`sep-${idx}`} className={cn(isFirstSep ? 'pt-1 pb-1 px-3' : 'pt-3 pb-1 px-3')}><span className="text-[10px] uppercase tracking-[0.12em] font-semibold text-sidebar-muted/50">{t(item.labelKey)}</span>@@ -480,6 +547,15 @@ export function AppLayout() {<HardDriveDownload size={14} />{backingUp ? t('backup.downloading') : t('backup.button')}</DropdownMenuItem>+ {agentsEnabled && (+ <DropdownMenuItem+ onClick={() => navigate('/agents')}+ className="flex items-center gap-2"+ >+ <Sparkles size={14} />+ {t('nav.aiAgents')}+ </DropdownMenuItem>+ )}<DropdownMenuItemonClick={() => setUpdateDialogOpen(true)}className="flex items-center gap-2"@@ -564,6 +640,10 @@ export function AppLayout() {onClose={() => setTwoFactorOpen(false)}/><CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} />+ {/* Slide-over global chat — opened from the sidebar pill or via+ ⌘J. The previous floating bottom-right button was removed+ since the entry point now lives in the sidebar next to ⌘K. */}+ {agentsEnabled && <GlobalChatPanel open={chatOpen} onOpenChange={setChatOpen} />}<UpdateAvailableDialogopen={updateDialogOpen}onClose={() => setUpdateDialogOpen(false)}@@ -581,6 +661,7 @@ function UserMenu({backingUp,dark,isAdmin,+ agentsEnabled,}: {userInitial: stringlogout: () => void@@ -590,6 +671,7 @@ function UserMenu({backingUp: booleandark?: booleanisAdmin?: boolean+ agentsEnabled?: boolean}) {const { t, i18n } = useTranslation()const nav = useNavigate()@@ -646,6 +728,15 @@ function UserMenu({<HardDriveDownload size={14} />{backingUp ? t('backup.downloading') : t('backup.button')}</DropdownMenuItem>+ {agentsEnabled && (+ <DropdownMenuItem+ onClick={() => nav('/agents')}+ className="flex items-center gap-2"+ >+ <Sparkles size={14} />+ {t('nav.aiAgents')}+ </DropdownMenuItem>+ )}<DropdownMenuSub><DropdownMenuSubTrigger className="flex items-center gap-2"><Languages size={14} />diff --git a/frontend/src/components/global-chat-panel.tsx b/frontend/src/components/global-chat-panel.tsxnew file mode 100644index 00000000..eeef5f40--- /dev/null+++ b/frontend/src/components/global-chat-panel.tsx@@ -0,0 +1,424 @@+/**+ * Global slide-over chat — available from every page (⌘J / Ctrl+J).+ *+ * Header surfaces:+ * - Agent selector (all non-archived agents; default agent pre-selected)+ * - Conversation history toggle (resume any prior thread)+ * - New-conversation ++ * - Close ×+ *+ * Conversation persistence: the active conversationId is kept in+ * localStorage keyed by agent. Re-opening the panel resumes the same+ * thread instead of starting fresh — the explicit "+" button is the+ * only way to start a new one.+ *+ * Page context: each send forwards a `page_context` snapshot built+ * from the active page's registration (or a synthesized fallback).+ */+import { useEffect, useMemo, useState } from 'react'+import { Dialog as DialogPrimitive } from 'radix-ui'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { Link } from 'react-router-dom'+import { ArrowLeft, History, Loader2, Plus, Settings, X } from 'lucide-react'+import { Button } from '@/components/ui/button'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { agents } from '@/lib/api'+import type { Agent, AgentConversation } from '@/lib/api'+import { ChatPanel } from '@/components/agents/chat-panel'+import { getEffectivePageChatContext } from '@/lib/page-chat-context'+import { formatRelative } from '@/lib/relative-time'+import { cn } from '@/lib/utils'++interface Props {+ open: boolean+ onOpenChange: (open: boolean) => void+}++const STORAGE_KEY = 'securo.global-chat'++interface PersistedState {+ agentId?: string+ // One conversation pinned per agent so switching agents doesn't lose+ // either thread. Keyed by agent id.+ conversationByAgent?: Record<string, string>+}++function readState(): PersistedState {+ try {+ const raw = localStorage.getItem(STORAGE_KEY)+ return raw ? (JSON.parse(raw) as PersistedState) : {}+ } catch {+ return {}+ }+}++function writeState(s: PersistedState) {+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(s))+ } catch {+ // localStorage can be disabled (private mode, quota); silent fallback.+ }+}++export function GlobalChatPanel({ open, onOpenChange }: Props) {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const [view, setView] = useState<'chat' | 'history'>('chat')+ // Bumped on every "new conversation" click + agent switch so the+ // textarea refocuses even when conversationId itself doesn't change.+ const [focusBump, setFocusBump] = useState(0)++ // Persisted preferences (agent + per-agent active conversation).+ const [persisted, setPersisted] = useState<PersistedState>(() => readState())++ const { data: agentsList, isLoading: loadingAgents } = useQuery({+ queryKey: ['agents'],+ queryFn: () => agents.list(false),+ enabled: open,+ staleTime: 1000 * 30,+ })+ const { data: defaultAgent } = useQuery({+ queryKey: ['agents-default'],+ queryFn: () => agents.getDefault(),+ enabled: open && !persisted.agentId,+ retry: false,+ staleTime: 1000 * 60,+ })++ // Resolve which agent is active. Order: persisted choice → default →+ // first in the list. The picked id always points at an agent that+ // still exists; falls back gracefully when the persisted one was+ // archived/deleted.+ const activeAgent: Agent | undefined = useMemo(() => {+ if (!agentsList || agentsList.length === 0) return undefined+ if (persisted.agentId) {+ const hit = agentsList.find((a) => a.id === persisted.agentId)+ if (hit) return hit+ }+ if (defaultAgent && agentsList.find((a) => a.id === defaultAgent.id)) {+ return agentsList.find((a) => a.id === defaultAgent.id)+ }+ return agentsList[0]+ }, [agentsList, persisted.agentId, defaultAgent])++ const conversationId = activeAgent ? persisted.conversationByAgent?.[activeAgent.id] ?? null : null++ function setConversationForActive(cid: string | null) {+ if (!activeAgent) return+ setPersisted((prev) => {+ const next = { ...prev, conversationByAgent: { ...(prev.conversationByAgent || {}) } }+ if (cid === null) delete next.conversationByAgent![activeAgent.id]+ else next.conversationByAgent![activeAgent.id] = cid+ writeState(next)+ return next+ })+ }++ function selectAgent(id: string) {+ setPersisted((prev) => {+ const next = { ...prev, agentId: id }+ writeState(next)+ return next+ })+ setView('chat')+ setFocusBump((n) => n + 1)+ }++ function startNewConversation() {+ setConversationForActive(null)+ setView('chat')+ setFocusBump((n) => n + 1)+ }++ // When the panel opens, default the inner view to chat (history view+ // is opt-in). Conversation itself is NOT reset — the user explicitly+ // clicks + to start a new one.+ useEffect(() => {+ if (open) {+ setView('chat')+ setFocusBump((n) => n + 1)+ }+ }, [open])++ return (+ <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>+ <DialogPrimitive.Portal>+ <DialogPrimitive.Overlay+ className={cn(+ // Match the command palette (⌘K) overlay: light background-+ // tinted veil + small blur. Distinct from the heavier+ // bg-black/30 we had before, which felt like a modal cut.+ 'fixed inset-0 z-50 backdrop-blur-[3px] bg-background/40',+ 'data-[state=open]:animate-in data-[state=closed]:animate-out',+ 'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',+ )}+ />+ <DialogPrimitive.Content+ aria-describedby={undefined}+ className={cn(+ 'fixed right-0 top-0 z-50 h-full w-full sm:w-[440px] md:w-[480px] bg-background border-l shadow-xl',+ 'flex flex-col outline-none',+ 'data-[state=open]:animate-in data-[state=closed]:animate-out',+ 'data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right',+ 'duration-200',+ )}+ >+ <DialogPrimitive.Title className="sr-only">+ {t('agents.globalChat.title', 'Chat')}+ </DialogPrimitive.Title>++ <header className="flex items-center justify-between gap-2 px-3 py-2 border-b shrink-0">+ <div className="flex items-center gap-1 min-w-0 flex-1">+ {view === 'history' ? (+ <>+ <Button+ size="sm"+ variant="ghost"+ className="-ml-1 px-1.5"+ onClick={() => setView('chat')}+ aria-label="Back to chat"+ >+ <ArrowLeft className="h-4 w-4" />+ </Button>+ <span className="text-sm font-medium truncate">+ {t('agents.globalChat.history', 'Recent conversations')}+ </span>+ </>+ ) : agentsList && agentsList.length > 1 ? (+ // Styled Radix Select — matches the rest of the app and+ // gets a proper popover with active-state styling. The+ // trigger sheds borders to fit the slim header bar.+ <Select value={activeAgent?.id ?? ''} onValueChange={selectAgent}>+ <SelectTrigger+ aria-label={t('agents.globalChat.selectAgent', 'Select agent')}+ className={cn(+ 'h-8 gap-1.5 border-0 bg-transparent shadow-none focus-visible:ring-0',+ 'px-2 -ml-1 hover:bg-muted text-sm font-medium',+ 'data-[size=default]:h-8',+ )}+ >+ {/* The SelectValue renders the matching SelectItem's+ children, so the dot + name + badge live inside+ each item. We don't add a separate dot here or+ it'd appear twice. */}+ <SelectValue placeholder={t('agents.globalChat.selectAgent', 'Select agent')} />+ </SelectTrigger>+ <SelectContent align="start" className="max-h-[60vh]">+ {agentsList.map((a) => (+ <SelectItem key={a.id} value={a.id}>+ <span className="inline-flex items-center gap-2">+ <span+ className="inline-block h-2 w-2 rounded-full shrink-0"+ style={{ backgroundColor: a.color }}+ aria-hidden+ />+ <span>{a.name}</span>+ {a.is_default && (+ <span className="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-amber-200/70 text-amber-900 dark:bg-amber-900/40 dark:text-amber-200">+ {t('agents.defaultBadge', 'Default')}+ </span>+ )}+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <div className="inline-flex items-center gap-2 px-2 -ml-1">+ <span+ className="inline-block h-2 w-2 rounded-full shrink-0"+ style={{ backgroundColor: activeAgent?.color ?? 'transparent' }}+ aria-hidden+ />+ <span className="text-sm font-medium truncate">+ {activeAgent?.name ?? t('agents.globalChat.title', 'Chat')}+ </span>+ {activeAgent?.is_default && (+ <span className="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-amber-200/70 text-amber-900 dark:bg-amber-900/40 dark:text-amber-200 shrink-0">+ {t('agents.defaultBadge', 'Default')}+ </span>+ )}+ </div>+ )}+ </div>+ <div className="flex items-center gap-1">+ {view === 'chat' && activeAgent && (+ <>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => {+ setView('history')+ qc.invalidateQueries({ queryKey: ['global-chat-conversations', activeAgent.id] })+ }}+ aria-label={t('agents.globalChat.history', 'Recent conversations')}+ title={t('agents.globalChat.history', 'Recent conversations')}+ >+ <History className="h-4 w-4" />+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={startNewConversation}+ aria-label={t('agents.newConversation', 'New conversation')}+ title={t('agents.newConversation', 'New conversation')}+ >+ <Plus className="h-4 w-4" />+ </Button>+ </>+ )}+ {/* Settings — jumps to /agents (the management page).+ Closing the panel after navigation so the user lands+ on a clean view of the agents config. */}+ <Button+ asChild+ size="sm"+ variant="ghost"+ aria-label={t('agents.globalChat.openSettings', 'Agent settings')}+ title={t('agents.globalChat.openSettings', 'Agent settings')}+ >+ <Link to="/agents" onClick={() => onOpenChange(false)}>+ <Settings className="h-4 w-4" />+ </Link>+ </Button>+ <DialogPrimitive.Close asChild>+ <Button size="sm" variant="ghost" aria-label="Close">+ <X className="h-4 w-4" />+ </Button>+ </DialogPrimitive.Close>+ </div>+ </header>++ <div className="flex-1 min-h-0 flex flex-col">+ {loadingAgents && (+ <div className="flex-1 flex items-center justify-center text-muted-foreground gap-2">+ <Loader2 className="h-4 w-4 animate-spin" />+ <span className="text-sm">{t('common.loading', 'Loading…')}</span>+ </div>+ )}+ {!loadingAgents && agentsList && agentsList.length === 0 && (+ <div className="flex-1 flex flex-col items-center justify-center text-center px-6 gap-2 text-sm text-muted-foreground">+ <span>+ {t(+ 'agents.globalChat.empty',+ 'No agent available. Create one in the Agents page to enable the global chat.',+ )}+ </span>+ <a href="/agents" className="underline text-foreground">+ {t('agents.globalChat.openAgents', 'Go to Agents')}+ </a>+ </div>+ )}+ {activeAgent && view === 'chat' && (+ <ChatPanel+ // Key on agent only. Including conversationId here would+ // remount the panel mid-stream when the SSE assigns a+ // brand-new conversation an id (null → real), wiping the+ // streaming state and hiding the loading bubble for the+ // first message of a fresh chat.+ key={activeAgent.id}+ agent={activeAgent}+ conversationId={conversationId}+ onConversationCreated={(id) => setConversationForActive(id)}+ focusSignal={focusBump}+ getPageContext={() => getEffectivePageChatContext()}+ />+ )}+ {activeAgent && view === 'history' && (+ <ConversationsList+ agentId={activeAgent.id}+ activeConversationId={conversationId}+ onPick={(id) => {+ setConversationForActive(id)+ setView('chat')+ setFocusBump((n) => n + 1)+ }}+ />+ )}+ </div>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ )+}++interface ConvListProps {+ agentId: string+ activeConversationId: string | null+ onPick: (id: string) => void+}++function ConversationsList({ agentId, activeConversationId, onPick }: ConvListProps) {+ const { t } = useTranslation()+ const { data, isLoading } = useQuery({+ queryKey: ['global-chat-conversations', agentId],+ queryFn: () => agents.conversations.list(agentId, 50),+ staleTime: 1000 * 10,+ })++ if (isLoading) {+ return (+ <div className="flex-1 flex items-center justify-center text-muted-foreground gap-2">+ <Loader2 className="h-4 w-4 animate-spin" />+ <span className="text-sm">{t('common.loading', 'Loading…')}</span>+ </div>+ )+ }+ if (!data || data.length === 0) {+ return (+ <div className="flex-1 flex items-center justify-center text-sm text-muted-foreground px-6 text-center">+ {t('agents.globalChat.noConversations', 'No conversations yet.')}+ </div>+ )+ }+ return (+ <div className="flex-1 overflow-y-auto divide-y">+ {data.map((c) => (+ <ConversationRow+ key={c.id}+ conv={c}+ isActive={c.id === activeConversationId}+ onClick={() => onPick(c.id)}+ />+ ))}+ </div>+ )+}++function ConversationRow({+ conv,+ isActive,+ onClick,+}: {+ conv: AgentConversation+ isActive: boolean+ onClick: () => void+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ 'w-full text-left px-3 py-2.5 hover:bg-muted transition-colors flex flex-col gap-0.5',+ isActive && 'bg-muted',+ )}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-medium truncate">+ {conv.title || 'Untitled'}+ </span>+ <span className="text-[11px] text-muted-foreground shrink-0 tabular-nums">+ {formatRelative(conv.updated_at)}+ </span>+ </div>+ </button>+ )+}+diff --git a/frontend/src/hooks/use-feature-flags.ts b/frontend/src/hooks/use-feature-flags.tsnew file mode 100644index 00000000..4f5f2f7a--- /dev/null+++ b/frontend/src/hooks/use-feature-flags.ts@@ -0,0 +1,19 @@+import { useQuery } from '@tanstack/react-query'+import { info } from '@/lib/api'++/**+ * Reads /api/info once per session. Optional modules (agents, etc.) check+ * the returned flags so their nav items / routes stay hidden when the+ * server has the feature disabled.+ */+export function useFeatureFlags() {+ const { data, isLoading } = useQuery({+ queryKey: ['app-info'],+ queryFn: () => info.get(),+ staleTime: 1000 * 60 * 60,+ })+ return {+ isLoading,+ agentsEnabled: !!data?.features?.agents,+ }+}diff --git a/frontend/src/lib/agents-stream.ts b/frontend/src/lib/agents-stream.tsnew file mode 100644index 00000000..24720299--- /dev/null+++ b/frontend/src/lib/agents-stream.ts@@ -0,0 +1,103 @@+/**+ * Tiny SSE consumer for /api/agents/{id}/chat.+ *+ * We can't use the native EventSource because it doesn't allow setting an+ * Authorization header. Instead we POST with fetch, then parse the SSE+ * response stream by hand.+ */++export type AgentStreamEvent =+ | { kind: 'conversation'; conversation_id: string }+ | { kind: 'text_delta'; text: string }+ | { kind: 'tool_call'; tool_name: string; tool_args: Record<string, unknown> }+ | { kind: 'tool_result'; tool_name: string; tool_result: { ok?: boolean; data?: unknown; text?: string | null } }+ | { kind: 'error'; error_code?: string; error_message?: string }+ | { kind: 'done'; finish_reason?: string }++export interface SendMessageOptions {+ agentId: string+ content: string+ conversationId?: string | null+ channel?: string+ // Snapshot of the page the user was on when sending. Forwarded as a+ // system primer so the agent can answer "what about this row?" style+ // questions. Built by the global slide-over from page registrations.+ pageContext?: Record<string, unknown> | null+ signal?: AbortSignal+ onEvent: (ev: AgentStreamEvent) => void+}++export async function streamChat(opts: SendMessageOptions): Promise<void> {+ const token = localStorage.getItem('token') || ''+ const res = await fetch(`/api/agents/${opts.agentId}/chat`, {+ method: 'POST',+ signal: opts.signal,+ headers: {+ 'Content-Type': 'application/json',+ Authorization: token ? `Bearer ${token}` : '',+ },+ body: JSON.stringify({+ content: opts.content,+ conversation_id: opts.conversationId ?? null,+ channel: opts.channel ?? 'web',+ page_context: opts.pageContext ?? null,+ }),+ })++ if (!res.ok || !res.body) {+ let detail = ''+ try {+ detail = await res.text()+ } catch {+ detail = ''+ }+ opts.onEvent({ kind: 'error', error_code: String(res.status), error_message: detail || res.statusText })+ return+ }++ const reader = res.body.getReader()+ const decoder = new TextDecoder('utf-8')+ let buffer = ''++ // SSE framing: events are separated by a blank line. Within an event,+ // `event: <type>` and `data: <json>` lines. We accumulate lines into a+ // buffer until we hit a blank line, then dispatch.+ let currentEvent = 'message'+ let currentData = ''++ function flushEvent() {+ if (!currentData) {+ currentEvent = 'message'+ return+ }+ try {+ const parsed = JSON.parse(currentData)+ const ev = { kind: currentEvent, ...parsed } as AgentStreamEvent+ opts.onEvent(ev)+ } catch {+ // Malformed payload — surface as error so the UI can recover.+ opts.onEvent({ kind: 'error', error_code: 'parse', error_message: currentData })+ }+ currentEvent = 'message'+ currentData = ''+ }++ for (;;) {+ const { value, done } = await reader.read()+ if (done) break+ buffer += decoder.decode(value, { stream: true })+ let idx: number+ while ((idx = buffer.indexOf('\n')) !== -1) {+ const line = buffer.slice(0, idx).replace(/\r$/, '')+ buffer = buffer.slice(idx + 1)+ if (line === '') {+ flushEvent()+ } else if (line.startsWith('event:')) {+ currentEvent = line.slice(6).trim()+ } else if (line.startsWith('data:')) {+ currentData += (currentData ? '\n' : '') + line.slice(5).trim()+ }+ }+ }+ flushEvent()+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1e2140b4..247a9273 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -957,4 +957,243 @@ export const search = {},}+// App-level feature flags (whether optional modules like agents are mounted)+export interface AppInfo {+ features: { agents: boolean }+}++export const info = {+ get: async (): Promise<AppInfo> => {+ const { data } = await api.get('/info')+ return data+ },+}++// Agents / MCP / RAG -- only meaningful when info.features.agents === true.+export interface Agent {+ id: string+ name: string+ description: string | null+ system_prompt: string+ icon: string+ color: string+ connection_id: string | null+ provider: string | null+ model: string | null+ temperature: number+ max_history_messages: number+ top_n: number+ similarity_threshold: number+ extra: Record<string, unknown>+ auto_context: boolean+ is_archived: boolean+ is_default: boolean+ // Populated by GET /agents (list endpoint) for the agents page.+ // Single-agent endpoints leave them at 0 since the row-level page+ // already shows tabs for both lists.+ conversation_count: number+ knowledge_count: number+ created_at: string+ updated_at: string+}++export type LlmConnectionKind = 'ollama' | 'openai' | 'anthropic' | 'openai_compatible'++export interface LlmConnection {+ id: string+ name: string+ kind: LlmConnectionKind+ base_url: string | null+ default_model: string | null+ extra: Record<string, unknown>+ is_default: boolean+ has_api_key: boolean+ created_at: string+ updated_at: string+}++export interface LlmConnectionPayload {+ name: string+ kind: LlmConnectionKind+ base_url?: string | null+ api_key?: string | null+ default_model?: string | null+ extra?: Record<string, unknown>+ is_default?: boolean+}++export interface LlmConnectionTestResult {+ ok: boolean+ detail: string+ models?: string[]+}++export interface AgentConversation {+ id: string+ agent_id: string+ channel: string+ title: string | null+ created_at: string+ updated_at: string+}++export interface AgentMessage {+ id: string+ role: 'system' | 'user' | 'assistant' | 'tool'+ ordinal: number+ content: string | null+ tool_calls: Array<{ id: string; name: string; arguments: Record<string, unknown> }> | null+ tool_result: { tool_call_id?: string; name?: string; data?: unknown; ok?: boolean } | null+ citations: unknown[] | null+ input_tokens: number | null+ output_tokens: number | null+ created_at: string+}++export interface AgentToolHandle {+ server: string+ name: string+ description: string+ is_proposal: boolean+ enabled: boolean+}++export interface KnowledgeDoc {+ id: string+ agent_id: string+ title: string+ source: string | null+ mime: string+ size_bytes: number+ status: 'pending' | 'processing' | 'ready' | 'failed'+ error: string | null+ chunk_count: number+ pinned: boolean+ created_at: string+ updated_at: string+}++export const agents = {+ info: async () => {+ const { data } = await api.get('/agents/info')+ return data as {+ enabled: boolean+ providers: string[]+ embedding_dim: number+ default_top_n: number+ default_similarity_threshold: number+ extra_mcp_servers_configured: boolean+ }+ },+ list: async (includeArchived = false): Promise<Agent[]> => {+ const { data } = await api.get('/agents', { params: { include_archived: includeArchived } })+ return data+ },+ // Default agent for the global slide-over chat panel. Returns the+ // user-flagged default; falls back to the most recent agent.+ // Throws 404 if the user has no agents at all.+ getDefault: async (): Promise<Agent> => {+ const { data } = await api.get('/agents/default')+ return data+ },+ get: async (id: string): Promise<Agent> => {+ const { data } = await api.get(`/agents/${id}`)+ return data+ },+ create: async (payload: Partial<Agent> & { name: string }): Promise<Agent> => {+ const { data } = await api.post('/agents', payload)+ return data+ },+ update: async (id: string, payload: Partial<Agent>): Promise<Agent> => {+ const { data } = await api.patch(`/agents/${id}`, payload)+ return data+ },+ remove: async (id: string): Promise<void> => {+ await api.delete(`/agents/${id}`)+ },+ tools: async (id: string): Promise<{ servers: { name: string }[]; tools: AgentToolHandle[] }> => {+ const { data } = await api.get(`/agents/${id}/tools`)+ return data+ },+ setTools: async (id: string, items: { server: string; tool_name: string; enabled: boolean }[]): Promise<void> => {+ await api.put(`/agents/${id}/tools`, items)+ },+ knowledge: {+ list: async (id: string): Promise<{ items: KnowledgeDoc[]; total: number }> => {+ const { data } = await api.get(`/agents/${id}/knowledge`)+ return data+ },+ upload: async (id: string, file: File, pinned = false): Promise<KnowledgeDoc> => {+ const fd = new FormData()+ fd.append('file', file)+ fd.append('pinned', String(pinned))+ const { data } = await api.post(`/agents/${id}/knowledge`, fd)+ return data+ },+ pin: async (agentId: string, docId: string, pinned: boolean): Promise<KnowledgeDoc> => {+ const { data } = await api.patch(`/agents/${agentId}/knowledge/${docId}/pin`, null, {+ params: { pinned },+ })+ return data+ },+ remove: async (agentId: string, docId: string): Promise<void> => {+ await api.delete(`/agents/${agentId}/knowledge/${docId}`)+ },+ },+ conversations: {+ list: async (agentId?: string, limit = 50): Promise<AgentConversation[]> => {+ const { data } = await api.get('/agents/conversations', { params: { agent_id: agentId, limit } })+ return data+ },+ get: async (id: string): Promise<AgentConversation> => {+ const { data } = await api.get(`/agents/conversations/${id}`)+ return data+ },+ messages: async (id: string, limit = 200): Promise<AgentMessage[]> => {+ const { data } = await api.get(`/agents/conversations/${id}/messages`, { params: { limit } })+ return data+ },+ rename: async (id: string, title: string): Promise<AgentConversation> => {+ const { data } = await api.patch(`/agents/conversations/${id}`, { title })+ return data+ },+ generateTitle: async (id: string): Promise<AgentConversation> => {+ const { data } = await api.post(`/agents/conversations/${id}/generate-title`)+ return data+ },+ remove: async (id: string): Promise<void> => {+ await api.delete(`/agents/conversations/${id}`)+ },+ },+ // Streaming chat endpoint — caller handles the SSE response themselves+ // (see lib/agents-stream.ts). We just expose the URL + body builder.+ chatUrl: (agentId: string) => `/api/agents/${agentId}/chat`,++ connections: {+ list: async (): Promise<LlmConnection[]> => {+ const { data } = await api.get('/agents/connections')+ return data+ },+ get: async (id: string): Promise<LlmConnection> => {+ const { data } = await api.get(`/agents/connections/${id}`)+ return data+ },+ create: async (payload: LlmConnectionPayload): Promise<LlmConnection> => {+ const { data } = await api.post('/agents/connections', payload)+ return data+ },+ update: async (id: string, payload: Partial<LlmConnectionPayload>): Promise<LlmConnection> => {+ const { data } = await api.patch(`/agents/connections/${id}`, payload)+ return data+ },+ remove: async (id: string): Promise<void> => {+ await api.delete(`/agents/connections/${id}`)+ },+ test: async (id: string): Promise<LlmConnectionTestResult> => {+ const { data } = await api.post(`/agents/connections/${id}/test`)+ return data+ },+ },+}+export default apidiff --git a/frontend/src/lib/page-chat-context.tsx b/frontend/src/lib/page-chat-context.tsxnew file mode 100644index 00000000..c5486691--- /dev/null+++ b/frontend/src/lib/page-chat-context.tsx@@ -0,0 +1,67 @@+/**+ * Lightweight page→chat context registry.+ *+ * Pages call `useRegisterPageChatContext({...})` to publish what's+ * currently visible (route, filters, selection). The global slide-over+ * chat reads the latest snapshot at send time via `getPageChatContext()`+ * and forwards it to the executor as `page_context`. Free-form by+ * design — the backend renders whatever it gets into a system primer.+ *+ * Implementation note: we deliberately use a plain ref, NOT React+ * context, so the slide-over can read it without re-rendering on every+ * page state change. The slide-over polls the ref only on send.+ */+import { useEffect, useRef } from 'react'++export type PageChatContext = Record<string, unknown> | null++const _ref: { current: PageChatContext } = { current: null }++export function getPageChatContext(): PageChatContext {+ return _ref.current+}++/** Synthesized fallback when a page hasn't registered explicit context.+ * Gives the agent at least the route + title + a hint that no detailed+ * page state was published — beats sending nothing and having the+ * agent ask "what page?". */+export function getDefaultPageChatContext(): PageChatContext {+ if (typeof window === 'undefined') return null+ const path = window.location.pathname+ const title = (typeof document !== 'undefined' && document.title) || path+ return {+ path,+ label: title,+ summary: `User is on ${title} (${path}). No detailed page state has been published — ask the user what they want explained.`,+ }+}++/** What the global slide-over actually sends: explicit registration if+ * any, else the synthesized fallback. Always at least returns a path. */+export function getEffectivePageChatContext(): PageChatContext {+ return getPageChatContext() ?? getDefaultPageChatContext()+}++/** Pages call this in a useEffect to publish their context. The latest+ * registration wins; on unmount the registration is cleared if it+ * still matches (so navigating away doesn't leave a stale snapshot). */+export function useRegisterPageChatContext(+ ctx: PageChatContext,+ // Pass a stable string — when it changes the registration updates.+ // If you want every render to publish, pass a JSON.stringify of ctx.+ depKey: string,+) {+ const currentRef = useRef<PageChatContext>(null)+ useEffect(() => {+ currentRef.current = ctx+ _ref.current = ctx+ return () => {+ // Only clear if our registration is still the active one — avoids+ // racing with the next page's mount.+ if (_ref.current === currentRef.current) {+ _ref.current = null+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [depKey])+}diff --git a/frontend/src/lib/relative-time.ts b/frontend/src/lib/relative-time.tsnew file mode 100644index 00000000..82186ac9--- /dev/null+++ b/frontend/src/lib/relative-time.ts@@ -0,0 +1,17 @@+/** Compact relative-time formatter shared by chat lists and similar+ * surfaces — "2m ago / 3h ago / yesterday / 4d ago / Mar 14".+ * Plain Date math, no date library. */+export function formatRelative(iso: string): string {+ const d = new Date(iso)+ const diffMs = Date.now() - d.getTime()+ if (Number.isNaN(diffMs)) return ''+ const diffMin = Math.floor(diffMs / 60000)+ if (diffMin < 1) return 'now'+ if (diffMin < 60) return `${diffMin}m ago`+ const diffH = Math.floor(diffMin / 60)+ if (diffH < 24) return `${diffH}h ago`+ const diffD = Math.floor(diffH / 24)+ if (diffD === 1) return 'yesterday'+ if (diffD < 7) return `${diffD}d ago`+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })+}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 25c53698..4f1174dd 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -10,6 +10,7 @@"title": "Command palette","description": "Search transactions, accounts, categories and more.","triggerLabel": "Search everything…",+ "triggerShortLabel": "Search","triggerAria": "Open command palette","placeholder": "What are you looking for?","groups": {@@ -59,7 +60,10 @@"groupAnalysis": "Analysis","groupSetup": "Setup","groupAccounts": "Accounts",- "groupAdmin": "Administration"+ "groupAdmin": "Administration",+ "groupAgents": "AI",+ "agents": "Agents",+ "aiAgents": "AI Agents"},"auth": {"login": "Login",@@ -1069,5 +1073,197 @@"next": "Next","back": "Back","finish": "Get Started"+ },+ "agents": {+ "title": "Agents",+ "subtitle": "Build conversational assistants on top of your Securo data. Each agent can have its own knowledge base, tools, and provider.",+ "newAgent": "New agent",+ "loading": "Loading…",+ "instanceDefault": "instance default",+ "emptyState": {+ "tryAsking": "Try asking",+ "connectedVia": "via",+ "suggestions": [+ "what's my biggest expense category this month?",+ "show my expenses by category as a pie chart",+ "compare my income vs expenses over the last 6 months",+ "what was my last transaction?",+ "how much have I spent in total this month?",+ "which categories grew the most month over month?",+ "summarize my spending trends and flag anything unusual",+ "list my recurring transactions",+ "what's my net worth right now?",+ "how am I doing against my budgets this month?"+ ]+ },+ "empty": {+ "title": "No agents yet",+ "subtitle": "Create your first agent — give it a system prompt, pick a model, and start chatting with your finances.",+ "create": "Create agent"+ },+ "card": {+ "chat": "Chat"+ },+ "form": {+ "createTitle": "New agent",+ "editTitle": "Edit agent",+ "name": "Name",+ "namePlaceholder": "e.g. Brazilian Tax Advisor",+ "description": "Description",+ "descriptionPlaceholder": "What is this agent for?",+ "systemPrompt": "System prompt",+ "systemPromptPlaceholder": "You are a helpful financial assistant. Always cite sources...",+ "provider": "Provider",+ "model": "Model",+ "modelPlaceholder": "llama3.1:8b, gpt-4o-mini, ...",+ "temperature": "Temperature",+ "cancel": "Cancel",+ "save": "Save",+ "create": "Create",+ "saving": "Saving…",+ "nameRequired": "Name is required",+ "saveFailed": "Save failed",+ "created": "Agent created",+ "updated": "Agent updated",+ "connection": "Connection",+ "connectionRequired": "Pick a connection — agents need one to talk to an LLM.",+ "connectionPlaceholder": "Pick a connection",+ "needConnectionTitle": "Add an LLM connection first",+ "needConnectionHint": "An agent needs a connection (OpenAI, Anthropic, Ollama, …) to talk to a model. Set one up, then come back here.",+ "goToConnections": "Go to connections",+ "manageConnections": "manage",+ "willUseConnectionDefault": "Will use the connection's default: {{model}}",+ "autoContext": "Auto-inject account context",+ "autoContextHint": "Prepend a small primer with your name, currency, today's date, and account list at the start of every conversation. Saves the agent from having to ask. Turn off for pure knowledge-base agents."+ },+ "detail": {+ "notFound": "Agent not found.",+ "edit": "Edit",+ "delete": "Delete",+ "deleteConfirm": "Delete this agent? Conversations and uploaded knowledge will also be removed.",+ "deleted": "Agent removed",+ "tabs": {+ "chat": "Chat",+ "knowledge": "Knowledge",+ "tools": "Tools"+ },+ "conversations": "Conversations",+ "newConversation": "New conversation",+ "untitled": "New conversation"+ },+ "knowledge": {+ "title": "Knowledge base",+ "subtitle": "PDF, MD, or TXT. Pinned docs always go into context.",+ "upload": "Upload",+ "uploading": "Uploading…",+ "loading": "Loading…",+ "empty": "No knowledge yet. Upload a doc to enrich this agent.",+ "uploaded": "Uploaded — processing in the background",+ "uploadFailed": "Upload failed",+ "pinTitle": "Pin (always include in context)",+ "unpinTitle": "Unpin",+ "ready": "ready",+ "failed": "failed",+ "chunks": "{{count}} chunks"+ },+ "tools": {+ "title": "Tools",+ "subtitle": "Choose which tools this agent may call. Discovered from your MCP servers.",+ "save": "Save changes",+ "saving": "Saving…",+ "saved": "Tools updated",+ "saveFailed": "Failed to save tool selection",+ "empty": "No tools discovered. Is the MCP server running? (`docker compose --profile agents up -d`)",+ "proposeBadge": "propose",+ "loading": "Loading tools…"+ },+ "chat": {+ "placeholder": "Talk to {{name}}..."+ },+ "chart": {+ "noData": "No data to chart"+ },+ "proposal": {+ "label": "PROPOSAL",+ "applied": "applied",+ "apply": "Apply",+ "applyFailed": "Failed to apply",+ "showRaw": "Tool details",+ "collision": "name already used by {{name}}",+ "kind": {+ "categorize": "Re-categorize transactions",+ "create_category": "Create category",+ "create_budget": "Create budget",+ "create_payee_rule": "Create auto-categorization rule",+ "create_transaction": "Add transaction",+ "create_recurring_transaction": "Add recurring transaction",+ "update_recurring_transaction": "Update recurring transaction",+ "cancel_recurring_transaction": "Cancel recurring transaction",+ "create_goal": "Create goal"+ },+ "summary": {+ "categorize": "{{count}} transaction(s) → {{category}}",+ "createCategory": "“{{name}}”",+ "createBudget": "{{category}}: {{amount}} for {{month}}",+ "createPayeeRule": "matches “{{pattern}}” → {{category}}",+ "createTransaction": "{{type}} of {{amount}} on {{date}} — {{description}} ({{account}})",+ "createRecurring": "{{description}} {{amount}} — {{frequency}} (day {{day}}, {{account}})",+ "updateRecurring": "{{description}} → {{changes}}",+ "deactivateRecurring": "Stop future occurrences of “{{description}}” (history kept)",+ "deleteRecurring": "Permanently delete “{{description}}”",+ "createGoal": "“{{name}}” — target {{target}}, deadline {{deadline}}"+ }+ },+ "conversation": {+ "rename": "Rename",+ "delete": "Delete",+ "save": "Save",+ "cancel": "Cancel",+ "deleted": "Conversation deleted",+ "deleteFailed": "Failed to delete conversation",+ "renameFailed": "Failed to rename conversation",+ "deleteConfirm": "Delete \"{{name}}\"? This will also remove all messages."+ },+ "connections": {+ "title": "LLM Connections",+ "subtitle": "Add the LLM providers you want to use — local Ollama, OpenAI, Anthropic, or any OpenAI-compatible endpoint. Pick one per agent.",+ "manage": "Manage connections",+ "add": "Add connection",+ "createTitle": "New connection",+ "editTitle": "Edit connection",+ "name": "Name",+ "namePlaceholder": "My Ollama (local)",+ "kind": "Provider type",+ "baseUrl": "Endpoint URL",+ "baseUrlPlaceholder": "https://...",+ "baseUrlRequired": "Endpoint URL is required for this provider",+ "ollamaHint": "If Ollama runs on your host machine, use http://host.docker.internal:11434 (Mac/Windows) or your host IP (Linux).",+ "openaiCompatHint": "Just paste the host:port (e.g. http://192.168.1.142:1234). The /v1 path is added automatically. From inside Docker on Mac/Windows, replace localhost with host.docker.internal.",+ "apiKey": "API key / token",+ "apiKeyPlaceholder": "sk-... or leave blank for local providers",+ "apiKeyPlaceholderEdit": "Leave blank to keep the existing key",+ "apiKeyHint": "Stored encrypted using your instance secret. Never returned by the API.",+ "defaultModel": "Default model",+ "setAsDefault": "Use as default for new agents",+ "default": "default",+ "providerDefaultEndpoint": "(provider default)",+ "noDefaultModel": "no default model",+ "test": "Test",+ "cancel": "Cancel",+ "save": "Save",+ "saving": "Saving…",+ "create": "Create",+ "created": "Connection created",+ "updated": "Connection updated",+ "deleted": "Connection removed",+ "saveFailed": "Save failed",+ "nameRequired": "Name is required",+ "deleteConfirm": "Delete connection \"{{name}}\"? Agents pointing at it will fall back to the instance default.",+ "optional": "optional",+ "empty": {+ "title": "No connections yet",+ "subtitle": "Add a connection to point Securo at your local Ollama, OpenAI, Anthropic, or any OpenAI-compatible endpoint."+ }+ }}}diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 2fd8e3cb..4e264654 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -10,6 +10,7 @@"title": "Paleta de comandos","description": "Busque transações, contas, categorias e muito mais.","triggerLabel": "Buscar em tudo…",+ "triggerShortLabel": "Buscar","triggerAria": "Abrir paleta de comandos","placeholder": "O que você está procurando?","groups": {@@ -59,7 +60,10 @@"groupAnalysis": "Análise","groupSetup": "Configuração","groupAccounts": "Contas",- "groupAdmin": "Administração"+ "groupAdmin": "Administração",+ "groupAgents": "IA",+ "agents": "Agentes",+ "aiAgents": "Agentes IA"},"auth": {"login": "Entrar",@@ -1069,5 +1073,197 @@"next": "Próximo","back": "Voltar","finish": "Começar"+ },+ "agents": {+ "title": "Agentes",+ "subtitle": "Construa assistentes conversacionais sobre seus dados do Securo. Cada agente pode ter sua própria base de conhecimento, ferramentas e provedor.",+ "newAgent": "Novo agente",+ "loading": "Carregando…",+ "instanceDefault": "padrão da instância",+ "emptyState": {+ "tryAsking": "Experimente perguntar",+ "connectedVia": "via",+ "suggestions": [+ "qual minha maior categoria de gasto esse mês?",+ "me mostra meus gastos por categoria num gráfico de pizza",+ "compara minha receita e despesa nos últimos 6 meses",+ "qual foi minha última transação?",+ "quanto gastei no total esse mês?",+ "quais categorias mais cresceram mês a mês?",+ "resume meus padrões de gasto e aponta algo fora do comum",+ "lista minhas transações recorrentes",+ "qual meu patrimônio líquido agora?",+ "como estou em relação aos meus orçamentos esse mês?"+ ]+ },+ "empty": {+ "title": "Nenhum agente ainda",+ "subtitle": "Crie seu primeiro agente — defina um prompt do sistema, escolha um modelo e comece a conversar com suas finanças.",+ "create": "Criar agente"+ },+ "card": {+ "chat": "Conversar"+ },+ "form": {+ "createTitle": "Novo agente",+ "editTitle": "Editar agente",+ "name": "Nome",+ "namePlaceholder": "ex.: Consultor Tributário Brasileiro",+ "description": "Descrição",+ "descriptionPlaceholder": "Para que serve este agente?",+ "systemPrompt": "Prompt do sistema",+ "systemPromptPlaceholder": "Você é um assistente financeiro útil. Sempre cite as fontes...",+ "provider": "Provedor",+ "model": "Modelo",+ "modelPlaceholder": "llama3.1:8b, gpt-4o-mini, ...",+ "temperature": "Temperatura",+ "cancel": "Cancelar",+ "save": "Salvar",+ "create": "Criar",+ "saving": "Salvando…",+ "nameRequired": "Nome é obrigatório",+ "saveFailed": "Falha ao salvar",+ "created": "Agente criado",+ "updated": "Agente atualizado",+ "connection": "Conexão",+ "connectionRequired": "Escolha uma conexão — agentes precisam de uma para conversar com um LLM.",+ "connectionPlaceholder": "Escolha uma conexão",+ "needConnectionTitle": "Adicione uma conexão LLM primeiro",+ "needConnectionHint": "Um agente precisa de uma conexão (OpenAI, Anthropic, Ollama, …) para conversar com um modelo. Configure uma e volte aqui.",+ "goToConnections": "Ir para conexões",+ "manageConnections": "gerenciar",+ "willUseConnectionDefault": "Usará o padrão da conexão: {{model}}",+ "autoContext": "Injetar contexto da conta automaticamente",+ "autoContextHint": "Prepende um pequeno resumo com seu nome, moeda, data de hoje e lista de contas no início de cada conversa. Evita que o agente precise perguntar. Desligue para agentes que usam só base de conhecimento."+ },+ "detail": {+ "notFound": "Agente não encontrado.",+ "edit": "Editar",+ "delete": "Excluir",+ "deleteConfirm": "Excluir este agente? Conversas e conhecimento enviado também serão removidos.",+ "deleted": "Agente removido",+ "tabs": {+ "chat": "Conversa",+ "knowledge": "Conhecimento",+ "tools": "Ferramentas"+ },+ "conversations": "Conversas",+ "newConversation": "Nova conversa",+ "untitled": "Nova conversa"+ },+ "knowledge": {+ "title": "Base de conhecimento",+ "subtitle": "PDF, MD ou TXT. Documentos fixados sempre entram no contexto.",+ "upload": "Enviar",+ "uploading": "Enviando…",+ "loading": "Carregando…",+ "empty": "Sem conhecimento ainda. Envie um documento para enriquecer este agente.",+ "uploaded": "Enviado — processando em segundo plano",+ "uploadFailed": "Falha no envio",+ "pinTitle": "Fixar (sempre incluir no contexto)",+ "unpinTitle": "Desafixar",+ "ready": "pronto",+ "failed": "falhou",+ "chunks": "{{count}} trechos"+ },+ "tools": {+ "title": "Ferramentas",+ "subtitle": "Escolha quais ferramentas este agente pode chamar. Descobertas a partir dos seus servidores MCP.",+ "save": "Salvar alterações",+ "saving": "Salvando…",+ "saved": "Ferramentas atualizadas",+ "saveFailed": "Falha ao salvar a seleção de ferramentas",+ "empty": "Nenhuma ferramenta descoberta. O servidor MCP está rodando? (`docker compose --profile agents up -d`)",+ "proposeBadge": "proposta",+ "loading": "Carregando ferramentas…"+ },+ "chat": {+ "placeholder": "Converse com {{name}}..."+ },+ "chart": {+ "noData": "Sem dados para o gráfico"+ },+ "proposal": {+ "label": "PROPOSTA",+ "applied": "aplicada",+ "apply": "Aplicar",+ "applyFailed": "Falha ao aplicar",+ "showRaw": "Detalhes da ferramenta",+ "collision": "nome já usado por {{name}}",+ "kind": {+ "categorize": "Recategorizar transações",+ "create_category": "Criar categoria",+ "create_budget": "Criar orçamento",+ "create_payee_rule": "Criar regra de categorização automática",+ "create_transaction": "Adicionar transação",+ "create_recurring_transaction": "Adicionar transação recorrente",+ "update_recurring_transaction": "Atualizar transação recorrente",+ "cancel_recurring_transaction": "Cancelar transação recorrente",+ "create_goal": "Criar meta"+ },+ "summary": {+ "categorize": "{{count}} transação(ões) → {{category}}",+ "createCategory": "“{{name}}”",+ "createBudget": "{{category}}: {{amount}} para {{month}}",+ "createPayeeRule": "casa “{{pattern}}” → {{category}}",+ "createTransaction": "{{type}} de {{amount}} em {{date}} — {{description}} ({{account}})",+ "createRecurring": "{{description}} {{amount}} — {{frequency}} (dia {{day}}, {{account}})",+ "updateRecurring": "{{description}} → {{changes}}",+ "deactivateRecurring": "Parar futuras ocorrências de “{{description}}” (histórico mantido)",+ "deleteRecurring": "Excluir permanentemente “{{description}}”",+ "createGoal": "“{{name}}” — meta {{target}}, prazo {{deadline}}"+ }+ },+ "conversation": {+ "rename": "Renomear",+ "delete": "Excluir",+ "save": "Salvar",+ "cancel": "Cancelar",+ "deleted": "Conversa excluída",+ "deleteFailed": "Falha ao excluir a conversa",+ "renameFailed": "Falha ao renomear a conversa",+ "deleteConfirm": "Excluir \"{{name}}\"? Isso também removerá todas as mensagens."+ },+ "connections": {+ "title": "Conexões de LLM",+ "subtitle": "Adicione os provedores de LLM que você quer usar — Ollama local, OpenAI, Anthropic ou qualquer endpoint compatível com OpenAI. Escolha um por agente.",+ "manage": "Gerenciar conexões",+ "add": "Adicionar conexão",+ "createTitle": "Nova conexão",+ "editTitle": "Editar conexão",+ "name": "Nome",+ "namePlaceholder": "Meu Ollama (local)",+ "kind": "Tipo de provedor",+ "baseUrl": "URL do endpoint",+ "baseUrlPlaceholder": "https://...",+ "baseUrlRequired": "A URL do endpoint é obrigatória para este provedor",+ "ollamaHint": "Se o Ollama roda na sua máquina, use http://host.docker.internal:11434 (Mac/Windows) ou o IP do seu host (Linux).",+ "openaiCompatHint": "Cole apenas host:porta (ex.: http://192.168.1.142:1234). O caminho /v1 é adicionado automaticamente. De dentro do Docker no Mac/Windows, troque localhost por host.docker.internal.",+ "apiKey": "Chave de API / token",+ "apiKeyPlaceholder": "sk-... ou deixe em branco para provedores locais",+ "apiKeyPlaceholderEdit": "Deixe em branco para manter a chave atual",+ "apiKeyHint": "Armazenada criptografada com a chave secreta da instância. Nunca retornada pela API.",+ "defaultModel": "Modelo padrão",+ "setAsDefault": "Usar como padrão para novos agentes",+ "default": "padrão",+ "providerDefaultEndpoint": "(padrão do provedor)",+ "noDefaultModel": "sem modelo padrão",+ "test": "Testar",+ "cancel": "Cancelar",+ "save": "Salvar",+ "saving": "Salvando…",+ "create": "Criar",+ "created": "Conexão criada",+ "updated": "Conexão atualizada",+ "deleted": "Conexão removida",+ "saveFailed": "Falha ao salvar",+ "nameRequired": "Nome é obrigatório",+ "deleteConfirm": "Excluir a conexão \"{{name}}\"? Agentes que a usam voltarão ao padrão da instância.",+ "optional": "opcional",+ "empty": {+ "title": "Nenhuma conexão ainda",+ "subtitle": "Adicione uma conexão para apontar o Securo para seu Ollama local, OpenAI, Anthropic ou qualquer endpoint compatível com OpenAI."+ }+ }}}diff --git a/frontend/src/pages/agent-connections.tsx b/frontend/src/pages/agent-connections.tsxnew file mode 100644index 00000000..77938f77--- /dev/null+++ b/frontend/src/pages/agent-connections.tsx@@ -0,0 +1,163 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { ArrowLeft, CheckCircle2, Edit2, Plug, Plus, Star, Trash2, XCircle } from 'lucide-react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Badge } from '@/components/ui/badge'+import { PageHeader } from '@/components/page-header'+import { agents } from '@/lib/api'+import type { LlmConnection } from '@/lib/api'+import { ConnectionFormDialog } from '@/components/agents/connection-form-dialog'++export default function AgentConnectionsPage() {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const [editing, setEditing] = useState<LlmConnection | null>(null)+ const [createOpen, setCreateOpen] = useState(false)+ const [testResults, setTestResults] = useState<Record<string, { ok: boolean; detail: string }>>({})++ const { data: list, isLoading } = useQuery({+ queryKey: ['agent-connections'],+ queryFn: () => agents.connections.list(),+ })++ const removeMut = useMutation({+ mutationFn: (id: string) => agents.connections.remove(id),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agent-connections'] })+ toast.success(t('agents.connections.deleted'))+ },+ })++ const testMut = useMutation({+ mutationFn: (id: string) => agents.connections.test(id),+ onSuccess: (res, id) => {+ setTestResults((r) => ({ ...r, [id]: { ok: res.ok, detail: res.detail } }))+ },+ })++ return (+ <div>+ <Link+ to="/agents"+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground mb-2 transition-colors"+ >+ <ArrowLeft className="h-3.5 w-3.5" /> {t('agents.title')}+ </Link>++ <PageHeader+ section={t('agents.title')}+ title={t('agents.connections.title')}+ action={+ <Button size="sm" className="gap-1.5 h-8" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.connections.add')}+ </Button>+ }+ />++ <p className="text-sm text-muted-foreground mb-6 max-w-2xl">{t('agents.connections.subtitle')}</p>++ {isLoading ? (+ <div className="bg-card rounded-xl border border-border shadow-sm p-6 text-sm text-muted-foreground">+ {t('agents.loading')}+ </div>+ ) : (list?.length ?? 0) === 0 ? (+ <div className="bg-card rounded-xl border border-border shadow-sm p-10 text-center">+ <div className="h-12 w-12 mx-auto rounded-full bg-muted flex items-center justify-center mb-3">+ <Plug className="h-6 w-6 text-muted-foreground" />+ </div>+ <h2 className="text-base font-semibold">{t('agents.connections.empty.title')}</h2>+ <p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">+ {t('agents.connections.empty.subtitle')}+ </p>+ <Button size="sm" className="gap-1.5 h-8 mt-4" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.connections.add')}+ </Button>+ </div>+ ) : (+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">+ <div className="divide-y divide-border">+ {list?.map((c) => {+ const tested = testResults[c.id]+ return (+ <div+ key={c.id}+ className="flex items-start gap-3 px-4 sm:px-5 py-4 hover:bg-muted/50 transition-colors"+ >+ <div className="h-10 w-10 rounded-md bg-muted flex items-center justify-center shrink-0">+ <Plug className="h-5 w-5 text-muted-foreground" />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <span className="text-sm font-semibold truncate">{c.name}</span>+ <Badge variant="secondary" className="text-[10px] uppercase tracking-wider px-1.5 py-0">+ {c.kind}+ </Badge>+ {c.is_default && (+ <Badge className="text-[10px] uppercase tracking-wider px-1.5 py-0 bg-amber-100 hover:bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200 inline-flex items-center gap-1">+ <Star className="h-3 w-3" /> {t('agents.connections.default')}+ </Badge>+ )}+ </div>+ <div className="text-xs text-muted-foreground mt-0.5 truncate">+ {c.base_url || t('agents.connections.providerDefaultEndpoint')} ·{' '}+ {c.default_model || t('agents.connections.noDefaultModel')}+ </div>+ {tested && (+ <div+ className={`mt-2 inline-flex items-center gap-1.5 text-xs ${+ tested.ok ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400'+ }`}+ >+ {tested.ok ? <CheckCircle2 className="h-3.5 w-3.5" /> : <XCircle className="h-3.5 w-3.5" />}+ {tested.detail}+ </div>+ )}+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <Button+ size="sm"+ variant="outline"+ className="h-8 text-xs"+ onClick={() => testMut.mutate(c.id)}+ disabled={testMut.isPending}+ >+ {t('agents.connections.test')}+ </Button>+ <button+ type="button"+ onClick={() => setEditing(c)}+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ >+ <Edit2 className="h-4 w-4" />+ </button>+ <button+ type="button"+ onClick={() => {+ if (confirm(t('agents.connections.deleteConfirm', { name: c.name }))) {+ removeMut.mutate(c.id)+ }+ }}+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-950/30 transition-colors"+ >+ <Trash2 className="h-4 w-4" />+ </button>+ </div>+ </div>+ )+ })}+ </div>+ </div>+ )}++ <ConnectionFormDialog open={createOpen} onOpenChange={setCreateOpen} />+ <ConnectionFormDialog+ open={!!editing}+ onOpenChange={(o) => !o && setEditing(null)}+ connection={editing}+ />+ </div>+ )+}diff --git a/frontend/src/pages/agent-detail.tsx b/frontend/src/pages/agent-detail.tsxnew file mode 100644index 00000000..bd05805d--- /dev/null+++ b/frontend/src/pages/agent-detail.tsx@@ -0,0 +1,179 @@+import { useState } from 'react'+import { useParams, useNavigate } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { ArrowLeft, Edit2, Trash2, Plus, MessageSquare } from 'lucide-react'+import { ConversationRow } from '@/components/agents/conversation-row'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'+import { agents } from '@/lib/api'+import { AgentFormDialog } from '@/components/agents/agent-form-dialog'+import { ChatPanel } from '@/components/agents/chat-panel'+import { KnowledgeSection } from '@/components/agents/knowledge-section'+import { ToolsSection } from '@/components/agents/tools-section'++export default function AgentDetailPage() {+ const { t } = useTranslation()+ const { id = '' } = useParams<{ id: string }>()+ const navigate = useNavigate()+ const qc = useQueryClient()+ const [editOpen, setEditOpen] = useState(false)+ const [conversationId, setConversationId] = useState<string | null>(null)+ // Increments on every sidebar click so the chat input refocuses even+ // when the conversation id didn't actually change (e.g. clicking "+"+ // while already on a null conversation).+ const [focusSignal, setFocusSignal] = useState(0)+ const pickConversation = (id: string | null) => {+ setConversationId(id)+ setFocusSignal((n) => n + 1)+ }++ const { data: info } = useQuery({ queryKey: ['agents-info'], queryFn: () => agents.info() })+ const { data: agent, isLoading } = useQuery({+ queryKey: ['agent', id],+ queryFn: () => agents.get(id),+ enabled: !!id,+ })+ const { data: conversations } = useQuery({+ queryKey: ['agent-conversations', id],+ queryFn: () => agents.conversations.list(id),+ enabled: !!id,+ })+ const { data: connections } = useQuery({+ queryKey: ['agent-connections'],+ queryFn: () => agents.connections.list(),+ })+ const linkedConnection = agent?.connection_id+ ? connections?.find((c) => c.id === agent.connection_id)+ : undefined+ const providerLabel =+ linkedConnection?.name ||+ (linkedConnection ? linkedConnection.kind : null) ||+ agent?.provider ||+ t('agents.instanceDefault')+ const modelLabel = agent?.model || linkedConnection?.default_model || '—'++ const removeMut = useMutation({+ mutationFn: () => agents.remove(id),+ onSuccess: () => {+ toast.success(t('agents.detail.deleted'))+ qc.invalidateQueries({ queryKey: ['agents'] })+ navigate('/agents')+ },+ })++ if (isLoading) return <div className="p-6 text-sm text-muted-foreground">{t('agents.loading')}</div>+ if (!agent) return <div className="p-6 text-sm text-muted-foreground">{t('agents.detail.notFound')}</div>++ return (+ // Height has to account for the AppLayout's chrome around <Outlet />:+ // - mobile sticky header = h-14 (3.5rem)+ // - p-6 wrapper top+bottom = 3rem+ // Without subtracting both, the input bar gets pushed past the viewport+ // and the user has to scroll the whole page — which they don't want.+ // overflow-hidden ensures only the messages div inside ChatPanel scrolls.+ <div className="flex flex-col h-[calc(100dvh-6.5rem)] lg:h-[calc(100dvh-3rem)] overflow-hidden">+ <div className="border-b px-4 py-3 flex items-center gap-3">+ <Button size="icon" variant="ghost" onClick={() => navigate('/agents')}>+ <ArrowLeft className="h-4 w-4" />+ </Button>+ <div+ className="h-9 w-9 rounded-md flex items-center justify-center text-white shrink-0"+ style={{ backgroundColor: agent.color }}+ >+ <span className="font-semibold">{agent.name[0]}</span>+ </div>+ <div className="min-w-0 flex-1">+ <div className="font-semibold truncate">{agent.name}</div>+ <div className="text-xs text-muted-foreground truncate">+ {providerLabel} · {modelLabel} · temp {agent.temperature}+ </div>+ </div>+ <Button size="sm" variant="outline" onClick={() => setEditOpen(true)}>+ <Edit2 className="h-3.5 w-3.5 mr-1.5" /> {t('agents.detail.edit')}+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => {+ if (confirm(t('agents.detail.deleteConfirm'))) {+ removeMut.mutate()+ }+ }}+ >+ <Trash2 className="h-3.5 w-3.5 mr-1.5" /> {t('agents.detail.delete')}+ </Button>+ </div>++ <Tabs defaultValue="chat" className="flex-1 flex flex-col min-h-0">+ <div className="px-4 pt-3">+ <TabsList>+ <TabsTrigger value="chat">{t('agents.detail.tabs.chat')}</TabsTrigger>+ <TabsTrigger value="knowledge">{t('agents.detail.tabs.knowledge')}</TabsTrigger>+ <TabsTrigger value="tools">{t('agents.detail.tabs.tools')}</TabsTrigger>+ </TabsList>+ </div>++ <TabsContent value="chat" className="flex-1 flex min-h-0 mt-3">+ <aside className="hidden md:flex md:w-64 border-r flex-col min-h-0">+ <div className="px-3 pt-2 pb-1 flex items-center justify-between shrink-0">+ <span className="text-xs uppercase tracking-wider text-muted-foreground">{t('agents.detail.conversations')}</span>+ <Button size="icon" variant="ghost" onClick={() => pickConversation(null)} title={t('agents.detail.newConversation')}>+ <Plus className="h-4 w-4" />+ </Button>+ </div>+ <div className="flex-1 min-h-0 overflow-y-auto">+ {/* Placeholder row for an unsaved new conversation — appears+ when conversationId is null so the user can see what+ they're working on. Replaced by the real entry once the+ first message is sent. */}+ {conversationId === null && (+ <button+ onClick={() => pickConversation(null)}+ className="w-full text-left px-3 py-2 text-sm bg-muted flex items-center gap-2 truncate text-muted-foreground italic"+ >+ <MessageSquare className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">{t('agents.detail.newConversation')}</span>+ </button>+ )}+ {(conversations ?? []).map((c) => (+ <ConversationRow+ key={c.id}+ conv={c}+ agentId={id}+ active={conversationId === c.id}+ onPick={() => pickConversation(c.id)}+ onDeleted={() => {+ if (conversationId === c.id) pickConversation(null)+ }}+ />+ ))}+ </div>+ </aside>+ <div className="flex-1 min-w-0">+ <ChatPanel+ agent={agent}+ conversationId={conversationId}+ focusSignal={focusSignal}+ onConversationCreated={(cid) => {+ setConversationId(cid)+ qc.invalidateQueries({ queryKey: ['agent-conversations', id] })+ }}+ />+ </div>+ </TabsContent>++ <TabsContent value="knowledge" className="flex-1 overflow-y-auto px-4 py-3">+ <KnowledgeSection agentId={id} />+ </TabsContent>++ <TabsContent value="tools" className="flex-1 overflow-y-auto px-4 py-3">+ <ToolsSection agentId={id} />+ </TabsContent>+ </Tabs>++ <AgentFormDialog open={editOpen} onOpenChange={setEditOpen} agent={agent} providers={info?.providers ?? []} />+ </div>+ )+}diff --git a/frontend/src/pages/agents-list.tsx b/frontend/src/pages/agents-list.tsxnew file mode 100644index 00000000..6cb8474b--- /dev/null+++ b/frontend/src/pages/agents-list.tsx@@ -0,0 +1,173 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { Link } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { Bot, ChevronRight, FileText, MessageSquare, Plug, Plus } from 'lucide-react'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Switch } from '@/components/ui/switch'+import { PageHeader } from '@/components/page-header'+import { agents } from '@/lib/api'+import { AgentFormDialog } from '@/components/agents/agent-form-dialog'++export default function AgentsListPage() {+ const { t } = useTranslation()+ const qc = useQueryClient()+ const [createOpen, setCreateOpen] = useState(false)+ const { data: info } = useQuery({ queryKey: ['agents-info'], queryFn: () => agents.info() })+ const { data: list, isLoading } = useQuery({ queryKey: ['agents'], queryFn: () => agents.list() })+ const { data: connections } = useQuery({+ queryKey: ['agent-connections'],+ queryFn: () => agents.connections.list(),+ })+ // Setting an agent as default clears the flag on every other agent+ // server-side; we still need to refresh both queries so the badge+ // and the global-chat picker pick up the change immediately.+ const setDefaultMut = useMutation({+ mutationFn: ({ id, value }: { id: string; value: boolean }) =>+ agents.update(id, { is_default: value }),+ onSuccess: () => {+ qc.invalidateQueries({ queryKey: ['agents'] })+ qc.invalidateQueries({ queryKey: ['agents-default'] })+ },+ onError: () => toast.error(t('agents.form.saveFailed')),+ })++ return (+ <div>+ <PageHeader+ section={t('agents.title')}+ title={t('agents.title')}+ action={+ <div className="flex items-center gap-2">+ <Link to="/agents/connections">+ <Button variant="outline" size="sm" className="gap-1.5 h-8">+ <Plug size={13} /> {t('agents.connections.manage')}+ </Button>+ </Link>+ <Button size="sm" className="gap-1.5 h-8" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.newAgent')}+ </Button>+ </div>+ }+ />++ <p className="text-sm text-muted-foreground mb-6 max-w-2xl">{t('agents.subtitle')}</p>++ {isLoading ? (+ <div className="bg-card rounded-xl border border-border shadow-sm p-6 text-sm text-muted-foreground">+ {t('agents.loading')}+ </div>+ ) : (list?.length ?? 0) === 0 ? (+ <div className="bg-card rounded-xl border border-border shadow-sm p-10 text-center">+ <div className="h-12 w-12 mx-auto rounded-full bg-muted flex items-center justify-center mb-3">+ <Bot className="h-6 w-6 text-muted-foreground" />+ </div>+ <h2 className="text-base font-semibold">{t('agents.empty.title')}</h2>+ <p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">{t('agents.empty.subtitle')}</p>+ <Button size="sm" className="gap-1.5 h-8 mt-4" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.empty.create')}+ </Button>+ </div>+ ) : (+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">+ <div className="divide-y divide-border">+ {list?.map((a) => (+ <div+ key={a.id}+ className="group flex items-center gap-3 px-4 sm:px-5 py-4 hover:bg-muted transition-colors"+ >+ <Link to={`/agents/${a.id}`} className="flex items-center gap-3 flex-1 min-w-0">+ <div+ className="h-10 w-10 rounded-md flex items-center justify-center text-white shrink-0"+ style={{ backgroundColor: a.color }}+ >+ <Bot className="h-5 w-5" />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <div className="text-sm font-semibold truncate group-hover:text-primary transition-colors">+ {a.name}+ </div>+ {a.is_default && (+ <span className="text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-amber-200/70 text-amber-900 dark:bg-amber-900/40 dark:text-amber-200 shrink-0">+ {t('agents.defaultBadge', 'Default')}+ </span>+ )}+ </div>+ <div className="text-xs text-muted-foreground truncate mt-0.5">+ {(() => {+ // Three layers of LLM config (most → least specific):+ // 1. connection_id → user-managed LlmConnection row+ // 2. provider + model → raw values, instance creds+ // 3. nothing → instance default+ // Show the most specific one we can resolve so the+ // row tells the truth instead of always saying+ // "Instance default · —" when the agent uses a+ // connection.+ const conn = a.connection_id+ ? connections?.find((c) => c.id === a.connection_id)+ : undefined+ if (conn) {+ const model = a.model || conn.default_model+ return `${conn.name} · ${model || '—'}`+ }+ if (a.provider) {+ return `${a.provider} · ${a.model || '—'}`+ }+ return t('agents.instanceDefault')+ })()}+ </div>+ {a.description && (+ <p className="text-sm text-muted-foreground mt-1 line-clamp-1">{a.description}</p>+ )}+ <div className="flex items-center gap-3 mt-1.5 text-xs text-muted-foreground">+ <span className="inline-flex items-center gap-1" title={t('agents.conversationsCount', 'Conversations')}>+ <MessageSquare className="h-3 w-3" />+ {a.conversation_count ?? 0}+ </span>+ <span className="inline-flex items-center gap-1" title={t('agents.knowledgeCount', 'Knowledge files')}>+ <FileText className="h-3 w-3" />+ {a.knowledge_count ?? 0}+ </span>+ </div>+ </div>+ </Link>+ {/* Default toggle — wrapper stops the click bubbling so+ flipping the switch doesn't navigate into the agent. */}+ <div+ className="flex items-center gap-2 shrink-0"+ onClick={(e) => e.stopPropagation()}+ title={t(+ 'agents.form.isDefaultHint',+ 'Used by the global slide-over chat (⌘J). Only one agent can be the default — turning this on clears it on others.',+ )}+ >+ <span className="text-xs text-muted-foreground hidden sm:inline">+ {t('agents.defaultLabel', 'Default')}+ </span>+ <Switch+ checked={a.is_default}+ onCheckedChange={(value) =>+ setDefaultMut.mutate({ id: a.id, value: !!value })+ }+ disabled={setDefaultMut.isPending}+ aria-label={t('agents.defaultLabel', 'Default')}+ />+ </div>+ <Link+ to={`/agents/${a.id}`}+ className="shrink-0 text-muted-foreground/60 hover:text-muted-foreground"+ >+ <ChevronRight className="h-4 w-4" />+ </Link>+ </div>+ ))}+ </div>+ </div>+ )}++ <AgentFormDialog open={createOpen} onOpenChange={setCreateOpen} providers={info?.providers ?? []} />+ </div>+ )+}diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex ab74208a..85b1ccc9 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -1,6 +1,7 @@import { useState, useMemo, useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'+import { useRegisterPageChatContext } from '@/lib/page-chat-context'import { assets, assetGroups, currencies as currenciesApi } from '@/lib/api'import { toast } from 'sonner'import { Button } from '@/components/ui/button'@@ -233,6 +234,36 @@ export default function AssetsPage() {queryFn: () => assets.portfolioTrend(),})+ // Publish a snapshot of what's on the Assets page so the global chat+ // (⌘J) can answer "what does this chart mean / what are these+ // wallets?" without needing the user to spell it out.+ const totalValue = (assetsList ?? []).reduce(+ (acc: number, a: { current_value?: number | null }) => acc + Number(a.current_value || 0),+ 0,+ )+ const byType: Record<string, number> = {}+ for (const a of (assetsList ?? []) as Array<{ type?: string; current_value?: number | null }>) {+ if (!a.type) continue+ byType[a.type] = (byType[a.type] || 0) + Number(a.current_value || 0)+ }+ const portfolioTotal = (portfolioData as { total?: number } | undefined)?.total+ const assetsCtxKey = `${assetsList?.length ?? 0}:${totalValue.toFixed(2)}:${portfolioTotal ?? ''}`+ useRegisterPageChatContext(+ {+ path: '/assets',+ label: 'Assets',+ summary:+ `Portfolio overview page. ${assetsList?.length ?? 0} assets totaling ` ++ `~${totalValue.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })} ` ++ `(by current_value). The portfolio chart shows value over time grouped by wallet or asset.`,+ totals_by_type: byType,+ asset_count: assetsList?.length ?? 0,+ total_value: Number(totalValue.toFixed(2)),+ hint: 'For exact per-asset numbers, use the get_net_worth or list_assets tools.',+ },+ assetsCtxKey,+ )+// `refetchQueries` (vs. `invalidateQueries`) forces an immediate refetch// regardless of stale-state heuristics. Our global staleTime of 5 min// combined with the dialog-close re-render was sometimes leaving thediff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 704a15c7..1c54862a 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -1,4 +1,5 @@import { useState, useMemo, useEffect, useRef } from 'react'+import { useRegisterPageChatContext } from '@/lib/page-chat-context'import { getAccountName } from '@/lib/account-utils'import { useNavigate, useSearchParams } from 'react-router-dom'import { useTranslation } from 'react-i18next'@@ -247,6 +248,38 @@ export default function TransactionsPage() {}),})+ // Publish the active filters + result count to the global chat panel.+ // The agent uses this so "what about THIS list?" / "soma essas" /+ // "categorize these" resolve against the filtered view, not the user's+ // entire history. Free-form blob — backend turns it into a primer.+ const ctxFilters = {+ search: searchQuery || undefined,+ account_ids: filterAccountIds.length ? filterAccountIds : undefined,+ category_ids: filterCategoryIds.length ? filterCategoryIds : undefined,+ payee_id: filterPayee || undefined,+ group_id: filterGroupId || undefined,+ type: filterType || undefined,+ uncategorized: filterUncategorized || undefined,+ from: filterFrom || undefined,+ to: filterTo || undefined,+ tags: tagFilters.length ? tagFilters : undefined,+ sort_by: grid.sortBy,+ sort_dir: grid.sortDir,+ page,+ }+ const ctxKey = JSON.stringify(ctxFilters) + ':' + (data?.total ?? '')+ useRegisterPageChatContext(+ {+ path: '/transactions',+ label: 'Transactions',+ summary: data?.total != null+ ? `${data.total} transaction(s) match the active filters (showing page ${page}, 20 per page).`+ : 'Transactions list with active filters.',+ filters: ctxFilters,+ },+ ctxKey,+ )+const { data: categoriesList } = useQuery({queryKey: ['categories'],queryFn: categoriesApi.list,