ai-editor-client-dev 1.0.244__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.
@@ -0,0 +1,60 @@
1
+ """
2
+ Dynamic command wrappers: schema from server ``help``, then local shallow validation.
3
+
4
+ Author: Vasiliy Zdanovskiy
5
+ email: vasilyvz@gmail.com
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING, Any, Dict, Optional, cast
11
+
12
+ if TYPE_CHECKING:
13
+ from ai_editor_client.client import CodeAnalysisAsyncClient
14
+
15
+
16
+ class ValidatedCommandsProxy:
17
+ """``client.commands.<name>(**params)`` — fetch schema via ``help``, validate, ``execute_command``."""
18
+
19
+ __slots__ = ("_client",)
20
+
21
+ def __init__(self, client: CodeAnalysisAsyncClient) -> None:
22
+ object.__setattr__(self, "_client", client)
23
+
24
+ def clear_schema_cache(self) -> None:
25
+ """Forget cached schemas (e.g. after server ``reload``)."""
26
+ self._client.clear_command_schema_cache()
27
+
28
+ async def fetch_schema(
29
+ self, command: str, *, refresh: bool = False
30
+ ) -> Dict[str, Any]:
31
+ """Return input JSON schema for ``command`` (from server ``help``)."""
32
+ return cast(
33
+ Dict[str, Any],
34
+ await self._client.get_command_schema(command, refresh=refresh),
35
+ )
36
+
37
+ async def invoke(
38
+ self,
39
+ command: str,
40
+ params: Optional[Dict[str, Any]] = None,
41
+ **kwargs: Any,
42
+ ) -> Dict[str, Any]:
43
+ """Merge ``params`` and ``kwargs``, validate against server schema, execute."""
44
+ merged: Dict[str, Any] = dict(params or {})
45
+ if kwargs:
46
+ merged.update(kwargs)
47
+ return cast(Dict[str, Any], await self._client.call_validated(command, merged))
48
+
49
+ def __getattr__(self, name: str) -> Any:
50
+ if name.startswith("_"):
51
+ raise AttributeError(name)
52
+
53
+ async def _bound(**kw: Any) -> Dict[str, Any]:
54
+ return cast(Dict[str, Any], await self._client.call_validated(name, kw))
55
+
56
+ _bound.__name__ = name
57
+ _bound.__doc__ = (
58
+ f"Validated call for command {name!r} (schema from server help)."
59
+ )
60
+ return _bound
@@ -0,0 +1,126 @@
1
+ """
2
+ Map server / adapter-style settings dicts to JsonRpcClient constructor kwargs.
3
+
4
+ Author: Vasiliy Zdanovskiy
5
+ email: vasilyvz@gmail.com
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Any, Mapping
13
+
14
+
15
+ def _expand_path(value: Any) -> str | None:
16
+ if value is None or value == "":
17
+ return None
18
+ return str(Path(str(value)).expanduser().resolve())
19
+
20
+
21
+ def _ssl_paths_from_section(ssl_section: Any) -> dict[str, str]:
22
+ if not isinstance(ssl_section, dict):
23
+ return {}
24
+ out: dict[str, str] = {}
25
+ for key in ("cert", "key", "ca", "cert_path", "key_path", "ca_path"):
26
+ raw = ssl_section.get(key)
27
+ expanded = _expand_path(raw) if raw else None
28
+ if expanded:
29
+ out[key] = expanded
30
+ # Normalize aliases to cert/key/ca for downstream comparison / JsonRpcClient
31
+ if "cert" not in out and out.get("cert_path"):
32
+ out["cert"] = out["cert_path"]
33
+ if "key" not in out and out.get("key_path"):
34
+ out["key"] = out["key_path"]
35
+ if "ca" not in out and out.get("ca_path"):
36
+ out["ca"] = out["ca_path"]
37
+ return out
38
+
39
+
40
+ def _network_from_server_config(config: Mapping[str, Any]) -> dict[str, Any]:
41
+ server = config.get("server", {})
42
+ if not isinstance(server, dict):
43
+ server = {}
44
+ host = server.get("host", "127.0.0.1")
45
+ if host in ("0.0.0.0", "::", "[::]"):
46
+ host = "127.0.0.1"
47
+ return {
48
+ "host": host,
49
+ "port": int(server.get("port", 15001)),
50
+ "protocol": server.get("protocol", "http"),
51
+ }
52
+
53
+
54
+ def _client_mtls_paths_from_server_config(config: Mapping[str, Any]) -> dict[str, str]:
55
+ """Prefer client.ssl; fall back to server.ssl (same rules as pipeline)."""
56
+ client_section = config.get("client", {})
57
+ if isinstance(client_section, dict):
58
+ ssl_section = client_section.get("ssl", {})
59
+ if isinstance(ssl_section, dict) and any(
60
+ ssl_section.get(k) for k in ("cert", "cert_path", "key", "key_path")
61
+ ):
62
+ return _ssl_paths_from_section(ssl_section)
63
+ server = config.get("server", {})
64
+ if not isinstance(server, dict):
65
+ return {}
66
+ return _ssl_paths_from_section(server.get("ssl", {}))
67
+
68
+
69
+ def adapter_settings_from_server_config(config: Mapping[str, Any]) -> dict[str, Any]:
70
+ """Build adapter-style settings from a ai-editor server config dict."""
71
+ settings = dict(_network_from_server_config(config))
72
+ proto = str(settings.get("protocol", "")).lower()
73
+ if proto == "mtls":
74
+ settings["ssl"] = _client_mtls_paths_from_server_config(config)
75
+ elif proto == "https":
76
+ ssl_paths = _client_mtls_paths_from_server_config(config)
77
+ if ssl_paths.get("cert") and ssl_paths.get("key"):
78
+ settings["ssl"] = ssl_paths
79
+ return settings
80
+
81
+
82
+ def adapter_settings_to_jsonrpc_kwargs(
83
+ settings: Mapping[str, Any],
84
+ *,
85
+ timeout: float | None = 60.0,
86
+ check_hostname: bool = False,
87
+ token_header: str | None = None,
88
+ token: str | None = None,
89
+ ) -> dict[str, Any]:
90
+ """Turn adapter-style settings into keyword args for JsonRpcClient."""
91
+ ssl_section = settings.get("ssl")
92
+ cert = key = ca = None
93
+ if isinstance(ssl_section, dict):
94
+ cert = ssl_section.get("cert") or ssl_section.get("cert_path")
95
+ key = ssl_section.get("key") or ssl_section.get("key_path")
96
+ ca = ssl_section.get("ca") or ssl_section.get("ca_path")
97
+ cert = _expand_path(cert) if cert else None
98
+ key = _expand_path(key) if key else None
99
+ ca = _expand_path(ca) if ca else None
100
+
101
+ th = token_header if token_header is not None else settings.get("token_header")
102
+ tok = token if token is not None else settings.get("token")
103
+
104
+ return {
105
+ "protocol": str(settings.get("protocol", "http")),
106
+ "host": str(settings.get("host", "127.0.0.1")),
107
+ "port": int(settings.get("port", 8080)),
108
+ "token_header": str(th) if th else None,
109
+ "token": str(tok) if tok else None,
110
+ "cert": cert,
111
+ "key": key,
112
+ "ca": ca,
113
+ "check_hostname": check_hostname,
114
+ "timeout": timeout,
115
+ }
116
+
117
+
118
+ def load_server_config(path: str | Path) -> dict[str, Any]:
119
+ """Load server config.json into a dict."""
120
+ p = Path(path).expanduser()
121
+ with p.open("r", encoding="utf-8") as f:
122
+ data: Any = json.load(f)
123
+ if not isinstance(data, dict):
124
+ raise ValueError("Server config must be a JSON object")
125
+ # py3.10: return plain dict for mutability
126
+ return dict(data)
@@ -0,0 +1,205 @@
1
+ """
2
+ Five-step editor workflow over CA transfer + local session directory.
3
+
4
+ 1. **checkout** — download file to baseline path and lock in CA DB.
5
+ 2. **open_workspace** — create local ``{name}-{uuid}/`` session dir; edit inside it.
6
+ 3. *(edit)* — application mutates :attr:`EditorFileHandle.working_path`.
7
+ 4. **save_to_server** — upload working bytes; on success sync baseline outside session.
8
+ 5. **close** — unlock on CA; on success delete session dir and baseline.
9
+
10
+ Distinct from ``UniversalFileClient`` (server-side in-memory agent sessions).
11
+
12
+ Author: Vasiliy Zdanovskiy
13
+ email: vasilyvz@gmail.com
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any, Dict, Optional, Union
21
+
22
+ from ai_editor_client.exceptions import ClientValidationError
23
+ from ai_editor_client.file_session import FileSessionClient
24
+ from ai_editor_client.local_edit_workspace import (
25
+ EditorFileWorkflowError,
26
+ LocalEditWorkspace,
27
+ )
28
+
29
+
30
+ def _require_non_empty(value: str, *, field_name: str) -> str:
31
+ text = str(value or "").strip()
32
+ if not text:
33
+ raise ClientValidationError(f"{field_name} is required", field=field_name)
34
+ return text
35
+
36
+
37
+ @dataclass
38
+ class EditorFileHandle:
39
+ """State for one checked-out project file in the editor."""
40
+
41
+ ca_session_id: str
42
+ project_id: str
43
+ file_id: str
44
+ file_path: str
45
+ baseline_path: Path
46
+ workspace: Optional[LocalEditWorkspace] = None
47
+ is_closed: bool = field(default=False, repr=False)
48
+
49
+ @property
50
+ def is_open(self) -> bool:
51
+ return (
52
+ not self.is_closed
53
+ and self.workspace is not None
54
+ and self.workspace.is_open
55
+ )
56
+
57
+ @property
58
+ def working_path(self) -> Path:
59
+ if not self.is_open or self.workspace is None:
60
+ raise EditorFileWorkflowError(
61
+ "workspace is not open; call open_workspace first",
62
+ field="workspace",
63
+ )
64
+ path: Path = self.workspace.working_path
65
+ return path
66
+
67
+ def _assert_active(self) -> None:
68
+ if self.is_closed:
69
+ raise EditorFileWorkflowError(
70
+ "handle is closed",
71
+ field="handle",
72
+ )
73
+
74
+
75
+ class EditorFileClient:
76
+ """Orchestrates download → local session → upload → unlock for one file."""
77
+
78
+ __slots__ = ("_fs",)
79
+
80
+ def __init__(self, file_sessions: FileSessionClient) -> None:
81
+ self._fs = file_sessions
82
+
83
+ async def checkout(
84
+ self,
85
+ ca_session_id: str,
86
+ baseline_path: Union[str, Path],
87
+ file_id: str,
88
+ *,
89
+ project_id: Optional[str] = None,
90
+ lock: bool = True,
91
+ compression: str = "identity",
92
+ include_backup_history: bool = True,
93
+ ) -> EditorFileHandle:
94
+ """Step 1: download to *baseline_path* (outside session) and lock on CA."""
95
+ sid = _require_non_empty(ca_session_id, field_name="ca_session_id")
96
+ fid = _require_non_empty(file_id, field_name="file_id")
97
+ baseline = Path(baseline_path).resolve()
98
+ baseline.parent.mkdir(parents=True, exist_ok=True)
99
+
100
+ begin, _receipt = await self._fs.download(
101
+ sid,
102
+ baseline,
103
+ fid,
104
+ compression=compression,
105
+ lock=lock,
106
+ include_backup_history=include_backup_history,
107
+ project_id=project_id,
108
+ )
109
+ if not baseline.is_file():
110
+ raise EditorFileWorkflowError(
111
+ "download did not create baseline file",
112
+ field="baseline_path",
113
+ details={"baseline_path": str(baseline), "begin": begin},
114
+ )
115
+
116
+ effective_pid = str(begin.get("project_id") or project_id or "").strip()
117
+ if not effective_pid:
118
+ raise EditorFileWorkflowError(
119
+ "project_id missing from download response",
120
+ field="project_id",
121
+ details={"begin": begin},
122
+ )
123
+ rel_path = str(begin.get("file_path") or "").strip().replace("\\", "/")
124
+ if not rel_path:
125
+ rel_path = baseline.name
126
+
127
+ return EditorFileHandle(
128
+ ca_session_id=sid,
129
+ project_id=effective_pid,
130
+ file_id=str(begin.get("file_id") or fid).strip(),
131
+ file_path=rel_path,
132
+ baseline_path=baseline,
133
+ )
134
+
135
+ def open_workspace(self, handle: EditorFileHandle) -> Path:
136
+ """Step 2: create local session directory; return path to edit inside."""
137
+ handle._assert_active()
138
+ if handle.workspace is not None:
139
+ if handle.workspace.is_open:
140
+ open_path: Path = handle.workspace.working_path
141
+ return open_path
142
+ raise EditorFileWorkflowError(
143
+ "workspace was closed but handle is still active",
144
+ field="workspace",
145
+ )
146
+ handle.workspace = LocalEditWorkspace.open(handle.baseline_path)
147
+ new_path: Path = handle.workspace.working_path
148
+ return new_path
149
+
150
+ async def save_to_server(
151
+ self,
152
+ handle: EditorFileHandle,
153
+ *,
154
+ backup: bool = True,
155
+ dry_run: bool = False,
156
+ diff: bool = False,
157
+ diff_context_lines: Optional[int] = None,
158
+ commit_message: Optional[str] = None,
159
+ validate_syntax_only: bool = False,
160
+ tree_id: Optional[str] = None,
161
+ lock_mode: Optional[str] = None,
162
+ ) -> Dict[str, Any]:
163
+ """Step 4: upload working copy; on success overwrite baseline (no unlock)."""
164
+ handle._assert_active()
165
+ if not handle.is_open or handle.workspace is None:
166
+ raise EditorFileWorkflowError(
167
+ "workspace is not open",
168
+ field="workspace",
169
+ )
170
+ payload = handle.workspace.working_path.read_bytes()
171
+ saved: Dict[str, Any] = await self._fs.upload(
172
+ handle.ca_session_id,
173
+ payload,
174
+ handle.file_id,
175
+ project_id=handle.project_id,
176
+ filename=Path(handle.file_path).name,
177
+ unlock=False,
178
+ backup=backup,
179
+ dry_run=dry_run,
180
+ diff=diff,
181
+ diff_context_lines=diff_context_lines,
182
+ commit_message=commit_message,
183
+ validate_syntax_only=validate_syntax_only,
184
+ tree_id=tree_id,
185
+ lock_mode=lock_mode,
186
+ )
187
+ if not dry_run:
188
+ handle.workspace.sync_baseline()
189
+ return saved
190
+
191
+ async def close(self, handle: EditorFileHandle) -> Dict[str, Any]:
192
+ """Step 5: unlock on CA; on success remove session dir and baseline."""
193
+ handle._assert_active()
194
+ unlock_result: Dict[str, Any] = await self._fs.unlock_file(
195
+ handle.ca_session_id,
196
+ handle.project_id,
197
+ handle.file_id,
198
+ )
199
+ if handle.workspace is not None and handle.workspace.is_open:
200
+ handle.workspace.close(delete_baseline=True)
201
+ handle.workspace = None
202
+ elif handle.baseline_path.is_file():
203
+ handle.baseline_path.unlink()
204
+ handle.is_closed = True
205
+ return unlock_result
@@ -0,0 +1,48 @@
1
+ """Client-side errors (no dependency on ai_editor server package)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+
8
+ class ClientValidationError(ValueError):
9
+ """Parameters do not match the command JSON schema (from server ``help``)."""
10
+
11
+ def __init__(
12
+ self,
13
+ message: str,
14
+ *,
15
+ field: Optional[str] = None,
16
+ details: Optional[Dict[str, Any]] = None,
17
+ ) -> None:
18
+ super().__init__(message)
19
+ self.field = field
20
+ self.details = details or {}
21
+
22
+
23
+ class ServerVersionMismatch(RuntimeError):
24
+ """The server on the other end is not the version this client declares.
25
+
26
+ Raised before the command is dispatched, so nothing is executed against a
27
+ server whose contract this client has not been built for. The rule is exact
28
+ equality, never a compatible range: "the client number, the engine number
29
+ and the server number must coincide."
30
+
31
+ ``health`` and ``info`` are exempt and keep working across a mismatch --
32
+ they are exactly the commands an operator uses to SEE a version mismatch,
33
+ so failing them would remove the tool needed to diagnose the problem. See
34
+ :mod:`ai_editor_client.server_version`.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ message: str,
40
+ *,
41
+ client_version: str,
42
+ server_version: Optional[str],
43
+ command: Optional[str] = None,
44
+ ) -> None:
45
+ super().__init__(message)
46
+ self.client_version = client_version
47
+ self.server_version = server_version
48
+ self.command = command