Open
合入 refactor 的 Python 后端 #17
合入 refactor 的 Python 后端 #17
Open
jaxAdd on Sep 29
Total: 336 files changed+23815-19373
@@ -87,9 +87,11 @@ AUTH_SMTP_SECURE=false
87AUTH_SMTP_USER=87AUTH_SMTP_USER=
88AUTH_SMTP_PASSWORD=88AUTH_SMTP_PASSWORD=
89 89 
90-# Next.js BFF (apps/web) → API. Set this in apps/web/.env.local (not required in root .env).90+# Next.js BFF (apps/web). Set these in apps/web/.env.local (not required in root .env).
91-# Used in password / formal mode when the browser calls same-origin `/api/v1/*` and `/api/copilotkit`.91+# `/api/v1/*` and GUI chat `/api/copilotkit` are both on the control plane (default 8787).
92+# One-click start does not listen on 8790. That port is only for a standalone `dataagent serve`.
92# API_PROXY_TARGET=http://127.0.0.1:878793# API_PROXY_TARGET=http://127.0.0.1:8787
94+# CHAT_PROXY_TARGET=http://127.0.0.1:8787
93 95 
94SQL_DEFAULT_LIMIT=10096SQL_DEFAULT_LIMIT=100
95SQL_MAX_LIMIT=100097SQL_MAX_LIMIT=1000
@@ -2,6 +2,8 @@
2.venv/2.venv/
3.venv-docs/3.venv-docs/
4venv/4venv/
5+__pycache__/
6+*.py[cod]
5node_modules/7node_modules/
6**/node_modules/8**/node_modules/
7dist/9dist/
AMakefile+75-0
@@ -0,0 +1,75 @@
1+# 开发:make prepare && make build && make test。出包:make prepare && make package && make start。
2+# prepare 装 npm、agentkit 和 apps/api。apps/api 要求 >=3.11,同步仍用 PYTHON_VERSION 和 PIP_INDEX_URL。
3+# build 编 tsconfig.build.json 的 TS 包和 TUI;package 再加 build:web。apps/api 是 Python,不进 tsc。
4+# 不另写启动器、不生成密钥、不打 agentkit wheel。编译不 omit=dev、也不 prune,node_modules 仍含构建期依赖。
5+# make start 没有 Make 变量,只调用 ./deploy.sh start:缺 .env 不会启动,缺 apps/web/.env.local 就按 .env 补上。
6+# ut/st 目标名覆盖 TIER:make ut TIER=st 仍跑 ut。范围目标才读 TIER,默认 test;不写 TIER 时 make test 一起跑 ut 和 st。
7+# make st 与 make test 的系统测试不能带 -n/--numprocesses(含 -n4、--numprocesses=4):st 直接失败,test 去掉后仍串行。
8+# -n 只交给 agentkit 单元测试;api 的 pytest 不带 -n。PYTEST_ARGS 的 $ 用单引号:make ut PYTEST_ARGS='-k $HOME'。
9+# make test 时 -k 同时过滤 ut、st 和 api。NODE_TEST_ARGS 只给 web、tui、packages、deploy。
10+# smoke:tui-python 不进 make test。单独:make smoke-tui-python,或 SCOPE=smoke-tui-python。
11+# 例:make prepare PYTHON_VERSION=3.12 PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple NPM_REGISTRY=https://registry.npmmirror.com
12+ 
13+PROJECT_DIR := $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST)))))
14+ 
15+# agentkit 要求 3.12。apps/api 要求 >=3.11。也可用 UV_PYTHON。
16+PYTHON_VERSION ?= $(or $(UV_PYTHON),3.12)
17+export UV_PYTHON := $(PYTHON_VERSION)
18+ 
19+# 不设则用 PyPI。
20+ifdef PIP_INDEX_URL
21+export UV_DEFAULT_INDEX := $(PIP_INDEX_URL)
22+export UV_INDEX_URL := $(PIP_INDEX_URL)
23+endif
24+ifdef PIP_EXTRA_INDEX_URL
25+export UV_EXTRA_INDEX_URL := $(PIP_EXTRA_INDEX_URL)
26+endif
27+ifdef PIP_FIND_LINKS
28+export UV_FIND_LINKS := $(PIP_FIND_LINKS)
29+endif
30+ 
31+ifdef NPM_REGISTRY
32+export npm_config_registry := $(NPM_REGISTRY)
33+endif
34+ 
35+ifeq ($(OS),Windows_NT)
36+ SHELL := bash.exe
37+endif
38+ 
39+.PHONY: ut st test prepare build package start agentkit api web tui packages deploy smoke-tui-python
40+ 
41+# 例:make test UV_RUN_OPTS=--no-sync(只跳过套件里的再次同步)。
42+UV := uv run --project "$(PROJECT_DIR)/runtime/agentkit" --python "$(PYTHON_VERSION)" python
43+TIER ?= test
44+ 
45+# 冻结命令行原文,$ 和 $(函数) 不再展开。
46+override PYTEST_ARGS := $(value PYTEST_ARGS)
47+override NODE_TEST_ARGS := $(value NODE_TEST_ARGS)
48+ 
49+ut st test:
50+ cd "$(PROJECT_DIR)" && $(UV) scripts/run_product_tests.py --tier $(if $(filter ut st,$(MAKECMDGOALS)),$@,$(TIER)) $(if $(SCOPE),--scope "$(SCOPE)") --pytest-args='$(PYTEST_ARGS)' --node-test-args='$(NODE_TEST_ARGS)' $(UV_RUN_OPTS)
51+ 
52+prepare:
53+ cd "$(PROJECT_DIR)" && uv sync --project runtime/agentkit --python "$(PYTHON_VERSION)"
54+ cd "$(PROJECT_DIR)" && uv sync --project apps/api --python "$(PYTHON_VERSION)"
55+ifdef NPM_REGISTRY
56+ cd "$(PROJECT_DIR)" && npm ci --engine-strict=false --registry "$(NPM_REGISTRY)"
57+else
58+ cd "$(PROJECT_DIR)" && npm ci --engine-strict=false
59+endif
60+ 
61+# 不含 Next 生产构建。
62+build:
63+ cd "$(PROJECT_DIR)" && npm run build
64+ cd "$(PROJECT_DIR)" && npm run build:tui
65+ 
66+# make packages 仍是测试范围。
67+package: build
68+ cd "$(PROJECT_DIR)" && npm run build:web
69+ 
70+start:
71+ cd "$(PROJECT_DIR)" && ./deploy.sh start
72+ 
73+# 该 scope 没有 st 用例时仍非 0 退出。
74+agentkit api web tui packages deploy smoke-tui-python:
75+ cd "$(PROJECT_DIR)" && $(UV) scripts/run_product_tests.py --tier $(TIER) --scope $@ --pytest-args='$(PYTEST_ARGS)' --node-test-args='$(NODE_TEST_ARGS)' $(UV_RUN_OPTS)
MREADME.md+4-12
@@ -71,6 +71,8 @@ See the [v0.2.0 release notes](docs/en/releases/v0.2.0.md) for the complete capa
71 71 
72## 🚀 Formal deploy72## 🚀 Formal deploy
73 73 
74+The Web GUI and the TUI are separate processes. The GUI still sends runs to the Python DataFoundry API at `POST /api/copilotkit`. `npm run start:tui` and `./deploy.sh tui` start the local DataAgent V2 backend and connect to `http://127.0.0.1:<port>/dataagent/stream`. They do not send the terminal client to `/api/copilotkit`.
75+ 
74Formal mode has two paths (do **not** run `npm run dev`). Docker / Compose is not provided in this release.76Formal mode has two paths (do **not** run `npm run dev`). Docker / Compose is not provided in this release.
75 77 
76### Recommended: Ubuntu / Debian one-click78### Recommended: Ubuntu / Debian one-click
@@ -191,16 +193,6 @@ Ask → Align semantics → Execute under control → Materialize output → Rep
191 <img src="docs/assets/readme/runtime-flow.png" alt="DataAgent runtime flow" width="100%">193 <img src="docs/assets/readme/runtime-flow.png" alt="DataAgent runtime flow" width="100%">
192</p>194</p>
193 195 
194-## 🖥️ More Than A Chat Box
195- 
196-The **Web workbench** fits day-to-day analysis and demos, the **TUI** fits terminals and remote servers, and the **API / CopilotKit / AG-UI** path lets you embed the same trusted runtime into your own product.
197- 
198-<p align="center">
199- <a href="docs/assets/readme/tui-demo.mp4">
200- <img src="docs/assets/readme/tui-demo.gif" alt="DataAgent TUI demo" width="100%">
201- </a>
202-</p>
203- 
204## 🗄️ Bring Your Data Stack, No Rebuild196## 🗄️ Bring Your Data Stack, No Rebuild
205 197 
206Connect through Data Gateway adapters: the built-in DTC Growth Review case works out of the box; DuckDB, SQLite, CSV, Excel, PostgreSQL, and MySQL fit local trials; cloud warehouses, search engines, and NoSQL systems plug in with their own services and credentials.198Connect through Data Gateway adapters: the built-in DTC Growth Review case works out of the box; DuckDB, SQLite, CSV, Excel, PostgreSQL, and MySQL fit local trials; cloud warehouses, search engines, and NoSQL systems plug in with their own services and credentials.
@@ -220,8 +212,8 @@ See the full list in [Supported Data Sources](docs/en/reference/supported-dataso
220 212 
221## 🗺️ Roadmap213## 🗺️ Roadmap
222 214 
223-- [x] **Governed data-task workbench** — Web and TUI share one TypeScript agent runtime, CopilotKit / AG-UI event stream, replayable run history, SQL audit trail, and unified asset layer.215+- [x] **Governed data-task workbench** — Web and TUI share one Python control plane and official AG-UI / LangGraph streaming. Phase 1 connects a baseline Deep Agents chat.
224-- [x] **Safe data access foundation** — Datasource registration, connection testing, schema introspection, table preview, read-only SQL, masking, knowledge imports, MCP resources, skill packages, and model configuration.216+- [ ] **Safe data access foundation** — Datasource registration, connection testing, schema introspection, table preview, read-only SQL, masking, knowledge imports, MCP resources, skill packages, and model configuration. Not wired into the current Python control plane.
225- [ ] **Unified semantic layer** — Durable metrics, entities, relationships, lineage, and policies, moving agents from "guessing fields" to "understanding business definitions" and from one-off SQL to a governable data operating layer.217- [ ] **Unified semantic layer** — Durable metrics, entities, relationships, lineage, and policies, moving agents from "guessing fields" to "understanding business definitions" and from one-off SQL to a governable data operating layer.
226- [ ] **Autonomous analyst loops** — Agents that plan investigations, run controlled experiments, critique findings, and converge on evidence-backed conclusions.218- [ ] **Autonomous analyst loops** — Agents that plan investigations, run controlled experiments, critique findings, and converge on evidence-backed conclusions.
227- [ ] **Evaluation and reliability lab** — NL2SQL, retrieval, tool-use, and end-to-end task benchmarks with regression gates and failure forensics.219- [ ] **Evaluation and reliability lab** — NL2SQL, retrieval, tool-use, and end-to-end task benchmarks with regression gates and failure forensics.
@@ -71,6 +71,8 @@ DataAgent 0.2 在首个可用版本上,进一步补齐了有状态、可追溯
71 71 
72## 🚀 正式态跑通72## 🚀 正式态跑通
73 73 
74+Web GUI 和 TUI 仍是两个进程。GUI 继续把运行发到 Python DataFoundry API 的 `POST /api/copilotkit`。`npm run start:tui` 和 `./deploy.sh tui` 会启动本地 DataAgent V2 后端,并连接 `http://127.0.0.1:<port>/dataagent/stream`,不会把终端客户端送进 `/api/copilotkit`。
75+ 
74正式态有两条路径(都不要跑 `npm run dev`)。本版本不提供 Docker / Compose。76正式态有两条路径(都不要跑 `npm run dev`)。本版本不提供 Docker / Compose。
75 77 
76### 推荐:Ubuntu / Debian 一键部署78### 推荐:Ubuntu / Debian 一键部署
@@ -190,16 +192,6 @@ Coding agent 改代码,SQL chatbot 回答问题,DataAgent 跑数据任务—
190 <img src="docs/assets/readme/runtime-flow.png" alt="DataAgent 运行流程" width="100%">192 <img src="docs/assets/readme/runtime-flow.png" alt="DataAgent 运行流程" width="100%">
191</p>193</p>
192 194 
193-## 🖥️ 不止一个聊天框
194- 
195-**Web 工作台**适合日常分析和演示,**TUI** 适合终端和远程服务器,**API / CopilotKit / AG-UI** 让你把同一套可信运行时嵌进自己的产品。
196- 
197-<p align="center">
198- <a href="docs/assets/readme/tui-demo.mp4">
199- <img src="docs/assets/readme/tui-demo.gif" alt="DataAgent TUI 演示" width="100%">
200- </a>
201-</p>
202- 
203## 🗄️ 接入现有数据栈,不重构195## 🗄️ 接入现有数据栈,不重构
204 196 
205通过 Data Gateway 适配器接入:内置 DTC 增长经营复盘案例开箱即用;DuckDB、SQLite、CSV、Excel、PostgreSQL、MySQL 适合本地试用;云数仓、搜索引擎和 NoSQL 按需配置服务与凭据。197通过 Data Gateway 适配器接入:内置 DTC 增长经营复盘案例开箱即用;DuckDB、SQLite、CSV、Excel、PostgreSQL、MySQL 适合本地试用;云数仓、搜索引擎和 NoSQL 按需配置服务与凭据。
@@ -219,8 +211,8 @@ Coding agent 改代码,SQL chatbot 回答问题,DataAgent 跑数据任务—
219 211 
220## 🗺️ 路线图212## 🗺️ 路线图
221 213 
222-- [x] **受控数据任务工作台** — Web 与 TUI 共用 TypeScript Agent Runtime、CopilotKit / AG-UI 事件流、可回放运行历史、SQL 审计和统一资产层。214+- [x] **受控数据任务工作台** — Web 与 TUI 共用 Python 控制面、官方 AG-UI / LangGraph 事件流。第一阶段先接入基础 Deep Agents 文本对话。
223-- [x] **安全数据访问底座** — 数据源注册、连接测试、schema 抓取、表预览、只读 SQL、脱敏、知识库导入、MCP 资源、Skill 包和模型配置。215+- [ ] **安全数据访问底座** — 数据源注册、连接测试、schema 抓取、表预览、只读 SQL、脱敏、知识库导入、MCP 资源、Skill 包和模型配置。当前 Python 控制面尚未接入。
224- [ ] **统一语义层** — 沉淀指标、实体、关联、血缘和策略,让 Agent 从「猜字段」走向「理解业务口径」,从一次性 SQL 走向可治理的数据操作层。216- [ ] **统一语义层** — 沉淀指标、实体、关联、血缘和策略,让 Agent 从「猜字段」走向「理解业务口径」,从一次性 SQL 走向可治理的数据操作层。
225- [ ] **自主分析循环** — Agent 规划分析、执行受控实验、审视结论,收敛到有证据支撑的结果。217- [ ] **自主分析循环** — Agent 规划分析、执行受控实验、审视结论,收敛到有证据支撑的结果。
226- [ ] **评测与可靠性实验室** — NL2SQL、检索、工具调用和端到端任务基准,支撑回归门禁和失败分析。218- [ ] **评测与可靠性实验室** — NL2SQL、检索、工具调用和端到端任务基准,支撑回归门禁和失败分析。
@@ -0,0 +1,7 @@
1+.venv/
2+.pytest_cache/
3+.ruff_cache/
4+__pycache__/
5+*.pyc
6+*.egg-info/
7+dist/
@@ -0,0 +1,18 @@
1+# DataFoundry API
2+ 
3+Python FastAPI 控制面。同一个进程也挂载 agentkit 的对话路由(`/api/copilotkit`、`/dataagent/stream`、`/sessions`),默认 `127.0.0.1:8787`。不再单独启动 8790,也不再构造旧 DataAgent 运行时。
4+ 
5+## 启动
6+ 
7+```bash
8+uv sync --python 3.12
9+uv run python -m datafoundry_api
10+```
11+ 
12+仓库根目录执行 `npm run dev` 或 `npm run start:api` 也会启动本服务,默认监听 `127.0.0.1:8787`。
13+ 
14+## 测试
15+ 
16+```bash
17+uv run pytest
18+```
@@ -1,38 +0,0 @@
1-{
2- "name": "@datafoundry/api",
3- "version": "0.2.0",
4- "private": true,
5- "type": "module",
6- "main": "dist/index.js",
7- "types": "dist/index.d.ts",
8- "scripts": {
9- "build": "tsc -p tsconfig.json",
10- "dev": "tsx watch src/index.ts",
11- "start": "node dist/index.js"
12- },
13- "dependencies": {
14- "@ag-ui/client": "^0.0.57",
15- "@ag-ui/mastra": "^1.0.3",
16- "@copilotkit/runtime": "0.0.0-mme-ag-ui-0-0-46-20260227141603",
17- "@datafoundry/agent-runtime": "0.2.0",
18- "@datafoundry/contracts": "0.2.0",
19- "@datafoundry/data-gateway": "0.2.0",
20- "@datafoundry/files": "0.2.0",
21- "@datafoundry/knowledge": "0.2.0",
22- "@datafoundry/metadata": "0.2.0",
23- "@datafoundry/skills": "0.2.0",
24- "@mastra/core": "^1.46.0",
25- "@modelcontextprotocol/sdk": "^1.29.0",
26- "argon2": "^0.44.0",
27- "busboy": "^1.6.0",
28- "dotenv": "^17.2.1",
29- "js-yaml": "^5.0.0",
30- "nodemailer": "^9.0.3",
31- "unpdf": "^1.6.2",
32- "write-excel-file": "^4.1.1",
33- "yauzl": "^3.4.0"
34- },
35- "devDependencies": {
36- "tsx": "^4.19.0"
37- }
38-}
@@ -0,0 +1,52 @@
1+[project]
2+name = "datafoundry-api"
3+version = "0.3.0"
4+description = "DataFoundry Python control plane"
5+requires-python = ">=3.12,<3.13"
6+license = "Apache-2.0"
7+authors = [
8+ { name = "DataFoundry" },
9+]
10+dependencies = [
11+ "argon2-cffi>=23.1.0",
12+ "cryptography>=44.0.0",
13+ "fastapi>=0.115.0",
14+ "langchain-core>=1.2.15,<2.0.0",
15+ "langchain-mcp-adapters==0.3.2",
16+ "pydantic-settings>=2.8.0",
17+ "PyYAML==6.0.2",
18+ "python-multipart>=0.0.18",
19+ "uvicorn[standard]>=0.32.0",
20+ "dataagent",
21+]
22+ 
23+[tool.uv.sources]
24+dataagent = { path = "../../runtime/agentkit", editable = true }
25+ 
26+[dependency-groups]
27+dev = [
28+ "httpx>=0.28.0",
29+ "pytest>=8.0",
30+ "pytest-asyncio>=0.24.0",
31+ "ruff>=0.9.0",
32+]
33+ 
34+[[tool.uv.index]]
35+url = "https://mirrors.aliyun.com/pypi/simple/"
36+default = true
37+ 
38+[build-system]
39+requires = ["hatchling"]
40+build-backend = "hatchling.build"
41+ 
42+[tool.hatch.build.targets.wheel]
43+packages = ["src/datafoundry_api"]
44+ 
45+[tool.pytest.ini_options]
46+testpaths = ["tests"]
47+pythonpath = ["src"]
48+asyncio_mode = "auto"
49+ 
50+[tool.ruff]
51+line-length = 120
52+target-version = "py312"
@@ -1,59 +0,0 @@
1-/**
2- * Process-lifetime memoization for idempotent async bootstrap work.
3- * Coalesces in-flight calls for the same key so concurrent first requests
4- * share one execution.
5- */
6-export function createAsyncMemoByKey<TArgs extends unknown[], TResult>(
7- run: (...args: TArgs) => Promise<TResult>,
8- keyOf: (...args: TArgs) => string,
9-): (...args: TArgs) => Promise<TResult> {
10- const results = new Map<string, TResult>();
11- const inflight = new Map<string, Promise<TResult>>();
12- 
13- return async (...args: TArgs): Promise<TResult> => {
14- const key = keyOf(...args);
15- if (results.has(key)) {
16- return results.get(key) as TResult;
17- }
18- const existing = inflight.get(key);
19- if (existing) {
20- return existing;
21- }
22- const pending = (async () => {
23- try {
24- const result = await run(...args);
25- results.set(key, result);
26- return result;
27- } finally {
28- inflight.delete(key);
29- }
30- })();
31- inflight.set(key, pending);
32- return pending;
33- };
34-}
35- 
36-export type StartupPhaseTimings = Record<string, number>;
37- 
38-/** Wall-clock phase timer for createServer cold-start observability. */
39-export function createStartupTimer(): {
40- measure: <T>(name: string, work: () => Promise<T> | T) => Promise<T>;
41- timings: () => StartupPhaseTimings;
42- totalMs: () => number;
43-} {
44- const timings: StartupPhaseTimings = {};
45- const startedAt = performance.now();
46- 
47- return {
48- async measure<T>(name: string, work: () => Promise<T> | T): Promise<T> {
49- const t0 = performance.now();
50- try {
51- return await work();
52- } finally {
53- timings[name] = Math.round(performance.now() - t0);
54- }
55- },
56- timings: () => ({ ...timings }),
57- totalMs: () => Math.round(performance.now() - startedAt),
58- };
59-}
@@ -1,146 +0,0 @@
1-export type RegistrationMode = "open" | "closed";
2- 
3-export type PasswordAuthConfig = {
4- publicBaseUrl: string;
5- registrationMode: RegistrationMode;
6- cookiePath: string;
7- cookieSecure: boolean;
8- sessionSecret: string;
9- emailDelivery: "smtp" | "test";
10- smtp?: {
11- from: string;
12- host: string;
13- password?: string | undefined;
14- port: number;
15- secure: boolean;
16- user?: string | undefined;
17- };
18-};
19- 
20-export function validateAuthPublicUrl(raw: string): {
21- publicBaseUrl: string;
22- loopback: boolean;
23- cookiePath: string;
24- cookieSecure: boolean;
25-} {
26- let url: URL;
27- try {
28- url = new URL(raw);
29- } catch {
30- throw new Error("AUTH_CONFIG_INVALID:AUTH_PUBLIC_BASE_URL must be a valid absolute URL.");
31- }
32- 
33- if (url.protocol !== "http:" && url.protocol !== "https:") {
34- throw new Error("AUTH_CONFIG_INVALID:AUTH_PUBLIC_BASE_URL must use http or https.");
35- }
36- if (url.username || url.password) {
37- throw new Error("AUTH_CONFIG_INVALID:AUTH_PUBLIC_BASE_URL must not include credentials.");
38- }
39- if (url.hash) {
40- throw new Error("AUTH_CONFIG_INVALID:AUTH_PUBLIC_BASE_URL must not include a fragment.");
41- }
42- 
43- const host = url.hostname.toLowerCase().replace(/^\[(.*)\]$/, "$1");
44- const loopback = host === "localhost" || host === "127.0.0.1" || host === "::1";
45- if (url.protocol === "http:" && !loopback) {
46- throw new Error(
47- "AUTH_CONFIG_INVALID:AUTH_PUBLIC_BASE_URL HTTP is only allowed for loopback hosts (localhost, 127.0.0.1, ::1); use HTTPS for other hosts."
48- );
49- }
50- 
51- const normalized = new URL(url.href);
52- normalized.hash = "";
53- normalized.search = "";
54- // Keep pathname (including deployment prefix); strip only a trailing slash on root-equivalent leaves.
55- if (normalized.pathname.length > 1) {
56- normalized.pathname = normalized.pathname.replace(/\/+$/, "");
57- }
58- 
59- const cookiePath = normalized.pathname === "/" ? "/" : normalized.pathname;
60- 
61- return {
62- publicBaseUrl: normalized.origin + (normalized.pathname === "/" ? "" : normalized.pathname),
63- loopback,
64- cookiePath,
65- cookieSecure: url.protocol === "https:"
66- };
67-}
68- 
69-export function loadPasswordAuthConfig(env: Record<string, string | undefined>): PasswordAuthConfig {
70- // Upgrade shim: previous .env.example / deploy defaults set DATAFOUNDRY_AUTH_MODE=password.
71- // Ignore empty/password leftovers; reject removed modes (especially dev).
72- if (env.DATAFOUNDRY_AUTH_MODE !== undefined) {
73- const legacyMode = String(env.DATAFOUNDRY_AUTH_MODE).trim();
74- if (legacyMode !== "" && legacyMode !== "password") {
75- throw new Error(
76- "AUTH_CONFIG_INVALID:DATAFOUNDRY_AUTH_MODE is no longer supported; remove it from the environment (dev mode has been removed)."
77- );
78- }
79- }
80- const config: PasswordAuthConfig = {
81- publicBaseUrl: env.AUTH_PUBLIC_BASE_URL ?? "",
82- registrationMode: parseRegistrationMode(env.AUTH_REGISTRATION_MODE),
83- cookiePath: "/",
84- cookieSecure: false,
85- sessionSecret: env.AUTH_SESSION_SECRET ?? "",
86- emailDelivery: parseEmailDelivery(env.AUTH_EMAIL_DELIVERY)
87- };
88- if (env.SMTP_HOST || env.AUTH_SMTP_HOST) {
89- config.smtp = {
90- host: env.AUTH_SMTP_HOST ?? env.SMTP_HOST ?? "",
91- port: Number.parseInt(env.AUTH_SMTP_PORT ?? env.SMTP_PORT ?? "587", 10),
92- secure: (env.AUTH_SMTP_SECURE ?? env.SMTP_SECURE) === "true",
93- from: env.AUTH_EMAIL_FROM ?? env.SMTP_FROM ?? "",
94- ...(env.AUTH_SMTP_USER ?? env.SMTP_USER ? { user: env.AUTH_SMTP_USER ?? env.SMTP_USER } : {}),
95- ...(env.AUTH_SMTP_PASSWORD ?? env.SMTP_PASSWORD
96- ? { password: env.AUTH_SMTP_PASSWORD ?? env.SMTP_PASSWORD }
97- : {})
98- };
99- }
100- validatePasswordAuthConfig(config);
101- return config;
102-}
103- 
104-function parseRegistrationMode(value: string | undefined): RegistrationMode {
105- if (value === undefined || value.trim() === "") {
106- throw new Error("AUTH_CONFIG_MISSING:AUTH_REGISTRATION_MODE is required.");
107- }
108- if (value === "open" || value === "closed") {
109- return value;
110- }
111- throw new Error("AUTH_CONFIG_INVALID:AUTH_REGISTRATION_MODE must be open or closed.");
112-}
113- 
114-function parseEmailDelivery(value: string | undefined): "smtp" | "test" {
115- if (value === undefined || value.trim() === "") {
116- return "smtp";
117- }
118- if (value === "smtp" || value === "test") {
119- return value;
120- }
121- throw new Error("AUTH_CONFIG_INVALID:AUTH_EMAIL_DELIVERY must be smtp or test.");
122-}
123- 
124-function validatePasswordAuthConfig(config: PasswordAuthConfig): void {
125- if (config.sessionSecret.length < 32) {
126- throw new Error("AUTH_CONFIG_MISSING:AUTH_SESSION_SECRET must be at least 32 characters.");
127- }
128- if (!config.publicBaseUrl) {
129- throw new Error("AUTH_CONFIG_MISSING:AUTH_PUBLIC_BASE_URL is required.");
130- }
131- const validated = validateAuthPublicUrl(config.publicBaseUrl);
132- config.publicBaseUrl = validated.publicBaseUrl;
133- config.cookiePath = validated.cookiePath;
134- config.cookieSecure = validated.cookieSecure;
135- 
136- if (config.emailDelivery === "test" && !validated.loopback) {
137- throw new Error(
138- "AUTH_CONFIG_INVALID:AUTH_EMAIL_DELIVERY=test is only allowed with a loopback AUTH_PUBLIC_BASE_URL."
139- );
140- }
141- if (config.emailDelivery === "smtp") {
142- if (!config.smtp?.host || !config.smtp.from) {
143- throw new Error("AUTH_CONFIG_MISSING:SMTP host and from address are required.");
144- }
145- }
146-}
@@ -1,121 +0,0 @@
1-import type { IncomingMessage, ServerResponse } from "node:http";
2- 
3-export const SESSION_COOKIE = "df_session";
4-export const CSRF_COOKIE = "df_csrf";
5- 
6-export type CookieSecurityOptions = {
7- path: string;
8- secure: boolean;
9-};
10- 
11-export function parseCookies(request: IncomingMessage): Record<string, string> {
12- const header = request.headers.cookie;
13- if (!header) {
14- return {};
15- }
16- const cookies: Record<string, string> = {};
17- for (const part of header.split(";")) {
18- const trimmed = part.trim();
19- if (!trimmed) {
20- continue;
21- }
22- const eq = trimmed.indexOf("=");
23- const name = (eq === -1 ? trimmed : trimmed.slice(0, eq)).trim();
24- if (!name) {
25- continue;
26- }
27- const rawValue = eq === -1 ? "" : trimmed.slice(eq + 1);
28- try {
29- cookies[name] = decodeURIComponent(rawValue);
30- } catch {
31- // Ignore malformed percent-encoding; treat the cookie as absent.
32- }
33- }
34- return cookies;
35-}
36- 
37-export function appendAuthCookies(response: ServerResponse, input: {
38- csrfToken: string;
39- maxAgeSeconds: number;
40- path: string;
41- sessionToken: string;
42- secure: boolean;
43-}): void {
44- appendSetCookie(response, serializeCookie(SESSION_COOKIE, input.sessionToken, {
45- httpOnly: true,
46- maxAgeSeconds: input.maxAgeSeconds,
47- path: input.path,
48- secure: input.secure
49- }));
50- appendSetCookie(response, serializeCookie(CSRF_COOKIE, input.csrfToken, {
51- httpOnly: false,
52- maxAgeSeconds: input.maxAgeSeconds,
53- path: input.path,
54- secure: input.secure
55- }));
56-}
57- 
58-export function appendCsrfCookie(
59- response: ServerResponse,
60- value: string,
61- input: { path: string; secure: boolean; maxAgeSeconds: number }
62-): void {
63- appendSetCookie(response, serializeCookie(CSRF_COOKIE, value, {
64- httpOnly: false,
65- maxAgeSeconds: input.maxAgeSeconds,
66- path: input.path,
67- secure: input.secure
68- }));
69-}
70- 
71-export function appendClearAuthCookies(
72- response: ServerResponse,
73- options: CookieSecurityOptions
74-): void {
75- appendSetCookie(response, serializeCookie(SESSION_COOKIE, "", {
76- httpOnly: true,
77- maxAgeSeconds: 0,
78- path: options.path,
79- secure: options.secure
80- }));
81- appendSetCookie(response, serializeCookie(CSRF_COOKIE, "", {
82- httpOnly: false,
83- maxAgeSeconds: 0,
84- path: options.path,
85- secure: options.secure
86- }));
87-}
88- 
89-function appendSetCookie(response: ServerResponse, cookie: string): void {
90- const current = response.getHeader("Set-Cookie");
91- const cookies = Array.isArray(current)
92- ? [...current, cookie]
93- : typeof current === "string"
94- ? [current, cookie]
95- : [cookie];
96- response.setHeader("Set-Cookie", cookies);
97-}
98- 
99-function serializeCookie(
100- name: string,
101- value: string,
102- input: { httpOnly: boolean; maxAgeSeconds: number; path: string; secure: boolean }
103-): string {
104- const path = normalizeCookiePath(input.path);
105- return [
106- `${name}=${encodeURIComponent(value)}`,
107- `Path=${path}`,
108- `Max-Age=${input.maxAgeSeconds}`,
109- "SameSite=Lax",
110- ...(input.secure ? ["Secure"] : []),
111- ...(input.httpOnly ? ["HttpOnly"] : [])
112- ].join("; ");
113-}
114- 
115-function normalizeCookiePath(path: string): string {
116- if (!path || path === "/") {
117- return "/";
118- }
119- const trimmed = path.replace(/\/+$/u, "");
120- return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
121-}
@@ -1,37 +0,0 @@
1-import argon2 from "argon2";
2-import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
3- 
4-const PASSWORD_HASH_PARAMS = {
5- algorithm: "argon2id",
6- memoryCost: 19456,
7- parallelism: 1,
8- timeCost: 2
9-} as const;
10- 
11-export async function hashPassword(password: string): Promise<{ hash: string; params: string }> {
12- const hash = await argon2.hash(password, {
13- type: argon2.argon2id,
14- memoryCost: PASSWORD_HASH_PARAMS.memoryCost,
15- parallelism: PASSWORD_HASH_PARAMS.parallelism,
16- timeCost: PASSWORD_HASH_PARAMS.timeCost
17- });
18- return { hash, params: JSON.stringify(PASSWORD_HASH_PARAMS) };
19-}
20- 
21-export async function verifyPassword(hash: string, password: string): Promise<boolean> {
22- return argon2.verify(hash, password);
23-}
24- 
25-export function createSecretToken(): string {
26- return randomBytes(32).toString("base64url");
27-}
28- 
29-export function hashToken(token: string, secret: string): string {
30- return createHmac("sha256", secret).update(token).digest("base64url");
31-}
32- 
33-export function constantTimeEqual(left: string, right: string): boolean {
34- const leftBuffer = Buffer.from(left);
35- const rightBuffer = Buffer.from(right);
36- return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
37-}
@@ -1,59 +0,0 @@
1-import nodemailer from "nodemailer";
2-import type { PasswordAuthConfig } from "./config.js";
3- 
4-export type AuthMailResult = {
5- testToken?: string;
6-};
7- 
8-export class AuthMailer {
9- constructor(private readonly config: PasswordAuthConfig) {}
10- 
11- async sendVerification(input: { email: string; token: string }): Promise<AuthMailResult> {
12- const url = `${this.config.publicBaseUrl.replace(/\/$/u, "")}/data-tasks?verify=${encodeURIComponent(input.token)}`;
13- return this.send({
14- email: input.email,
15- subject: "Verify your DataFoundry account",
16- text: `Verify your DataFoundry account: ${url}`,
17- token: input.token
18- });
19- }
20- 
21- async sendPasswordReset(input: { email: string; token: string }): Promise<AuthMailResult> {
22- const url = `${this.config.publicBaseUrl.replace(/\/$/u, "")}/data-tasks?reset=${encodeURIComponent(input.token)}`;
23- return this.send({
24- email: input.email,
25- subject: "Reset your DataFoundry password",
26- text: `Reset your DataFoundry password: ${url}`,
27- token: input.token
28- });
29- }
30- 
31- private async send(input: {
32- email: string;
33- subject: string;
34- text: string;
35- token: string;
36- }): Promise<AuthMailResult> {
37- if (this.config.emailDelivery === "test") {
38- return { testToken: input.token };
39- }
40- if (!this.config.smtp) {
41- throw new Error("AUTH_CONFIG_MISSING:SMTP is required.");
42- }
43- const transport = nodemailer.createTransport({
44- host: this.config.smtp.host,
45- port: this.config.smtp.port,
46- secure: this.config.smtp.secure,
47- auth: this.config.smtp.user
48- ? { user: this.config.smtp.user, pass: this.config.smtp.password ?? "" }
49- : undefined
50- });
51- await transport.sendMail({
52- from: this.config.smtp.from,
53- to: input.email,
54- subject: input.subject,
55- text: input.text
56- });
57- return {};
58- }
59-}
@@ -1,258 +0,0 @@
1-import { createErrorResult, createSuccessResult, type AppErrorCode } from "@datafoundry/contracts";
2-import type { IncomingMessage, ServerResponse } from "node:http";
3-import type { AuthIdentity, AuthService } from "./service.js";
4-import { AuthError, userDto, workspaceDto } from "./service.js";
5-import {
6- appendAuthCookies,
7- appendClearAuthCookies,
8- appendCsrfCookie,
9- CSRF_COOKIE,
10- parseCookies,
11- SESSION_COOKIE
12-} from "./cookies.js";
13- 
14-export type AuthRouteContext = {
15- authService: AuthService;
16- cookiePath: string;
17- cookieSecure: boolean;
18- identity?: AuthIdentity;
19-};
20- 
21-export async function handleAuthApiRequest(
22- request: IncomingMessage,
23- response: ServerResponse,
24- pathname: string,
25- context: AuthRouteContext
26-): Promise<boolean> {
27- if (!pathname.startsWith("/api/v1/auth/")) {
28- return false;
29- }
30- try {
31- const segments = pathname.slice("/api/v1/auth/".length).split("/").filter(Boolean);
32- const root = segments[0] ?? "";
33- const body = request.method === "GET" || request.method === "DELETE"
34- ? {}
35- : await readJsonBody(request);
36- 
37- if (root === "status" && request.method === "GET") {
38- sendJson(response, 200, createSuccessResult(context.authService.getPublicStatus()));
39- return true;
40- }
41- if (root === "register" && request.method === "POST") {
42- const result = await context.authService.register({
43- email: requiredString(body.email, "email"),
44- password: requiredString(body.password, "password"),
45- ...(optionalString(body.displayName) ? { displayName: optionalString(body.displayName) } : {}),
46- ...requestMeta(request)
47- });
48- sendJson(response, 201, createSuccessResult(result));
49- return true;
50- }
51- if (root === "login" && request.method === "POST") {
52- const result = await context.authService.login({
53- email: requiredString(body.email, "email"),
54- password: requiredString(body.password, "password"),
55- client: optionalClient(body.client),
56- ...requestMeta(request)
57- });
58- appendAuthCookies(response, {
59- csrfToken: result.csrfToken,
60- maxAgeSeconds: result.maxAgeSeconds,
61- path: context.cookiePath,
62- sessionToken: result.sessionToken,
63- secure: context.cookieSecure
64- });
65- sendJson(response, 200, createSuccessResult({
66- user: result.user,
67- workspace: result.workspace,
68- session: {
69- expiresAt: result.expiresAt
70- }
71- }));
72- return true;
73- }
74- if (root === "verify-email" && request.method === "POST") {
75- sendJson(response, 200, createSuccessResult(await context.authService.verifyEmail({
76- token: requiredString(body.token, "token"),
77- ...requestMeta(request)
78- })));
79- return true;
80- }
81- if (root === "password" && segments[1] === "forgot" && request.method === "POST") {
82- sendJson(response, 200, createSuccessResult(await context.authService.forgotPassword({
83- email: requiredString(body.email, "email"),
84- ...requestMeta(request)
85- })));
86- return true;
87- }
88- if (root === "password" && segments[1] === "reset" && request.method === "POST") {
89- sendJson(response, 200, createSuccessResult(await context.authService.resetPassword({
90- token: requiredString(body.token, "token"),
91- password: requiredString(body.password, "password"),
92- ...requestMeta(request)
93- })));
94- return true;
95- }
96- 
97- const identity = requireIdentity(context);
98- if (root === "csrf" && segments[1] === "refresh" && request.method === "POST") {
99- const rotated = context.authService.rotateCsrf(identity);
100- appendCsrfCookie(response, rotated.csrfToken, {
101- path: context.cookiePath,
102- secure: context.cookieSecure,
103- maxAgeSeconds: rotated.maxAgeSeconds
104- });
105- sendJson(response, 200, createSuccessResult({ csrfToken: rotated.csrfToken }), {
106- "Cache-Control": "no-store"
107- });
108- return true;
109- }
110- if (isUnsafeMethod(request.method)) {
111- context.authService.validateCsrf(identity, headerString(request.headers["x-csrf-token"]));
112- }
113- if (root === "csrf" && request.method === "GET") {
114- const token = parseCookies(request)[CSRF_COOKIE] ?? "";
115- sendJson(response, 200, createSuccessResult({ csrfToken: token }));
116- return true;
117- }
118- if (root === "logout" && request.method === "POST") {
119- const result = context.authService.logout(identity);
120- appendClearAuthCookies(response, {
121- path: context.cookiePath,
122- secure: context.cookieSecure
123- });
124- sendJson(response, 200, createSuccessResult(result));
125- return true;
126- }
127- if (root === "logout-all" && request.method === "POST") {
128- const result = context.authService.logoutAll(identity);
129- appendClearAuthCookies(response, {
130- path: context.cookiePath,
131- secure: context.cookieSecure
132- });
133- sendJson(response, 200, createSuccessResult(result));
134- return true;
135- }
136- if (root === "sessions" && request.method === "GET") {
137- sendJson(response, 200, createSuccessResult(context.authService.listSessions(identity)));
138- return true;
139- }
140- if (root === "sessions" && segments[1] && request.method === "DELETE") {
141- sendJson(response, 200, createSuccessResult(context.authService.revokeSession(identity, segments[1])));
142- return true;
143- }
144- if (root === "password" && segments[1] === "change" && request.method === "POST") {
145- sendJson(response, 200, createSuccessResult(await context.authService.changePassword({
146- identity,
147- currentPassword: requiredString(body.currentPassword, "currentPassword"),
148- newPassword: requiredString(body.newPassword ?? body.password, "newPassword"),
149- ...requestMeta(request)
150- })));
151- return true;
152- }
153- sendJson(response, 404, createErrorResult("RESOURCE_NOT_FOUND", "Unknown auth resource."));
154- return true;
155- } catch (error) {
156- sendAuthError(response, error);
157- return true;
158- }
159-}
160- 
161-export function resolvePasswordSessionIdentity(
162- authService: AuthService,
163- request: IncomingMessage
164-): AuthIdentity {
165- return authService.authenticateSession(parseCookies(request)[SESSION_COOKIE]);
166-}
167- 
168-export function authMeDto(identity: AuthIdentity): Record<string, unknown> {
169- return {
170- user: userDto(identity.user),
171- workspace: workspaceDto(identity.workspace)
172- };
173-}
174- 
175-export function isUnsafeMethod(method: string | undefined): boolean {
176- return method === "POST" || method === "PATCH" || method === "PUT" || method === "DELETE";
177-}
178- 
179-export function sendAuthError(response: ServerResponse, error: unknown): void {
180- if (error instanceof AuthError) {
181- sendJson(response, error.status, createErrorResult(error.code as AppErrorCode, error.message));
182- return;
183- }
184- const message = error instanceof Error ? error.message : "Unknown auth error";
185- sendJson(response, 500, createErrorResult("INTERNAL_ERROR", message));
186-}
187- 
188-function requireIdentity(context: AuthRouteContext): AuthIdentity {
189- if (!context.identity) {
190- throw new AuthError(401, "UNAUTHORIZED", "Authentication required.");
191- }
192- return context.identity;
193-}
194- 
195-async function readJsonBody(request: IncomingMessage): Promise<Record<string, unknown>> {
196- const chunks: Buffer[] = [];
197- for await (const chunk of request) {
198- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
199- }
200- if (chunks.length === 0) {
201- return {};
202- }
203- const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
204- return typeof parsed === "object" && parsed !== null ? parsed as Record<string, unknown> : {};
205-}
206- 
207-function requiredString(value: unknown, name: string): string {
208- if (typeof value !== "string" || !value.trim()) {
209- throw new AuthError(400, "BAD_REQUEST", `${name} is required.`);
210- }
211- return value.trim();
212-}
213- 
214-function optionalString(value: unknown): string | undefined {
215- return typeof value === "string" && value.trim() ? value.trim() : undefined;
216-}
217- 
218-function optionalClient(value: unknown): "web" | "tui" | undefined {
219- if (value === undefined || value === null || value === "") {
220- return undefined;
221- }
222- if (value === "web" || value === "tui") {
223- return value;
224- }
225- throw new AuthError(400, "BAD_REQUEST", "client must be web or tui.");
226-}
227- 
228-function requestMeta(request: IncomingMessage): { ipAddress?: string | undefined; userAgent?: string | undefined } {
229- return {
230- ...(headerString(request.headers["x-forwarded-for"]) ?? request.socket.remoteAddress
231- ? { ipAddress: (headerString(request.headers["x-forwarded-for"]) ?? request.socket.remoteAddress)?.split(",")[0]?.trim() }
232- : {}),
233- ...(headerString(request.headers["user-agent"]) ? { userAgent: headerString(request.headers["user-agent"]) } : {})
234- };
235-}
236- 
237-function headerString(value: string | string[] | undefined): string | undefined {
238- return Array.isArray(value) ? value[0] : value;
239-}
240- 
241-function sendJson(
242- response: ServerResponse,
243- statusCode: number,
244- body: unknown,
245- extraHeaders: Record<string, string> = {}
246-): void {
247- const existingCookies = response.getHeader("Set-Cookie");
248- response.writeHead(statusCode, {
249- "Access-Control-Allow-Origin": "*",
250- "Access-Control-Allow-Credentials": "true",
251- "Content-Type": "application/json; charset=utf-8",
252- ...extraHeaders,
253- ...(existingCookies
254- ? { "Set-Cookie": existingCookies as string | string[] }
255- : {})
256- });
257- response.end(JSON.stringify(body));
258-}
@@ -1,485 +0,0 @@
1-import { randomUUID } from "node:crypto";
2-import type {
3- AuthSessionRecord,
4- MetadataStore,
5- UserRecord,
6- WorkspaceRecord
7-} from "@datafoundry/metadata";
8- 
9-import type { PasswordAuthConfig } from "./config.js";
10-import { AuthMailer } from "./mailer.js";
11-import { createSecretToken, hashPassword, hashToken, verifyPassword } from "./crypto.js";
12- 
13-const WEB_SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;
14-const TUI_SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;
15-const EMAIL_VERIFICATION_TTL_MS = 1000 * 60 * 60 * 24;
16-const PASSWORD_RESET_TTL_MS = 1000 * 60 * 30;
17- 
18-export type AuthClientKind = "web" | "tui";
19- 
20-export type AuthUserDto = {
21- id: string;
22- email?: string;
23- displayName?: string;
24-};
25- 
26-export type AuthWorkspaceDto = {
27- id: string;
28- name?: string;
29-};
30- 
31-export type AuthIdentity = {
32- session?: AuthSessionRecord;
33- user: UserRecord;
34- workspace: WorkspaceRecord;
35-};
36- 
37-export class AuthError extends Error {
38- constructor(readonly status: number, readonly code: string, message: string) {
39- super(message);
40- this.name = "AuthError";
41- }
42-}
43- 
44-export class AuthService {
45- private readonly mailer: AuthMailer;
46- private readonly dummyPasswordHash = hashPassword(createSecretToken()).then((result) => result.hash);
47- 
48- constructor(
49- private readonly metadataStore: MetadataStore,
50- private readonly config: PasswordAuthConfig
51- ) {
52- this.mailer = new AuthMailer(config);
53- }
54- 
55- getPublicStatus(): { publicBaseUrl: string; registrationEnabled: boolean } {
56- return {
57- publicBaseUrl: this.config.publicBaseUrl,
58- registrationEnabled: this.config.registrationMode === "open"
59- };
60- }
61- 
62- async register(input: {
63- displayName?: string | undefined;
64- email: string;
65- ipAddress?: string | undefined;
66- password: string;
67- userAgent?: string | undefined;
68- }): Promise<{ user: AuthUserDto; workspace: AuthWorkspaceDto; verificationToken?: string }> {
69- if (this.config.registrationMode !== "open") {
70- throw new AuthError(403, "REGISTRATION_CLOSED", "Registration is closed for this deployment.");
71- }
72- const email = normalizeEmail(input.email);
73- assertPassword(input.password);
74- this.checkRateLimit(`register:ip:${input.ipAddress ?? "unknown"}`, 5, 60 * 60);
75- if (this.metadataStore.users.findByEmail({ email })) {
76- throw new AuthError(409, "CONFLICT", "Email is already registered.");
77- }
78- const user = this.metadataStore.users.createPasswordUser({
79- id: randomUUID(),
80- email,
81- ...(input.displayName ? { display_name: normalizeDisplayName(input.displayName) } : {})
82- });
83- const password = await hashPassword(input.password);
84- this.metadataStore.userPasswordCredentials.set({
85- user_id: user.id,
86- password_hash: password.hash,
87- password_hash_params: password.params
88- });
89- this.metadataStore.users.touchPasswordUpdated({ user_id: user.id });
90- const workspace = this.ensurePersonalWorkspace(user);
91- const verificationToken = createSecretToken();
92- this.metadataStore.authTokens.create({
93- id: randomUUID(),
94- user_id: user.id,
95- purpose: "email_verification",
96- token_hash: hashToken(verificationToken, this.config.sessionSecret),
97- expires_at: new Date(Date.now() + EMAIL_VERIFICATION_TTL_MS).toISOString()
98- });
99- const mail = await this.mailer.sendVerification({ email, token: verificationToken });
100- this.audit("auth.register", { email, ipAddress: input.ipAddress, userAgent: input.userAgent, userId: user.id });
101- return {
102- user: userDto(user),
103- workspace: workspaceDto(workspace),
104- ...(mail.testToken ? { verificationToken: mail.testToken } : {})
105- };
106- }
107- 
108- async verifyEmail(input: {
109- token: string;
110- ipAddress?: string | undefined;
111- userAgent?: string | undefined;
112- }): Promise<{ user: AuthUserDto }> {
113- const token = this.requireToken("email_verification", input.token);
114- const user = this.metadataStore.users.markEmailVerified({ user_id: token.user_id });
115- this.metadataStore.authTokens.consume({ id: token.id });
116- this.audit("auth.email_verified", {
117- email: user.email,
118- ipAddress: input.ipAddress,
119- userAgent: input.userAgent,
120- userId: user.id
121- });
122- return { user: userDto(user) };
123- }
124- 
125- async login(input: {
126- client?: AuthClientKind | undefined;
127- email: string;
128- ipAddress?: string | undefined;
129- password: string;
130- userAgent?: string | undefined;
131- }): Promise<{
132- csrfToken: string;
133- expiresAt: string;
134- maxAgeSeconds: number;
135- sessionToken: string;
136- user: AuthUserDto;
137- workspace: AuthWorkspaceDto;
138- }> {
139- const email = normalizeEmail(input.email);
140- this.checkRateLimit(`login:email:${email}`, 5, 60);
141- this.checkRateLimit(`login:ip:${input.ipAddress ?? "unknown"}`, 20, 60);
142- const user = this.metadataStore.users.findByEmail({ email });
143- const credential = user
144- ? this.metadataStore.userPasswordCredentials.find({ user_id: user.id })
145- : undefined;
146- if (!user || user.disabled_at || !credential) {
147- await verifyPassword(await this.dummyPasswordHash, input.password);
148- this.audit("auth.login_failed", { email, ipAddress: input.ipAddress, userAgent: input.userAgent });
149- throw new AuthError(401, "UNAUTHORIZED", "Invalid email or password.");
150- }
151- if (!(await verifyPassword(credential.password_hash, input.password))) {
152- this.audit("auth.login_failed", {
153- email,
154- ipAddress: input.ipAddress,
155- userAgent: input.userAgent,
156- userId: user.id
157- });
158- throw new AuthError(401, "UNAUTHORIZED", "Invalid email or password.");
159- }
160- if (!user.email_verified_at) {
161- this.audit("auth.login_unverified", {
162- email,
163- ipAddress: input.ipAddress,
164- userAgent: input.userAgent,
165- userId: user.id
166- });
167- throw new AuthError(403, "EMAIL_NOT_VERIFIED", "Email verification is required before login.");
168- }
169- const maxAgeSeconds = input.client === "tui" ? TUI_SESSION_TTL_SECONDS : WEB_SESSION_TTL_SECONDS;
170- const expiresAt = new Date(Date.now() + maxAgeSeconds * 1000).toISOString();
171- const sessionToken = createSecretToken();
172- const csrfToken = createSecretToken();
173- const session = this.metadataStore.authSessions.create({
174- id: randomUUID(),
175- user_id: user.id,
176- token_hash: hashToken(sessionToken, this.config.sessionSecret),
177- csrf_token_hash: hashToken(csrfToken, this.config.sessionSecret),
178- expires_at: expiresAt,
179- ...(input.ipAddress ? { ip_address: input.ipAddress } : {}),
180- ...(input.userAgent ? { user_agent: input.userAgent } : {})
181- });
182- const workspace = this.ensurePersonalWorkspace(user);
183- this.audit("auth.login_succeeded", {
184- email,
185- ipAddress: input.ipAddress,
186- metadata: { sessionId: session.id, client: input.client ?? "web" },
187- userAgent: input.userAgent,
188- userId: user.id
189- });
190- return {
191- csrfToken,
192- expiresAt: session.expires_at,
193- maxAgeSeconds,
194- sessionToken,
195- user: userDto(user),
196- workspace: workspaceDto(workspace)
197- };
198- }
199- 
200- async forgotPassword(input: {
201- email: string;
202- ipAddress?: string | undefined;
203- userAgent?: string | undefined;
204- }): Promise<{ resetToken?: string; ok: boolean }> {
205- const email = normalizeEmail(input.email);
206- this.checkRateLimit(`password-reset:email:${email}`, 3, 60 * 60);
207- const user = this.metadataStore.users.findByEmail({ email });
208- if (!user) {
209- this.audit("auth.password_reset_requested_unknown", {
210- email,
211- ipAddress: input.ipAddress,
212- userAgent: input.userAgent
213- });
214- return { ok: true };
215- }
216- const resetToken = createSecretToken();
217- this.metadataStore.authTokens.create({
218- id: randomUUID(),
219- user_id: user.id,
220- purpose: "password_reset",
221- token_hash: hashToken(resetToken, this.config.sessionSecret),
222- expires_at: new Date(Date.now() + PASSWORD_RESET_TTL_MS).toISOString()
223- });
224- const mail = await this.mailer.sendPasswordReset({ email, token: resetToken });
225- this.audit("auth.password_reset_requested", {
226- email,
227- ipAddress: input.ipAddress,
228- userAgent: input.userAgent,
229- userId: user.id
230- });
231- return { ok: true, ...(mail.testToken ? { resetToken: mail.testToken } : {}) };
232- }
233- 
234- async resetPassword(input: {
235- ipAddress?: string | undefined;
236- password: string;
237- token: string;
238- userAgent?: string | undefined;
239- }): Promise<{ ok: boolean }> {
240- assertPassword(input.password);
241- const token = this.requireToken("password_reset", input.token);
242- const password = await hashPassword(input.password);
243- this.metadataStore.userPasswordCredentials.set({
244- user_id: token.user_id,
245- password_hash: password.hash,
246- password_hash_params: password.params
247- });
248- const user = this.metadataStore.users.touchPasswordUpdated({ user_id: token.user_id });
249- this.metadataStore.authTokens.consume({ id: token.id });
250- this.metadataStore.authSessions.revokeByUser({ user_id: token.user_id });
251- this.audit("auth.password_reset_completed", {
252- email: user.email,
253- ipAddress: input.ipAddress,
254- userAgent: input.userAgent,
255- userId: user.id
256- });
257- return { ok: true };
258- }
259- 
260- async changePassword(input: {
261- currentPassword: string;
262- identity: AuthIdentity;
263- ipAddress?: string | undefined;
264- newPassword: string;
265- userAgent?: string | undefined;
266- }): Promise<{ ok: boolean }> {
267- assertPassword(input.newPassword);
268- const credential = this.metadataStore.userPasswordCredentials.get({ user_id: input.identity.user.id });
269- if (!(await verifyPassword(credential.password_hash, input.currentPassword))) {
270- throw new AuthError(401, "UNAUTHORIZED", "Current password is invalid.");
271- }
272- const password = await hashPassword(input.newPassword);
273- this.metadataStore.userPasswordCredentials.set({
274- user_id: input.identity.user.id,
275- password_hash: password.hash,
276- password_hash_params: password.params
277- });
278- this.metadataStore.users.touchPasswordUpdated({ user_id: input.identity.user.id });
279- this.metadataStore.authSessions.revokeByUser({
280- user_id: input.identity.user.id,
281- ...(input.identity.session ? { except_session_id: input.identity.session.id } : {})
282- });
283- this.audit("auth.password_changed", {
284- email: input.identity.user.email,
285- ipAddress: input.ipAddress,
286- userAgent: input.userAgent,
287- userId: input.identity.user.id
288- });
289- return { ok: true };
290- }
291- 
292- authenticateSession(sessionToken: string | undefined): AuthIdentity {
293- if (!sessionToken) {
294- throw new AuthError(401, "UNAUTHORIZED", "Authentication required.");
295- }
296- const session = this.metadataStore.authSessions.findByTokenHash({
297- token_hash: hashToken(sessionToken, this.config.sessionSecret)
298- });
299- if (!session) {
300- throw new AuthError(401, "UNAUTHORIZED", "Authentication required.");
301- }
302- const user = this.metadataStore.users.getById({ user_id: session.user_id });
303- if (user.disabled_at) {
304- throw new AuthError(401, "UNAUTHORIZED", "Authentication required.");
305- }
306- this.metadataStore.authSessions.touch({ id: session.id });
307- return {
308- session,
309- user,
310- workspace: this.ensurePersonalWorkspace(user)
311- };
312- }
313- 
314- validateCsrf(identity: AuthIdentity, csrfToken: string | undefined): void {
315- if (!identity.session || !csrfToken) {
316- throw new AuthError(403, "CSRF_INVALID", "CSRF token is required.");
317- }
318- const tokenHash = hashToken(csrfToken, this.config.sessionSecret);
319- if (tokenHash !== identity.session.csrf_token_hash) {
320- throw new AuthError(403, "CSRF_INVALID", "CSRF token is invalid.");
321- }
322- }
323- 
324- rotateCsrf(identity: AuthIdentity): { csrfToken: string; maxAgeSeconds: number } {
325- if (!identity.session) {
326- throw new AuthError(401, "UNAUTHORIZED", "Authentication required.");
327- }
328- const csrfToken = createSecretToken();
329- try {
330- this.metadataStore.authSessions.rotateCsrf({
331- id: identity.session.id,
332- csrf_token_hash: hashToken(csrfToken, this.config.sessionSecret)
333- });
334- } catch (error) {
335- if (error instanceof Error && error.message.startsWith("AUTH_SESSION_CSRF_ROTATE_FAILED:")) {
336- throw new AuthError(401, "UNAUTHORIZED", "Authentication required.");
337- }
338- throw error;
339- }
340- const remainingMs = Date.parse(identity.session.expires_at) - Date.now();
341- const maxAgeSeconds = Math.max(0, Math.floor(remainingMs / 1000));
342- return { csrfToken, maxAgeSeconds };
343- }
344- 
345- logout(identity: AuthIdentity): { ok: boolean } {
346- if (identity.session) {
347- this.metadataStore.authSessions.revoke({ id: identity.session.id });
348- this.audit("auth.logout", { email: identity.user.email, userId: identity.user.id });
349- }
350- return { ok: true };
351- }
352- 
353- logoutAll(identity: AuthIdentity): { ok: boolean } {
354- this.metadataStore.authSessions.revokeByUser({ user_id: identity.user.id });
355- this.audit("auth.logout_all", { email: identity.user.email, userId: identity.user.id });
356- return { ok: true };
357- }
358- 
359- listSessions(identity: AuthIdentity): { sessions: Array<Record<string, unknown>> } {
360- return {
361- sessions: this.metadataStore.authSessions.listByUser({ user_id: identity.user.id }).map((session) => ({
362- id: session.id,
363- createdAt: session.created_at,
364- expiresAt: session.expires_at,
365- lastSeenAt: session.last_seen_at,
366- userAgent: session.user_agent
367- }))
368- };
369- }
370- 
371- revokeSession(identity: AuthIdentity, id: string): { revoked: boolean } {
372- const sessions = this.metadataStore.authSessions.listByUser({ user_id: identity.user.id });
373- if (!sessions.some((session) => session.id === id)) {
374- throw new AuthError(404, "RESOURCE_NOT_FOUND", "Session not found.");
375- }
376- this.metadataStore.authSessions.revoke({ id });
377- return { revoked: true };
378- }
379- 
380- private requireToken(purpose: "email_verification" | "password_reset", token: string) {
381- const record = this.metadataStore.authTokens.findValid({
382- purpose,
383- token_hash: hashToken(token, this.config.sessionSecret)
384- });
385- if (!record) {
386- throw new AuthError(400, "BAD_REQUEST", "Token is invalid or expired.");
387- }
388- return record;
389- }
390- 
391- private ensurePersonalWorkspace(user: UserRecord): WorkspaceRecord {
392- const existing = this.metadataStore.workspaces.findPersonalByUser({ user_id: user.id });
393- if (existing) {
394- this.metadataStore.workspaceMemberships.upsertOwner({ workspace_id: existing.id, user_id: user.id });
395- return existing;
396- }
397- const workspace = this.metadataStore.workspaces.createPersonal({
398- id: `personal-${user.id}`,
399- owner_user_id: user.id,
400- name: user.display_name ? `${user.display_name}'s workspace` : "Personal workspace"
401- });
402- this.metadataStore.workspaceMemberships.upsertOwner({ workspace_id: workspace.id, user_id: user.id });
403- return workspace;
404- }
405- 
406- private checkRateLimit(bucket: string, limit: number, windowSeconds: number): void {
407- const now = new Date();
408- const current = this.metadataStore.db.prepare(`
409- SELECT bucket, count, reset_at FROM auth_rate_limits WHERE bucket = ?
410- `).get(bucket);
411- if (isRateLimitRow(current) && new Date(String(current.reset_at)).getTime() > now.getTime()) {
412- if (Number(current.count) >= limit) {
413- throw new AuthError(429, "RATE_LIMITED", "Too many requests. Try again later.");
414- }
415- this.metadataStore.db.prepare(`
416- UPDATE auth_rate_limits SET count = count + 1, updated_at = ? WHERE bucket = ?
417- `).run(now.toISOString(), bucket);
418- return;
419- }
420- this.metadataStore.db.prepare(`
421- INSERT INTO auth_rate_limits (bucket, count, reset_at, updated_at)
422- VALUES (?, 1, ?, ?)
423- ON CONFLICT(bucket) DO UPDATE SET count = 1, reset_at = excluded.reset_at, updated_at = excluded.updated_at
424- `).run(bucket, new Date(now.getTime() + windowSeconds * 1000).toISOString(), now.toISOString());
425- }
426- 
427- private audit(
428- eventType: string,
429- input: {
430- email?: string | undefined;
431- ipAddress?: string | undefined;
432- metadata?: unknown;
433- userAgent?: string | undefined;
434- userId?: string | undefined;
435- }
436- ): void {
437- this.metadataStore.authAuditEvents.append({
438- id: randomUUID(),
439- event_type: eventType,
440- ...(input.email ? { email: input.email } : {}),
441- ...(input.ipAddress ? { ip_address: input.ipAddress } : {}),
442- ...(input.metadata ? { metadata: input.metadata } : {}),
443- ...(input.userAgent ? { user_agent: input.userAgent } : {}),
444- ...(input.userId ? { user_id: input.userId } : {})
445- });
446- }
447-}
448- 
449-export function userDto(user: UserRecord): AuthUserDto {
450- return {
451- id: user.id,
452- ...(user.email ? { email: user.email } : {}),
453- ...(user.display_name ? { displayName: user.display_name } : {})
454- };
455-}
456- 
457-export function workspaceDto(workspace: WorkspaceRecord): AuthWorkspaceDto {
458- return {
459- id: workspace.id,
460- name: workspace.name
461- };
462-}
463- 
464-function normalizeEmail(email: string): string {
465- const normalized = email.trim().toLowerCase();
466- if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/u.test(normalized)) {
467- throw new AuthError(400, "BAD_REQUEST", "A valid email address is required.");
468- }
469- return normalized;
470-}
471- 
472-function normalizeDisplayName(value: string): string {
473- const normalized = value.replace(/\s+/gu, " ").trim();
474- return normalized.slice(0, 80);
475-}
476- 
477-function assertPassword(password: string): void {
478- if (password.length < 6) {
479- throw new AuthError(400, "BAD_REQUEST", "Password must be at least 6 characters.");
480- }
481-}
482- 
483-function isRateLimitRow(value: unknown): value is { count: number; reset_at: string } {
484- return typeof value === "object" && value !== null && "count" in value && "reset_at" in value;
485-}
@@ -1,166 +0,0 @@
1-/**
2- * Provision the DTC Growth Review SQLite case library for each user+workspace.
3- *
4- * Copies the repo fixture into the workspace datasources directory (user-writable
5- * copy) and registers a sqlite datasource pointing at that real file path.
6- * Idempotent: skips when already registered with a readable path; repairs a
7- * missing file / broken path; does not revive user-deleted datasources.
8- */
9-import { copyFileSync, existsSync, mkdirSync } from "node:fs";
10-import { dirname, join, resolve, sep } from "node:path";
11-import { fileURLToPath } from "node:url";
12- 
13-import { resolveWorkspaceDir } from "@datafoundry/agent-runtime";
14-import type { MetadataStore } from "@datafoundry/metadata";
15- 
16-export const DTC_GROWTH_DATASOURCE_ID = "dtc-growth-demo";
17-export const DTC_GROWTH_DATASOURCE_NAME = "DTC Growth Review";
18-export const DTC_GROWTH_FIXTURE_FILENAME = "dtc-growth-demo.sqlite";
19- 
20-const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
21-const DEFAULT_QUERY_POLICY = {
22- maxRows: 1000,
23- timeoutMs: 10000,
24- denyWrite: true
25-} as const;
26- 
27-/** Resolve the canonical fixture shipped with the repo (or env override). */
28-export const resolveDtcGrowthFixturePath = (injectedModuleDir = MODULE_DIR): string => {
29- const fromEnv = process.env.DTC_GROWTH_FIXTURE_PATH?.trim();
30- if (fromEnv) {
31- return resolve(fromEnv);
32- }
33- // apps/api/src|dist → repo root storage/fixtures/...
34- return resolve(injectedModuleDir, "../../../storage/fixtures", DTC_GROWTH_FIXTURE_FILENAME);
35-};
36- 
37-export type EnsureBuiltinDtcGrowthDatasourceInput = {
38- metadataStore: MetadataStore;
39- userId: string;
40- workspaceId: string;
41- /** Override for tests. */
42- fixturePath?: string;
43- workspaceRoot?: string;
44-};
45- 
46-export type EnsureBuiltinDtcGrowthDatasourceResult = {
47- action: "created" | "repaired" | "skipped" | "fixture_missing";
48- filePath?: string;
49-};
50- 
51-/**
52- * Ensure the current user has a usable DTC Growth Review sqlite datasource.
53- * Safe to call repeatedly; intended to run from builtin config bootstrap.
54- */
55-export const ensureBuiltinDtcGrowthDatasource = (
56- input: EnsureBuiltinDtcGrowthDatasourceInput
57-): EnsureBuiltinDtcGrowthDatasourceResult => {
58- const fixturePath = input.fixturePath ?? resolveDtcGrowthFixturePath();
59- if (!existsSync(fixturePath)) {
60- console.warn(`[builtin] DTC Growth fixture missing at ${fixturePath}; skip auto-provision`);
61- return { action: "fixture_missing" };
62- }
63- 
64- const workspaceRoot =
65- input.workspaceRoot
66- ?? process.env.WORKSPACE_ROOT
67- ?? join(process.env.STORAGE_ROOT_DIR ?? "storage", "workspaces");
68- const workspaceDir = resolveWorkspaceDir({
69- runContext: {
70- user_id: input.userId,
71- workspace_id: input.workspaceId,
72- session_id: "builtin-dtc-growth",
73- run_id: "builtin-dtc-growth",
74- selected_datasource_id: "",
75- enabled_datasource_ids: [],
76- user_input: "",
77- chat_mode: "server",
78- model_name: "builtin-dtc-growth"
79- },
80- workspaceRoot
81- });
82- const targetDir = join(workspaceDir, "datasources");
83- const targetPath = join(targetDir, DTC_GROWTH_FIXTURE_FILENAME);
84- if (!targetPath.startsWith(`${workspaceDir}${sep}`)) {
85- throw new Error("WORKSPACE_PATH_ESCAPE");
86- }
87- 
88- const existing = input.metadataStore.dataSources.find({
89- user_id: input.userId,
90- datasource_id: DTC_GROWTH_DATASOURCE_ID
91- });
92- if (existing?.status === "deleted") {
93- return { action: "skipped", filePath: targetPath };
94- }
95- 
96- const existingConfig = existing ? parseConfig(existing.config_json) : {};
97- const existingPath = stringValue(existingConfig.path);
98- const existingPathOk = Boolean(existingPath && existsSync(existingPath));
99- 
100- // Prefer an already-valid registered path (e.g. another workspace copy) over rewriting.
101- if (existing && existingPathOk && existingPath) {
102- return { action: "skipped", filePath: existingPath };
103- }
104- 
105- if (!existsSync(targetPath)) {
106- mkdirSync(targetDir, { recursive: true });
107- copyFileSync(fixturePath, targetPath);
108- }
109- 
110- const config = {
111- ...existingConfig,
112- path: targetPath,
113- builtin: true,
114- defaultEnabled: true,
115- mode: "readonly",
116- queryPolicy: {
117- ...DEFAULT_QUERY_POLICY,
118- ...recordValue(existingConfig.queryPolicy)
119- }
120- };
121- 
122- if (!existing) {
123- input.metadataStore.dataSources.create({
124- user_id: input.userId,
125- id: DTC_GROWTH_DATASOURCE_ID,
126- name: DTC_GROWTH_DATASOURCE_NAME,
127- type: "sqlite",
128- config,
129- description: "Built-in beauty DTC growth review case (SQLite).",
130- status: "ready"
131- });
132- return { action: "created", filePath: targetPath };
133- }
134- 
135- input.metadataStore.dataSources.create({
136- user_id: input.userId,
137- id: DTC_GROWTH_DATASOURCE_ID,
138- name: existing.name || DTC_GROWTH_DATASOURCE_NAME,
139- type: "sqlite",
140- config,
141- ...(existing.description ? { description: existing.description } : {
142- description: "Built-in beauty DTC growth review case (SQLite)."
143- }),
144- status: existing.status === "failed" ? "ready" : existing.status,
145- expected_revision: existing.revision
146- });
147- return { action: "repaired", filePath: targetPath };
148-};
149- 
150-const parseConfig = (configJson: string): Record<string, unknown> => {
151- try {
152- const parsed: unknown = JSON.parse(configJson);
153- return isRecord(parsed) ? parsed : {};
154- } catch {
155- return {};
156- }
157-};
158- 
159-const isRecord = (value: unknown): value is Record<string, unknown> =>
160- typeof value === "object" && value !== null && !Array.isArray(value);
161- 
162-const stringValue = (value: unknown): string | undefined =>
163- typeof value === "string" && value.trim() ? value.trim() : undefined;
164- 
165-const recordValue = (value: unknown): Record<string, unknown> | undefined =>
166- isRecord(value) ? value : undefined;
@@ -1,8 +0,0 @@
1-import { createEnvConfig } from "@datafoundry/contracts";
2- 
3-export type ApiConfig = {
4- host: string;
5- port: number;
6-};
7- 
8-export const loadApiConfig = (): ApiConfig => createEnvConfig(process.env).api;
@@ -1,21 +0,0 @@
1-import type { ContextPackageRecorder } from "@datafoundry/agent-runtime";
2-import type { MetadataStore } from "@datafoundry/metadata";
3- 
4-export const createMetadataContextPackageRecorder = (input: {
5- metadataStore: MetadataStore;
6- runId: string;
7- sessionId: string;
8- userId: string;
9-}): ContextPackageRecorder => ({
10- record: ({ contextPackage, plan }) => {
11- input.metadataStore.contextPackageSnapshots.create({
12- user_id: input.userId,
13- session_id: input.sessionId,
14- run_id: input.runId,
15- package_id: contextPackage.packageId,
16- revision: contextPackage.revision,
17- payload: contextPackage,
18- plan
19- });
20- }
21-});
@@ -1,86 +0,0 @@
1-import { Agent } from "@mastra/core/agent";
2-import type { ConversationMessageRecord, ConversationSummaryRecord } from "@datafoundry/metadata";
3- 
4-import { type ConversationSummarizer, type ConversationSummarizerInput } from "./conversation-memory.js";
5- 
6-export type MastraConversationSummarizerInput = {
7- maxOutputTokens?: number | undefined;
8- model: unknown;
9- temperature?: number | undefined;
10-};
11- 
12-export class MastraConversationSummarizer implements ConversationSummarizer {
13- readonly kind = "mastra-agent";
14- private readonly agent: Agent;
15- private readonly maxOutputTokens: number;
16- private readonly temperature: number;
17- 
18- constructor(input: MastraConversationSummarizerInput) {
19- this.maxOutputTokens = input.maxOutputTokens ?? 900;
20- this.temperature = input.temperature ?? 0.1;
21- this.agent = new Agent({
22- id: "conversation-summarizer",
23- name: "Conversation Summarizer",
24- instructions: [
25- "You maintain compact conversation memory for a data analysis agent.",
26- "Summarize only facts, user preferences, decisions, active goals, unresolved questions, and verified results.",
27- "Preserve datasource names, table names, field names, SQL intent, artifact references, and user constraints.",
28- "Do not invent schema, query results, tool output, credentials, or private environment values.",
29- "Return concise Chinese text unless the source messages are primarily in another language.",
30- "Do not include XML tags, markdown tables, or implementation commentary."
31- ].join("\n"),
32- model: input.model as never,
33- defaultOptions: {
34- maxSteps: 1,
35- modelSettings: {
36- maxOutputTokens: this.maxOutputTokens,
37- temperature: this.temperature
38- },
39- providerOptions: {
40- openai: {
41- systemMessageMode: "system"
42- }
43- }
44- }
45- });
46- }
47- 
48- async summarize(input: ConversationSummarizerInput): Promise<string> {
49- const prompt = buildSummarizerPrompt(input);
50- const output = await this.agent.generate(prompt);
51- return output.text.trim();
52- }
53-}
54- 
55-export const createMastraConversationSummarizer = (
56- input: MastraConversationSummarizerInput
57-): MastraConversationSummarizer => new MastraConversationSummarizer(input);
58- 
59-const buildSummarizerPrompt = (input: ConversationSummarizerInput): string => {
60- const previousSummary = formatPreviousSummary(input.previousSummary);
61- const sourceMessages = input.sourceMessages.map(formatSourceMessage).join("\n");
62- return [
63- `Summarize this conversation memory segment into at most ${input.maxChars} characters.`,
64- "The summary will replace the source messages in a future prompt, so keep durable context and omit filler.",
65- previousSummary,
66- "<source_messages>",
67- sourceMessages,
68- "</source_messages>"
69- ].filter(Boolean).join("\n\n");
70-};
71- 
72-const formatPreviousSummary = (summary?: ConversationSummaryRecord | undefined): string =>
73- summary
74- ? [
75- `<previous_summary from_position="${summary.from_position}" to_position="${summary.to_position}">`,
76- summary.summary_text,
77- "</previous_summary>"
78- ].join("\n")
79- : "";
80- 
81-const formatSourceMessage = (message: ConversationMessageRecord): string =>
82- [
83- `<message position="${message.position}" role="${message.role}" run_id="${message.run_id}">`,
84- message.content_text,
85- "</message>"
86- ].join("\n");
@@ -0,0 +1,3 @@
1+"""DataFoundry Python control plane."""
2+ 
3+__version__ = "0.3.0"
@@ -0,0 +1,23 @@
1+from __future__ import annotations
2+ 
3+import os
4+ 
5+import uvicorn
6+ 
7+from datafoundry_api.settings import Settings
8+ 
9+ 
10+def main() -> None:
11+ """Start the DataFoundry control-plane API."""
12+ settings = Settings.from_env()
13+ uvicorn.run(
14+ "datafoundry_api.app:create_app",
15+ host=settings.host,
16+ port=settings.port,
17+ factory=True,
18+ reload=os.environ.get("API_RELOAD") == "1",
19+ )
20+ 
21+ 
22+if __name__ == "__main__":
23+ main()
@@ -0,0 +1,286 @@
1+from __future__ import annotations
2+ 
3+import hashlib
4+import hmac
5+import secrets
6+from dataclasses import dataclass
7+from datetime import UTC, datetime, timedelta
8+from typing import Any
9+from uuid import uuid4
10+ 
11+from argon2 import PasswordHasher
12+from argon2.exceptions import VerifyMismatchError
13+from fastapi import Request, Response
14+ 
15+from datafoundry_api.deployment import DEPLOYMENT_WORKSPACE_ID, DEPLOYMENT_WORKSPACE_NAME
16+from datafoundry_api.errors import AuthError
17+from datafoundry_api.settings import Settings
18+from datafoundry_api.store import SqliteStore
19+ 
20+SESSION_COOKIE = "df_session"
21+CSRF_COOKIE = "df_csrf"
22+WEB_SESSION_TTL = timedelta(days=30)
23+TUI_SESSION_TTL = timedelta(days=7)
24+EMAIL_TOKEN_TTL = timedelta(hours=24)
25+PASSWORD_HASHER = PasswordHasher()
26+ 
27+ 
28+@dataclass
29+class Identity:
30+ user_id: str
31+ email: str
32+ display_name: str | None
33+ workspace_id: str
34+ workspace_name: str
35+ session_id: str
36+ csrf_token_hash: str
37+ expires_at: str
38+ 
39+ 
40+class AuthService:
41+ def __init__(self, store: SqliteStore, settings: Settings) -> None:
42+ self.store = store
43+ self.settings = settings
44+ 
45+ def public_status(self) -> dict[str, Any]:
46+ return {
47+ "publicBaseUrl": self.settings.public_base_url,
48+ "registrationEnabled": self.settings.registration_mode == "open",
49+ }
50+ 
51+ def register(self, email: str, password: str, display_name: str | None) -> dict[str, Any]:
52+ if self.settings.registration_mode != "open":
53+ raise AuthError(403, "REGISTRATION_CLOSED", "Registration is closed for this deployment.")
54+ normalized_email = _normalize_email(email)
55+ _assert_password(password)
56+ if self.store.fetchone("SELECT id FROM users WHERE email = ?", (normalized_email,)):
57+ raise AuthError(409, "CONFLICT", "Email is already registered.")
58+ user_id = str(uuid4())
59+ workspace = self._deployment_workspace()
60+ now = _now().isoformat()
61+ self.store.execute(
62+ "INSERT INTO users (id, email, display_name, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
63+ (user_id, normalized_email, display_name, PASSWORD_HASHER.hash(password), now),
64+ )
65+ verification_token = secrets.token_urlsafe(32)
66+ self.store.execute(
67+ "INSERT INTO auth_tokens (id, user_id, purpose, token_hash, expires_at) VALUES (?, ?, ?, ?, ?)",
68+ (
69+ str(uuid4()),
70+ user_id,
71+ "email_verification",
72+ self._hash_token(verification_token),
73+ (_now() + EMAIL_TOKEN_TTL).isoformat(),
74+ ),
75+ )
76+ payload = {
77+ "user": _user_dto(user_id, normalized_email, display_name),
78+ "workspace": {"id": workspace["id"], "name": workspace["name"]},
79+ }
80+ if self.settings.email_delivery == "test":
81+ payload["verificationToken"] = verification_token
82+ return payload
83+ 
84+ def verify_email(self, token: str) -> dict[str, Any]:
85+ row = self._require_token("email_verification", token)
86+ now = _now().isoformat()
87+ self.store.execute("UPDATE users SET email_verified_at = ? WHERE id = ?", (now, row["user_id"]))
88+ self.store.execute("UPDATE auth_tokens SET consumed_at = ? WHERE id = ?", (now, row["id"]))
89+ user = self.store.fetchone("SELECT * FROM users WHERE id = ?", (row["user_id"],))
90+ if user is None:
91+ raise AuthError(401, "UNAUTHORIZED", "Authentication required.")
92+ return {"user": _user_dto(user["id"], user["email"], user["display_name"])}
93+ 
94+ def login(self, email: str, password: str, client: str | None) -> tuple[dict[str, Any], str, str, int]:
95+ normalized_email = _normalize_email(email)
96+ user = self.store.fetchone("SELECT * FROM users WHERE email = ?", (normalized_email,))
97+ if user is None or not _verify_password(user["password_hash"], password):
98+ raise AuthError(401, "UNAUTHORIZED", "Invalid email or password.")
99+ if not user["email_verified_at"]:
100+ raise AuthError(403, "EMAIL_NOT_VERIFIED", "Email verification is required before login.")
101+ ttl = TUI_SESSION_TTL if client == "tui" else WEB_SESSION_TTL
102+ expires_at = (_now() + ttl).isoformat()
103+ session_token = secrets.token_urlsafe(32)
104+ csrf_token = secrets.token_urlsafe(32)
105+ workspace = self._deployment_workspace()
106+ self.store.execute(
107+ """
108+ INSERT INTO auth_sessions (id, user_id, token_hash, csrf_token_hash, expires_at)
109+ VALUES (?, ?, ?, ?, ?)
110+ """,
111+ (str(uuid4()), user["id"], self._hash_token(session_token), self._hash_token(csrf_token), expires_at),
112+ )
113+ return (
114+ {
115+ "user": _user_dto(user["id"], user["email"], user["display_name"]),
116+ "workspace": {"id": workspace["id"], "name": workspace["name"]},
117+ "session": {"expiresAt": expires_at},
118+ },
119+ session_token,
120+ csrf_token,
121+ int(ttl.total_seconds()),
122+ )
123+ 
124+ def authenticate(self, session_token: str | None) -> Identity:
125+ if self.settings.auth_disabled:
126+ return _local_preview_identity()
127+ if not session_token:
128+ raise AuthError(401, "UNAUTHORIZED", "Authentication required.")
129+ session = self.store.fetchone(
130+ """
131+ SELECT s.*, u.email, u.display_name, w.id AS workspace_id, w.name AS workspace_name
132+ FROM auth_sessions s
133+ JOIN users u ON u.id = s.user_id
134+ JOIN workspaces w ON w.id = ?
135+ WHERE s.token_hash = ? AND s.revoked_at IS NULL
136+ """,
137+ (DEPLOYMENT_WORKSPACE_ID, self._hash_token(session_token)),
138+ )
139+ if session is None or datetime.fromisoformat(session["expires_at"]) <= _now():
140+ raise AuthError(401, "UNAUTHORIZED", "Authentication required.")
141+ return Identity(
142+ user_id=session["user_id"],
143+ email=session["email"],
144+ display_name=session["display_name"],
145+ workspace_id=session["workspace_id"],
146+ workspace_name=session["workspace_name"],
147+ session_id=session["id"],
148+ csrf_token_hash=session["csrf_token_hash"],
149+ expires_at=session["expires_at"],
150+ )
151+ 
152+ def validate_csrf(self, identity: Identity, csrf_token: str | None) -> None:
153+ if self.settings.auth_disabled:
154+ return
155+ if not csrf_token:
156+ raise AuthError(403, "CSRF_INVALID", "CSRF token is required.")
157+ if self._hash_token(csrf_token) != identity.csrf_token_hash:
158+ raise AuthError(403, "CSRF_INVALID", "CSRF token is invalid.")
159+ 
160+ def rotate_csrf(self, identity: Identity) -> tuple[str, int]:
161+ csrf_token = secrets.token_urlsafe(32)
162+ self.store.execute(
163+ "UPDATE auth_sessions SET csrf_token_hash = ? WHERE id = ?",
164+ (self._hash_token(csrf_token), identity.session_id),
165+ )
166+ remaining = max(0, int((datetime.fromisoformat(identity.expires_at) - _now()).total_seconds()))
167+ return csrf_token, remaining
168+ 
169+ def logout(self, identity: Identity) -> dict[str, bool]:
170+ self.store.execute(
171+ "UPDATE auth_sessions SET revoked_at = ? WHERE id = ?",
172+ (_now().isoformat(), identity.session_id),
173+ )
174+ return {"ok": True}
175+ 
176+ def me(self, identity: Identity) -> dict[str, Any]:
177+ return {
178+ "user": _user_dto(identity.user_id, identity.email, identity.display_name),
179+ "workspace": {"id": identity.workspace_id, "name": identity.workspace_name},
180+ }
181+ 
182+ def _deployment_workspace(self) -> Any:
183+ workspace = self.store.fetchone("SELECT * FROM workspaces WHERE id = ?", (DEPLOYMENT_WORKSPACE_ID,))
184+ if workspace is None:
185+ raise AuthError(500, "INTERNAL_ERROR", "Workspace is missing.")
186+ return workspace
187+ 
188+ def _hash_token(self, token: str) -> str:
189+ return hmac.new(self.settings.session_secret.encode("utf-8"), token.encode("utf-8"), hashlib.sha256).hexdigest()
190+ 
191+ def _require_token(self, purpose: str, token: str) -> Any:
192+ row = self.store.fetchone(
193+ """
194+ SELECT * FROM auth_tokens
195+ WHERE purpose = ? AND token_hash = ? AND consumed_at IS NULL
196+ """,
197+ (purpose, self._hash_token(token)),
198+ )
199+ if row is None or datetime.fromisoformat(row["expires_at"]) <= _now():
200+ raise AuthError(400, "BAD_REQUEST", "Token is invalid or expired.")
201+ return row
202+ 
203+ 
204+def identity_from_request(request: Request, auth: AuthService) -> Identity:
205+ """Resolve the request identity, including the guarded local-preview identity."""
206+ return auth.authenticate(request.cookies.get(SESSION_COOKIE))
207+ 
208+ 
209+def _local_preview_identity() -> Identity:
210+ return Identity(
211+ user_id="local-preview",
212+ email="local-preview@localhost",
213+ display_name="Local Preview",
214+ workspace_id=DEPLOYMENT_WORKSPACE_ID,
215+ workspace_name=DEPLOYMENT_WORKSPACE_NAME,
216+ session_id="local-preview-session",
217+ csrf_token_hash="",
218+ expires_at=(_now() + WEB_SESSION_TTL).isoformat(),
219+ )
220+ 
221+ 
222+def attach_auth_cookies(
223+ response: Response,
224+ *,
225+ session_token: str,
226+ csrf_token: str,
227+ max_age: int,
228+ settings: Settings,
229+) -> None:
230+ _set_cookie(response, SESSION_COOKIE, session_token, http_only=True, max_age=max_age, settings=settings)
231+ _set_cookie(response, CSRF_COOKIE, csrf_token, http_only=False, max_age=max_age, settings=settings)
232+ 
233+ 
234+def clear_auth_cookies(response: Response, settings: Settings) -> None:
235+ _set_cookie(response, SESSION_COOKIE, "", http_only=True, max_age=0, settings=settings)
236+ _set_cookie(response, CSRF_COOKIE, "", http_only=False, max_age=0, settings=settings)
237+ 
238+ 
239+def _set_cookie(
240+ response: Response,
241+ name: str,
242+ value: str,
243+ *,
244+ http_only: bool,
245+ max_age: int,
246+ settings: Settings,
247+) -> None:
248+ response.set_cookie(
249+ name,
250+ value,
251+ max_age=max_age,
252+ path=settings.cookie_path,
253+ secure=settings.cookie_secure,
254+ httponly=http_only,
255+ samesite="lax",
256+ )
257+ 
258+ 
259+def _user_dto(user_id: str, email: str, display_name: str | None) -> dict[str, str]:
260+ payload = {"id": user_id, "email": email}
261+ if display_name:
262+ payload["displayName"] = display_name
263+ return payload
264+ 
265+ 
266+def _normalize_email(email: str) -> str:
267+ normalized = email.strip().lower()
268+ if "@" not in normalized or normalized.startswith("@") or normalized.endswith("@"):
269+ raise AuthError(400, "BAD_REQUEST", "A valid email address is required.")
270+ return normalized
271+ 
272+ 
273+def _assert_password(password: str) -> None:
274+ if len(password) < 6:
275+ raise AuthError(400, "BAD_REQUEST", "Password must be at least 6 characters.")
276+ 
277+ 
278+def _verify_password(password_hash: str, password: str) -> bool:
279+ try:
280+ return PASSWORD_HASHER.verify(password_hash, password)
281+ except VerifyMismatchError:
282+ return False
283+ 
284+ 
285+def _now() -> datetime:
286+ return datetime.now(UTC)
@@ -0,0 +1,51 @@
1+from __future__ import annotations
2+ 
3+from typing import Any
4+ 
5+CAPABILITIES: dict[str, bool] = {
6+ "artifact.export": False,
7+ "artifact.list": False,
8+ "artifact.promote": False,
9+ "chat.fileUpload": True,
10+ "chat.imageInput": False,
11+ "conversation.memory": False,
12+ "conversation.title": False,
13+ "interaction.resume": False,
14+ "runtime.dataTools": False,
15+ "runtime.traceDag": False,
16+ "datasource.fieldMasking": False,
17+ "datasource.extendedTypes": False,
18+ "datasource.introspectionPolicy": False,
19+ "datasource.queryPolicy": False,
20+ "datasource.samplePolicy": False,
21+ "datasource.server": False,
22+ "files": True,
23+ "kb.chunking": False,
24+ "kb.citationPolicy": False,
25+ "kb.scope": False,
26+ "llm.advancedSampling": False,
27+ "llm.samplingParams": True,
28+ "knowledge": False,
29+ "mcp": True,
30+ "mcp.stdio": False,
31+ "mcp.toolPolicy": True,
32+ "skill.resourceBinding": False,
33+ "skills": True,
34+}
35+ 
36+WORKSPACE_CONFIG: dict[str, list[Any]] = {
37+ "datasources": [],
38+ "knowledgeBases": [],
39+ "mcpServers": [],
40+ "modelProfiles": [],
41+ "skills": [],
42+}
43+ 
44+RUN_DEFAULTS: dict[str, Any] = {
45+ "enabledDatasourceIds": [],
46+ "enabledKnowledgeIds": [],
47+ "enabledMcpServerIds": [],
48+ "enabledSkillIds": [],
49+ "activeLlmProfileId": "server-default",
50+ "activeSkillId": "",
51+}
@@ -0,0 +1,275 @@
1+"""Mount agentkit conversation routes on the control-plane process.
2+ 
3+The handlers stay in ``restapi``. This module only prepares that runtime and
4+opens the same lifespan the standalone ``dataagent serve`` command uses.
5+"""
6+ 
7+from __future__ import annotations
8+ 
9+import logging
10+import os
11+import threading
12+from contextlib import asynccontextmanager
13+from logging.handlers import RotatingFileHandler
14+from pathlib import Path
15+from uuid import uuid4
16+ 
17+from fastapi import FastAPI
18+from fastapi.responses import JSONResponse
19+ 
20+logger = logging.getLogger("datafoundry_api.conversation")
21+_BACKEND_LOG_HANDLER: logging.Handler | None = None
22+_BACKEND_LOG_LOCK = threading.Lock()
23+# agentkit loads a plugin file as this module name. Hook examples that call
24+# logging.getLogger(__name__) therefore log under this prefix, not under dataagent.
25+_PLUGIN_LOGGER_PREFIX = "_dataagent_v2_plugin_"
26+ 
27+ 
28+def _unavailable() -> JSONResponse:
29+ return JSONResponse(
30+ {
31+ "success": False,
32+ "error": {
33+ "code": "CONVERSATION_UNAVAILABLE",
34+ "message": "对话引擎未就绪。",
35+ },
36+ },
37+ status_code=503,
38+ )
39+ 
40+ 
41+def is_conversation_path(path: str) -> bool:
42+ """True for agentkit routes. Control-plane ``/api/v1`` auth does not apply."""
43+ if path in {"/dataagent/stream", "/api/copilotkit", "/sessions"}:
44+ return True
45+ return path.startswith(("/dataagent/stream/", "/api/copilotkit/", "/sessions/"))
46+ 
47+ 
48+class ConversationMount:
49+ """In-process agentkit runtime, registered onto the control-plane app."""
50+ 
51+ def __init__(self) -> None:
52+ self.runtime, self.error = prepare_conversation_runtime()
53+ self.instance_id = (os.environ.get("DATAAGENT_V2_INSTANCE_ID") or "").strip() or str(uuid4())
54+ 
55+ @asynccontextmanager
56+ async def lifespan(self, app: FastAPI):
57+ """Initialize conversation state during control-plane startup and close it on exit."""
58+ app.state.conversation_runtime = self.runtime
59+ app.state.conversation_instance_id = self.instance_id
60+ app.state.conversation_error = self.error
61+ async with open_conversation(app, self.runtime):
62+ yield
63+ 
64+ def register(self, app: FastAPI) -> None:
65+ """Register conversation routes before the control plane's 404 fallback."""
66+ if self.runtime is None:
67+ _register_unavailable(app)
68+ return
69+ from restapi.app import register_conversation_routes
70+ 
71+ register_conversation_routes(
72+ app,
73+ self.runtime,
74+ instance_id=self.instance_id,
75+ include_health=False,
76+ )
77+ 
78+ 
79+def prepare_conversation_runtime():
80+ """Build the agentkit runtime. Failures stay in-process; nothing else is spawned."""
81+ try:
82+ from dataagent import LaunchOptions, prepare_runtime
83+ 
84+ config = _conversation_config()
85+ runtime = prepare_runtime(
86+ LaunchOptions(
87+ config=config,
88+ init_home=True,
89+ cwd=config.parent if config is not None else Path.cwd(),
90+ )
91+ )
92+ except Exception as exc: # noqa: BLE001 - a setup failure must not take down the control plane
93+ logger.warning("Conversation engine is not ready: %s", exc)
94+ return None, exc
95+ try:
96+ _ensure_backend_log(runtime)
97+ except Exception as exc: # noqa: BLE001 - a log file must not take down the control plane
98+ logger.warning("Conversation audit log was not attached: %s", exc)
99+ return runtime, None
100+ 
101+ 
102+class _RedactingFormatter(logging.Formatter):
103+ """Format a line, then redact the current secret list.
104+ 
105+ The list is replaced in place when the same Home is prepared again with a
106+ new key, so the open handler does not keep writing the old set.
107+ """
108+ 
109+ def __init__(self, fmt: str, secrets: list[str]) -> None:
110+ super().__init__(fmt)
111+ self.secrets = secrets
112+ 
113+ def format(self, record: logging.LogRecord) -> str:
114+ from dataagent import safe_error
115+ 
116+ return safe_error(RuntimeError(super().format(record)), tuple(self.secrets))["message"]
117+ 
118+ 
119+def _plugin_loggers() -> list[logging.Logger]:
120+ found: list[logging.Logger] = []
121+ for name in list(logging.Logger.manager.loggerDict):
122+ if isinstance(name, str) and name.startswith(_PLUGIN_LOGGER_PREFIX):
123+ found.append(logging.getLogger(name))
124+ return found
125+ 
126+ 
127+def _detach_backend_handler(handler: logging.Handler) -> None:
128+ logging.getLogger("dataagent").removeHandler(handler)
129+ for plugin_logger in _plugin_loggers():
130+ plugin_logger.removeHandler(handler)
131+ 
132+ 
133+def _attach_plugin_loggers(handler: logging.Handler) -> None:
134+ for plugin_logger in _plugin_loggers():
135+ if handler not in plugin_logger.handlers:
136+ plugin_logger.addHandler(handler)
137+ if plugin_logger.level == logging.NOTSET or plugin_logger.level > logging.INFO:
138+ plugin_logger.setLevel(logging.INFO)
139+ 
140+ 
141+def _ensure_backend_log(runtime) -> None:
142+ """Append selected loggers to this Home's ``runtime/logs/backend.log``.
143+ 
144+ The file receives:
145+ 
146+ * ``dataagent`` and its children, including ``dataagent.audit`` and
147+ ``dataagent.startup``
148+ * plugin and hook loggers named ``_dataagent_v2_plugin_<sha256>`` that
149+ already exist when the runtime is prepared (agentkit's module name in
150+ ``dataagent.extensions.loading``; ``getLogger(__name__)`` in a hook uses it)
151+ * the startup line ``Enabled plugins and sources``
152+ 
153+ Loggers created under that prefix after this call, and every other logger,
154+ are not attached. ``restapi.configure_logging`` is not called: it uses
155+ ``logging.basicConfig(force=True)`` and is not exported from the ``dataagent``
156+ package root.
157+ """
158+ global _BACKEND_LOG_HANDLER
159+ state_dir = runtime.paths.state_dir
160+ directory = state_dir / "logs"
161+ state_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
162+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
163+ state_dir.chmod(0o700)
164+ directory.chmod(0o700)
165+ path = str((directory / "backend.log").resolve())
166+ secrets = [str(item) for item in (getattr(runtime, "redaction_secrets", ()) or ()) if item]
167+ audit = logging.getLogger("dataagent")
168+ with _BACKEND_LOG_LOCK:
169+ current = _BACKEND_LOG_HANDLER
170+ if (
171+ current is not None
172+ and getattr(current, "_dataagent_backend_log", None) == path
173+ and current in audit.handlers
174+ ):
175+ formatter = current.formatter
176+ if isinstance(formatter, _RedactingFormatter):
177+ formatter.secrets[:] = secrets
178+ _attach_plugin_loggers(current)
179+ _log_enabled_plugins(runtime)
180+ return
181+ if current is not None:
182+ _detach_backend_handler(current)
183+ current.close()
184+ _BACKEND_LOG_HANDLER = None
185+ handler = RotatingFileHandler(path, maxBytes=5_000_000, backupCount=3)
186+ handler.setFormatter(_RedactingFormatter("%(asctime)s %(levelname)s %(name)s %(message)s", secrets))
187+ handler._dataagent_backend_log = path # type: ignore[attr-defined]
188+ audit.addHandler(handler)
189+ _attach_plugin_loggers(handler)
190+ _BACKEND_LOG_HANDLER = handler
191+ if audit.level == logging.NOTSET or audit.level > logging.INFO:
192+ audit.setLevel(logging.INFO)
193+ _log_enabled_plugins(runtime)
194+ 
195+ 
196+def _log_enabled_plugins(runtime) -> None:
197+ report = getattr(runtime, "report", None)
198+ origins = getattr(report, "plugin_origins", None) if report is not None else None
199+ if origins is None:
200+ return
201+ logging.getLogger("dataagent.startup").info("Enabled plugins and sources: %s", origins)
202+ 
203+ 
204+@asynccontextmanager
205+async def open_conversation(app: FastAPI, runtime):
206+ """Run agentkit's lifespan. A startup failure leaves the control plane up."""
207+ if runtime is None:
208+ yield
209+ return
210+ from restapi.app import conversation_lifespan
211+ 
212+ started = False
213+ try:
214+ async with conversation_lifespan(app, runtime):
215+ started = True
216+ yield
217+ except Exception as exc:
218+ if started:
219+ raise
220+ logger.warning("Conversation engine failed during startup: %s", exc)
221+ app.state.conversation_error = exc
222+ app.state.agents = None
223+ yield
224+ 
225+ 
226+def conversation_status(app: FastAPI) -> dict:
227+ """Report whether the in-process engine is ready, including model and plugins when readable."""
228+ agents = getattr(app.state, "agents", None)
229+ runtime = getattr(agents, "runtime", None)
230+ if runtime is None:
231+ runtime = getattr(app.state, "conversation_runtime", None)
232+ if runtime is None:
233+ return {"ready": False}
234+ partial = _readable_model(runtime)
235+ return {"ready": False, **partial} if partial else {"ready": False}
236+ from restapi.app import agentkit_health_body
237+ 
238+ instance_id = getattr(app.state, "conversation_instance_id", "")
239+ return {"ready": True, **agentkit_health_body(runtime, instance_id)}
240+ 
241+ 
242+def _readable_model(runtime) -> dict:
243+ try:
244+ return {
245+ "model": runtime.model_name,
246+ "plugins": list(runtime.settings.plugins.enabled),
247+ }
248+ except Exception: # noqa: BLE001 - unreadable model settings are reported as not ready
249+ return {}
250+ 
251+ 
252+def _conversation_config() -> Path | None:
253+ """Use an explicit config when set. Otherwise agentkit reads Home ``config.json``."""
254+ override = (os.environ.get("DATAAGENT_CONFIG") or "").strip()
255+ if override:
256+ return Path(override).expanduser()
257+ return None
258+ 
259+ 
260+def _register_unavailable(app: FastAPI) -> None:
261+ async def unavailable() -> JSONResponse:
262+ return _unavailable()
263+ 
264+ routes = (
265+ ("/api/copilotkit/info", ["GET"]),
266+ ("/api/copilotkit", ["POST", "OPTIONS"]),
267+ ("/api/copilotkit/{rest:path}", ["OPTIONS"]),
268+ ("/dataagent/stream", ["POST"]),
269+ ("/sessions", ["GET"]),
270+ ("/sessions/{thread_id}", ["GET"]),
271+ ("/sessions/{thread_id}/outputs", ["GET"]),
272+ ("/sessions/{thread_id}/outputs/preview", ["GET"]),
273+ )
274+ for path, methods in routes:
275+ app.add_api_route(path, unavailable, methods=methods)
@@ -0,0 +1,14 @@
1+"""Identifiers shared by one deployment.
2+ 
3+One process and one ``DATAAGENT_HOME`` are one team. These values are not
4+per-user settings and are not a tenant id.
5+"""
6+ 
7+from __future__ import annotations
8+ 
9+DEPLOYMENT_WORKSPACE_ID = "deployment"
10+DEPLOYMENT_WORKSPACE_NAME = "Team"
11+# Skill packages are deployment files. Chat uploads stay under the real user id.
12+DEPLOYMENT_FILE_OWNER = "deployment"
13+SECRET_SCOPE_TEAM = "team"
14+SCHEMA_VERSION = 1
@@ -0,0 +1,13 @@
1+from __future__ import annotations
2+ 
3+from typing import Any
4+ 
5+from fastapi.responses import JSONResponse
6+ 
7+ 
8+def success(data: Any, status_code: int = 200) -> JSONResponse:
9+ return JSONResponse({"success": True, "data": data}, status_code=status_code)
10+ 
11+ 
12+def error(code: str, message: str, status_code: int) -> JSONResponse:
13+ return JSONResponse({"success": False, "error": {"code": code, "message": message}}, status_code=status_code)
@@ -0,0 +1,19 @@
1+from __future__ import annotations
2+ 
3+ 
4+class ApiError(Exception):
5+ """Stable HTTP-facing error returned through the API envelope."""
6+ 
7+ def __init__(self, status: int, code: str, message: str) -> None:
8+ super().__init__(message)
9+ self.status = status
10+ self.code = code
11+ self.message = message
12+ 
13+ 
14+class AuthError(ApiError):
15+ """Authentication or authorization failure."""
16+ 
17+ 
18+class ResourceError(ApiError):
19+ """Workspace, Skill, or MCP resource failure."""
@@ -0,0 +1,528 @@
1+"""Content-addressed files and the session/common workspace boundary."""
2+ 
3+from __future__ import annotations
4+ 
5+import hashlib
6+import json
7+import mimetypes
8+import os
9+import re
10+import shutil
11+import tempfile
12+from datetime import UTC, datetime
13+from pathlib import Path, PurePosixPath
14+from typing import Any
15+from uuid import uuid4
16+ 
17+from datafoundry_api.auth import Identity
18+from datafoundry_api.deployment import DEPLOYMENT_FILE_OWNER, DEPLOYMENT_WORKSPACE_ID
19+from datafoundry_api.errors import ResourceError
20+from datafoundry_api.storage_paths import session_outputs_dir, user_root, validate_session_id, validate_user_id
21+from datafoundry_api.store import SqliteStore
22+ 
23+_SAFE_FILE_CHARACTER = re.compile(r"[^A-Za-z0-9._ -]+")
24+_ORIGIN_BY_SOURCE = {
25+ "artifact": "generated",
26+ "knowledge": "knowledge",
27+ "run-attachment": "run-attachment",
28+ "skill-package": "skill-package",
29+ "upload": "uploaded",
30+ "workspace": "saved",
31+}
32+ 
33+ 
34+class FileAssetService:
35+ """Persist deduplicated bytes and scoped references under ``~/.dataagent``."""
36+ 
37+ def __init__(self, store: SqliteStore) -> None:
38+ self._store = store
39+ 
40+ def ensure_workspace(self, user_id: str, session_id: str) -> tuple[Path, Path]:
41+ """Create session outputs and the user-common workspace. Return both directories."""
42+ resolved_user_id = validate_user_id(user_id)
43+ outputs = _session_outputs(resolved_user_id, session_id)
44+ workspace_root = user_root(resolved_user_id) / "workspace"
45+ outputs.mkdir(parents=True, exist_ok=True)
46+ workspace_root.mkdir(parents=True, exist_ok=True)
47+ (user_root(resolved_user_id) / "assets").mkdir(parents=True, exist_ok=True)
48+ return outputs, workspace_root.resolve()
49+ 
50+ def create_ref(
51+ self,
52+ identity: Identity,
53+ *,
54+ filename: str,
55+ content: bytes,
56+ source: str,
57+ mime_type: str | None = None,
58+ session_id: str | None = None,
59+ run_id: str | None = None,
60+ metadata: dict[str, Any] | None = None,
61+ preserve_relative_path: bool = False,
62+ ) -> dict[str, Any]:
63+ """Create a content-addressed asset and one tenant-scoped reference.
64+ 
65+ Session uploads reuse their active reference when the same filename is uploaded again.
66+ """
67+ if source == "skill-package":
68+ resolved_user_id = DEPLOYMENT_FILE_OWNER
69+ workspace_id = DEPLOYMENT_WORKSPACE_ID
70+ else:
71+ resolved_user_id = validate_user_id(identity.user_id)
72+ workspace_id = identity.workspace_id
73+ resolved_session_id = _validated_session_id(session_id) if session_id else None
74+ safe_name = _safe_relative_path(filename) if preserve_relative_path else _safe_filename(filename)
75+ sha256 = hashlib.sha256(content).hexdigest()
76+ existing = self._store.fetchone(
77+ "SELECT * FROM file_assets WHERE user_id = ? AND sha256 = ?",
78+ (resolved_user_id, sha256),
79+ )
80+ if existing is None:
81+ asset_id = str(uuid4())
82+ storage_path = self._asset_path(resolved_user_id, sha256)
83+ self._write_asset(storage_path, content)
84+ self._store.execute(
85+ """
86+ INSERT INTO file_assets (id, user_id, sha256, size_bytes, storage_path, detected_mime_type, created_at)
87+ VALUES (?, ?, ?, ?, ?, ?, ?)
88+ """,
89+ (
90+ asset_id,
91+ resolved_user_id,
92+ sha256,
93+ len(content),
94+ str(storage_path),
95+ mime_type or _mime_type(safe_name),
96+ _now(),
97+ ),
98+ )
99+ else:
100+ asset = dict(existing)
@@ -0,0 +1,65 @@
1+"""Private, launcher-owned local API; uses ordinary sessions, never anonymous auth."""
2+from __future__ import annotations
3+ 
4+import json
5+import os
6+import secrets
7+import socket
8+from datetime import UTC, datetime, timedelta
9+from pathlib import Path
10+from uuid import uuid4
11+ 
12+import uvicorn
13+ 
14+from datafoundry_api.auth import PASSWORD_HASHER, AuthService
15+from datafoundry_api.deployment import DEPLOYMENT_WORKSPACE_ID, DEPLOYMENT_WORKSPACE_NAME
16+from datafoundry_api.settings import Settings
17+from datafoundry_api.store import SqliteStore
18+ 
19+ 
20+def seed_local_session(settings: Settings, token: str, csrf: str) -> None:
21+ if settings.host != "127.0.0.1" or settings.auth_disabled or settings.registration_mode != "closed":
22+ raise ValueError("Local TUI requires loopback, authenticated access and closed registration.")
23+ if len(token) < 32 or len(csrf) < 32:
24+ raise ValueError("Local TUI requires launcher-generated credentials.")
25+ store = SqliteStore(settings.metadata_db_path)
26+ try:
27+ now = datetime.now(UTC)
28+ if not store.fetchone("SELECT id FROM users WHERE id = ?", ("local-tui",)):
29+ store.execute(
30+ "INSERT INTO users (id,email,display_name,password_hash,email_verified_at,created_at) VALUES (?,?,?,?,?,?)",
31+ ("local-tui", "local@localhost", "Local User", PASSWORD_HASHER.hash(secrets.token_urlsafe(32)),
32+ now.isoformat(), now.isoformat()),
33+ )
34+ store.execute(
35+ "INSERT OR IGNORE INTO workspaces (id, name) VALUES (?, ?)",
36+ (DEPLOYMENT_WORKSPACE_ID, DEPLOYMENT_WORKSPACE_NAME),
37+ )
38+ auth = AuthService(store, settings)
39+ store.execute(
40+ "INSERT INTO auth_sessions (id,user_id,token_hash,csrf_token_hash,expires_at) VALUES (?,?,?,?,?)",
41+ (str(uuid4()), "local-tui", auth._hash_token(token), auth._hash_token(csrf),
42+ (now + timedelta(days=7)).isoformat()),
43+ )
44+ finally:
45+ store.close()
46+ 
47+ 
48+def main() -> None:
49+ # Do not expose bootstrap credentials to subsequently spawned tools.
50+ token = os.environ.pop("TUI_LOCAL_SESSION_TOKEN")
51+ csrf = os.environ.pop("TUI_LOCAL_CSRF_TOKEN")
52+ ready_file = Path(os.environ.pop("TUI_LOCAL_READY_FILE"))
53+ settings = Settings.from_env()
54+ seed_local_session(settings, token, csrf)
55+ with socket.socket() as sock:
56+ sock.bind(("127.0.0.1", 0))
57+ ready_file.write_text(json.dumps({"port": sock.getsockname()[1]}))
58+ server = uvicorn.Server(uvicorn.Config(
59+ "datafoundry_api.app:create_app", factory=True, log_level="warning", access_log=False,
60+ ))
61+ server.run(sockets=[sock])
62+ 
63+ 
64+if __name__ == "__main__":
65+ main()
@@ -0,0 +1,8 @@
1+"""Process-wide lock around Home config read-modify-write."""
2+ 
3+from __future__ import annotations
4+ 
5+from threading import RLock
6+ 
7+# Serializes config.json and .mcp.json updates in this process.
8+PUBLISH_LOCK = RLock()
Rruntime/agentkit/docs/architecture-and-configuration.md→runtime/agentkit/docs/archive/initial-design/architecture-and-configuration.md+2-2
Rruntime/agentkit/docs/extension-refresh.md→runtime/agentkit/docs/archive/initial-design/extension-refresh.md+0-0
Rruntime/agentkit/docs/home-root-cleanup.md→runtime/agentkit/docs/archive/initial-design/home-root-cleanup.md+0-0
Rruntime/agentkit/docs/mcp.md→runtime/agentkit/docs/archive/initial-design/mcp.md+1-1
Rruntime/agentkit/docs/plugin-compiler-native-hooks.md→runtime/agentkit/docs/archive/initial-design/plugin-compiler-native-hooks.md+0-0
Rruntime/agentkit/docs/runtime-boundaries.md→runtime/agentkit/docs/archive/initial-design/runtime-boundaries.md+0-0
Rruntime/agentkit/docs/user-session-isolation.md→runtime/agentkit/docs/archive/initial-design/user-session-isolation.md+0-0