@nelsonlongxiang/dsh-prompt-templates 0.2.8

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.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * dsh-prompt-templates host half: spawns the Python backend child through
3
+ * the subprocess seam and exposes template CRUD over web-server routes the
4
+ * browser panel fetches (`/plugins/dsh-prompt-templates/*`). The Python
5
+ * child owns all durable state; this plugin owns the child process, the
6
+ * routes, and the settings namespace (panel default-open + placement).
7
+ *
8
+ * Route map (JSON bodies, `Cache-Control: no-store`):
9
+ * GET /plugins/dsh-prompt-templates/templates → { items }
10
+ * POST /plugins/dsh-prompt-templates/templates → { template }
11
+ * GET /plugins/dsh-prompt-templates/templates/:id → { template } | 404
12
+ * PATCH /plugins/dsh-prompt-templates/templates/:id → { template } | 404
13
+ * POST /plugins/dsh-prompt-templates/templates/:id/make-global → { template } | 404
14
+ * DELETE /plugins/dsh-prompt-templates/templates/:id → { deleted }
15
+ *
16
+ * @module dsh-prompt-templates
17
+ */
18
+ import type { Context } from '@deepseek-ai/cordis';
19
+ import s from '@deepseek-ai/schemastery';
20
+ export type * from './types.ts';
21
+ export declare const name = "prompt-templates";
22
+ /** Spawns the Python child through the pythonBridge service; the web-server route registration waits for it lazily. */
23
+ export declare const inject: string[];
24
+ /** Deployment-varying spawn facts for the Python backend child. */
25
+ export interface Config {
26
+ /** Complete argv; `argv[0]` is the executable running the backend `serve`. */
27
+ readonly command: string[];
28
+ /** Absolute working directory for the child. */
29
+ readonly cwd?: string | null;
30
+ /** Grace (ms) for the stdin-EOF quiesce before terminate escalation. */
31
+ readonly eofGraceMs?: number | null;
32
+ /** Optional explicit database path forwarded as `--db`. */
33
+ readonly dbPath?: string | null;
34
+ }
35
+ export declare const Config: s<Config>;
36
+ /** Business error envelope shared with the browser face. */
37
+ export interface TemplateError {
38
+ readonly code: string;
39
+ readonly message: string;
40
+ }
41
+ /**
42
+ * Host plugin body: lazily register the web routes once the web server and
43
+ * this plugin's pythonBridge service are both live; headless profiles without a
44
+ * web server never block boot.
45
+ * @param ctx - Host context carrying the pythonBridge service.
46
+ * @param config - validated spawn facts for the Python backend.
47
+ */
48
+ export declare function apply(ctx: Context, config: Config): void;
@@ -0,0 +1,8 @@
1
+ /** Package-owned invariant companion. @module dsh-prompt-templates/invariant */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ /** Cordis companion plugin name. */
4
+ export declare const name = "prompt-templates-invariant";
5
+ /** Service required before the companion can reserve package ownership. */
6
+ export declare const inject: string[];
7
+ /** Register this package's invariant companion. */
8
+ export declare const apply: (ctx: Context) => Promise<() => void>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Wire payload types shared by the host routes and the browser API. Field
3
+ * names match the Python side's Pydantic models verbatim (snake_case): the
4
+ * type is the protocol and no field mapping can drift.
5
+ * @module dsh-prompt-templates/types
6
+ */
7
+ /** Scope partition of one template: global or private to one session. */
8
+ export type PromptScope = 'global' | 'session';
9
+ /** Canonical template record as stored by the Python backend. */
10
+ export interface TemplateView {
11
+ readonly id: string;
12
+ readonly name: string;
13
+ readonly content: string;
14
+ readonly scope: PromptScope;
15
+ /** Owning session id; `null` for a global template. */
16
+ readonly session_id: string | null;
17
+ readonly description: string | null;
18
+ readonly position: number;
19
+ /** ISO timestamp without timezone, as emitted by the backend. */
20
+ readonly created_at: string;
21
+ readonly updated_at: string;
22
+ }
23
+ /** Create payload; the backend validates scope/session consistency. */
24
+ export interface TemplateCreateRequest {
25
+ readonly name: string;
26
+ readonly content: string;
27
+ readonly scope?: PromptScope;
28
+ readonly session_id?: string | null;
29
+ readonly description?: string | null;
30
+ readonly position?: number;
31
+ }
32
+ /** Update payload; every field optional. */
33
+ export interface TemplateUpdateRequest {
34
+ readonly name?: string;
35
+ readonly content?: string;
36
+ readonly description?: string | null;
37
+ readonly position?: number;
38
+ }
package/lib/types.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Wire payload types shared by the host routes and the browser API. Field
3
+ * names match the Python side's Pydantic models verbatim (snake_case): the
4
+ * type is the protocol and no field mapping can drift.
5
+ * @module dsh-prompt-templates/types
6
+ */
7
+ export {};
package/package.json ADDED
@@ -0,0 +1,111 @@
1
+ {
2
+ "name": "@nelsonlongxiang/dsh-prompt-templates",
3
+ "version": "0.2.8",
4
+ "description": "Quick prompt templates for DeepSeek Harness: global and per-session templates, a browser panel, and a Python-backed persistence backend",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/types/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./client": {
14
+ "types": "./lib/types/client/index.d.ts",
15
+ "default": "./lib/client.js"
16
+ },
17
+ "./cordis.patch.yml": "./cordis.patch.yml",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "files": [
21
+ "lib",
22
+ "python/src",
23
+ "python/pyproject.toml",
24
+ "python/uv.lock",
25
+ "python/README.md",
26
+ "scripts",
27
+ "cordis.patch.yml",
28
+ "README.md"
29
+ ],
30
+ "dsh": {
31
+ "bundle": {
32
+ "patch": "./cordis.patch.yml"
33
+ },
34
+ "client": {
35
+ "platform": "web",
36
+ "inject": [
37
+ "@deepseek-ai/dsh-client-runtime",
38
+ "@deepseek-ai/dsh-client-locale",
39
+ "@deepseek-ai/dsh-client-ui-conversation"
40
+ ]
41
+ }
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json && tsc -p tsconfig.client.json && tsdown",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
46
+ "bootstrap:python": "node scripts/bootstrap.mjs",
47
+ "prepare": "pnpm build && node scripts/bootstrap.mjs",
48
+ "test:python": "uv run --project python pytest",
49
+ "verify": "pnpm typecheck && pnpm test:python"
50
+ },
51
+ "peerDependencies": {
52
+ "@deepseek-ai/cordis": ">=4.0.1-rc.1",
53
+ "@deepseek-ai/dsh-invariants": ">=0.1.0-rc.6",
54
+ "@deepseek-ai/dsh-settings": ">=0.1.0-rc.6",
55
+ "@deepseek-ai/dsh-subprocess": ">=0.1.0-rc.6",
56
+ "@deepseek-ai/dsh-client-locale": ">=0.1.0-rc.6",
57
+ "@deepseek-ai/dsh-client-runtime": ">=0.1.0-rc.6",
58
+ "@deepseek-ai/dsh-client-ui-conversation": ">=0.1.0-rc.6",
59
+ "@deepseek-ai/dsh-client-ui-primitives": ">=0.1.0-rc.6",
60
+ "@deepseek-ai/dsh-client-ui-slots": ">=0.1.0-rc.6",
61
+ "@deepseek-ai/schemastery": ">=3.18.1-rc.1",
62
+ "react": "^18.2.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@deepseek-ai/cordis": {
66
+ "optional": true
67
+ },
68
+ "@deepseek-ai/dsh-invariants": {
69
+ "optional": true
70
+ },
71
+ "@deepseek-ai/dsh-settings": {
72
+ "optional": true
73
+ },
74
+ "@deepseek-ai/dsh-subprocess": {
75
+ "optional": true
76
+ },
77
+ "@deepseek-ai/dsh-client-locale": {
78
+ "optional": true
79
+ },
80
+ "@deepseek-ai/dsh-client-runtime": {
81
+ "optional": true
82
+ },
83
+ "@deepseek-ai/dsh-client-ui-conversation": {
84
+ "optional": true
85
+ },
86
+ "@deepseek-ai/dsh-client-ui-primitives": {
87
+ "optional": true
88
+ },
89
+ "@deepseek-ai/dsh-client-ui-slots": {
90
+ "optional": true
91
+ },
92
+ "@deepseek-ai/schemastery": {
93
+ "optional": true
94
+ },
95
+ "react": {
96
+ "optional": true
97
+ }
98
+ },
99
+ "devDependencies": {
100
+ "@types/node": "^24.13.3",
101
+ "@types/react": "~18.3.1",
102
+ "@types/react-dom": "^18.3.7",
103
+ "lightningcss": "^1.33.0",
104
+ "react": "^18.2.0",
105
+ "react-dom": "^18.2.0",
106
+ "tsdown": "0.22.2",
107
+ "typescript": "^5.9.3",
108
+ "@nelsonlongxiang/dsh-python-bridge": "file:../dsh-python-bridge"
109
+ },
110
+ "license": "MIT"
111
+ }
@@ -0,0 +1,26 @@
1
+ # dsh-prompt-templates Python backend
2
+
3
+ Quick prompt-template persistence: SQLAlchemy ORM over one SQLite database
4
+ under `$DSH_HOME/ext/prompt-templates/db.sqlite3`, Pydantic validation, a
5
+ Typer CLI, and a newline-delimited JSON-RPC 2.0 stdio server the plugin's
6
+ Host bridge spawns.
7
+
8
+ ## Development
9
+
10
+ ```sh
11
+ uv sync --group test
12
+ uv run pytest
13
+ ```
14
+
15
+ ## CLI
16
+
17
+ ```sh
18
+ dsh-prompt-templates init
19
+ dsh-prompt-templates templates list [--scope global|session] [--session-id <id>] [--json]
20
+ dsh-prompt-templates templates add <name> <content> [--scope session] [--session-id <id>]
21
+ dsh-prompt-templates templates get <id> [--json]
22
+ dsh-prompt-templates templates update <id> [--name] [--content] [--description] [--position]
23
+ dsh-prompt-templates templates make-global <id>
24
+ dsh-prompt-templates templates remove <id>
25
+ dsh-prompt-templates serve [--db <path>]
26
+ ```
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.30.1"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dsh-prompt-templates-backend"
7
+ version = "0.1.0"
8
+ description = "Quick prompt-template backend for the dsh-prompt-templates plugin (CLI + SQLite + stdio JSON-RPC)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dependencies = [
13
+ "pydantic>=2.12,<3",
14
+ "sqlalchemy>=2.0",
15
+ "typer>=0.12",
16
+ ]
17
+
18
+ [dependency-groups]
19
+ test = ["pytest>=8"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/NelsonLongXiang/dsh-prompt-templates"
23
+ Source = "https://github.com/NelsonLongXiang/dsh-prompt-templates"
24
+
25
+ [project.scripts]
26
+ dsh-prompt-templates = "dsh_prompt_templates.cli:main"
27
+
28
+ [tool.pytest.ini_options]
29
+ addopts = "-q"
30
+ testpaths = ["tests"]
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/dsh_prompt_templates"]
@@ -0,0 +1,22 @@
1
+ """dsh-prompt-templates: quick prompt-template backend for DeepSeek Harness.
2
+
3
+ One SQLite database owned by Python code (SQLAlchemy ORM + Pydantic
4
+ validation), exposed through a CLI and a newline-delimited JSON-RPC 2.0
5
+ server over stdio for Host-side bridge integration.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .db import default_db_path
11
+ from .models import PromptTemplate, PromptTemplateCreate, PromptTemplateUpdate
12
+ from .store import PromptTemplateStore
13
+
14
+ __all__ = [
15
+ "PromptTemplate",
16
+ "PromptTemplateCreate",
17
+ "PromptTemplateStore",
18
+ "PromptTemplateUpdate",
19
+ "default_db_path",
20
+ ]
21
+
22
+ __version__ = "0.0.0.dev0"
@@ -0,0 +1,216 @@
1
+ """dsh-prompt-templates command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import typer
10
+
11
+ from .db import default_db_path
12
+ from .models import PromptTemplateCreate, PromptTemplateUpdate
13
+ from .server import JsonRpcServer, default_domains
14
+ from .store import PromptTemplateStore
15
+
16
+ app = typer.Typer(help="Quick prompt-templates backend for DeepSeek Harness.")
17
+ templates = typer.Typer(help="Manage prompt templates.")
18
+ app.add_typer(templates, name="templates")
19
+
20
+
21
+ def _store(db: Optional[Path]) -> PromptTemplateStore:
22
+ return PromptTemplateStore(db if db is not None else default_db_path())
23
+
24
+
25
+ def _fail(exc: Exception) -> None:
26
+ typer.secho(f"error: {exc}", fg=typer.colors.RED, err=True)
27
+ raise typer.Exit(code=1)
28
+
29
+
30
+ @app.command()
31
+ def init(
32
+ db: Optional[Path] = typer.Option(
33
+ None,
34
+ "--db",
35
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
36
+ ),
37
+ ) -> None:
38
+ """Create the database schema if absent."""
39
+ store = _store(db)
40
+ typer.echo(f"database ready at {store.path}")
41
+
42
+
43
+ @app.command()
44
+ def serve(
45
+ templates_db: Optional[Path] = typer.Option(
46
+ None,
47
+ "--db",
48
+ "--templates-db",
49
+ help="Prompt-template database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
50
+ ),
51
+ ) -> None:
52
+ """Run the stdio JSON-RPC server for Host bridge integration."""
53
+ JsonRpcServer(
54
+ default_domains(str(templates_db) if templates_db is not None else None)
55
+ ).serve()
56
+
57
+
58
+ @templates.command("list")
59
+ def list_templates(
60
+ scope: Optional[str] = typer.Option(
61
+ None, "--scope", help="Filter by scope: global|session."
62
+ ),
63
+ session_id: Optional[str] = typer.Option(
64
+ None, "--session-id", help="Filter by owning session id."
65
+ ),
66
+ json_output: bool = typer.Option(False, "--json", help="Emit a JSON array."),
67
+ db: Optional[Path] = typer.Option(
68
+ None,
69
+ "--db",
70
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
71
+ ),
72
+ ) -> None:
73
+ """List prompt templates."""
74
+ items = _store(db).list(scope=scope, session_id=session_id)
75
+ if json_output:
76
+ typer.echo(
77
+ json.dumps(
78
+ [item.model_dump(mode="json") for item in items],
79
+ ensure_ascii=False,
80
+ indent=2,
81
+ )
82
+ )
83
+ else:
84
+ for item in items:
85
+ typer.echo(f"{item.id}\t{item.scope}\t{item.name}\t{item.position}")
86
+
87
+
88
+ @templates.command("add")
89
+ def add_template(
90
+ name: str = typer.Argument(..., help="Template name."),
91
+ content: str = typer.Argument(..., help="Template body."),
92
+ scope: str = typer.Option("global", "--scope", help="global|session."),
93
+ session_id: Optional[str] = typer.Option(
94
+ None, "--session-id", help="Owning session id; required when scope=session."
95
+ ),
96
+ description: Optional[str] = typer.Option(None, "--description"),
97
+ position: int = typer.Option(0, "--position"),
98
+ db: Optional[Path] = typer.Option(
99
+ None,
100
+ "--db",
101
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
102
+ ),
103
+ ) -> None:
104
+ """Add a prompt template and print its id."""
105
+ try:
106
+ data = PromptTemplateCreate(
107
+ name=name,
108
+ content=content,
109
+ scope=scope,
110
+ session_id=session_id,
111
+ description=description,
112
+ position=position,
113
+ )
114
+ item = _store(db).create(data)
115
+ except ValueError as exc:
116
+ _fail(exc)
117
+ typer.echo(item.id)
118
+
119
+
120
+ @templates.command("get")
121
+ def get_template(
122
+ template_id: str = typer.Argument(..., help="Template id."),
123
+ json_output: bool = typer.Option(False, "--json", help="Emit the record as JSON."),
124
+ db: Optional[Path] = typer.Option(
125
+ None,
126
+ "--db",
127
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
128
+ ),
129
+ ) -> None:
130
+ """Show one prompt template."""
131
+ item = _store(db).get(template_id)
132
+ if item is None:
133
+ _fail(ValueError(f"template {template_id!r} not found"))
134
+ if json_output:
135
+ typer.echo(json.dumps(item.model_dump(mode="json"), ensure_ascii=False, indent=2))
136
+ else:
137
+ typer.echo(f"{item.id}\t{item.scope}\t{item.name}")
138
+ typer.echo(item.content)
139
+
140
+
141
+ @templates.command("update")
142
+ def update_template(
143
+ template_id: str = typer.Argument(..., help="Template id."),
144
+ name: Optional[str] = typer.Option(None, "--name"),
145
+ content: Optional[str] = typer.Option(None, "--content"),
146
+ description: Optional[str] = typer.Option(None, "--description"),
147
+ position: Optional[int] = typer.Option(None, "--position"),
148
+ db: Optional[Path] = typer.Option(
149
+ None,
150
+ "--db",
151
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
152
+ ),
153
+ ) -> None:
154
+ """Update one prompt template."""
155
+ try:
156
+ fields = {
157
+ "name": name,
158
+ "content": content,
159
+ "description": description,
160
+ "position": position,
161
+ }
162
+ # Only fields the caller actually passed become part of the patch;
163
+ # an untouched typer Option defaults to None and must stay absent so
164
+ # `exclude_unset` keeps the stored column intact.
165
+ patch = PromptTemplateUpdate(
166
+ **{key: value for key, value in fields.items() if value is not None}
167
+ )
168
+ item = _store(db).update(template_id, patch)
169
+ except ValueError as exc:
170
+ _fail(exc)
171
+ if item is None:
172
+ _fail(ValueError(f"template {template_id!r} not found"))
173
+ typer.echo(item.id)
174
+
175
+
176
+ @templates.command("make-global")
177
+ def make_global_template(
178
+ template_id: str = typer.Argument(..., help="Template id."),
179
+ db: Optional[Path] = typer.Option(
180
+ None,
181
+ "--db",
182
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
183
+ ),
184
+ ) -> None:
185
+ """Promote one session template to the global scope."""
186
+ try:
187
+ item = _store(db).make_global(template_id)
188
+ except ValueError as exc:
189
+ _fail(exc)
190
+ if item is None:
191
+ _fail(ValueError(f"template {template_id!r} not found"))
192
+ typer.echo(item.id)
193
+
194
+
195
+ @templates.command("remove")
196
+ def remove_template(
197
+ template_id: str = typer.Argument(..., help="Template id."),
198
+ db: Optional[Path] = typer.Option(
199
+ None,
200
+ "--db",
201
+ help="Database path (default: $DSH_HOME/ext/prompt-templates/db.sqlite3).",
202
+ ),
203
+ ) -> None:
204
+ """Remove one prompt template."""
205
+ removed = _store(db).delete(template_id)
206
+ if not removed:
207
+ _fail(ValueError(f"template {template_id!r} not found"))
208
+ typer.echo("removed")
209
+
210
+
211
+ def main() -> None:
212
+ app()
213
+
214
+
215
+ if __name__ == "__main__":
216
+ main()
@@ -0,0 +1,125 @@
1
+ """Shared SQLite plumbing for extension domains plus the prompt-template schema.
2
+
3
+ Each extension domain owns its own database file under `$DSH_HOME/ext/<domain>/`
4
+ and its own `DeclarativeBase`; this module owns the cross-domain pieces: the
5
+ home-path rule, private-file hardening, WAL, and the monotonic `user_version`
6
+ gate (an unversioned empty database initializes at the domain's schema version;
7
+ any other on-disk version rejects instead of migrating).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Optional
16
+
17
+ from sqlalchemy import DateTime, Integer, String, Text, create_engine, event, func
18
+ from sqlalchemy.engine import Engine
19
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
20
+
21
+ TEMPLATES_SCHEMA_VERSION = 1
22
+
23
+
24
+ class Base(DeclarativeBase):
25
+ pass
26
+
27
+
28
+ class TemplateRow(Base):
29
+ """One prompt template row. `scope` discriminates global vs session; a
30
+ session-scoped row carries the owning session id in `session_id`."""
31
+
32
+ __tablename__ = "templates"
33
+
34
+ id: Mapped[str] = mapped_column(String(32), primary_key=True)
35
+ name: Mapped[str] = mapped_column(String(128))
36
+ content: Mapped[str] = mapped_column(Text)
37
+ scope: Mapped[str] = mapped_column(String(16))
38
+ session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
39
+ description: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
40
+ position: Mapped[int] = mapped_column(Integer, nullable=False, server_default="0")
41
+ created_at: Mapped[datetime] = mapped_column(
42
+ DateTime, nullable=False, server_default=func.now()
43
+ )
44
+ updated_at: Mapped[datetime] = mapped_column(
45
+ DateTime, nullable=False, server_default=func.now(), onupdate=func.now()
46
+ )
47
+
48
+
49
+ def ext_home() -> Path:
50
+ """Resolve `$DSH_HOME` (default `~/.dsh`), matching the repository
51
+ home-paths convention."""
52
+ home = os.environ.get("DSH_HOME")
53
+ return Path(home).expanduser() if home and home.strip() else Path.home() / ".dsh"
54
+
55
+
56
+ def default_domain_db_path(domain: str) -> Path:
57
+ """Resolve `<ext_home>/ext/<domain>/db.sqlite3` for one extension domain.
58
+
59
+ The `ext/` subdirectory keeps extension data out of the root (never flat
60
+ files beside `settings.yaml`)."""
61
+ return ext_home() / "ext" / domain / "db.sqlite3"
62
+
63
+
64
+ def default_db_path() -> Path:
65
+ """The prompt-template domain's default database path."""
66
+ return default_domain_db_path("prompt-templates")
67
+
68
+
69
+ def _ensure_private_dir(path: Path) -> None:
70
+ path.mkdir(parents=True, exist_ok=True)
71
+ try:
72
+ os.chmod(path, 0o700)
73
+ except OSError:
74
+ # Best-effort on platforms without POSIX modes.
75
+ pass
76
+
77
+
78
+ def _ensure_private_file(path: Path) -> None:
79
+ try:
80
+ os.chmod(path, 0o600)
81
+ except OSError:
82
+ pass
83
+
84
+
85
+ def _enable_wal(dbapi_connection, _record) -> None:
86
+ cursor = dbapi_connection.cursor()
87
+ cursor.execute("PRAGMA journal_mode=WAL")
88
+ cursor.execute("PRAGMA busy_timeout=5000")
89
+ cursor.close()
90
+
91
+
92
+ def open_domain_engine(db_path: str | Path, base: type[DeclarativeBase], schema_version: int) -> Engine:
93
+ """Create the SQLite engine for one domain database, creating the schema
94
+ when absent and gating on the monotonic `user_version`.
95
+
96
+ The parent directory is created owner-only and the database file is
97
+ chmodded to owner-only, matching the TS persistence backends. The
98
+ in-memory database skips all filesystem handling. An empty database with
99
+ `user_version` 0 initializes at `schema_version`; any other non-current
100
+ version rejects rather than migrating."""
101
+ if str(db_path) == ":memory:":
102
+ engine = create_engine("sqlite:///:memory:", future=True)
103
+ else:
104
+ path = Path(db_path)
105
+ _ensure_private_dir(path.parent)
106
+ engine = create_engine(f"sqlite:///{path}", future=True)
107
+ event.listen(engine, "connect", _enable_wal)
108
+ with engine.begin() as connection:
109
+ on_disk = connection.exec_driver_sql("PRAGMA user_version").scalar_one()
110
+ if on_disk == 0:
111
+ base.metadata.create_all(connection)
112
+ connection.exec_driver_sql(f"PRAGMA user_version={schema_version}")
113
+ elif on_disk != schema_version:
114
+ raise RuntimeError(
115
+ f"{db_path} has schema version {on_disk}, "
116
+ f"incompatible with this build (expected {schema_version})"
117
+ )
118
+ if str(db_path) != ":memory:":
119
+ _ensure_private_file(Path(db_path))
120
+ return engine
121
+
122
+
123
+ def create_engine_for(db_path: str | Path) -> Engine:
124
+ """Create the prompt-template domain engine (see {@link open_domain_engine})."""
125
+ return open_domain_engine(db_path, Base, TEMPLATES_SCHEMA_VERSION)