@nelsonlongxiang/dsh-prompt-templates 0.2.10 → 0.4.4

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.
@@ -1,170 +0,0 @@
1
- """Newline-delimited JSON-RPC 2.0 server over stdio.
2
-
3
- The Host bridge spawns `dsh-prompt-templates serve` and exchanges one JSON
4
- object per line: requests carry `{"jsonrpc":"2.0","id",...,"method",...,
5
- "params":{}}` and responses echo the id with `result` or `error`.
6
- Notifications (no `id`) are processed without a response.
7
-
8
- Methods are `<domain>/<operation>` (`templates/list`). The domain is created
9
- lazily on its first request, so a child serving only templates never creates
10
- another domain's database file."""
11
-
12
- from __future__ import annotations
13
-
14
- import json
15
- import sys
16
- from typing import Any, BinaryIO, Callable, Optional, Protocol
17
-
18
- from .models import PromptTemplateCreate, PromptTemplateUpdate
19
- from .store import PromptTemplateStore
20
-
21
-
22
- def _error(code: int, message: str, data: Any = None) -> dict[str, Any]:
23
- payload: dict[str, Any] = {"code": code, "message": message}
24
- if data is not None:
25
- payload["data"] = data
26
- return payload
27
-
28
-
29
- def require_id(params: dict[str, Any]) -> str:
30
- """Extract the required template id as a business error when malformed."""
31
- value = params.get("id")
32
- if not isinstance(value, str) or value == "":
33
- raise ValueError("template id must be a non-empty string")
34
- return value
35
-
36
-
37
- class Domain(Protocol):
38
- """One extension domain: dispatch `<operation>` within its namespace."""
39
-
40
- def dispatch(self, operation: str, params: dict[str, Any]) -> Any: ...
41
-
42
-
43
- class TemplateDomain:
44
- """The prompt-template domain over one {@link PromptTemplateStore}."""
45
-
46
- def __init__(self, store: PromptTemplateStore) -> None:
47
- self._store = store
48
-
49
- def dispatch(self, operation: str, params: dict[str, Any]) -> Any:
50
- if operation == "list":
51
- return [
52
- template.model_dump(mode="json")
53
- for template in self._store.list(
54
- scope=params.get("scope"), session_id=params.get("session_id")
55
- )
56
- ]
57
- if operation == "get":
58
- template_id = require_id(params)
59
- template = self._store.get(template_id)
60
- return template.model_dump(mode="json") if template is not None else None
61
- if operation == "create":
62
- data = PromptTemplateCreate.model_validate(params)
63
- return self._store.create(data).model_dump(mode="json")
64
- if operation == "update":
65
- template_id = require_id(params)
66
- patch = PromptTemplateUpdate.model_validate(
67
- {key: value for key, value in params.items() if key != "id"}
68
- )
69
- template = self._store.update(template_id, patch)
70
- return template.model_dump(mode="json") if template is not None else None
71
- if operation == "make_global":
72
- template = self._store.make_global(require_id(params))
73
- return template.model_dump(mode="json") if template is not None else None
74
- if operation == "delete":
75
- return self._store.delete(require_id(params))
76
- raise ValueError(f"unknown method: templates/{operation}")
77
-
78
-
79
- def default_domains(
80
- templates_db: Optional[str] = None,
81
- ) -> dict[str, Callable[[], Domain]]:
82
- """The production domain table: every domain the
83
- `dsh-prompt-templates serve` child exposes, created lazily on first use.
84
-
85
- The domain resolves its own default database path; the argument overrides
86
- it (the Host bridge forwards `--db`)."""
87
- from .db import default_db_path
88
-
89
- def _templates() -> Domain:
90
- return TemplateDomain(PromptTemplateStore(templates_db or default_db_path()))
91
-
92
- return {"templates": _templates}
93
-
94
-
95
- class JsonRpcServer:
96
- """Serve every extension domain over newline-delimited JSON-RPC 2.0."""
97
-
98
- def __init__(self, domains: dict[str, Callable[[], Domain]]) -> None:
99
- self._factories = domains
100
- self._domains: dict[str, Domain] = {}
101
-
102
- def _domain(self, namespace: str) -> Domain:
103
- domain = self._domains.get(namespace)
104
- if domain is None:
105
- factory = self._factories.get(namespace)
106
- if factory is None:
107
- raise ValueError(f"unknown method namespace: {namespace}")
108
- domain = factory()
109
- self._domains[namespace] = domain
110
- return domain
111
-
112
- def handle(self, request: dict[str, Any]) -> Optional[dict[str, Any]]:
113
- """Handle one parsed request; `None` for notifications."""
114
- method = request.get("method")
115
- params = request.get("params") or {}
116
- request_id = request.get("id")
117
- try:
118
- result = self._dispatch(method, params)
119
- except ValueError as exc:
120
- return self._response(request_id, error=_error(-32000, str(exc)))
121
- except Exception as exc: # noqa: BLE001 -- reported to the peer, never raised
122
- return self._response(
123
- request_id, error=_error(-32603, f"internal error: {exc}")
124
- )
125
- if request_id is None:
126
- return None
127
- return self._response(request_id, result=result)
128
-
129
- def _dispatch(self, method: Optional[str], params: dict[str, Any]) -> Any:
130
- if not isinstance(method, str) or "/" not in method:
131
- raise ValueError(f"unknown method: {method}")
132
- namespace, _, operation = method.partition("/")
133
- return self._domain(namespace).dispatch(operation, params)
134
-
135
- def _response(
136
- self,
137
- request_id: Any,
138
- result: Any = None,
139
- error: Optional[dict[str, Any]] = None,
140
- ) -> dict[str, Any]:
141
- payload: dict[str, Any] = {"jsonrpc": "2.0", "id": request_id}
142
- if error is not None:
143
- payload["error"] = error
144
- else:
145
- payload["result"] = result
146
- return payload
147
-
148
- def serve(
149
- self,
150
- stdin: BinaryIO = sys.stdin.buffer,
151
- stdout: BinaryIO = sys.stdout.buffer,
152
- ) -> None:
153
- """Read requests line by line until EOF, writing one response per request."""
154
- for raw in stdin:
155
- line = raw.strip()
156
- if not line:
157
- continue
158
- try:
159
- request = json.loads(line)
160
- except json.JSONDecodeError as exc:
161
- response = self._response(
162
- None, error=_error(-32700, f"parse error: {exc}")
163
- )
164
- stdout.write(json.dumps(response).encode("utf-8") + b"\n")
165
- stdout.flush()
166
- continue
167
- response = self.handle(request)
168
- if response is not None:
169
- stdout.write(json.dumps(response).encode("utf-8") + b"\n")
170
- stdout.flush()
@@ -1,156 +0,0 @@
1
- """Domain CRUD over the SQLite schema."""
2
-
3
- from __future__ import annotations
4
-
5
- import uuid
6
- from pathlib import Path
7
- from typing import Optional
8
-
9
- from sqlalchemy import select
10
- from sqlalchemy.orm import sessionmaker
11
-
12
- from .db import TemplateRow, create_engine_for
13
- from .models import PromptTemplate, PromptTemplateCreate, PromptTemplateUpdate
14
-
15
-
16
- class PromptTemplateStore:
17
- """Owns one SQLite database and exposes template CRUD.
18
-
19
- A template name is unique within its scope partition
20
- (`(scope, session_id)`); a global template must not carry a session id
21
- and a session template must."""
22
-
23
- def __init__(self, db_path: str | Path) -> None:
24
- self._db_path = Path(db_path)
25
- self._engine = create_engine_for(self._db_path)
26
- self._session_factory = sessionmaker(self._engine, expire_on_commit=False)
27
-
28
- @property
29
- def path(self) -> Path:
30
- """Absolute database path this store owns."""
31
- return self._db_path
32
-
33
- def list(
34
- self,
35
- scope: Optional[str] = None,
36
- session_id: Optional[str] = None,
37
- ) -> list[PromptTemplate]:
38
- """List templates, ordered by position then creation time.
39
-
40
- `scope` and `session_id` are optional filters; pass `session_id`
41
- alone to select one session's private templates."""
42
- with self._session_factory() as session:
43
- stmt = select(TemplateRow).order_by(
44
- TemplateRow.position, TemplateRow.created_at
45
- )
46
- if scope is not None:
47
- stmt = stmt.where(TemplateRow.scope == scope)
48
- if session_id is not None:
49
- stmt = stmt.where(TemplateRow.session_id == session_id)
50
- rows = session.scalars(stmt).all()
51
- return [PromptTemplate.model_validate(row) for row in rows]
52
-
53
- def get(self, template_id: str) -> Optional[PromptTemplate]:
54
- """Fetch one template by id; `None` when absent."""
55
- with self._session_factory() as session:
56
- row = session.get(TemplateRow, template_id)
57
- return PromptTemplate.model_validate(row) if row is not None else None
58
-
59
- def create(self, data: PromptTemplateCreate) -> PromptTemplate:
60
- """Insert a template, rejecting a duplicate name in its scope partition."""
61
- with self._session_factory() as session:
62
- existing = session.scalars(
63
- select(TemplateRow).where(
64
- TemplateRow.scope == data.scope,
65
- TemplateRow.session_id == data.session_id,
66
- TemplateRow.name == data.name,
67
- )
68
- ).first()
69
- if existing is not None:
70
- raise ValueError(
71
- f"template name {data.name!r} already exists in scope {data.scope}"
72
- )
73
- row = TemplateRow(
74
- id=uuid.uuid4().hex,
75
- name=data.name,
76
- content=data.content,
77
- scope=data.scope,
78
- session_id=data.session_id,
79
- description=data.description,
80
- position=data.position,
81
- )
82
- session.add(row)
83
- session.commit()
84
- session.refresh(row)
85
- return PromptTemplate.model_validate(row)
86
-
87
- def update(
88
- self, template_id: str, patch: PromptTemplateUpdate
89
- ) -> Optional[PromptTemplate]:
90
- """Apply a patch; `None` when the template is absent.
91
-
92
- A renamed template keeps the create-path uniqueness rule: a name
93
- already taken in its scope partition rejects the update."""
94
- with self._session_factory() as session:
95
- row = session.get(TemplateRow, template_id)
96
- if row is None:
97
- return None
98
- fields = patch.model_dump(exclude_unset=True)
99
- new_name = fields.get("name")
100
- if new_name is not None and new_name != row.name:
101
- existing = session.scalars(
102
- select(TemplateRow).where(
103
- TemplateRow.id != row.id,
104
- TemplateRow.scope == row.scope,
105
- TemplateRow.session_id == row.session_id,
106
- TemplateRow.name == new_name,
107
- )
108
- ).first()
109
- if existing is not None:
110
- raise ValueError(
111
- f"template name {new_name!r} already exists in scope {row.scope}"
112
- )
113
- for field, value in fields.items():
114
- setattr(row, field, value)
115
- session.commit()
116
- session.refresh(row)
117
- return PromptTemplate.model_validate(row)
118
-
119
- def make_global(self, template_id: str) -> Optional[PromptTemplate]:
120
- """Promote one session template to the global partition.
121
-
122
- `None` when the template is absent. Rejects a template that is
123
- already global and a global name collision, mirroring the
124
- create-path uniqueness rule across the partition move."""
125
- with self._session_factory() as session:
126
- row = session.get(TemplateRow, template_id)
127
- if row is None:
128
- return None
129
- if row.scope == "global":
130
- raise ValueError(f"template {template_id!r} is already global")
131
- existing = session.scalars(
132
- select(TemplateRow).where(
133
- TemplateRow.scope == "global",
134
- TemplateRow.session_id.is_(None),
135
- TemplateRow.name == row.name,
136
- )
137
- ).first()
138
- if existing is not None:
139
- raise ValueError(
140
- f"template name {row.name!r} already exists in scope global"
141
- )
142
- row.scope = "global"
143
- row.session_id = None
144
- session.commit()
145
- session.refresh(row)
146
- return PromptTemplate.model_validate(row)
147
-
148
- def delete(self, template_id: str) -> bool:
149
- """Delete a template; `False` when it is absent."""
150
- with self._session_factory() as session:
151
- row = session.get(TemplateRow, template_id)
152
- if row is None:
153
- return False
154
- session.delete(row)
155
- session.commit()
156
- return True