@agentsdock/server 1.0.12-beta.1 → 1.0.12-beta.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.
@@ -0,0 +1,309 @@
1
+ """Native, on-demand language servers owned by individual editor connections."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from contextlib import suppress
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import signal
11
+ from typing import Any, Callable
12
+
13
+ from fastapi import HTTPException, Request, WebSocket, WebSocketDisconnect
14
+
15
+
16
+ WEBSOCKET_PROTOCOL = "agentsdock-intelligence-v1"
17
+ LANGUAGES = {
18
+ "python": {
19
+ "binary": "pyright-langserver",
20
+ "local": (".venv/bin/pyright-langserver", "node_modules/.bin/pyright-langserver"),
21
+ "install_hint": "Install Pyright in this project's environment or make pyright-langserver available on the server PATH.",
22
+ },
23
+ "typescript": {
24
+ "binary": "typescript-language-server",
25
+ "local": ("node_modules/.bin/typescript-language-server",),
26
+ "install_hint": "Install typescript-language-server with a TypeScript version that provides tsserver.js (TypeScript 6 is supported) in this project or on the server PATH.",
27
+ },
28
+ }
29
+
30
+
31
+ class IntelligenceError(Exception):
32
+ """A bridge failure that the editor can present without losing its buffer."""
33
+
34
+
35
+ def language_command(root: Path, language: str, environment: dict[str, str]) -> tuple[str, ...] | None:
36
+ specification = LANGUAGES.get(language)
37
+ if specification is None:
38
+ raise HTTPException(404, "Unsupported intelligence language.")
39
+ for relative in specification["local"]:
40
+ candidate = root / relative
41
+ if candidate.is_file() and os.access(candidate, os.X_OK):
42
+ return (str(candidate), "--stdio")
43
+ # Resolve relative PATH components against the selected workspace, never
44
+ # against the server process's unrelated working directory.
45
+ search_path = os.pathsep.join(
46
+ str(Path(entry) if Path(entry).is_absolute() else root / entry)
47
+ for entry in environment.get("PATH", os.defpath).split(os.pathsep)
48
+ )
49
+ installed = shutil.which(specification["binary"], path=search_path)
50
+ return (installed, "--stdio") if installed else None
51
+
52
+
53
+ def rpc_object(value: Any) -> dict[str, Any]:
54
+ if (not isinstance(value, dict) or value.get("jsonrpc") != "2.0"
55
+ or not (isinstance(value.get("method"), str) or "id" in value)):
56
+ raise IntelligenceError("Expected a JSON-RPC 2.0 object.")
57
+ return value
58
+
59
+
60
+ async def read_message(stream: asyncio.StreamReader) -> dict[str, Any] | None:
61
+ """Read UTF-8 LSP content using its byte length, including split frames."""
62
+ try:
63
+ headers = await stream.readuntil(b"\r\n\r\n")
64
+ except asyncio.IncompleteReadError as exc:
65
+ if not exc.partial:
66
+ return None
67
+ raise IntelligenceError("The language server closed an incomplete message.") from exc
68
+ lengths = []
69
+ for line in headers[:-4].split(b"\r\n"):
70
+ name, separator, value = line.partition(b":")
71
+ if not separator:
72
+ raise IntelligenceError("The language server sent an invalid message header.")
73
+ if name.lower() == b"content-length":
74
+ lengths.append(value.strip())
75
+ if len(lengths) != 1 or not lengths[0].isdigit():
76
+ raise IntelligenceError("The language server sent an invalid Content-Length.")
77
+ try:
78
+ body = await stream.readexactly(int(lengths[0]))
79
+ return rpc_object(json.loads(body.decode("utf-8")))
80
+ except (asyncio.IncompleteReadError, UnicodeError, ValueError) as exc:
81
+ raise IntelligenceError("The language server sent an incomplete or invalid JSON message.") from exc
82
+
83
+
84
+ async def write_message(stream: asyncio.StreamWriter, message: dict[str, Any]) -> None:
85
+ body = json.dumps(message, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
86
+ stream.write(f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") + body)
87
+ await stream.drain()
88
+
89
+
90
+ async def stop_process(process: asyncio.subprocess.Process) -> None:
91
+ """Reap only the process group created for this connection, including tsserver."""
92
+ async def discard(stream: asyncio.StreamReader | None) -> None:
93
+ if stream is not None:
94
+ while await stream.read(65536):
95
+ pass
96
+
97
+ # A paused full pipe can otherwise keep asyncio's Process.wait pending
98
+ # after the child has exited. The regular pumps have already been joined.
99
+ drains = [asyncio.create_task(discard(stream)) for stream in (process.stdout, process.stderr)]
100
+ if process.stdin is not None:
101
+ process.stdin.close()
102
+ with suppress(ProcessLookupError):
103
+ os.killpg(process.pid, signal.SIGTERM)
104
+ try:
105
+ await asyncio.wait_for(process.wait(), timeout=1.0)
106
+ except asyncio.TimeoutError:
107
+ pass
108
+ finally:
109
+ # The wrapper can exit before its children. Its private process group
110
+ # remains ours until all children exit; no agent process shares it.
111
+ try:
112
+ os.killpg(process.pid, signal.SIGKILL)
113
+ except ProcessLookupError:
114
+ pass
115
+ except PermissionError:
116
+ # macOS can report EPERM for a group whose already-exited members
117
+ # are awaiting reaping. Do not mask a live parent's signal failure.
118
+ if process.returncode is None:
119
+ raise
120
+ await process.wait()
121
+ await asyncio.gather(*drains, return_exceptions=True)
122
+
123
+
124
+ class WorkspaceIntelligence:
125
+ def __init__(self, *, workspace_root: Callable, environment: Callable):
126
+ self.workspace_root = workspace_root
127
+ self.environment = environment
128
+ self.connections: set[asyncio.Task] = set()
129
+ self.closing = False
130
+
131
+ def checked_root(self, session_id: str, expected: tuple[Path, int, int] | None = None) -> tuple[Path, int, int]:
132
+ _, root = self.workspace_root(session_id)
133
+ info = root.stat()
134
+ selected = (root, info.st_dev, info.st_ino)
135
+ if expected is not None and selected != expected:
136
+ raise HTTPException(409, "This chat's working directory changed. Reopen the editor intelligence connection.")
137
+ return selected
138
+
139
+ def status(self, session_id: str) -> dict[str, Any]:
140
+ selected = self.checked_root(session_id)
141
+ root = selected[0]
142
+ environment = self.environment()
143
+ languages = []
144
+ for language, specification in LANGUAGES.items():
145
+ available = language_command(root, language, environment) is not None
146
+ languages.append({"id": language, "available": available, **({} if available else {
147
+ "message": f"{specification['binary']} is not installed for this workspace.",
148
+ "install_hint": specification["install_hint"],
149
+ })})
150
+ self.checked_root(session_id, selected)
151
+ return {"root": str(root), "root_uri": root.as_uri(), "languages": languages}
152
+
153
+ async def shutdown(self) -> None:
154
+ self.closing = True
155
+ owners = tuple(self.connections)
156
+ for owner in owners:
157
+ owner.cancel()
158
+ await asyncio.gather(*owners, return_exceptions=True)
159
+
160
+ async def serve(self, session_id: str, language: str, ws: WebSocket,
161
+ *, authorize: Callable, protocols: Callable) -> None:
162
+ offered = protocols(ws)
163
+ await ws.accept(subprotocol=WEBSOCKET_PROTOCOL if WEBSOCKET_PROTOCOL in offered else None)
164
+ if not authorize(ws):
165
+ await ws.close(code=4401)
166
+ return
167
+ if WEBSOCKET_PROTOCOL not in offered:
168
+ await ws.close(code=4406)
169
+ return
170
+ if ws.query_params:
171
+ await ws.close(code=4400)
172
+ return
173
+ if self.closing:
174
+ await ws.close(code=1012)
175
+ return
176
+
177
+ owner = asyncio.current_task()
178
+ assert owner is not None
179
+ self.connections.add(owner)
180
+ spawn: asyncio.Task | None = None
181
+ pumps: set[asyncio.Task] = set()
182
+ close_code = 1000
183
+ error: str | None = None
184
+ try:
185
+ selected = await asyncio.to_thread(self.checked_root, session_id)
186
+ environment = await asyncio.to_thread(self.environment)
187
+ command = await asyncio.to_thread(language_command, selected[0], language, environment)
188
+ if command is None:
189
+ raise HTTPException(503, LANGUAGES[language]["install_hint"])
190
+ await asyncio.to_thread(self.checked_root, session_id, selected)
191
+ # Shield creation so disconnect/cancellation cannot lose ownership
192
+ # between OS process creation and delivery of its Process handle.
193
+ spawn = asyncio.create_task(asyncio.create_subprocess_exec(
194
+ *command, cwd=selected[0], env=environment,
195
+ stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
196
+ stderr=asyncio.subprocess.PIPE, start_new_session=True,
197
+ ))
198
+ process = await asyncio.shield(spawn)
199
+ await asyncio.to_thread(self.checked_root, session_id, selected)
200
+ assert process.stdin is not None and process.stdout is not None and process.stderr is not None
201
+
202
+ async def from_client() -> None:
203
+ while True:
204
+ frame = await ws.receive()
205
+ if frame["type"] == "websocket.disconnect":
206
+ return
207
+ raw = frame.get("text")
208
+ if raw is None:
209
+ raise IntelligenceError("Intelligence messages must be JSON text.")
210
+ message = rpc_object(json.loads(raw))
211
+ await asyncio.to_thread(self.checked_root, session_id, selected)
212
+ if message.get("method") == "initialize":
213
+ params = message.get("params")
214
+ if not isinstance(params, dict):
215
+ raise IntelligenceError("Initialize requires an object of parameters.")
216
+ options = params.get("initializationOptions")
217
+ tsserver = options.get("tsserver") if isinstance(options, dict) else None
218
+ semantic_only = (language == "typescript" and isinstance(tsserver, dict)
219
+ and tsserver.get("useSyntaxServer") == "never")
220
+ # The server owns workspace and process identity. Do not
221
+ # accept executable/configuration paths from the client.
222
+ params = {key: value for key, value in params.items()
223
+ if key not in {"initializationOptions", "processId", "rootUri", "rootPath", "workspaceFolders"}}
224
+ if semantic_only:
225
+ # Symbol search needs the semantic project's initial
226
+ # load, not the fast syntax server's partial view.
227
+ params["initializationOptions"] = {"tsserver": {"useSyntaxServer": "never"}}
228
+ params.update(processId=None, rootUri=selected[0].as_uri(), rootPath=str(selected[0]),
229
+ workspaceFolders=[{"uri": selected[0].as_uri(), "name": selected[0].name}])
230
+ message = {**message, "params": params}
231
+ await write_message(process.stdin, message)
232
+
233
+ async def from_server() -> None:
234
+ while True:
235
+ message = await read_message(process.stdout)
236
+ if message is None:
237
+ code = await process.wait()
238
+ if code:
239
+ raise IntelligenceError(f"The language server exited with status {code}.")
240
+ return
241
+ await asyncio.to_thread(self.checked_root, session_id, selected)
242
+ await ws.send_json(message)
243
+
244
+ async def drain_errors() -> None:
245
+ # Language server logs can be large and contain workspace text.
246
+ # Drain without retaining them or mixing them into JSON-RPC.
247
+ while await process.stderr.read(65536):
248
+ pass
249
+
250
+ incoming = asyncio.create_task(from_client())
251
+ outgoing = asyncio.create_task(from_server())
252
+ errors = asyncio.create_task(drain_errors())
253
+ pumps.update((incoming, outgoing, errors))
254
+ done, _ = await asyncio.wait((incoming, outgoing), return_when=asyncio.FIRST_COMPLETED)
255
+ for task in done:
256
+ task.result()
257
+ except WebSocketDisconnect:
258
+ pass
259
+ except HTTPException as exc:
260
+ close_code = 4404 if exc.status_code == 404 else 4409 if exc.status_code == 409 else 1011
261
+ error = exc.detail.get("message", str(exc.detail)) if isinstance(exc.detail, dict) else str(exc.detail)
262
+ except (IntelligenceError, OSError, ValueError, asyncio.LimitOverrunError) as exc:
263
+ close_code = 1011
264
+ error = str(exc) or "The language server connection failed."
265
+ except asyncio.CancelledError:
266
+ close_code = 1001
267
+ raise
268
+ finally:
269
+ async def cleanup() -> None:
270
+ for task in pumps:
271
+ task.cancel()
272
+ await asyncio.gather(*pumps, return_exceptions=True)
273
+ if spawn is not None:
274
+ with suppress(Exception):
275
+ process = await spawn
276
+ await stop_process(process)
277
+ with suppress(Exception):
278
+ if error:
279
+ await ws.send_json({"type": "intelligence_error", "message": error})
280
+ await ws.close(code=close_code)
281
+
282
+ cleanup_task = asyncio.create_task(cleanup())
283
+ try:
284
+ # Repeated lifecycle cancellation must still reap our process.
285
+ while not cleanup_task.done():
286
+ try:
287
+ await asyncio.shield(cleanup_task)
288
+ except asyncio.CancelledError:
289
+ continue
290
+ cleanup_task.result()
291
+ finally:
292
+ self.connections.discard(owner)
293
+
294
+
295
+ def register_workspace_intelligence_routes(app, *, authorize: Callable,
296
+ authorize_websocket: Callable, protocols: Callable,
297
+ workspace_root: Callable, environment: Callable) -> WorkspaceIntelligence:
298
+ runtime = WorkspaceIntelligence(workspace_root=workspace_root, environment=environment)
299
+
300
+ @app.get("/api/sessions/{session_id}/workspace/intelligence")
301
+ async def intelligence_status(session_id: str, request: Request) -> dict[str, Any]:
302
+ authorize(request)
303
+ return await asyncio.to_thread(runtime.status, session_id)
304
+
305
+ @app.websocket("/api/sessions/{session_id}/workspace/intelligence/{language}")
306
+ async def intelligence_socket(session_id: str, language: str, ws: WebSocket) -> None:
307
+ await runtime.serve(session_id, language, ws, authorize=authorize_websocket, protocols=protocols)
308
+
309
+ return runtime