@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.
Files changed (255) hide show
  1. package/README.md +227 -2
  2. package/catalog.yaml +140 -0
  3. package/cli/copypasta.js +4 -0
  4. package/cli/lib/catalog.js +131 -0
  5. package/cli/lib/commands.js +162 -0
  6. package/cli/lib/index.js +4 -0
  7. package/cli/lib/main.js +130 -0
  8. package/package.json +38 -4
  9. package/recipes/agents/agent-memory/RECIPE.md +75 -0
  10. package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
  11. package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
  12. package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
  13. package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
  14. package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
  15. package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
  16. package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
  17. package/recipes/agents/agent-memory/files/pytest.ini +5 -0
  18. package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
  19. package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
  20. package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
  21. package/recipes/agents/langchain-agent/RECIPE.md +101 -0
  22. package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
  23. package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
  24. package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
  25. package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
  26. package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
  27. package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
  28. package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
  29. package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
  30. package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
  31. package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
  32. package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
  33. package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
  34. package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
  35. package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
  36. package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
  37. package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
  38. package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
  39. package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
  40. package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
  41. package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
  42. package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
  43. package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
  44. package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
  45. package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
  46. package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
  47. package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
  48. package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
  49. package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
  50. package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
  51. package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
  52. package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
  53. package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
  54. package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
  55. package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
  56. package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
  57. package/recipes/backend/.gitkeep +0 -0
  58. package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
  59. package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
  60. package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
  61. package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
  62. package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
  63. package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
  64. package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
  65. package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
  66. package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
  67. package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
  68. package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
  69. package/recipes/backend/agent-feedback/RECIPE.md +63 -0
  70. package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
  71. package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
  72. package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
  73. package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
  74. package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
  75. package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
  76. package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
  77. package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
  78. package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
  79. package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
  80. package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
  81. package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
  82. package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
  83. package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
  84. package/recipes/backend/auth-verifier/RECIPE.md +63 -0
  85. package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
  86. package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
  87. package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
  88. package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
  89. package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
  90. package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
  91. package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
  92. package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
  93. package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
  94. package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
  95. package/recipes/backend/conversation-history/RECIPE.md +49 -0
  96. package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
  97. package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
  98. package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
  99. package/recipes/backend/conversation-history/files/pytest.ini +5 -0
  100. package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
  101. package/recipes/backend/fastapi-base/RECIPE.md +57 -0
  102. package/recipes/backend/fastapi-base/files/api/app.py +37 -0
  103. package/recipes/backend/fastapi-base/files/api/base.py +54 -0
  104. package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
  105. package/recipes/backend/fastapi-base/files/api/health.py +19 -0
  106. package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
  107. package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
  108. package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
  109. package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
  110. package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
  111. package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
  112. package/recipes/backend/observability/RECIPE.md +68 -0
  113. package/recipes/backend/observability/files/observability/__init__.py +34 -0
  114. package/recipes/backend/observability/files/observability/factory.py +73 -0
  115. package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
  116. package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
  117. package/recipes/backend/observability/files/observability/models.py +90 -0
  118. package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
  119. package/recipes/backend/observability/files/observability/settings.py +58 -0
  120. package/recipes/backend/observability/files/observability/tracer.py +142 -0
  121. package/recipes/backend/observability/files/observability/usage.py +61 -0
  122. package/recipes/backend/observability/files/pytest.ini +5 -0
  123. package/recipes/backend/observability/files/tests/__init__.py +0 -0
  124. package/recipes/backend/observability/files/tests/test_observability.py +219 -0
  125. package/recipes/backend/project-settings/RECIPE.md +40 -0
  126. package/recipes/backend/project-settings/files/.env.example +7 -0
  127. package/recipes/backend/project-settings/files/core/__init__.py +0 -0
  128. package/recipes/backend/project-settings/files/core/config.py +41 -0
  129. package/recipes/backend/project-settings/files/pytest.ini +3 -0
  130. package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
  131. package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
  132. package/recipes/backend/rag-retriever/RECIPE.md +79 -0
  133. package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
  134. package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
  135. package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
  136. package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
  137. package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
  138. package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
  139. package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
  140. package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
  141. package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
  142. package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
  143. package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
  144. package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
  145. package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
  146. package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
  147. package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
  148. package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
  149. package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
  150. package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
  151. package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
  152. package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
  153. package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
  154. package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
  155. package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
  156. package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
  157. package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
  158. package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
  159. package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
  160. package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
  161. package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
  162. package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
  163. package/recipes/backend/voice-providers/RECIPE.md +73 -0
  164. package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
  165. package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
  166. package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
  167. package/recipes/backend/voice-providers/files/pytest.ini +5 -0
  168. package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
  169. package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
  170. package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
  171. package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
  172. package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
  173. package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
  174. package/recipes/backend/voice-providers/files/voice/base.py +116 -0
  175. package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
  176. package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
  177. package/recipes/backend/voice-providers/files/voice/models.py +85 -0
  178. package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
  179. package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
  180. package/recipes/frontend/.gitkeep +0 -0
  181. package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
  182. package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
  183. package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
  184. package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
  185. package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
  186. package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
  187. package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
  188. package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
  189. package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
  190. package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
  191. package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
  192. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
  193. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
  194. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
  195. package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
  196. package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
  197. package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
  198. package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
  199. package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
  200. package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
  201. package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
  202. package/recipes/frontend/react-app-router/RECIPE.md +58 -0
  203. package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
  204. package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
  205. package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
  206. package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
  207. package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
  208. package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
  209. package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
  210. package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
  211. package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
  212. package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
  213. package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
  214. package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
  215. package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
  216. package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
  217. package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
  218. package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
  219. package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
  220. package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
  221. package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
  222. package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
  223. package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
  224. package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
  225. package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
  226. package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
  227. package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
  228. package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
  229. package/recipes/frontend/vite-react-base/files/.env +6 -0
  230. package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
  231. package/recipes/frontend/vite-react-base/files/index.html +12 -0
  232. package/recipes/frontend/vite-react-base/files/package.json +30 -0
  233. package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
  234. package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
  235. package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
  236. package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
  237. package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
  238. package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
  239. package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
  240. package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
  241. package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
  242. package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
  243. package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
  244. package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
  245. package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
  246. package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
  247. package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
  248. package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
  249. package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
  250. package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
  251. package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
  252. package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
  253. package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
  254. package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
  255. package/unpacked-files.json +3 -0
