t4l-server 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
t4l_server/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Self-hosted REST and MCP server for T4L Trainer."""
2
+
3
+ __all__ = ["__version__"]
4
+
5
+ __version__ = "0.1.0"
t4l_server/cli.py ADDED
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import secrets
5
+ import socket
6
+ from pathlib import Path
7
+
8
+ from .server import ServerConfig, run_server
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> int:
12
+ parser = argparse.ArgumentParser(prog="t4l-server")
13
+ subparsers = parser.add_subparsers(dest="command", required=True)
14
+
15
+ serve = subparsers.add_parser("serve", help="Start the self-hosted T4L server.")
16
+ serve.add_argument(
17
+ "--data-dir",
18
+ type=Path,
19
+ help="Server data directory. Stores t4l.sqlite and blobs.",
20
+ )
21
+ serve.add_argument(
22
+ "--dir",
23
+ type=Path,
24
+ help="Compatibility alias for --data-dir.",
25
+ )
26
+ serve.add_argument("--host", default="0.0.0.0", help="Bind host.")
27
+ serve.add_argument("--port", default=8787, type=int, help="Bind port.")
28
+ serve.add_argument(
29
+ "--api-key",
30
+ default=None,
31
+ help="API key. Defaults to a new key for every start.",
32
+ )
33
+ serve.add_argument(
34
+ "--token",
35
+ default=None,
36
+ help="Compatibility alias for --api-key.",
37
+ )
38
+
39
+ args = parser.parse_args(argv)
40
+ if args.command == "serve":
41
+ data_dir = args.data_dir or args.dir
42
+ if data_dir is None:
43
+ parser.error("serve requires --data-dir")
44
+ token = args.api_key or args.token or _new_api_key()
45
+ config = ServerConfig(
46
+ exchange_dir=data_dir.expanduser().resolve(),
47
+ host=args.host,
48
+ port=args.port,
49
+ token=token,
50
+ )
51
+ _print_startup(config)
52
+ run_server(config)
53
+ return 0
54
+ return 1
55
+
56
+
57
+ def _bridge_main(argv: list[str] | None = None) -> int:
58
+ if argv is None:
59
+ import sys
60
+
61
+ argv = sys.argv[1:]
62
+ translated = ["serve" if item == "serve" else item for item in argv]
63
+ if "--data-dir" not in translated and "--dir" in translated:
64
+ # The parser accepts --dir directly; this keeps the old command shape.
65
+ pass
66
+ return main(translated)
67
+
68
+
69
+ def _new_api_key() -> str:
70
+ return secrets.token_urlsafe(24)
71
+
72
+
73
+ def _print_startup(config: ServerConfig) -> None:
74
+ lan_host = _lan_ip() if config.host in {"0.0.0.0", "::"} else config.host
75
+ print("T4L Self-Hosted Server")
76
+ print(f"Data dir: {config.data_dir}")
77
+ print(f"Server URL: http://{lan_host}:{config.port}")
78
+ print(f"MCP URL: http://{lan_host}:{config.port}/mcp")
79
+ print(f"API key: {config.token}")
80
+ print("Enter the server URL and API key in the T4L Trainer Settings screen.")
81
+
82
+
83
+ def _lan_ip() -> str:
84
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
85
+ try:
86
+ sock.connect(("8.8.8.8", 80))
87
+ return str(sock.getsockname()[0])
88
+ except OSError:
89
+ return "127.0.0.1"
90
+
91
+
92
+ if __name__ == "__main__":
93
+ raise SystemExit(main())
t4l_server/mcp.py ADDED
@@ -0,0 +1,154 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from . import __version__
6
+ from .store import Artifact, ArtifactStore
7
+
8
+
9
+ def handle_mcp_message(store: ArtifactStore, message: dict[str, Any]) -> dict[str, Any]:
10
+ method = str(message.get("method") or "")
11
+ request_id = message.get("id")
12
+ if method == "initialize":
13
+ return _result(
14
+ request_id,
15
+ {
16
+ "protocolVersion": "2025-06-18",
17
+ "serverInfo": {"name": "t4l-server", "version": __version__},
18
+ "capabilities": {"tools": {}},
19
+ },
20
+ )
21
+ if method == "tools/list":
22
+ return _result(request_id, {"tools": _tools()})
23
+ if method == "tools/call":
24
+ params = message.get("params")
25
+ if not isinstance(params, dict):
26
+ return _error(request_id, -32602, "Invalid params.")
27
+ return _call_tool(store, request_id, params)
28
+ return _error(request_id, -32601, f"Unsupported MCP method: {method}")
29
+
30
+
31
+ def _call_tool(
32
+ store: ArtifactStore,
33
+ request_id: object,
34
+ params: dict[str, Any],
35
+ ) -> dict[str, Any]:
36
+ name = str(params.get("name") or "")
37
+ arguments = params.get("arguments")
38
+ args = arguments if isinstance(arguments, dict) else {}
39
+ if name == "get_day_context":
40
+ return _artifact_result(request_id, store.latest("day_context"))
41
+ if name == "get_app_snapshot":
42
+ return _artifact_result(request_id, store.latest("app_snapshot"))
43
+ if name == "get_profile":
44
+ return _artifact_result(request_id, store.latest("athlete_profile"))
45
+ if name == "get_pending_requests":
46
+ return _payload_result(
47
+ request_id,
48
+ {
49
+ "requests": [
50
+ artifact.summary()
51
+ for artifact in [
52
+ store.latest("training_block_request"),
53
+ store.latest("nutrition_analysis_request"),
54
+ ]
55
+ if artifact is not None
56
+ ]
57
+ },
58
+ )
59
+ write_kinds = {
60
+ "write_training_block_plan": "training_block_plan",
61
+ "write_fuel_guidance": "fuel_guidance",
62
+ "write_nutrition_analysis_result": "nutrition_analysis_result",
63
+ }
64
+ if name in write_kinds:
65
+ payload = args.get("payload")
66
+ if not isinstance(payload, dict):
67
+ return _error(request_id, -32602, "Tool requires object argument: payload.")
68
+ artifact = store.upsert_artifact(write_kinds[name], payload, status="pending")
69
+ return _payload_result(request_id, {"stored": artifact.summary()})
70
+ return _error(request_id, -32602, f"Unknown tool: {name}")
71
+
72
+
73
+ def _artifact_result(request_id: object, artifact: Artifact | None) -> dict[str, Any]:
74
+ if artifact is None:
75
+ return _payload_result(request_id, None)
76
+ return _payload_result(request_id, artifact.payload)
77
+
78
+
79
+ def _payload_result(request_id: object, payload: object) -> dict[str, Any]:
80
+ return _result(
81
+ request_id,
82
+ {
83
+ "content": [
84
+ {
85
+ "type": "text",
86
+ "text": _json_text(payload),
87
+ }
88
+ ],
89
+ "structuredContent": payload,
90
+ },
91
+ )
92
+
93
+
94
+ def _json_text(payload: object) -> str:
95
+ import json
96
+
97
+ return json.dumps(payload, ensure_ascii=False, indent=2)
98
+
99
+
100
+ def _tools() -> list[dict[str, Any]]:
101
+ object_schema = {
102
+ "type": "object",
103
+ "properties": {"payload": {"type": "object"}},
104
+ "required": ["payload"],
105
+ }
106
+ return [
107
+ {
108
+ "name": "get_day_context",
109
+ "description": "Read latest day context.",
110
+ "inputSchema": {"type": "object"},
111
+ },
112
+ {
113
+ "name": "get_app_snapshot",
114
+ "description": "Read latest full app snapshot.",
115
+ "inputSchema": {"type": "object"},
116
+ },
117
+ {
118
+ "name": "get_profile",
119
+ "description": "Read latest athlete profile.",
120
+ "inputSchema": {"type": "object"},
121
+ },
122
+ {
123
+ "name": "get_pending_requests",
124
+ "description": "List pending app requests.",
125
+ "inputSchema": {"type": "object"},
126
+ },
127
+ {
128
+ "name": "write_training_block_plan",
129
+ "description": "Write a pending training block plan.",
130
+ "inputSchema": object_schema,
131
+ },
132
+ {
133
+ "name": "write_fuel_guidance",
134
+ "description": "Write pending fuel guidance.",
135
+ "inputSchema": object_schema,
136
+ },
137
+ {
138
+ "name": "write_nutrition_analysis_result",
139
+ "description": "Write a pending nutrition result.",
140
+ "inputSchema": object_schema,
141
+ },
142
+ ]
143
+
144
+
145
+ def _result(request_id: object, result: dict[str, Any]) -> dict[str, Any]:
146
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
147
+
148
+
149
+ def _error(request_id: object, code: int, message: str) -> dict[str, Any]:
150
+ return {
151
+ "jsonrpc": "2.0",
152
+ "id": request_id,
153
+ "error": {"code": code, "message": message},
154
+ }
t4l_server/server.py ADDED
@@ -0,0 +1,357 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from dataclasses import dataclass
6
+ from http import HTTPStatus
7
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
8
+ from pathlib import Path
9
+ from tempfile import NamedTemporaryFile
10
+ from typing import Any
11
+ from urllib.parse import unquote, urlparse
12
+
13
+ from .mcp import handle_mcp_message
14
+ from .store import ArtifactStore
15
+
16
+ APP_UPLOAD_FILES = {
17
+ "day_context.json": "day_context",
18
+ "daily_snapshot.json": "daily_snapshot",
19
+ "athlete_profile.json": "athlete_profile",
20
+ "training_block_request.json": "training_block_request",
21
+ "nutrition_analysis_request.json": "nutrition_analysis_request",
22
+ }
23
+ AGENT_RESULT_FILES = {
24
+ "training_block_plan.json": "training_block_plan",
25
+ "next_day_plan.json": "next_day_plan",
26
+ "nutrition_analysis_result.json": "nutrition_analysis_result",
27
+ "fuel_guidance.json": "fuel_guidance",
28
+ }
29
+ ALL_EXCHANGE_FILES = APP_UPLOAD_FILES | AGENT_RESULT_FILES
30
+ REST_CONTEXT_PATHS = {
31
+ "/v1/context/day": "day_context",
32
+ "/v1/context/daily-snapshot": "daily_snapshot",
33
+ "/v1/profile": "athlete_profile",
34
+ }
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ServerConfig:
39
+ exchange_dir: Path
40
+ host: str
41
+ port: int
42
+ token: str
43
+
44
+ @property
45
+ def data_dir(self) -> Path:
46
+ return self.exchange_dir
47
+
48
+
49
+ def run_server(config: ServerConfig) -> None:
50
+ server = create_server(config)
51
+ try:
52
+ server.serve_forever()
53
+ except KeyboardInterrupt:
54
+ pass
55
+ finally:
56
+ server.server_close()
57
+
58
+
59
+ def create_server(config: ServerConfig) -> ThreadingHTTPServer:
60
+ config.data_dir.mkdir(parents=True, exist_ok=True)
61
+ store = ArtifactStore(config.data_dir)
62
+ handler = _handler_factory(config, store)
63
+ return ThreadingHTTPServer((config.host, config.port), handler)
64
+
65
+
66
+ def _handler_factory(
67
+ config: ServerConfig,
68
+ store: ArtifactStore,
69
+ ) -> type[BaseHTTPRequestHandler]:
70
+ class T4LHandler(BaseHTTPRequestHandler):
71
+ server_version = "T4LServer/0.2"
72
+
73
+ def do_GET(self) -> None:
74
+ path = urlparse(self.path).path
75
+ if path == "/health":
76
+ self._send_json(
77
+ {
78
+ "status": "ok",
79
+ "service": "t4l-server",
80
+ "dataDir": str(config.data_dir),
81
+ "sqlite": str(store.db_path),
82
+ }
83
+ )
84
+ return
85
+ if path == "/manifest":
86
+ if not self._authorized():
87
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
88
+ return
89
+ self._send_json(_manifest(store))
90
+ return
91
+ if path == "/v1/results/pending":
92
+ if not self._authorized():
93
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
94
+ return
95
+ self._send_json(
96
+ {
97
+ "results": [
98
+ artifact.summary() for artifact in store.pending_results()
99
+ ]
100
+ }
101
+ )
102
+ return
103
+ result_kind = _result_kind_from_path(path)
104
+ if result_kind is not None:
105
+ if not self._authorized():
106
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
107
+ return
108
+ artifact = store.latest(result_kind)
109
+ if artifact is None or artifact.consumed_at is not None:
110
+ self._send_error(HTTPStatus.NOT_FOUND, "Result not found.")
111
+ return
112
+ self._send_json(artifact.payload)
113
+ return
114
+ file_name = _file_name_from_path(path)
115
+ if file_name is None:
116
+ self._send_error(HTTPStatus.NOT_FOUND, "Unknown endpoint.")
117
+ return
118
+ self._handle_file_get(file_name)
119
+
120
+ def do_POST(self) -> None:
121
+ path = urlparse(self.path).path
122
+ if path == "/mcp":
123
+ self._handle_mcp()
124
+ return
125
+ file_name = _file_name_from_path(path)
126
+ if file_name is None:
127
+ self._send_error(HTTPStatus.NOT_FOUND, "Unknown endpoint.")
128
+ return
129
+ self._handle_file_write(file_name)
130
+
131
+ def do_PUT(self) -> None:
132
+ path = urlparse(self.path).path
133
+ if not self._authorized():
134
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
135
+ return
136
+ if path == "/v1/app/snapshot":
137
+ payload = self._read_json_body()
138
+ if payload is None:
139
+ return
140
+ store.upsert_artifact("app_snapshot", payload, status="current")
141
+ self._send_json({"status": "stored", "kind": "app_snapshot"})
142
+ return
143
+ kind = REST_CONTEXT_PATHS.get(path)
144
+ if kind is not None:
145
+ payload = self._read_json_body()
146
+ if payload is None:
147
+ return
148
+ store.upsert_artifact(kind, payload, status="current")
149
+ self._send_json({"status": "stored", "kind": kind})
150
+ return
151
+ self._send_error(HTTPStatus.NOT_FOUND, "Unknown endpoint.")
152
+
153
+ def do_DELETE(self) -> None:
154
+ path = urlparse(self.path).path
155
+ result_kind = _result_kind_from_path(path)
156
+ if result_kind is not None:
157
+ if not self._authorized():
158
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
159
+ return
160
+ store.mark_consumed(result_kind)
161
+ self._send_json({"status": "consumed", "kind": result_kind})
162
+ return
163
+ file_name = _file_name_from_path(path)
164
+ if file_name is None:
165
+ self._send_error(HTTPStatus.NOT_FOUND, "Unknown endpoint.")
166
+ return
167
+ self._handle_file_delete(file_name)
168
+
169
+ def log_message(self, format: str, *args: object) -> None:
170
+ return
171
+
172
+ def _handle_mcp(self) -> None:
173
+ if not self._authorized():
174
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
175
+ return
176
+ payload = self._read_json_body()
177
+ if payload is None:
178
+ return
179
+ self._send_json(handle_mcp_message(store, payload))
180
+
181
+ def _handle_file_get(self, file_name: str) -> None:
182
+ if not self._authorized():
183
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
184
+ return
185
+ if file_name.startswith("meal_images/"):
186
+ target = _safe_blob_path(config.data_dir, file_name)
187
+ if target is None:
188
+ self._send_error(HTTPStatus.FORBIDDEN, "File is not allowed.")
189
+ return
190
+ if not target.exists():
191
+ self._send_error(HTTPStatus.NOT_FOUND, "File not found.")
192
+ return
193
+ self._send_bytes(target.read_bytes(), "application/octet-stream")
194
+ return
195
+ kind = ALL_EXCHANGE_FILES.get(file_name)
196
+ if kind is None:
197
+ self._send_error(HTTPStatus.FORBIDDEN, "File is not allowed.")
198
+ return
199
+ artifact = store.latest(kind)
200
+ if artifact is None or artifact.consumed_at is not None:
201
+ self._send_error(HTTPStatus.NOT_FOUND, "File not found.")
202
+ return
203
+ self._send_json(artifact.payload)
204
+
205
+ def _handle_file_write(self, file_name: str) -> None:
206
+ if not self._authorized():
207
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
208
+ return
209
+ body = self._read_body()
210
+ if body is None:
211
+ return
212
+ if file_name.startswith("meal_images/"):
213
+ target = _safe_blob_path(config.data_dir, file_name)
214
+ if target is None:
215
+ self._send_error(HTTPStatus.FORBIDDEN, "File is not allowed.")
216
+ return
217
+ _atomic_write(target, body)
218
+ self._send_json({"status": "stored", "file": file_name})
219
+ return
220
+ kind = ALL_EXCHANGE_FILES.get(file_name)
221
+ if kind is None:
222
+ self._send_error(HTTPStatus.FORBIDDEN, "File is not allowed.")
223
+ return
224
+ payload = _decode_json(body)
225
+ if payload is None:
226
+ self._send_error(HTTPStatus.BAD_REQUEST, "Invalid JSON payload.")
227
+ return
228
+ status = "pending" if file_name in AGENT_RESULT_FILES else "current"
229
+ store.upsert_artifact(kind, payload, status=status)
230
+ self._send_json({"status": "stored", "file": file_name, "kind": kind})
231
+
232
+ def _handle_file_delete(self, file_name: str) -> None:
233
+ if not self._authorized():
234
+ self._send_error(HTTPStatus.UNAUTHORIZED, "Invalid API key.")
235
+ return
236
+ kind = AGENT_RESULT_FILES.get(file_name)
237
+ if kind is None:
238
+ self._send_error(HTTPStatus.FORBIDDEN, "File is not allowed.")
239
+ return
240
+ store.mark_consumed(kind)
241
+ self._send_json({"status": "deleted", "file": file_name, "kind": kind})
242
+
243
+ def _authorized(self) -> bool:
244
+ auth = self.headers.get("authorization", "")
245
+ bearer = auth.removeprefix("Bearer ").strip()
246
+ return (
247
+ self.headers.get("x-t4l-token") == config.token
248
+ or bearer == config.token
249
+ )
250
+
251
+ def _read_body(self) -> bytes | None:
252
+ length = int(self.headers.get("content-length", "0"))
253
+ if length <= 0:
254
+ self._send_error(HTTPStatus.BAD_REQUEST, "Request body is empty.")
255
+ return None
256
+ return self.rfile.read(length)
257
+
258
+ def _read_json_body(self) -> dict[str, Any] | None:
259
+ body = self._read_body()
260
+ if body is None:
261
+ return None
262
+ payload = _decode_json(body)
263
+ if payload is None:
264
+ self._send_error(HTTPStatus.BAD_REQUEST, "Invalid JSON payload.")
265
+ return None
266
+ return payload
267
+
268
+ def _send_json(self, payload: dict[str, Any]) -> None:
269
+ self._send_bytes(
270
+ json.dumps(payload, indent=2).encode("utf-8"),
271
+ "application/json",
272
+ )
273
+
274
+ def _send_bytes(self, body: bytes, content_type: str) -> None:
275
+ self.send_response(HTTPStatus.OK)
276
+ self.send_header("content-type", content_type)
277
+ self.send_header("content-length", str(len(body)))
278
+ self.end_headers()
279
+ self.wfile.write(body)
280
+
281
+ def _send_error(self, status: HTTPStatus, message: str) -> None:
282
+ body = json.dumps({"error": message}).encode("utf-8")
283
+ self.send_response(status)
284
+ self.send_header("content-type", "application/json")
285
+ self.send_header("content-length", str(len(body)))
286
+ self.end_headers()
287
+ self.wfile.write(body)
288
+
289
+ return T4LHandler
290
+
291
+
292
+ def _manifest(store: ArtifactStore) -> dict[str, Any]:
293
+ files = []
294
+ for file_name, kind in sorted(ALL_EXCHANGE_FILES.items()):
295
+ artifact = store.latest(kind)
296
+ if artifact is None or artifact.consumed_at is not None:
297
+ continue
298
+ files.append({"name": file_name, **artifact.summary()})
299
+ return {
300
+ "schema": "t4l_server_manifest.v1",
301
+ "appUploadFiles": sorted(APP_UPLOAD_FILES),
302
+ "agentResultFiles": sorted(AGENT_RESULT_FILES),
303
+ "files": files,
304
+ }
305
+
306
+
307
+ def _file_name_from_path(path: str) -> str | None:
308
+ prefix = "/files/"
309
+ if not path.startswith(prefix):
310
+ return None
311
+ return unquote(path[len(prefix) :])
312
+
313
+
314
+ def _result_kind_from_path(path: str) -> str | None:
315
+ prefix = "/v1/results/"
316
+ if not path.startswith(prefix):
317
+ return None
318
+ kind = path[len(prefix) :].strip("/")
319
+ return kind if kind in set(AGENT_RESULT_FILES.values()) else None
320
+
321
+
322
+ def _safe_blob_path(data_dir: Path, file_name: str) -> Path | None:
323
+ if file_name.startswith("/") or "\\" in file_name:
324
+ return None
325
+ normalized = Path(file_name)
326
+ if any(part in {"", ".", ".."} for part in normalized.parts):
327
+ return None
328
+ if len(normalized.parts) < 2 or normalized.parts[0] != "meal_images":
329
+ return None
330
+ resolved = (data_dir / "blobs" / normalized).resolve()
331
+ try:
332
+ resolved.relative_to((data_dir / "blobs").resolve())
333
+ except ValueError:
334
+ return None
335
+ return resolved
336
+
337
+
338
+ def _decode_json(body: bytes) -> dict[str, Any] | None:
339
+ try:
340
+ decoded = json.loads(body.decode("utf-8"))
341
+ except (UnicodeDecodeError, json.JSONDecodeError):
342
+ return None
343
+ return decoded if isinstance(decoded, dict) else None
344
+
345
+
346
+ def _atomic_write(target: Path, body: bytes) -> None:
347
+ target.parent.mkdir(parents=True, exist_ok=True)
348
+ with NamedTemporaryFile(
349
+ "wb",
350
+ delete=False,
351
+ dir=target.parent,
352
+ prefix=f".{target.name}.",
353
+ suffix=".tmp",
354
+ ) as tmp:
355
+ tmp.write(body)
356
+ tmp_path = Path(tmp.name)
357
+ os.replace(tmp_path, target)
t4l_server/store.py ADDED
@@ -0,0 +1,213 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sqlite3
5
+ from dataclasses import dataclass
6
+ from datetime import UTC, datetime
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ _ARTIFACT_COLUMNS = (
11
+ "id, kind, schema, payload_json, status, created_at, updated_at, consumed_at"
12
+ )
13
+
14
+
15
+ RESULT_KINDS = frozenset(
16
+ {
17
+ "training_block_plan",
18
+ "next_day_plan",
19
+ "nutrition_analysis_result",
20
+ "fuel_guidance",
21
+ }
22
+ )
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Artifact:
27
+ id: str
28
+ kind: str
29
+ schema: str
30
+ payload: dict[str, Any]
31
+ status: str
32
+ created_at: str
33
+ updated_at: str
34
+ consumed_at: str | None
35
+
36
+ def summary(self) -> dict[str, Any]:
37
+ return {
38
+ "id": self.id,
39
+ "kind": self.kind,
40
+ "schema": self.schema,
41
+ "status": self.status,
42
+ "createdAt": self.created_at,
43
+ "updatedAt": self.updated_at,
44
+ "consumedAt": self.consumed_at,
45
+ }
46
+
47
+
48
+ class ArtifactStore:
49
+ def __init__(self, data_dir: Path) -> None:
50
+ self.data_dir = data_dir
51
+ self.db_path = data_dir / "t4l.sqlite"
52
+ self.blobs_dir = data_dir / "blobs"
53
+ self.data_dir.mkdir(parents=True, exist_ok=True)
54
+ self.blobs_dir.mkdir(parents=True, exist_ok=True)
55
+ self._init_db()
56
+
57
+ def upsert_artifact(
58
+ self,
59
+ kind: str,
60
+ payload: dict[str, Any],
61
+ *,
62
+ status: str | None = None,
63
+ ) -> Artifact:
64
+ now = _now()
65
+ schema = str(payload.get("schema") or f"{kind}.v1")
66
+ artifact_id = f"{kind}:latest"
67
+ artifact_status = status or ("pending" if kind in RESULT_KINDS else "current")
68
+ encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True)
69
+ with self._connect() as db:
70
+ existing = db.execute(
71
+ "SELECT created_at FROM artifacts WHERE id = ?",
72
+ [artifact_id],
73
+ ).fetchone()
74
+ created_at = str(existing["created_at"]) if existing else now
75
+ db.execute(
76
+ """
77
+ INSERT INTO artifacts(
78
+ id, kind, schema, payload_json, status,
79
+ created_at, updated_at, consumed_at
80
+ )
81
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
82
+ ON CONFLICT(id) DO UPDATE SET
83
+ schema = excluded.schema,
84
+ payload_json = excluded.payload_json,
85
+ status = excluded.status,
86
+ updated_at = excluded.updated_at,
87
+ consumed_at = NULL
88
+ """,
89
+ [
90
+ artifact_id,
91
+ kind,
92
+ schema,
93
+ encoded,
94
+ artifact_status,
95
+ created_at,
96
+ now,
97
+ ],
98
+ )
99
+ return self.latest(kind) or Artifact(
100
+ id=artifact_id,
101
+ kind=kind,
102
+ schema=schema,
103
+ payload=payload,
104
+ status=artifact_status,
105
+ created_at=created_at,
106
+ updated_at=now,
107
+ consumed_at=None,
108
+ )
109
+
110
+ def latest(self, kind: str) -> Artifact | None:
111
+ with self._connect() as db:
112
+ row = db.execute(
113
+ f"""
114
+ SELECT {_ARTIFACT_COLUMNS}
115
+ FROM artifacts
116
+ WHERE kind = ?
117
+ ORDER BY updated_at DESC
118
+ LIMIT 1
119
+ """,
120
+ [kind],
121
+ ).fetchone()
122
+ return _artifact_from_row(row) if row else None
123
+
124
+ def pending_results(self) -> list[Artifact]:
125
+ placeholders = ",".join("?" for _ in RESULT_KINDS)
126
+ with self._connect() as db:
127
+ rows = db.execute(
128
+ f"""
129
+ SELECT {_ARTIFACT_COLUMNS}
130
+ FROM artifacts
131
+ WHERE kind IN ({placeholders}) AND consumed_at IS NULL
132
+ ORDER BY updated_at DESC
133
+ """,
134
+ sorted(RESULT_KINDS),
135
+ ).fetchall()
136
+ return [_artifact_from_row(row) for row in rows]
137
+
138
+ def mark_consumed(self, kind: str) -> bool:
139
+ now = _now()
140
+ with self._connect() as db:
141
+ cursor = db.execute(
142
+ """
143
+ UPDATE artifacts
144
+ SET status = 'consumed', consumed_at = ?, updated_at = ?
145
+ WHERE kind = ? AND consumed_at IS NULL
146
+ """,
147
+ [now, now, kind],
148
+ )
149
+ return cursor.rowcount > 0
150
+
151
+ def history(self, kind: str) -> list[Artifact]:
152
+ with self._connect() as db:
153
+ rows = db.execute(
154
+ f"""
155
+ SELECT {_ARTIFACT_COLUMNS}
156
+ FROM artifacts
157
+ WHERE kind = ?
158
+ ORDER BY updated_at DESC
159
+ """,
160
+ [kind],
161
+ ).fetchall()
162
+ return [_artifact_from_row(row) for row in rows]
163
+
164
+ def _init_db(self) -> None:
165
+ with self._connect() as db:
166
+ db.execute(
167
+ """
168
+ CREATE TABLE IF NOT EXISTS artifacts (
169
+ id TEXT PRIMARY KEY,
170
+ kind TEXT NOT NULL,
171
+ schema TEXT NOT NULL,
172
+ payload_json TEXT NOT NULL,
173
+ status TEXT NOT NULL,
174
+ created_at TEXT NOT NULL,
175
+ updated_at TEXT NOT NULL,
176
+ consumed_at TEXT
177
+ )
178
+ """
179
+ )
180
+ db.execute(
181
+ """
182
+ CREATE INDEX IF NOT EXISTS idx_artifacts_kind_updated
183
+ ON artifacts(kind, updated_at)
184
+ """
185
+ )
186
+ db.execute(
187
+ "CREATE INDEX IF NOT EXISTS idx_artifacts_status ON artifacts(status)"
188
+ )
189
+
190
+ def _connect(self) -> sqlite3.Connection:
191
+ db = sqlite3.connect(self.db_path)
192
+ db.row_factory = sqlite3.Row
193
+ return db
194
+
195
+
196
+ def _artifact_from_row(row: sqlite3.Row) -> Artifact:
197
+ decoded = json.loads(str(row["payload_json"]))
198
+ if not isinstance(decoded, dict):
199
+ raise ValueError("Artifact payload_json must decode to an object.")
200
+ return Artifact(
201
+ id=str(row["id"]),
202
+ kind=str(row["kind"]),
203
+ schema=str(row["schema"]),
204
+ payload=decoded,
205
+ status=str(row["status"]),
206
+ created_at=str(row["created_at"]),
207
+ updated_at=str(row["updated_at"]),
208
+ consumed_at=row["consumed_at"],
209
+ )
210
+
211
+
212
+ def _now() -> str:
213
+ return datetime.now(UTC).replace(microsecond=0).isoformat()
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: t4l-server
3
+ Version: 0.1.0
4
+ Summary: Self-hosted REST and MCP server for T4L Trainer agent workflows.
5
+ Project-URL: Homepage, https://github.com/BigSlikTobi/t4l-server
6
+ Project-URL: Repository, https://github.com/BigSlikTobi/t4l-server
7
+ Project-URL: Issues, https://github.com/BigSlikTobi/t4l-server/issues
8
+ Author: T4L Trainer
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
21
+ Requires-Python: >=3.11
22
+ Provides-Extra: dev
23
+ Requires-Dist: build>=1.3; extra == 'dev'
24
+ Requires-Dist: mypy>=1.18; extra == 'dev'
25
+ Requires-Dist: pytest>=8.0; extra == 'dev'
26
+ Requires-Dist: ruff>=0.14; extra == 'dev'
27
+ Requires-Dist: twine>=6.2; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # T4L Server
31
+
32
+ Self-hosted REST and MCP server for exchanging T4L Trainer JSON artifacts
33
+ between the iPhone app and a coaching agent.
34
+
35
+ The phone remains the source of truth for accepted training state. The server
36
+ stores synced context and pending agent results in SQLite so local agents,
37
+ home-server agents, and private VPS agents can work through the same protocol.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pipx install t4l-server
43
+ t4l-server serve --data-dir ~/T4LServerData
44
+ ```
45
+
46
+ The command prints the server URL, MCP URL, and API key. Enter the server URL
47
+ and API key in the T4L Trainer Settings screen.
48
+
49
+ ## Agent setup
50
+
51
+ Agents should read the public instruction repo first:
52
+
53
+ ```text
54
+ https://github.com/BigSlikTobi/t4l-agent-instructions
55
+ ```
56
+
57
+ Those instructions explain how to start or verify this server, connect through
58
+ MCP, wait for fresh phone context, and write app-consumed results safely.
59
+
60
+ ## Compatibility
61
+
62
+ The old command remains available for one transition cycle:
63
+
64
+ ```bash
65
+ t4l-bridge serve --dir ~/CodexFitnessExchange
66
+ ```
67
+
68
+ New setups should use `t4l-server serve --data-dir ~/T4LServerData`.
69
+
70
+ ## Safety model
71
+
72
+ - REST, MCP, and compatibility file endpoints require the API key.
73
+ - JSON artifacts are stored in `t4l.sqlite`.
74
+ - Image blobs are stored under `blobs/`.
75
+ - Only known exchange files and `meal_images/` are accessible through
76
+ compatibility endpoints.
77
+ - Path traversal and arbitrary file access are rejected.
78
+
79
+ ## Development
80
+
81
+ ```bash
82
+ python -m venv .venv
83
+ . .venv/bin/activate
84
+ python -m pip install -e ".[dev]"
85
+ ruff format --check .
86
+ ruff check .
87
+ mypy
88
+ pytest
89
+ python -m build
90
+ twine check dist/*
91
+ ```
@@ -0,0 +1,10 @@
1
+ t4l_server/__init__.py,sha256=mRMiAJD-C59M5KZW63YZAu8Yky8uvmT6U_ypkM8rZHk,105
2
+ t4l_server/cli.py,sha256=ZT4GZm47a_cZtL3f-3PQ0SGLuo-0h4BrdYysyMBzrEk,2803
3
+ t4l_server/mcp.py,sha256=HPBAw4f0fD9U2hpFmTVr04DIKgggq1Y4o5xGlszUGcQ,5071
4
+ t4l_server/server.py,sha256=clJOTTPWvt0pbaB0SuudHcd9tQVkiFM7AnV2tr3Gzcw,13386
5
+ t4l_server/store.py,sha256=hbZiy0I4srAZbVe6xucmAD7wfEACt1kabhN18KCQa4M,6548
6
+ t4l_server-0.1.0.dist-info/METADATA,sha256=byfEdkveyXcgMS9FdARDhd0GtzvGTBqJ9oqx-SOYGsc,2777
7
+ t4l_server-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ t4l_server-0.1.0.dist-info/entry_points.txt,sha256=93klHUaS56Uos4PaB2Vida3nRcmSIaNloAScOFZCGeA,92
9
+ t4l_server-0.1.0.dist-info/licenses/LICENSE,sha256=QXNV7JWcWDVZL0kZ_dWGM6lfZeRgZ6HBh5HOWuwQk3w,1068
10
+ t4l_server-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ t4l-bridge = t4l_server.cli:_bridge_main
3
+ t4l-server = t4l_server.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 T4L Trainer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.