@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
package/README.md
CHANGED
|
@@ -1,3 +1,228 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/img/logo/logo-lockup-dark.png">
|
|
4
|
+
<img src="docs/img/logo/logo-lockup-light.png" alt="CopyPasta Kitchen" width="520">
|
|
5
|
+
</picture>
|
|
6
|
+
</p>
|
|
2
7
|
|
|
3
|
-
|
|
8
|
+
# CopyPasta-Kitchen 🍝
|
|
9
|
+
|
|
10
|
+
Recetario de plantillas para que los agentes de código (Claude Code y similares) **no se inventen la estructura** de un proyecto, sino que partan de patrones ya probados.
|
|
11
|
+
|
|
12
|
+
Cuando un agente tenga que crear una API con FastAPI, un agente con LangGraph, un frontend, etc., consulta este recetario, carga **solo la receta que necesita** y la usa como referencia.
|
|
13
|
+
|
|
14
|
+
## Objetivo
|
|
15
|
+
|
|
16
|
+
- Reunir en un único sitio patrones extraídos de proyectos reales en producción.
|
|
17
|
+
- Convertirlos en **recetas** reutilizables: backend, agentes, frontend, infraestructura, tests…
|
|
18
|
+
- Que un agente pueda **descubrir, leer y descargar** una receta sin tener que cargar el repositorio entero en su contexto.
|
|
19
|
+
|
|
20
|
+
## Filosofía de las recetas
|
|
21
|
+
|
|
22
|
+
Las recetas siguen la forma de trabajar del autor, sobre todo en backend:
|
|
23
|
+
|
|
24
|
+
- **Factories.** Un único punto construye cada pieza intercambiable: el LLM, la memoria, la autenticación, el STT o el TTS. Un proveedor desconocido lanza un error explícito, nunca un valor por defecto silencioso.
|
|
25
|
+
- **Clases base y herencia.** Cada familia tiene una clase base abstracta (`BaseAgent`, `AppTool`, `Memory`…) y las implementaciones concretas solo declaran lo que las distingue.
|
|
26
|
+
- **Cambiar de proveedor sin tocar código.** El proveedor o el backend se eligen en los **settings** (`.env`): `ASSISTANT_MODEL=claude-sonnet-5-5` o `MEMORY_BACKEND=sql`. La factory lee el valor y construye la implementación. Cambiar de OpenAI a Anthropic, o de memoria en RAM a Postgres, es cambiar una variable.
|
|
27
|
+
- **Settings por bloques.** Hay un único `Settings` por proyecto y cada receta aporta su bloque, que ese `Settings` hereda.
|
|
28
|
+
- **Pydantic siempre.** Cualquier dato estructurado es un modelo Pydantic (`BaseModel`, `frozen=True` si es inmutable): se valida, se serializa y documenta sus campos. No hay `dataclass` en las recetas.
|
|
29
|
+
- **Costuras de test.** Todo se puede probar sin claves ni red: LLMs falsos, implementaciones en memoria e inyección por constructor.
|
|
30
|
+
|
|
31
|
+
## Cómo se estructura un proyecto
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+
|
|
35
|
+
La visión: **el código se lee como una pirámide**. Abres una carpeta, sabes qué fichero mirar primero y desde ahí bajas de lo general al detalle sin buscar en diez sitios a la vez. No es una arquitectura hexagonal por capas (`domain/`, `application/`, `infrastructure/`), que reparte una misma funcionalidad por tres carpetas transversales. Es lo contrario: **lo que cambia junto vive junto**.
|
|
36
|
+
|
|
37
|
+
Un backend típico:
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
backend/src/{{app_name}}/
|
|
41
|
+
├── app.py # la cima: lee Settings, llama a cada factory una vez y monta la app
|
|
42
|
+
├── api/ # rutas FastAPI: solo hablan con los servicios ya construidos
|
|
43
|
+
├── core/ # lo que usa todo el mundo: settings, errores, ids, modelos base
|
|
44
|
+
├── agentic/ # el agente: grafo, nodos, tools, prompts, memoria
|
|
45
|
+
├── rag/ # búsqueda en documentos: contrato, proveedores (Qdrant, pgvector, RAM), chunking
|
|
46
|
+
├── auth/ # quién llama: contrato y proveedores (Supabase, JWT, doble de test)
|
|
47
|
+
├── limits/ # cuota y rate limit: lógica en la base, almacenamiento intercambiable
|
|
48
|
+
└── observability/ # trazas y coste: contrato y proveedores (Langfuse, Opik, LangSmith, nulo)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Cuatro reglas lo sostienen:
|
|
52
|
+
|
|
53
|
+
1. **Por funcionalidad.** Una carpeta por cosa que hace el sistema, con su contrato, sus proveedores, sus modelos y su doble de test dentro. `core/` es la única carpeta transversal y debe quedarse pequeña: settings, errores, ids y modelos que de verdad usan todos. Si algo de `core/` solo lo usa una carpeta, pertenece a esa carpeta.
|
|
54
|
+
|
|
55
|
+
<img src="docs/img/pillars/pillar-01.png" alt="Pilar 1: por funcionalidad, no por capas" width="560">
|
|
56
|
+
|
|
57
|
+
2. **Fachada.** Cada carpeta tiene una puerta: un fichero con su mismo nombre (`store/store.py`, `rag/rag.py`) o, en Python, el `__init__.py` que re-exporta lo público. El resto son piezas internas que nadie importa desde fuera. Excepciones: `core/`, que se importa por ficheros, y las subcarpetas de detalle (`providers/`, `queries/`).
|
|
58
|
+
|
|
59
|
+
<img src="docs/img/pillars/pillar-02.png" alt="Pilar 2: una puerta por carpeta" width="560">
|
|
60
|
+
|
|
61
|
+
3. **Regla de descenso.** Un fichero se lee de arriba abajo: la clase principal primero, los detalles después. Entre carpetas, igual: `app.py`, luego quien orquesta, luego cada capacidad, luego los proveedores. Las dependencias apuntan **siempre hacia abajo**: `app.py` → orquestación → capacidades → `core/`. Dos capacidades no se importan entre sí; si lo necesitan, quien las combina está un nivel por encima.
|
|
62
|
+
|
|
63
|
+
<img src="docs/img/pillars/pillar-03.png" alt="Pilar 3: se lee de arriba abajo" width="560">
|
|
64
|
+
|
|
65
|
+
4. **Strategy + Factory, solo cuando hay algo que elegir.** Cada capacidad **intercambiable** tiene una clase base `ABC` en `base.py`, un fichero por proveedor y un `factory.py` con un `match` sobre un Enum que viene del `.env`. El proveedor se importa solo cuando se elige (instalas solo lo que usas) y un valor desconocido falla con un error que lo nombra. La lógica común vive en la clase base; la subclase solo guarda y lee. **Si solo hay un proveedor y no va a haber un doble de test, no hay clase base ni factory**: una clase concreta y punto. La abstracción se paga cuando aparece la segunda implementación, no antes.
|
|
66
|
+
|
|
67
|
+
<img src="docs/img/pillars/pillar-04.png" alt="Pilar 4: proveedores intercambiables, solo cuando hace falta" width="560">
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
### De dónde viene
|
|
71
|
+
|
|
72
|
+
Nada de esto es nuevo; es una combinación concreta de ideas con nombre y con libro:
|
|
73
|
+
|
|
74
|
+
| Regla de aquí | Idea | Dónde está escrita |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| Por funcionalidad | *Package by feature*, *vertical slices*, *screaming architecture*: la estructura grita qué hace el sistema, no con qué framework está hecho | Robert C. Martin, **Clean Architecture** (Prentice Hall, 2017), cap. 34 "The Missing Chapter" (con Simon Brown) y cap. 21 "Screaming Architecture". Simon Brown, charla y artículos *Modular Monoliths* (2018). Jimmy Bogard, *Vertical Slice Architecture* (2018). En Python, las *apps* de Django; en Go, los paquetes |
|
|
77
|
+
| Clase base + proveedores | Puertos y adaptadores (hexagonal), pero con el puerto dentro de su capacidad y no en una capa `domain/` común | Alistair Cockburn, *Hexagonal Architecture* (artículo, 2005). Martin, **Clean Architecture**, cap. 11 "DIP: The Dependency Inversion Principle" |
|
|
78
|
+
| Strategy + Factory | Patrones *Strategy* y *Factory Method*; el `match` sobre un Enum es la factory moderna en Python 3.10+ | Gamma, Helm, Johnson y Vlissides, **Design Patterns** (Addison-Wesley, 1994), "Strategy" y "Factory Method" |
|
|
79
|
+
| Solo con un segundo proveedor | YAGNI: no se abstrae hasta que hay dos implementaciones (o un doble de test) | Kent Beck, **Extreme Programming Explained** (Addison-Wesley, 1999). Martin Fowler, artículo *Yagni* (2015) |
|
|
80
|
+
| `app.py` en la cima | *Composition root*: un solo sitio construye el grafo de objetos y lo inyecta; nadie más llama a una factory | Mark Seemann y Steven van Deursen, **Dependency Injection: Principles, Practices, and Patterns** (Manning, 2019), cap. 4 |
|
|
81
|
+
| Regla de descenso | *Stepdown rule*: el código se lee como un periódico, titular arriba y detalle abajo; aquí también entre carpetas | Robert C. Martin, **Clean Code** (Prentice Hall, 2008), cap. 3 "Functions", apartado "Reading Code from Top to Bottom" |
|
|
82
|
+
| Dependencias hacia abajo | *Acyclic Dependencies Principle* y *Stable Dependencies Principle*: sin ciclos entre paquetes, y se depende hacia lo estable | Martin, **Clean Architecture**, cap. 14 "Component Coupling" |
|
|
83
|
+
| Fachada | Patrón *Facade*: una puerta por módulo esconde las piezas internas | Gamma et al., **Design Patterns**, "Facade" |
|
|
84
|
+
| Lo que cambia junto vive junto | *Common Closure Principle* | Martin, **Clean Architecture**, cap. 13 "Component Cohesion" |
|
|
85
|
+
|
|
86
|
+
### Límites y cómo evitarlos
|
|
87
|
+
|
|
88
|
+
Esta forma de estructurar tiene riesgos conocidos; conviene nombrarlos para no caer en ellos:
|
|
89
|
+
|
|
90
|
+
- **Ciclos entre capacidades.** El peligro número uno de organizar por funcionalidad: `rag/` importa `auth/`, `auth/` importa `limits/`, y la pirámide se convierte en una red. La regla de dependencias hacia abajo es lo que lo evita, y se puede hacer cumplir con una herramienta (`import-linter` con contratos de capas) en lugar de confiar en la disciplina.
|
|
91
|
+
- **`core/` como cajón desastre.** Todo lo que no se sabe dónde poner acaba en `core/` y se vuelve la carpeta más grande del proyecto. Regla práctica: si lo usa una sola capacidad, va a esa capacidad; si lo usan dos, se pregunta primero si una debería estar encima de la otra.
|
|
92
|
+
- **Abstraer antes de tiempo.** Una `ABC` y una factory para algo que solo tendrá un proveedor es ceremonia (regla 4). La única excepción que la justifica es el doble de test (RAM, nulo, falso): si no vas a querer un doble, una clase concreta. Cuando llegue el segundo proveedor se extrae la base; es un cambio local y barato.
|
|
93
|
+
- **Imports perezosos que fallan tarde.** Importar el proveedor dentro del `match` significa que un paquete que falta no se nota hasta que ese proveedor se elige en producción. Un test que construya cada proveedor desde settings lo descubre antes.
|
|
94
|
+
- **Capacidades que crecen.** Una carpeta con quince ficheros ya no se lee como una pirámide. Es la señal para subcarpetas de detalle (`providers/`, `queries/`) o para partirla en dos capacidades.
|
|
95
|
+
- **Quién orquesta.** Cuando varias capacidades se combinan, hace falta una carpeta por encima que lo haga (`orchestrator/`, `conversation.py`). Si esa lógica se reparte entre las capacidades, se pierde el descenso.
|
|
96
|
+
- **Onboarding.** Quien viene de Django, de Clean Architecture por capas o de la hexagonal clásica busca `models/`, `services/` y `repositories/`. Un párrafo como este en el README del proyecto ahorra esa semana.
|
|
97
|
+
|
|
98
|
+
Las recetas de este repositorio siguen estas reglas: cada una es una capacidad con `base.py`, un fichero por proveedor, `factory.py`, `settings.py` y su doble de test, y `create_app`/`main.py` es la cima que llama a cada factory una vez.
|
|
99
|
+
|
|
100
|
+
<details><summary>Cada pilar en detalle</summary>
|
|
101
|
+
|
|
102
|
+