@@ -0,0 +1,162 @@
1
+ // What each command does, without printing: `main.js` only formats. Tested directly.
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+
5
+ import { CatalogError, UnknownRecipeError, closure, filesDir, filterRecipes, getRecipeEntry, recipeMd } from './catalog.js';
6
+
7
+ // npm never packs a `.gitignore` (nor `.npmrc`), wherever it sits. A recipe that ships one would lose it
8
+ // in the published package, so `scripts/prepack.js` writes those files into this side file, keyed by their
9
+ // path from the kitchen root, and every read of a recipe file goes through here. In a checkout the side
10
+ // file does not exist and the real files are on disk.
11
+ const UNPACKED_FILE = 'unpacked-files.json';
12
+
13
+ function unpacked(kitchen) {
14
+ const path = join(kitchen.root, UNPACKED_FILE);
15
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
16
+ }
17
+
18
+ function walk(folder, prefix = '') {
19
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) return [];
20
+ const found = [];
21
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
22
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
23
+ if (entry.isDirectory()) found.push(...walk(join(folder, entry.name), relative));
24
+ else if (entry.isFile()) found.push(relative);
25
+ }
26
+ return found;
27
+ }
28
+
29
+ const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
30
+
31
+ export function listRecipes(kitchen, filters = {}) {
32
+ return filterRecipes(kitchen.catalog, filters);
33
+ }
34
+
35
+ export function showRecipe(kitchen, recipeId) {
36
+ return readFileSync(recipeMd(kitchen, getRecipeEntry(kitchen.catalog, recipeId)), 'utf8');
37
+ }
38
+
39
+ /** Relative paths of `files/`, sorted, with `/` separators. */
40
+ export function recipeFiles(kitchen, recipeId) {
41
+ const recipe = getRecipeEntry(kitchen.catalog, recipeId);
42
+ const prefix = `${recipe.path}/files/`;
43
+ const fromSideFile = Object.keys(unpacked(kitchen))
44
+ .filter((path) => path.startsWith(prefix))
45
+ .map((path) => path.slice(prefix.length));
46
+ return [...new Set([...walk(filesDir(kitchen, recipe)), ...fromSideFile])].sort(byCodePoint);
47
+ }
48
+
49
+ /** The bytes of one recipe file, from disk or from the side file of the published package. */
50
+ function readRecipeFile(kitchen, recipe, relative) {
51
+ const onDisk = join(filesDir(kitchen, recipe), relative);
52
+ if (existsSync(onDisk)) return readFileSync(onDisk);
53
+ const encoded = unpacked(kitchen)[`${recipe.path}/files/${relative}`];
54
+ if (encoded === undefined) throw new CatalogError(`${recipe.id}: ${relative} is listed but cannot be read`);
55
+ return Buffer.from(encoded, 'base64');
56
+ }
57
+
58
+ /**
59
+ * Copies `files/` of the recipe (and of what it `requires`, if asked) into `destination`.
60
+ *
61
+ * Existing files are never overwritten unless `force`: a template must not clobber the project's own code.
62
+ * The exception is a file this same run just copied from a required recipe: a recipe that `requires` another
63
+ * may replace its files (react-app-router replaces App.tsx of vite-react-base).
64
+ */
65
+ export function getRecipe(kitchen, recipeId, destination, { force = false, withRequires = false } = {}) {
66
+ const recipes = withRequires ? closure(kitchen.catalog, recipeId) : [getRecipeEntry(kitchen.catalog, recipeId)];
67
+ const writtenNow = new Set();
68
+ return recipes.map((recipe) => {
69
+ const copied = [];
70
+ const skipped = [];
71
+ for (const relative of recipeFiles(kitchen, recipe.id)) {
72
+ const target = resolve(destination, relative);
73
+ if (existsSync(target) && !force && !writtenNow.has(target)) {
74
+ skipped.push(relative);
75
+ continue;
76
+ }
77
+ writtenNow.add(target);
78
+ mkdirSync(dirname(target), { recursive: true });
79
+ const source = join(filesDir(kitchen, recipe), relative);
80
+ if (existsSync(source)) copyFileSync(source, target);
81
+ else writeFileSync(target, readRecipeFile(kitchen, recipe, relative));
82
+ copied.push(relative);
83
+ }
84
+ return Object.freeze({ recipeId: recipe.id, copied, skipped, requires: recipe.requires, uses: recipe.uses });
85
+ });
86
+ }
87
+
88
+ /** `{{name}}` markers found in the recipe files: what the consumer has to replace after copying. */
89
+ export function placeholders(kitchen, recipeId) {
90
+ const recipe = getRecipeEntry(kitchen.catalog, recipeId);
91
+ const found = new Set();
92
+ for (const relative of recipeFiles(kitchen, recipeId)) {
93
+ const bytes = readRecipeFile(kitchen, recipe, relative);
94
+ if (bytes.includes(0)) continue; // binary file (an image, a font)
95
+ for (const match of bytes.toString('utf8').matchAll(/\{\{([a-z_][a-z0-9_]*)\}\}/g)) found.add(match[1]);
96
+ }
97
+ return [...found].sort(byCodePoint);
98
+ }
99
+
100
+ class Problem {
101
+ constructor(recipeId, message) {
102
+ this.recipeId = recipeId;
103
+ this.message = message;
104
+ }
105
+
106
+ toString() {
107
+ return `${this.recipeId ?? 'catalog'}: ${this.message}`;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The rules of AGENTS.md: every recipe on disk is in the catalog, every entry exists with RECIPE.md and files/,
113
+ * ids are unique, `requires`/`uses` point to real recipes, no self-reference, no `requires` cycle.
114
+ */
115
+ export function check(kitchen) {
116
+ const problems = [];
117
+ const { catalog } = kitchen;
118
+ const ids = new Set(catalog.recipes.map((recipe) => recipe.id));
119
+
120
+ const seen = new Set();
121
+ for (const recipe of catalog.recipes) {
122
+ const report = (message) => problems.push(new Problem(recipe.id, message));
123
+ if (seen.has(recipe.id)) report('duplicate id');
124
+ seen.add(recipe.id);
125
+
126
+ const expected = `recipes/${recipe.category}/${recipe.id}`;
127
+ if (recipe.path !== expected) report(`path is '${recipe.path}', expected '${expected}'`);
128
+ const readme = recipeMd(kitchen, recipe);
129
+ if (!existsSync(readme)) report('RECIPE.md missing');
130
+ else if (!readFileSync(readme, 'utf8').trimStart().startsWith(`# ${recipe.id}`)) report(`RECIPE.md must start with '# ${recipe.id}'`);
131
+ if (recipeFiles(kitchen, recipe.id).length === 0) report('files/ missing or empty');
132
+ if (recipe.tags.length === 0) report('no tags');
133
+ for (const field of ['requires', 'uses']) {
134
+ for (const other of recipe[field]) {
135
+ if (other === recipe.id) report(`${field} itself`);
136
+ else if (!ids.has(other)) report(`${field} unknown recipe '${other}'`);
137
+ }
138
+ }
139
+ try {
140
+ closure(catalog, recipe.id);
141
+ } catch (error) {
142
+ if (!(error instanceof CatalogError || error instanceof UnknownRecipeError)) throw error;
143
+ report(error.message);
144
+ }
145
+ }
146
+
147
+ const recipesDir = join(kitchen.root, 'recipes');
148
+ const inCatalog = new Set(catalog.recipes.map((recipe) => recipe.path));
149
+ const onDisk = [];
150
+ if (existsSync(recipesDir)) {
151
+ for (const category of readdirSync(recipesDir, { withFileTypes: true })) {
152
+ if (!category.isDirectory()) continue;
153
+ for (const folder of readdirSync(join(recipesDir, category.name), { withFileTypes: true })) {
154
+ if (folder.isDirectory() && !folder.name.startsWith('.')) onDisk.push(`recipes/${category.name}/${folder.name}`);
155
+ }
156
+ }
157
+ }
158
+ for (const path of onDisk.sort(byCodePoint)) {
159
+ if (!inCatalog.has(path)) problems.push(new Problem(null, `${path} exists on disk but is not in catalog.yaml`));
160
+ }
161
+ return problems;
162
+ }
@@ -0,0 +1,4 @@
1
+ // Public surface of the package: the CLI as a function, and the pieces behind it for a host program.
2
+ export { main, usage, USAGE } from './main.js';
3
+ export { CatalogError, UnknownRecipeError, findRoot, openKitchen, parseCatalog } from './catalog.js';
4
+ export { check, getRecipe, listRecipes, placeholders, recipeFiles, showRecipe } from './commands.js';
@@ -0,0 +1,130 @@
1
+ // `copypasta`: list, show, get and check recipes. Output is made for an agent's context: short, no decoration.
2
+ import { parseArgs } from 'node:util';
3
+
4
+ import { CatalogError, UnknownRecipeError, openKitchen } from './catalog.js';
5
+ import * as commands from './commands.js';
6
+
7
+ /** The help text, under the name the user typed: a host CLI (`harness recipes`) passes its own. */
8
+ export const usage = (name = 'copypasta') => `${name}: recetas de CopyPasta-Kitchen (descubrir, leer y copiar)
9
+
10
+ ${name} list [--tag T] [--category C] [--json] ids y descripción de una línea
11
+ ${name} show <id> [--files] el RECIPE.md de una receta, o sus archivos
12
+ ${name} get <id> --to DIR [--with-requires] [--force] copia files/ de la receta al proyecto
13
+ ${name} check valida catalog.yaml contra recipes/
14
+
15
+ --root DIR carpeta con catalog.yaml y recipes/ (por defecto: el paquete o el checkout)
16
+ `;
17
+ export const USAGE = usage();
18
+
19
+ class UsageError extends Error {}
20
+
21
+ const OPTIONS = {
22
+ list: { tag: { type: 'string' }, category: { type: 'string' }, json: { type: 'boolean' } },
23
+ show: { files: { type: 'boolean' } },
24
+ get: { to: { type: 'string' }, 'with-requires': { type: 'boolean' }, force: { type: 'boolean' } },
25
+ check: {},
26
+ };
27
+ const TAKES_ID = ['show', 'get'];
28
+
29
+ function parse(argv) {
30
+ // `--root` is accepted before or after the command, so it is lifted out first.
31
+ const rest = [];
32
+ let root;
33
+ for (let index = 0; index < argv.length; index += 1) {
34
+ const arg = argv[index];
35
+ if (arg === '--root') {
36
+ root = argv[index + 1];
37
+ if (root === undefined) throw new UsageError('--root necesita una carpeta');
38
+ index += 1;
39
+ } else if (arg.startsWith('--root=')) root = arg.slice('--root='.length);
40
+ else rest.push(arg);
41
+ }
42
+ const [command, ...tail] = rest;
43
+ if (command === undefined) throw new UsageError('falta el comando');
44
+ if (!(command in OPTIONS)) throw new UsageError(`comando desconocido '${command}'`);
45
+ let parsed;
46
+ try {
47
+ parsed = parseArgs({ args: tail, options: OPTIONS[command], allowPositionals: true, strict: true });
48
+ } catch (error) {
49
+ throw new UsageError(error.message);
50
+ }
51
+ const expected = TAKES_ID.includes(command) ? 1 : 0;
52
+ if (parsed.positionals.length !== expected) {
53
+ throw new UsageError(expected ? `'${command}' necesita exactamente un id de receta` : `'${command}' no lleva argumentos`);
54
+ }
55
+ if (command === 'get' && !parsed.values.to) throw new UsageError("'get' necesita --to DIR");
56
+ return { root, command, id: parsed.positionals[0], options: parsed.values };
57
+ }
58
+
59
+ const DEFAULT_IO = {
60
+ out: (text) => process.stdout.write(text),
61
+ err: (text) => process.stderr.write(text),
62
+ };
63
+
64
+ /**
65
+ * Runs the CLI and returns the exit code. `io` is how tests (and a host CLI) capture the output;
66
+ * `io.command` is the name printed in help and hints (`copypasta` unless a host says otherwise).
67
+ */
68
+ export function main(argv = process.argv.slice(2), io = DEFAULT_IO) {
69
+ const name = io.command ?? 'copypasta';
70
+ const print = (line = '') => io.out(`${line}\n`);
71
+ if (argv.includes('--help') || argv.includes('-h')) {
72
+ io.out(usage(name));
73
+ return 0;
74
+ }
75
+ try {
76
+ const args = parse(argv);
77
+ return run(openKitchen(args.root), args, print, io, name);
78
+ } catch (error) {
79
+ if (error instanceof UsageError) io.err(`error: ${error.message}\n\n${usage(name)}`);
80
+ else if (error instanceof UnknownRecipeError) io.err(`error: receta desconocida '${error.recipeId}'. Prueba \`${name} list\`.\n`);
81
+ else if (error instanceof CatalogError) io.err(`error: ${error.message}\n`);
82
+ else throw error;
83
+ return 2;
84
+ }
85
+ }
86
+
87
+ function run(kitchen, { command, id, options }, print, io, name) {
88
+ if (command === 'list') {
89
+ const recipes = commands.listRecipes(kitchen, { tag: options.tag, category: options.category });
90
+ if (options.json) {
91
+ const rows = recipes.map(({ id: recipeId, category, description, tags, requires, uses }) => ({ id: recipeId, category, description, tags, requires, uses }));
92
+ print(JSON.stringify(rows, null, 2));
93
+ return 0;
94
+ }
95
+ const width = Math.max(0, ...recipes.map((recipe) => recipe.id.length));
96
+ for (const recipe of recipes) {
97
+ const extra = recipe.requires.length ? ` [requiere ${recipe.requires.join(', ')}]` : '';
98
+ print(`${recipe.id.padEnd(width)} ${recipe.category.padEnd(8)} ${recipe.description}${extra}`);
99
+ }
100
+ return 0;
101
+ }
102
+
103
+ if (command === 'show') {
104
+ if (options.files) print(commands.recipeFiles(kitchen, id).join('\n'));
105
+ else io.out(commands.showRecipe(kitchen, id));
106
+ return 0;
107
+ }
108
+
109
+ if (command === 'get') {
110
+ const withRequires = Boolean(options['with-requires']);
111
+ const results = commands.getRecipe(kitchen, id, options.to, { force: Boolean(options.force), withRequires });
112
+ for (const result of results) {
113
+ print(`${result.recipeId}: ${result.copied.length} archivos copiados en ${options.to}`);
114
+ for (const path of result.skipped) print(` ya existía, no se toca: ${path} (usa --force para sobrescribir)`);
115
+ }
116
+ const last = results.at(-1);
117
+ if (last.requires.length && !withRequires) print(`requiere: ${last.requires.join(', ')} (cópialas también, o usa --with-requires)`);
118
+ if (last.uses.length) print(`se integra con: ${last.uses.join(', ')}`);
119
+ const markers = [...new Set(results.flatMap((result) => commands.placeholders(kitchen, result.recipeId)))].sort();
120
+ if (markers.length) print(`sustituye los marcadores: ${markers.map((marker) => `{{${marker}}}`).join(', ')}`);
121
+ print(`lee cómo adaptarla: ${name} show ${id}`);
122
+ return 0;
123
+ }
124
+
125
+ // check
126
+ const problems = commands.check(kitchen);
127
+ for (const problem of problems) print(String(problem));
128
+ print(`${kitchen.catalog.recipes.length} recetas, ${problems.length} problemas`);
129
+ return problems.length ? 1 : 0;
130
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@damiangilgonzalez/copypasta",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "CLI del recetario CopyPasta-Kitchen: list, show, get y check de recetas, con las recetas dentro.",
5
+ "type": "module",
6
+ "bin": {
7
+ "copypasta": "cli/copypasta.js"
8
+ },
9
+ "exports": {
10
+ ".": "./cli/lib/index.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "engines": {
14
+ "node": ">=18.3"
15
+ },
16
+ "scripts": {
17
+ "test": "node --test cli/tests/",
18
+ "check": "node cli/copypasta.js check",
19
+ "prepack": "node scripts/prepack.js",
20
+ "postpack": "node scripts/prepack.js --clean",
21
+ "prepublishOnly": "npm run check && npm test"
22
+ },
23
+ "dependencies": {
24
+ "yaml": "^2.8.0"
25
+ },
26
+ "files": [
27
+ "cli/copypasta.js",
28
+ "cli/lib",
29
+ "catalog.yaml",
30
+ "recipes",
31
+ "unpacked-files.json"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/damiangilgonzalez1995/CopyPasta-Kitchen.git"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ }
40
+ }
@@ -0,0 +1,75 @@
1
+ # agent-memory
2
+
3
+ ## Cuándo usarla
4
+
5
+ Cuando un agente, suelto o dentro de un grafo, tenga que **recordar la conversación** entre peticiones: chat multiusuario y multitenant, con el historial persistido y una ventana acotada que se reenvía al LLM.
6
+
7
+ No sirve para memoria a largo plazo (hechos del usuario, resúmenes o búsqueda semántica en recuerdos).
8
+
9
+ No depende de otras recetas. **Usa `project-settings`**: trae el bloque `MemorySettings` para heredarlo en el `Settings` del proyecto.
10
+
11
+ ## Qué incluye
12
+
13
+ ```
14
+ agentic/memory/
15
+ models.py MemoryKey (tenant, user, conversation; inmutable) · MemoryBackend (in_memory | sql) · HistoryMessage · ConversationSummary · title_from
16
+ settings.py bloque MemorySettings: MEMORY_BACKEND (obligatorio) y MEMORY_WINDOW_TURNS (10)
17
+ base.py ABC Memory: ventana por turnos, escritura idempotente, get_history, list_conversations, clear(), id de la respuesta
18
+ in_memory.py InMemoryMemory: tests y desarrollo local
19
+ sql.py SqlMemory + tabla agent_messages (SQLAlchemy 2: Postgres o Supabase; SQLite en tests)
20
+ factory.py MemoryFactory.create(settings, session_factory=...)
21
+ tests/
22
+ memory_conformance.py lo que TODO backend debe cumplir (14 tests) + FakeClock
23
+ test_memory.py conformidad en los dos backends + settings y factory (34 tests)
24
+ pytest.ini
25
+ ```
26
+
27
+ ## Decisiones
28
+
29
+ - **El backend se elige en los settings, no en el código.** `MEMORY_BACKEND=in_memory` o `sql`, y `MemoryFactory` construye la implementación. Pasar de RAM a Postgres es cambiar una variable. **No hay valor por defecto**: caer en memoria del proceso "por si acaso" convertiría un error de configuración en historial perdido en cada reinicio.
30
+ - **Clase base y conformidad.** `Memory` (ABC) fija el contrato y cada backend implementa `_fetch_recent_turns`, `_append` y `clear`. Todos pasan la misma `MemoryConformance`. Un backend nuevo (Redis, Mongo…) es una subclase, una rama en la factory y una clase de test.
31
+ - **Ventana en turnos, no en mensajes.** Un turno es un mensaje humano y todo lo que el agente hizo por él. Así la ventana siempre empieza en un mensaje humano y nunca separa una tool de su resultado, que los proveedores rechazan. Además, un agente que usa más tools no recuerda menos. En la base de datos se guarda todo y la ventana solo limita lo que se lee.
32
+ - **`MemoryKey` con los tres ids, siempre.** El `conversation_id` lo elige el cliente; `tenant_id` y `user_id` salen del token. La clave es inmutable y `SqlMemory._thread` es el único sitio que filtra.
33
+ - **Escritura idempotente por `message.id`.** Un reintento no duplica mensajes. Los mensajes sin id se añaden siempre, así que conviene darle al mensaje humano el id del cliente (`HumanMessage(text, id=client_message_id)`).
34
+ - **`add_messages` devuelve el id de la última respuesta** (un `AIMessage` con texto), útil para que el frontend vote o dé feedback.
35
+ - **Dos lectores.** `get_messages` devuelve la ventana para el LLM; `get_history` devuelve el hilo completo con `created_at` para la interfaz, y `list_conversations` el listado del usuario (más reciente primero, título = primer mensaje humano recortado, paginado). Es lo que expone la receta `conversation-history`. El reloj (`clock`) se inyecta para que los tests fijen las fechas.
36
+ - **Sin checkpointer de LangGraph.** La memoria es independiente del grafo: quien llama lee la ventana, ejecuta el agente y guarda los mensajes nuevos.
37
+ - **Asíncrona incluso en RAM.** El contrato lo marca el backend más lento. En SQL, las consultas síncronas van en `asyncio.to_thread`.
38
+
39
+ ## Cómo adaptarla
40
+
41
+ 1. Copia `files/` en la raíz del backend, junto al `agentic/` de las otras recetas.
42
+ 2. **Settings:** en el `Settings` del proyecto (receta `project-settings`):
43
+
44
+ ```python
45
+ from agentic.memory.settings import MemorySettings
46
+
47
+ class Settings(MemorySettings, BaseAppSettings): ...
48
+ ```
49
+
50
+ En el `.env`: `MEMORY_BACKEND=sql` y, si quieres, `MEMORY_WINDOW_TURNS=10`.
51
+ 3. **Tabla:** `metadata.create_all(engine)` o una migración Alembic con la `Table` de `sql.py`.
52
+ 4. **Construirla una vez** en el arranque (FastAPI `lifespan`) con la sesión de la app:
53
+
54
+ ```python
55
+ memory = MemoryFactory.create(get_settings(), session_factory=SessionLocal)
56
+ ```
57
+
58
+ 5. **Un turno con un agente suelto:**
59
+
60
+ ```python
61
+ key = MemoryKey(tenant_id=user.tenant_id, user_id=user.id, conversation_id=body.conversation_id)
62
+ history = await memory.get_messages(key)
63
+ turn = await agent.process(body.question, context=ctx, history=history)
64
+ answer_id = await memory.add_messages(key, turn.new_messages)
65
+ ```
66
+
67
+ 6. **Nuevo backend:** una subclase de `Memory`, un valor en `MemoryBackend`, una rama en `MemoryFactory` y `class TestXMemory(MemoryConformance)` con su fixture `memory`.
68
+
69
+ **Dependencias:** `langchain-core`, `pydantic-settings>=2.6`, `sqlalchemy>=2.0` y un driver Postgres (`psycopg[binary]`) para SQL; `pytest` y `pytest-asyncio` para los tests.
70
+
71
+ ## Origen
72
+
73
+ - Probado en producción: ABC `Memory`, `MemoryKey` con los tres ids e inmutable, ventana por turnos con red de seguridad en el mensaje humano, `MemoryFactory` sin valor por defecto, Postgres con `session_factory` inyectada, id de la última respuesta, backend elegido en los settings y validado por la factory, escritura idempotente y tests de conformidad comunes a todos los backends.
74
+ - Descartado: memoria a través de un servicio externo (MCP sobre Qdrant) sin clase base.
75
+ - Nuevo en esta receta: `clear()`.
@@ -0,0 +1,25 @@
1
+ """Conversation memory for agents. Independent: used by a plain agent or by a graph.
2
+
3
+ Backend chosen in the settings (`MEMORY_BACKEND`), built by `MemoryFactory`. Nothing here imports the app.
4
+ """
5
+
6
+ from .base import DEFAULT_WINDOW_TURNS, Memory, last_answer_id
7
+ from .factory import MemoryFactory
8
+ from .in_memory import InMemoryMemory
9
+ from .models import TITLE_MAX_LENGTH, ConversationSummary, HistoryMessage, MemoryBackend, MemoryKey, title_from
10
+ from .settings import MemorySettings
11
+
12
+ __all__ = [
13
+ "DEFAULT_WINDOW_TURNS",
14
+ "ConversationSummary",
15
+ "HistoryMessage",
16
+ "InMemoryMemory",
17
+ "Memory",
18
+ "MemoryBackend",
19
+ "MemoryFactory",
20
+ "MemoryKey",
21
+ "MemorySettings",
22
+ "TITLE_MAX_LENGTH",
23
+ "last_answer_id",
24
+ "title_from",
25
+ ]
@@ -0,0 +1,101 @@
1
+ """Conversation memory contract. Every backend passes the same tests (`tests/memory_conformance.py`).
2
+
3
+ Not a LangGraph checkpointer: the caller reads a window, runs the agent or graph, and stores
4
+ the new messages. That keeps the memory usable by a plain agent too.
5
+
6
+ - Window in TURNS (a human message plus everything the agent did for it), not in messages:
7
+ the window always starts at a human message, so a tool call is never split from its result
8
+ (providers reject that), and an agent that uses more tools does not remember less.
9
+ - Idempotent writes by `message.id`: a message whose id is already in the thread is skipped,
10
+ so a retry never duplicates. Messages without id are always appended; give the human
11
+ message an id from the client (`HumanMessage(text, id=client_message_id)`) to make retries safe.
12
+ - Two readers: `get_messages` (the window, for the LLM) and `get_history` (the whole thread
13
+ with timestamps, for the UI). `list_conversations` is the sidebar.
14
+ - Async even in memory: the contract follows the slowest backend.
15
+ """
16
+
17
+ from abc import ABC, abstractmethod
18
+ from collections.abc import Callable, Sequence
19
+ from datetime import UTC, datetime
20
+
21
+ from langchain_core.messages import BaseMessage
22
+
23
+ from .models import ConversationSummary, HistoryMessage, MemoryKey
24
+
25
+ DEFAULT_WINDOW_TURNS = 10
26
+ Clock = Callable[[], datetime]
27
+
28
+
29
+ def utc_now() -> datetime:
30
+ return datetime.now(UTC)
31
+
32
+
33
+ class Memory(ABC):
34
+ def __init__(self, *, window_turns: int = DEFAULT_WINDOW_TURNS, clock: Clock = utc_now) -> None:
35
+ if window_turns < 1:
36
+ raise ValueError(f"`window_turns` must be >= 1, got {window_turns}")
37
+ self.window_turns = window_turns
38
+ self._clock = clock # stamps `created_at`; tests inject a fake one
39
+
40
+ async def get_messages(self, key: MemoryKey, *, turns: int | None = None) -> list[BaseMessage]:
41
+ """Last `turns` turns (default: `window_turns`) in order, ready for the LLM. [] for an unknown thread.
42
+
43
+ `turns=0` is a ValueError, not "no limit": it would be an agent with silent amnesia.
44
+ """
45
+ turns = self.window_turns if turns is None else turns
46
+ if turns < 1:
47
+ raise ValueError(f"`turns` must be >= 1, got {turns}")
48
+ return self._start_at_human(await self._fetch_recent_turns(key, turns))
49
+
50
+ async def add_messages(self, key: MemoryKey, messages: Sequence[BaseMessage]) -> str | None:
51
+ """Append to the thread (created if needed). Returns the id of the last AI message with
52
+ content (the answer the frontend can vote on), or None."""
53
+ if messages:
54
+ await self._append(key, list(messages))
55
+ return last_answer_id(messages)
56
+
57
+ @abstractmethod
58
+ async def get_history(self, key: MemoryKey) -> list[HistoryMessage]:
59
+ """The WHOLE thread in order with timestamps, tool calls included. [] for an unknown thread.
60
+ For the UI; the LLM gets `get_messages`."""
61
+
62
+ @abstractmethod
63
+ async def list_conversations(
64
+ self, tenant_id: str, user_id: str, *, limit: int = 50, offset: int = 0
65
+ ) -> list[ConversationSummary]:
66
+ """The user's conversations, most recently updated first. Title = first human message."""
67
+
68
+ @abstractmethod
69
+ async def _fetch_recent_turns(self, key: MemoryKey, turns: int) -> list[BaseMessage]:
70
+ """From the `turns`-th human message counting from the end, to the end. Whole thread if shorter."""
71
+
72
+ @abstractmethod
73
+ async def _append(self, key: MemoryKey, messages: list[BaseMessage]) -> None:
74
+ """Store `messages` in order with `created_at = self._clock()`, skipping any whose `id` is
75
+ already in the thread."""
76
+
77
+ @abstractmethod
78
+ async def clear(self, key: MemoryKey) -> None:
79
+ """Delete the thread (user asks to forget it). Unknown thread: no-op."""
80
+
81
+ @staticmethod
82
+ def _start_at_human(messages: list[BaseMessage]) -> list[BaseMessage]:
83
+ """Safety net: drop any prefix before the first human message."""
84
+ for index, message in enumerate(messages):
85
+ if message.type == "human":
86
+ return messages[index:]
87
+ return []
88
+
89
+ @staticmethod
90
+ def window_start(messages: Sequence[BaseMessage], turns: int) -> int:
91
+ """Index where the last `turns` turns begin (0 if there are fewer)."""
92
+ humans = [i for i, m in enumerate(messages) if m.type == "human"]
93
+ return humans[-turns] if len(humans) >= turns else 0
94
+
95
+
96
+ def last_answer_id(messages: Sequence[BaseMessage]) -> str | None:
97
+ """Id of the last AI message with text. Empty AI messages are tool calls, not answers."""
98
+ for message in reversed(messages):
99
+ if message.type == "ai" and str(message.text).strip():
100
+ return message.id
101
+ return None
@@ -0,0 +1,33 @@
1
+ """The one place that builds the memory from the backend the settings name. There is no default."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ from .base import Memory
7
+ from .models import MemoryBackend
8
+ from .settings import MemorySettings
9
+
10
+
11
+ class MemoryFactory:
12
+ @staticmethod
13
+ def create(settings: MemorySettings, *, session_factory: Callable[[], Any] | None = None) -> Memory:
14
+ """Build the backend in `settings.memory_backend` with `settings.memory_window_turns`.
15
+
16
+ Call it once at startup (FastAPI `lifespan`) with the project settings:
17
+ memory = MemoryFactory.create(get_settings(), session_factory=SessionLocal)
18
+
19
+ `SQL` needs the app's `session_factory`. Unknown backend -> ValueError.
20
+ """
21
+ window = settings.memory_window_turns
22
+ match settings.memory_backend:
23
+ case MemoryBackend.IN_MEMORY:
24
+ from .in_memory import InMemoryMemory
25
+
26
+ return InMemoryMemory(window_turns=window)
27
+ case MemoryBackend.SQL:
28
+ if session_factory is None:
29
+ raise ValueError("MEMORY_BACKEND=sql needs the app's session_factory")
30
+ from .sql import SqlMemory
31
+
32
+ return SqlMemory(session_factory, window_turns=window)
33
+ raise ValueError(f"Unknown memory backend: {settings.memory_backend!r}")
@@ -0,0 +1,59 @@
1
+ import asyncio
2
+ from collections import defaultdict
3
+
4
+ from langchain_core.messages import BaseMessage
5
+
6
+ from .base import Memory
7
+ from .models import ConversationSummary, HistoryMessage, MemoryKey, title_from
8
+
9
+
10
+ class InMemoryMemory(Memory):
11
+ """Per-process dict. For tests and local dev only: lost on restart, not shared between workers."""
12
+
13
+ def __init__(self, **kwargs) -> None:
14
+ super().__init__(**kwargs)
15
+ self._threads: dict[MemoryKey, list[HistoryMessage]] = defaultdict(list)
16
+ self._lock = asyncio.Lock()
17
+
18
+ async def _fetch_recent_turns(self, key: MemoryKey, turns: int) -> list[BaseMessage]:
19
+ async with self._lock:
20
+ thread = [h.message for h in self._threads.get(key, [])]
21
+ return thread[self.window_start(thread, turns) :]
22
+
23
+ async def _append(self, key: MemoryKey, messages: list[BaseMessage]) -> None:
24
+ now = self._clock()
25
+ async with self._lock:
26
+ thread = self._threads[key]
27
+ seen = {h.message.id for h in thread if h.message.id}
28
+ for message in messages:
29
+ if message.id and message.id in seen:
30
+ continue
31
+ thread.append(HistoryMessage(message=message, created_at=now))
32
+ if message.id:
33
+ seen.add(message.id)
34
+
35
+ async def get_history(self, key: MemoryKey) -> list[HistoryMessage]:
36
+ async with self._lock:
37
+ return list(self._threads.get(key, []))
38
+
39
+ async def list_conversations(
40
+ self, tenant_id: str, user_id: str, *, limit: int = 50, offset: int = 0
41
+ ) -> list[ConversationSummary]:
42
+ async with self._lock:
43
+ mine = {k: v for k, v in self._threads.items() if k.tenant_id == tenant_id and k.user_id == user_id and v}
44
+ summaries = [
45
+ ConversationSummary(
46
+ conversation_id=key.conversation_id,
47
+ title=title_from(next((str(h.message.text) for h in thread if h.message.type == "human"), "")),
48
+ created_at=thread[0].created_at,
49
+ updated_at=thread[-1].created_at,
50
+ message_count=len(thread),
51
+ )
52
+ for key, thread in mine.items()
53
+ ]
54
+ summaries.sort(key=lambda s: s.updated_at, reverse=True)
55
+ return summaries[offset : offset + limit]
56
+
57
+ async def clear(self, key: MemoryKey) -> None:
58
+ async with self._lock:
59
+ self._threads.pop(key, None)