|
|
103
|
+

|
|
104
|
+

|
|
105
|
+

|
|
106
|
+
|
|
107
|
+
</details>
|
|
108
|
+
|
|
109
|
+
Las imágenes están en inglés y en `docs/img/` (la montaña también como `01-the-mountain.png` estático y `01-the-mountain-3d.mp4`); su guion está en [docs/diagrams.md](docs/diagrams.md).
|
|
110
|
+
|
|
111
|
+
## Recetas
|
|
112
|
+
|
|
113
|
+
### Disponibles
|
|
114
|
+
|
|
115
|
+
| id | Categoría | Para qué | Relación |
|
|
116
|
+
|---|---|---|---|
|
|
117
|
+
| `project-settings` | backend | `Settings` único del backend (pydantic-settings, `.env`), `get_settings()` y composición por bloques | — |
|
|
118
|
+
| `langchain-agent` | agents | Agente con `create_agent`: clase base, factory de LLM (OpenAI, Anthropic, Azure y Groq), tools, prompts YAML | usa `project-settings` |
|
|
119
|
+
| `agent-memory` | agents | Memoria de conversación: backend en settings (RAM o SQL), ventana por turnos, idempotente, tests de conformidad | usa `project-settings` |
|
|
120
|
+
| `langgraph-graph` | agents | Grafo de flujo fijo (router → agente \| rechazo) con salida en JSON o SSE | requiere `langchain-agent` y `agent-memory` |
|
|
121
|
+
| `fastapi-base` | backend | Base de una API FastAPI: `build_app` con request id en respuestas y logs, 500 sin internals, errores con `code`, CORS por settings, `/health`, docs solo en desarrollo | usa `project-settings` |
|
|
122
|
+
| `auth-verifier` | backend | Quién llama a partir del token Bearer: Supabase (JWKS), JWT propio o doble de test, elegido en settings, con 401/503 y mapeo de claims en un método | usa `project-settings` |
|
|
123
|
+
| `agent-chat-api` | backend | Endpoints FastAPI del chat: `POST /agent/chat` (JSON) y `/agent/stream` (SSE), auth Bearer, guards (404/401/403/429) y `create_app` | requiere `fastapi-base`, `langgraph-graph`; usa `project-settings`, `auth-verifier` |
|
|
124
|
+
| `conversation-history` | backend | Historial del chat: `GET /conversations` (lista paginada con título), `GET /conversations/{id}/messages` y `DELETE`, sobre la memoria de `agent-memory` | requiere `agent-chat-api` |
|
|
125
|
+
| `agent-feedback` | backend | Pulgares sobre las respuestas del agente: un voto por usuario y mensaje (upsert), comentario, deshacer y lista por conversación; backend RAM o SQL | requiere `agent-chat-api`, usa `project-settings` |
|
|
126
|
+
| `rate-limit-quota` | backend | Rate limit por usuario y cuota diaria/mensual por tenant: lógica en clases base, backend RAM o SQL por settings, 429 con `code` y `GET /agent/quota` | usa `project-settings`, `agent-chat-api` |
|
|
127
|
+
| `rag-retriever` | backend | Búsqueda en los documentos del tenant: chunking, embeddings (OpenAI o local), store RAM/Qdrant/pgvector por settings, indexado idempotente por hash y el `document_search` de la tool del agente | usa `project-settings`, `langchain-agent` |
|
|
128
|
+
| `observability` | backend | Trazas por turno en Langfuse, Opik o LangSmith (settings), tokens, coste y duración en el log; apagado por defecto y fail-open | usa `project-settings`, `agent-chat-api` |
|
|
129
|
+
| `voice-providers` | backend | Dictado y lectura en voz alta: `POST /voice/transcribe` (multipart) y `/voice/synthesize`, proveedor OpenAI o doble local por settings, audio nunca guardado, errores por causa (413/415/422/429/502/503/504) | requiere `fastapi-base`, `auth-verifier`; usa `project-settings` |
|
|
130
|
+
| `vite-react-base` | frontend | SPA Vite + React + TS para un backend Python: API intercambiable (http o fake) por configuración, cliente con auth y errores tipados | — |
|
|
131
|
+
| `react-agent-chat` | frontend | Chat con un agente en streaming SSE: tokens, tools, cancelar, errores, Markdown seguro | requiere `vite-react-base`, usa `agent-chat-api` |
|
|
132
|
+
| `react-supabase-auth` | frontend | Login con Supabase Auth o fake por settings, sesión persistida, guard `RequireSession`, caducidad y salir | requiere `vite-react-base`, usa `react-app-router` |
|
|
133
|
+
| `react-app-router` | frontend | Rutas con react-router: tabla única, cabecera, pantallas perezosas, 404, guard inyectado desde `main.tsx` | requiere `vite-react-base`, usa `react-supabase-auth` |
|
|
134
|
+
| `playwright-e2e` | frontend | E2E en navegador real contra la build en modo fake, escritorio y móvil, con workflow de CI | requiere `vite-react-base`, `react-supabase-auth`, `react-app-router` |
|
|
135
|
+
|
|
136
|
+
`requires`: hay que copiar las dos recetas. `uses`: se integra con la otra receta, pero no la trae.
|
|
137
|
+
|
|
138
|
+
### Pendientes
|
|
139
|
+
|
|
140
|
+
Nada por ahora: la hoja de ruta está completa. Pendiente de decidir: en los diagramas `limits/` muestra `redis.py`, pero la receta `rate-limit-quota` ofrece `in_memory | sql`.
|
|
141
|
+
|
|
142
|
+
## Conceptos
|
|
143
|
+
|
|
144
|
+
| Concepto | Qué es |
|
|
145
|
+
|---|---|
|
|
146
|
+
| **Receta** | Una pieza reutilizable (p. ej. `fastapi-base`). Vive en `recipes/<categoría>/<id>/`. |
|
|
147
|
+
| `RECIPE.md` | Explica cuándo usar la receta, las decisiones que toma y cómo adaptarla. |
|
|
148
|
+
| `files/` | Los archivos de la plantilla, listos para copiar. |
|
|
149
|
+
| `catalog.yaml` | Índice de todas las recetas: id, categoría, descripción de una línea y tags. |
|
|
150
|
+
|
|
151
|
+
## Estructura
|
|
152
|
+
|
|
153
|
+
```
|
|
154
|
+
CopyPasta-Kitchen/
|
|
155
|
+
├── README.md
|
|
156
|
+
├── AGENTS.md # instrucciones para agentes que trabajan EN este repo
|
|
157
|
+
├── CLAUDE.md # importa AGENTS.md para Claude Code
|
|
158
|
+
├── catalog.yaml # índice de recetas
|
|
159
|
+
├── recipes/
|
|
160
|
+
│ ├── backend/
|
|
161
|
+
│ ├── agents/
|
|
162
|
+
│ └── frontend/
|
|
163
|
+
├── cli/ # CLI "copypasta" (Node, con sus tests)
|
|
164
|
+
├── package.json # el paquete npm @damiangilgonzalez/copypasta: la CLI con las recetas dentro
|
|
165
|
+
├── scripts/prepack.js # rescata los ficheros que npm no empaqueta (.gitignore de una receta)
|
|
166
|
+
└── skills/copypasta/ # skill que envuelve la CLI (la misma que instala el harness)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Uso (CLI `copypasta`)
|
|
170
|
+
|
|
171
|
+
El flujo está pensado para gastar el mínimo contexto en cada paso:
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
# 1. Descubrir: solo ids y descripción corta (filtra por --tag o --category; --json para máquinas)
|
|
175
|
+
copypasta list --tag api
|
|
176
|
+
|
|
177
|
+
# 2. Leer: solo el RECIPE.md de una receta (--files lista los archivos de files/)
|
|
178
|
+
copypasta show fastapi-base
|
|
179
|
+
|
|
180
|
+
# 3. Copiar: los archivos al proyecto. Nunca pisa un archivo que ya exista (salvo --force);
|
|
181
|
+
# --with-requires copia antes las recetas que requiere. Al final dice qué marcadores sustituir.
|
|
182
|
+
copypasta get fastapi-base --to ./backend --with-requires
|
|
183
|
+
|
|
184
|
+
# 4. Mantener el recetario: valida catalog.yaml contra recipes/ (reglas de AGENTS.md)
|
|
185
|
+
copypasta check
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Sin instalación, con `npx` (necesita Node 18.3 o superior):
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
npx @damiangilgonzalez/copypasta list
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Quien usa el [harness](https://www.npmjs.com/package/@damiangilgonzalez/harness) ya lo tiene dentro, en una versión fijada:
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
npx @damiangilgonzalez/harness recipes list
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
El paquete lleva dentro el catálogo y las recetas, así que `get` funciona desde cualquier carpeta. Dentro del checkout vale `node cli/copypasta.js <comando>`. Tests: `npm install` y `npm test` (incluyen empaquetar de verdad y comprobar que el paquete entrega los mismos ficheros que el repo).
|
|
201
|
+
|
|
202
|
+
### Publicar una versión
|
|
203
|
+
|
|
204
|
+
Sube la versión en `package.json`, confirma y empuja un tag con el mismo número (`v0.2.0`). El workflow `release` valida el catálogo, pasa los tests y publica en npm; necesita el secreto `NPM_TOKEN` en el repositorio.
|
|
205
|
+
|
|
206
|
+
### En otros proyectos
|
|
207
|
+
|
|
208
|
+
Dos formas, compatibles entre sí:
|
|
209
|
+
|
|
210
|
+
**Skill de Claude Code** ([skills/copypasta/SKILL.md](skills/copypasta/SKILL.md)): copia la carpeta `skills/copypasta` a `.claude/skills/` del proyecto (o a `~/.claude/skills/` para tenerla en todos). Claude la carga sola cuando va a crear una API, un agente, un frontend, auth, RAG, etc., y sigue el flujo `list` → `show` → `get` → adaptar, respetando las reglas de las recetas. Necesita Node para ejecutar la CLI con `npx`. Con el harness no hay que copiar nada: la skill va en su instalación base.
|
|
211
|
+
|
|
212
|
+
**Una nota en `AGENTS.md`** (o `CLAUDE.md`) del proyecto, para cualquier agente:
|
|
213
|
+
|
|
214
|
+
```markdown
|
|
215
|
+
## Plantillas
|
|
216
|
+
Antes de crear la estructura de una pieza nueva (API, agente, frontend…), ejecuta
|
|
217
|
+
`copypasta list` para ver si existe una receta. Si existe, léela con `copypasta show <id>`
|
|
218
|
+
y síguela en lugar de inventar una estructura.
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Hoja de ruta
|
|
222
|
+
|
|
223
|
+
1. [x] Definir objetivo y estructura (este README y `AGENTS.md`).
|
|
224
|
+
2. [x] Convertir los patrones comunes en recetas:
|
|
225
|
+
- [x] `project-settings`, `fastapi-base`, `langchain-agent`, `agent-memory`, `langgraph-graph`, `agent-chat-api`, `rate-limit-quota`, `conversation-history`, `agent-feedback`, `auth-verifier`, `rag-retriever`, `observability`, `voice-providers`
|
|
226
|
+
- [x] `vite-react-base`, `react-agent-chat`, `react-supabase-auth`, `react-app-router`, `playwright-e2e`
|
|
227
|
+
3. [x] Implementar la CLI `copypasta` (`list`, `show`, `get`, `check`; paquete npm `@damiangilgonzalez/copypasta`).
|
|
228
|
+
4. [x] Skill de Claude Code que envuelve la CLI (`skills/copypasta/`).
|
package/catalog.yaml
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# Índice de recetas. Lo que devuelve `copypasta list`.
|
|
2
|
+
# Cada entrada:
|
|
3
|
+
# - id: fastapi-base # único, kebab-case
|
|
4
|
+
# category: backend # backend | agents | frontend | infra | ...
|
|
5
|
+
# description: API REST base con FastAPI, config por entorno y tests # una línea
|
|
6
|
+
# tags: [api, python, fastapi]
|
|
7
|
+
# path: recipes/backend/fastapi-base
|
|
8
|
+
# requires: [otra-receta] # opcional: hay que copiarla también para que funcione
|
|
9
|
+
# uses: [otra-receta] # opcional: referencia; se integra con ella pero no la trae
|
|
10
|
+
|
|
11
|
+
recipes:
|
|
12
|
+
- id: project-settings
|
|
13
|
+
category: backend
|
|
14
|
+
description: Settings único del backend con pydantic-settings (.env), get_settings() en caché y composición por bloques
|
|
15
|
+
tags: [settings, config, env, pydantic, python]
|
|
16
|
+
path: recipes/backend/project-settings
|
|
17
|
+
|
|
18
|
+
- id: fastapi-base
|
|
19
|
+
category: backend
|
|
20
|
+
description: Base de cualquier API FastAPI con request id, 500 sin internals, errores con code, CORS por settings, /health y docs solo en desarrollo
|
|
21
|
+
tags: [api, fastapi, errors, request-id, cors, python]
|
|
22
|
+
path: recipes/backend/fastapi-base
|
|
23
|
+
uses: [project-settings]
|
|
24
|
+
|
|
25
|
+
- id: langchain-agent
|
|
26
|
+
category: agents
|
|
27
|
+
description: Agente LLM con create_agent (LangChain v1), clase base, factory multi-proveedor, tools, prompts YAML y tests sin API keys
|
|
28
|
+
tags: [agent, langchain, llm, tools, prompts, python]
|
|
29
|
+
path: recipes/agents/langchain-agent
|
|
30
|
+
uses: [project-settings]
|
|
31
|
+
|
|
32
|
+
- id: langgraph-graph
|
|
33
|
+
category: agents
|
|
34
|
+
description: Grafo LangGraph de flujo fijo (router → agente | rechazo) con memoria propia, invoke JSON y streaming SSE
|
|
35
|
+
tags: [graph, langgraph, agent, streaming, memory, python]
|
|
36
|
+
path: recipes/agents/langgraph-graph
|
|
37
|
+
requires: [langchain-agent, agent-memory]
|
|
38
|
+
|
|
39
|
+
- id: agent-memory
|
|
40
|
+
category: agents
|
|
41
|
+
description: Memoria de conversación para agentes con backend elegido en settings (RAM o SQL), ventana por turnos e idempotencia
|
|
42
|
+
tags: [memory, agent, history, sql, python]
|
|
43
|
+
path: recipes/agents/agent-memory
|
|
44
|
+
uses: [project-settings]
|
|
45
|
+
|
|
46
|
+
- id: auth-verifier
|
|
47
|
+
category: backend
|
|
48
|
+
description: Verificación del token Bearer con proveedor elegido en settings (Supabase por JWKS, JWT propio o doble de test) que devuelve el usuario y su tenant
|
|
49
|
+
tags: [auth, jwt, supabase, fastapi, security, python]
|
|
50
|
+
path: recipes/backend/auth-verifier
|
|
51
|
+
uses: [project-settings]
|
|
52
|
+
|
|
53
|
+
- id: agent-chat-api
|
|
54
|
+
category: backend
|
|
55
|
+
description: Endpoints FastAPI de chat con el agente (POST /agent/chat en JSON y /agent/stream en SSE) con auth Bearer, guards y create_app
|
|
56
|
+
tags: [api, fastapi, chat, sse, streaming, agent, python]
|
|
57
|
+
path: recipes/backend/agent-chat-api
|
|
58
|
+
requires: [fastapi-base, langgraph-graph]
|
|
59
|
+
uses: [project-settings, auth-verifier, rate-limit-quota, observability]
|
|
60
|
+
|
|
61
|
+
- id: rag-retriever
|
|
62
|
+
category: backend
|
|
63
|
+
description: Búsqueda en los documentos del tenant para el agente (trocear, embeber, store RAM/Qdrant/pgvector por settings, indexado idempotente) y el servicio de la tool search_documents
|
|
64
|
+
tags: [rag, retrieval, embeddings, qdrant, pgvector, vector-store, agent, python]
|
|
65
|
+
path: recipes/backend/rag-retriever
|
|
66
|
+
uses: [project-settings, langchain-agent]
|
|
67
|
+
|
|
68
|
+
- id: observability
|
|
69
|
+
category: backend
|
|
70
|
+
description: Trazas de cada turno del agente en Langfuse, Opik o LangSmith elegido en settings, más tokens, coste y duración por turno en el log, apagado por defecto y sin tumbar nunca el turno
|
|
71
|
+
tags: [observability, tracing, langfuse, opik, langsmith, tokens, cost, python]
|
|
72
|
+
path: recipes/backend/observability
|
|
73
|
+
uses: [project-settings, agent-chat-api]
|
|
74
|
+
|
|
75
|
+
- id: voice-providers
|
|
76
|
+
category: backend
|
|
77
|
+
description: Dictado y lectura en voz alta para la API (POST /voice/transcribe y /voice/synthesize) con proveedor OpenAI o doble local elegido en settings, sin guardar audio y con códigos de error por causa
|
|
78
|
+
tags: [voice, stt, tts, whisper, speech, audio, fastapi, python]
|
|
79
|
+
path: recipes/backend/voice-providers
|
|
80
|
+
requires: [fastapi-base, auth-verifier]
|
|
81
|
+
uses: [project-settings, rate-limit-quota]
|
|
82
|
+
|
|
83
|
+
- id: vite-react-base
|
|
84
|
+
category: frontend
|
|
85
|
+
description: SPA Vite + React + TypeScript para un backend Python, con API intercambiable (http o fake) por configuración y tests
|
|
86
|
+
tags: [frontend, react, vite, typescript, api-client]
|
|
87
|
+
path: recipes/frontend/vite-react-base
|
|
88
|
+
|
|
89
|
+
- id: react-agent-chat
|
|
90
|
+
category: frontend
|
|
91
|
+
description: Chat React con un agente en streaming SSE (tokens, tools, cancelar, errores, Markdown) para el contrato de langgraph-graph
|
|
92
|
+
tags: [frontend, react, chat, sse, streaming, agent]
|
|
93
|
+
path: recipes/frontend/react-agent-chat
|
|
94
|
+
requires: [vite-react-base]
|
|
95
|
+
uses: [agent-chat-api]
|
|
96
|
+
|
|
97
|
+
- id: react-supabase-auth
|
|
98
|
+
category: frontend
|
|
99
|
+
description: Login del frontend con Supabase Auth o un fake elegido en settings, sesión persistida, guard y caducidad
|
|
100
|
+
tags: [frontend, react, auth, supabase, session]
|
|
101
|
+
path: recipes/frontend/react-supabase-auth
|
|
102
|
+
requires: [vite-react-base]
|
|
103
|
+
uses: [react-app-router, playwright-e2e]
|
|
104
|
+
|
|
105
|
+
- id: react-app-router
|
|
106
|
+
category: frontend
|
|
107
|
+
description: Rutas de la SPA con react-router, cabecera con navegación, pantallas perezosas, 404 y guard inyectado desde main
|
|
108
|
+
tags: [frontend, react, router, navigation]
|
|
109
|
+
path: recipes/frontend/react-app-router
|
|
110
|
+
requires: [vite-react-base]
|
|
111
|
+
uses: [react-supabase-auth, playwright-e2e]
|
|
112
|
+
|
|
113
|
+
- id: playwright-e2e
|
|
114
|
+
category: frontend
|
|
115
|
+
description: E2E con Playwright contra la build en modo fake (sin backend ni Supabase), escritorio y móvil, con workflow de CI
|
|
116
|
+
tags: [frontend, e2e, playwright, ci, testing]
|
|
117
|
+
path: recipes/frontend/playwright-e2e
|
|
118
|
+
requires: [vite-react-base, react-supabase-auth, react-app-router]
|
|
119
|
+
|
|
120
|
+
- id: rate-limit-quota
|
|
121
|
+
category: backend
|
|
122
|
+
description: Rate limit por usuario y cuota diaria/mensual por tenant con la lógica en clases base, almacenamiento intercambiable (RAM o SQL) y 429 con código
|
|
123
|
+
tags: [rate-limit, quota, api, fastapi, sql, python]
|
|
124
|
+
path: recipes/backend/rate-limit-quota
|
|
125
|
+
uses: [project-settings, agent-chat-api]
|
|
126
|
+
|
|
127
|
+
- id: conversation-history
|
|
128
|
+
category: backend
|
|
129
|
+
description: Endpoints FastAPI del historial del chat (listar conversaciones con título y paginación, leer mensajes y borrar) sobre la memoria del agente
|
|
130
|
+
tags: [api, fastapi, chat, history, conversations, python]
|
|
131
|
+
path: recipes/backend/conversation-history
|
|
132
|
+
requires: [agent-chat-api]
|
|
133
|
+
|
|
134
|
+
- id: agent-feedback
|
|
135
|
+
category: backend
|
|
136
|
+
description: Pulgares arriba/abajo sobre respuestas del agente (un voto por usuario y mensaje, comentario, deshacer, lista por conversación) con backend RAM o SQL por settings
|
|
137
|
+
tags: [api, fastapi, feedback, chat, agent, sql, python]
|
|
138
|
+
path: recipes/backend/agent-feedback
|
|
139
|
+
requires: [agent-chat-api]
|
|
140
|
+
uses: [project-settings]
|
package/cli/copypasta.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The catalog: `catalog.yaml` validated into plain frozen objects, plus where the recipes live on disk.
|
|
2
|
+
//
|
|
3
|
+
// Two layouts are supported, same code:
|
|
4
|
+
// - the repo checkout (`catalog.yaml` and `recipes/` at the root, two levels above this file);
|
|
5
|
+
// - the installed npm package, which carries both at its root, in the same place.
|
|
6
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
7
|
+
import { dirname, join, resolve } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
|
|
10
|
+
import { parse as parseYaml } from 'yaml';
|
|
11
|
+
|
|
12
|
+
const ID_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
13
|
+
const RECIPE_KEYS = ['id', 'category', 'description', 'tags', 'path', 'requires', 'uses'];
|
|
14
|
+
const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
15
|
+
|
|
16
|
+
export class CatalogError extends Error {}
|
|
17
|
+
|
|
18
|
+
export class UnknownRecipeError extends Error {
|
|
19
|
+
constructor(recipeId) {
|
|
20
|
+
super(`unknown recipe '${recipeId}'`);
|
|
21
|
+
this.recipeId = recipeId;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function text(entry, key, where) {
|
|
26
|
+
const value = entry[key];
|
|
27
|
+
if (typeof value !== 'string' || value.trim() === '') throw new CatalogError(`${where}: '${key}' is required and must be text`);
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function idList(entry, key, where) {
|
|
32
|
+
const value = entry[key] ?? [];
|
|
33
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {
|
|
34
|
+
throw new CatalogError(`${where}: '${key}' must be a list of text`);
|
|
35
|
+
}
|
|
36
|
+
return Object.freeze([...value]);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseRecipe(entry, index) {
|
|
40
|
+
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) throw new CatalogError(`recipes[${index}]: must be a mapping`);
|
|
41
|
+
const where = typeof entry.id === 'string' ? entry.id : `recipes[${index}]`;
|
|
42
|
+
for (const key of Object.keys(entry)) {
|
|
43
|
+
if (!RECIPE_KEYS.includes(key)) throw new CatalogError(`${where}: unknown key '${key}'`);
|
|
44
|
+
}
|
|
45
|
+
const id = text(entry, 'id', where);
|
|
46
|
+
if (!ID_PATTERN.test(id)) throw new CatalogError(`id must be kebab-case: '${id}'`);
|
|
47
|
+
const description = text(entry, 'description', where).trim();
|
|
48
|
+
if (description.includes('\n')) throw new CatalogError(`${where}: description must be one line`);
|
|
49
|
+
return Object.freeze({
|
|
50
|
+
id,
|
|
51
|
+
category: text(entry, 'category', where),
|
|
52
|
+
description,
|
|
53
|
+
tags: idList(entry, 'tags', where),
|
|
54
|
+
path: text(entry, 'path', where),
|
|
55
|
+
requires: idList(entry, 'requires', where),
|
|
56
|
+
uses: idList(entry, 'uses', where),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Validates the parsed YAML. Unknown keys are an error: a typo in `requires` must not pass silently. */
|
|
61
|
+
export function parseCatalog(data) {
|
|
62
|
+
const source = data ?? {};
|
|
63
|
+
if (typeof source !== 'object' || Array.isArray(source)) throw new CatalogError('catalog.yaml must be a mapping with a `recipes` list');
|
|
64
|
+
for (const key of Object.keys(source)) {
|
|
65
|
+
if (key !== 'recipes') throw new CatalogError(`catalog.yaml: unknown key '${key}'`);
|
|
66
|
+
}
|
|
67
|
+
const entries = source.recipes ?? [];
|
|
68
|
+
if (!Array.isArray(entries)) throw new CatalogError('catalog.yaml: `recipes` must be a list');
|
|
69
|
+
return Object.freeze({ recipes: Object.freeze(entries.map(parseRecipe)) });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function getRecipeEntry(catalog, recipeId) {
|
|
73
|
+
const recipe = catalog.recipes.find((candidate) => candidate.id === recipeId);
|
|
74
|
+
if (!recipe) throw new UnknownRecipeError(recipeId);
|
|
75
|
+
return recipe;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function filterRecipes(catalog, { tag, category } = {}) {
|
|
79
|
+
return catalog.recipes.filter(
|
|
80
|
+
(recipe) => (tag === undefined || recipe.tags.includes(tag)) && (category === undefined || recipe.category === category),
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The recipe and everything it `requires`, transitively, dependencies first. */
|
|
85
|
+
export function closure(catalog, recipeId) {
|
|
86
|
+
const ordered = [];
|
|
87
|
+
const visit = (current, trail) => {
|
|
88
|
+
if (trail.includes(current)) throw new CatalogError(`requires cycle: ${[...trail, current].join(' -> ')}`);
|
|
89
|
+
const recipe = getRecipeEntry(catalog, current);
|
|
90
|
+
for (const dependency of recipe.requires) visit(dependency, [...trail, current]);
|
|
91
|
+
if (!ordered.includes(recipe)) ordered.push(recipe);
|
|
92
|
+
};
|
|
93
|
+
visit(recipeId, []);
|
|
94
|
+
return ordered;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export const recipeDir = (kitchen, recipe) => join(kitchen.root, recipe.path);
|
|
98
|
+
export const recipeMd = (kitchen, recipe) => join(recipeDir(kitchen, recipe), 'RECIPE.md');
|
|
99
|
+
export const filesDir = (kitchen, recipe) => join(recipeDir(kitchen, recipe), 'files');
|
|
100
|
+
|
|
101
|
+
const isFile = (path) => existsSync(path) && statSync(path).isFile();
|
|
102
|
+
const isDir = (path) => existsSync(path) && statSync(path).isDirectory();
|
|
103
|
+
const holdsKitchen = (folder) => isFile(join(folder, 'catalog.yaml')) && isDir(join(folder, 'recipes'));
|
|
104
|
+
|
|
105
|
+
/** The package first (it carries its own copy), then `start` upwards. */
|
|
106
|
+
export function findRoot(start, { packageRoot = PACKAGE_ROOT } = {}) {
|
|
107
|
+
const candidates = [resolve(packageRoot)];
|
|
108
|
+
if (start !== undefined) {
|
|
109
|
+
let current = resolve(start);
|
|
110
|
+
for (;;) {
|
|
111
|
+
candidates.push(current);
|
|
112
|
+
const parent = dirname(current);
|
|
113
|
+
if (parent === current) break;
|
|
114
|
+
current = parent;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const found = candidates.find(holdsKitchen);
|
|
118
|
+
if (!found) throw new CatalogError('catalog.yaml not found: run inside the CopyPasta-Kitchen checkout or install the package');
|
|
119
|
+
return found;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function loadCatalog(path) {
|
|
123
|
+
if (!isFile(path)) throw new CatalogError(`catalog.yaml not found at ${path}`);
|
|
124
|
+
return parseCatalog(parseYaml(readFileSync(path, 'utf8')));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A catalog bound to the directory that holds `catalog.yaml` and `recipes/`. */
|
|
128
|
+
export function openKitchen(root) {
|
|
129
|
+
const resolved = root === undefined ? findRoot(process.cwd()) : resolve(root);
|
|
130
|
+
return Object.freeze({ root: resolved, catalog: loadCatalog(join(resolved, 'catalog.yaml')) });
|
|
131
|
+
}
|