noodelapi 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.
noodelapi/cli.py ADDED
@@ -0,0 +1,490 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import getpass
5
+ import json
6
+ import os
7
+ import signal
8
+ import subprocess
9
+ import sys
10
+ import time
11
+ import urllib.error
12
+ import urllib.request
13
+ from pathlib import Path
14
+ from typing import Any, Dict, Optional
15
+
16
+ from . import __version__
17
+ from .browser import find_browser_tokens
18
+ from .client import DeepSeekClient, DeepSeekError
19
+ from .config import (
20
+ config_path,
21
+ generate_api_key,
22
+ load_config,
23
+ log_path,
24
+ masked,
25
+ normalize_cookie,
26
+ normalize_token,
27
+ pid_path,
28
+ save_config,
29
+ state_dir,
30
+ )
31
+ from .server import MODEL_SPECS, serve
32
+
33
+
34
+
35
+ def _fail(message: str) -> int:
36
+ print(f"error: {message}", file=sys.stderr)
37
+ return 1
38
+
39
+
40
+ def _runtime_path() -> Path:
41
+ return state_dir() / "runtime.json"
42
+
43
+
44
+ def _write_runtime(pid: int, host: str, port: int) -> None:
45
+ path = _runtime_path()
46
+ path.parent.mkdir(parents=True, exist_ok=True)
47
+ path.write_text(
48
+ json.dumps(
49
+ {
50
+ "pid": pid,
51
+ "host": host,
52
+ "port": port,
53
+ "started_at": time.time(),
54
+ }
55
+ )
56
+ + "\n",
57
+ encoding="utf-8",
58
+ )
59
+
60
+
61
+ def _read_runtime() -> Dict[str, Any]:
62
+ path = _runtime_path()
63
+ if path.exists():
64
+ try:
65
+ value = json.loads(path.read_text(encoding="utf-8"))
66
+ if isinstance(value, dict):
67
+ return value
68
+ except (OSError, ValueError):
69
+ pass
70
+ return {}
71
+
72
+
73
+ def _remove_runtime() -> None:
74
+ for path in (_runtime_path(), pid_path()):
75
+ try:
76
+ path.unlink()
77
+ except OSError:
78
+ pass
79
+
80
+
81
+ def _pid_alive(pid: int) -> bool:
82
+ if pid <= 0:
83
+ return False
84
+ if sys.platform == "win32":
85
+ import ctypes
86
+
87
+ process = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid)
88
+ if not process:
89
+ return False
90
+ try:
91
+ code = ctypes.c_ulong()
92
+ ctypes.windll.kernel32.GetExitCodeProcess(process, ctypes.byref(code))
93
+ return code.value == 259 # STILL_ACTIVE
94
+ finally:
95
+ ctypes.windll.kernel32.CloseHandle(process)
96
+ try:
97
+ os.kill(pid, 0)
98
+ except OSError:
99
+ return False
100
+ return True
101
+
102
+
103
+ def _process_command(pid: int) -> str:
104
+ try:
105
+ if sys.platform == "win32":
106
+ return ""
107
+ if sys.platform == "linux":
108
+ raw = Path(f"/proc/{pid}/cmdline").read_bytes()
109
+ return raw.replace(b"\0", b" ").decode("utf-8", "replace")
110
+ return subprocess.check_output(
111
+ ["ps", "-p", str(pid), "-o", "command="], text=True
112
+ )
113
+ except Exception:
114
+ return ""
115
+
116
+
117
+ def _looks_like_noodelapi(pid: int) -> bool:
118
+ command = _process_command(pid)
119
+ return not command or "noodelapi" in command
120
+
121
+
122
+ def _current_pid() -> int:
123
+ runtime = _read_runtime()
124
+ try:
125
+ pid = int(runtime.get("pid") or 0)
126
+ except (TypeError, ValueError):
127
+ pid = 0
128
+ if _pid_alive(pid) and _looks_like_noodelapi(pid):
129
+ return pid
130
+ try:
131
+ pid = int(pid_path().read_text(encoding="utf-8").strip())
132
+ except (OSError, ValueError):
133
+ return 0
134
+ return pid if _pid_alive(pid) and _looks_like_noodelapi(pid) else 0
135
+
136
+
137
+ def _local_host(host: str) -> str:
138
+ return "127.0.0.1" if host in ("0.0.0.0", "::", "") else host
139
+
140
+
141
+ def _health(host: str, port: int, timeout: float = 1.0) -> Optional[Dict[str, Any]]:
142
+ url = f"http://{_local_host(host)}:{port}/health"
143
+ try:
144
+ with urllib.request.urlopen(url, timeout=timeout) as response:
145
+ value = json.loads(response.read().decode("utf-8"))
146
+ return value if isinstance(value, dict) else None
147
+ except (urllib.error.URLError, OSError, ValueError):
148
+ return None
149
+
150
+
151
+ def _base_url(cfg: Dict[str, Any]) -> str:
152
+ host = _local_host(str(cfg.get("host") or "127.0.0.1"))
153
+ return f"http://{host}:{int(cfg.get('port') or 8787)}/v1"
154
+
155
+
156
+ def _print_setup(cfg: Dict[str, Any]) -> None:
157
+ print()
158
+ print("noodelAPI is configured.")
159
+ print(f"Config: {config_path()}")
160
+ print(f"Base URL: {_base_url(cfg)}")
161
+ print(f"API key: {cfg.get('api_key')}")
162
+ print(f"Models: {', '.join(MODEL_SPECS)}")
163
+ print()
164
+ print("Start the server: noodelapi start")
165
+ print("Check it: noodelapi status")
166
+
167
+
168
+ # ---------------------------------------------------------------------- commands
169
+ def cmd_setup(args: argparse.Namespace) -> int:
170
+ cfg = load_config()
171
+
172
+ cookie = normalize_cookie(args.cookie) if args.cookie else ""
173
+ if not cookie:
174
+ existing = str(cfg.get("cookie") or "")
175
+ hint = f" [{masked(existing)}]" if existing else ""
176
+ try:
177
+ value = input(f"DeepSeek ds_session_id cookie{hint}: ").strip()
178
+ except EOFError:
179
+ value = ""
180
+ cookie = normalize_cookie(value) if value else existing
181
+
182
+ token = normalize_token(args.token) if args.token else ""
183
+ if not token:
184
+ found = find_browser_tokens()
185
+ if found:
186
+ token = found[0].token
187
+ print(f"Found a DeepSeek token in {found[0].profile}.")
188
+ else:
189
+ print("No DeepSeek token found in a supported browser profile.")
190
+ try:
191
+ token = normalize_token(
192
+ getpass.getpass("Paste the userToken value from chat.deepseek.com: ")
193
+ )
194
+ except EOFError:
195
+ token = ""
196
+
197
+ if not token:
198
+ return _fail("a DeepSeek user token is required")
199
+ if len(token) < 32:
200
+ return _fail("that token looks too short; copy the full userToken value")
201
+
202
+ cfg["cookie"] = cookie
203
+ cfg["token"] = token
204
+ if not cfg.get("api_key"):
205
+ cfg["api_key"] = generate_api_key()
206
+
207
+ print("Checking credentials...")
208
+ try:
209
+ DeepSeekClient(cfg).validate()
210
+ except DeepSeekError as exc:
211
+ return _fail(f"DeepSeek rejected the credentials: {exc}")
212
+
213
+ path = save_config(cfg)
214
+ print(f"Saved {path}")
215
+ _print_setup(cfg)
216
+ return 0
217
+
218
+
219
+ def cmd_serve(args: argparse.Namespace) -> int:
220
+ cfg = load_config()
221
+ if not cfg.get("token"):
222
+ return _fail("no credentials configured; run: noodelapi setup")
223
+ host = args.host or str(cfg.get("host") or "127.0.0.1")
224
+ port = int(args.port or cfg.get("port") or 8787)
225
+ _write_runtime(os.getpid(), host, port)
226
+ pid_path().parent.mkdir(parents=True, exist_ok=True)
227
+ pid_path().write_text(str(os.getpid()) + "\n", encoding="utf-8")
228
+ try:
229
+ return serve(host, port)
230
+ finally:
231
+ _remove_runtime()
232
+
233
+
234
+ def cmd_start(args: argparse.Namespace) -> int:
235
+ cfg = load_config()
236
+ if not cfg.get("token"):
237
+ return _fail("no credentials configured; run: noodelapi setup")
238
+
239
+ host = args.host or str(cfg.get("host") or "127.0.0.1")
240
+ port = int(args.port or cfg.get("port") or 8787)
241
+
242
+ existing = _current_pid()
243
+ if existing:
244
+ print(f"noodelAPI is already running (pid {existing}).")
245
+ print(f"Base URL: {_base_url({**cfg, 'host': host, 'port': port})}")
246
+ return 0
247
+
248
+ if args.foreground:
249
+ return cmd_serve(argparse.Namespace(host=host, port=port))
250
+
251
+ path = log_path()
252
+ path.parent.mkdir(parents=True, exist_ok=True)
253
+ log_file = open(path, "ab", buffering=0)
254
+ command = [
255
+ sys.executable,
256
+ "-m",
257
+ "noodelapi",
258
+ "serve",
259
+ "--host",
260
+ host,
261
+ "--port",
262
+ str(port),
263
+ ]
264
+ popen_kwargs = {
265
+ "stdin": subprocess.DEVNULL,
266
+ "stdout": log_file,
267
+ "stderr": log_file,
268
+ "close_fds": True,
269
+ }
270
+ if sys.platform == "win32":
271
+ popen_kwargs["creationflags"] = (
272
+ getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
273
+ | getattr(subprocess, "DETACHED_PROCESS", 0)
274
+ )
275
+ else:
276
+ popen_kwargs["start_new_session"] = True
277
+ try:
278
+ process = subprocess.Popen(command, **popen_kwargs)
279
+ except OSError as exc:
280
+ log_file.close()
281
+ return _fail(f"could not start the server: {exc}")
282
+ finally:
283
+ try:
284
+ log_file.close()
285
+ except Exception:
286
+ pass
287
+
288
+ _write_runtime(process.pid, host, port)
289
+ pid_path().parent.mkdir(parents=True, exist_ok=True)
290
+ pid_path().write_text(str(process.pid) + "\n", encoding="utf-8")
291
+
292
+ deadline = time.time() + 10
293
+ while time.time() < deadline:
294
+ if process.poll() is not None:
295
+ _remove_runtime()
296
+ print("noodelAPI failed to start. Last log lines:", file=sys.stderr)
297
+ _tail(path, 20, stream=sys.stderr)
298
+ return 1
299
+ if _health(host, port, timeout=0.5):
300
+ print(f"noodelAPI started (pid {process.pid}).")
301
+ print(f"Base URL: {_base_url({**cfg, 'host': host, 'port': port})}")
302
+ print(f"API key: {cfg.get('api_key')}")
303
+ print(f"Logs: {path}")
304
+ return 0
305
+ time.sleep(0.2)
306
+
307
+ print(f"noodelAPI is starting (pid {process.pid}); it has not answered yet.")
308
+ print(f"Logs: {path}")
309
+ return 0
310
+
311
+
312
+ def cmd_stop(args: argparse.Namespace) -> int:
313
+ pid = _current_pid()
314
+ if not pid:
315
+ _remove_runtime()
316
+ print("noodelAPI is not running.")
317
+ return 0
318
+ try:
319
+ os.kill(pid, signal.SIGTERM)
320
+ except OSError as exc:
321
+ _remove_runtime()
322
+ return _fail(f"could not stop pid {pid}: {exc}")
323
+
324
+ deadline = time.time() + 8
325
+ while time.time() < deadline:
326
+ if not _pid_alive(pid):
327
+ _remove_runtime()
328
+ print(f"noodelAPI stopped (pid {pid}).")
329
+ return 0
330
+ time.sleep(0.2)
331
+
332
+ kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM)
333
+ try:
334
+ os.kill(pid, kill_signal)
335
+ except OSError:
336
+ pass
337
+ _remove_runtime()
338
+ print(f"noodelAPI killed (pid {pid}).")
339
+ return 0
340
+
341
+
342
+ def cmd_status(args: argparse.Namespace) -> int:
343
+ cfg = load_config()
344
+ runtime = _read_runtime()
345
+ host = str(runtime.get("host") or cfg.get("host") or "127.0.0.1")
346
+ port = int(runtime.get("port") or cfg.get("port") or 8787)
347
+ pid = _current_pid()
348
+ health = _health(host, port)
349
+
350
+ if not pid and not health:
351
+ print("noodelAPI is not running.")
352
+ return 1
353
+ print("noodelAPI is running." if health else "noodelAPI process is running but not answering.")
354
+ if pid:
355
+ print(f"PID: {pid}")
356
+ print(f"Base URL: http://{_local_host(host)}:{port}/v1")
357
+ print(f"Config: {config_path()}")
358
+ print(f"Logs: {log_path()}")
359
+ if health:
360
+ print(f"Version: {health.get('version')}")
361
+ return 0
362
+
363
+
364
+ def _tail(path: Path, lines: int, stream: Any = sys.stdout) -> None:
365
+ try:
366
+ content = path.read_text(encoding="utf-8", errors="replace").splitlines()
367
+ except OSError:
368
+ print(f"No log file at {path}", file=stream)
369
+ return
370
+ for line in content[-lines:]:
371
+ print(line, file=stream)
372
+
373
+
374
+ def cmd_logs(args: argparse.Namespace) -> int:
375
+ path = log_path()
376
+ if args.follow:
377
+ path.parent.mkdir(parents=True, exist_ok=True)
378
+ path.touch(exist_ok=True)
379
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
380
+ content = handle.read().splitlines()
381
+ for line in content[-args.lines :]:
382
+ print(line)
383
+ try:
384
+ while True:
385
+ line = handle.readline()
386
+ if line:
387
+ print(line, end="")
388
+ else:
389
+ time.sleep(0.4)
390
+ except KeyboardInterrupt:
391
+ return 0
392
+ _tail(path, args.lines)
393
+ return 0
394
+
395
+
396
+ def cmd_check(args: argparse.Namespace) -> int:
397
+ cfg = load_config()
398
+ if not cfg.get("token"):
399
+ return _fail("no credentials configured; run: noodelapi setup")
400
+ print(f"Config: {config_path()}")
401
+ print(f"Cookie: {masked(str(cfg.get('cookie') or '')) or '(not set)'}")
402
+ print(f"Token: {masked(str(cfg.get('token') or ''))}")
403
+ try:
404
+ data = DeepSeekClient(cfg).validate()
405
+ except DeepSeekError as exc:
406
+ return _fail(f"DeepSeek rejected the credentials: {exc}")
407
+ print("Credentials: ok")
408
+ if isinstance(data, dict):
409
+ print(f"Muted: {bool(data.get('is_muted'))}")
410
+ return 0
411
+
412
+
413
+ def cmd_config(args: argparse.Namespace) -> int:
414
+ cfg = load_config()
415
+ shown = dict(cfg)
416
+ shown["cookie"] = masked(str(cfg.get("cookie") or ""))
417
+ shown["token"] = masked(str(cfg.get("token") or ""))
418
+ shown["api_key"] = masked(str(cfg.get("api_key") or ""))
419
+ print(f"# {config_path()}")
420
+ print(json.dumps(shown, indent=2, sort_keys=True))
421
+ return 0
422
+
423
+
424
+ def cmd_models(args: argparse.Namespace) -> int:
425
+ cfg = load_config()
426
+ print(f"Base URL: {_base_url(cfg)}")
427
+ for model_id, spec in MODEL_SPECS.items():
428
+ print(f"{model_id:34} {spec['description']}")
429
+ return 0
430
+
431
+
432
+ # ---------------------------------------------------------------------- parser
433
+ def build_parser() -> argparse.ArgumentParser:
434
+ parser = argparse.ArgumentParser(
435
+ prog="noodelapi",
436
+ description="Local OpenAI-compatible API for chat.deepseek.com.",
437
+ )
438
+ parser.add_argument("--version", action="version", version=f"noodelapi {__version__}")
439
+ sub = parser.add_subparsers(dest="command")
440
+
441
+ setup = sub.add_parser("setup", aliases=["login"], help="save your DeepSeek session")
442
+ setup.add_argument("--cookie", help="ds_session_id cookie value")
443
+ setup.add_argument("--token", help="userToken value (normally found automatically)")
444
+ setup.set_defaults(func=cmd_setup)
445
+
446
+ start = sub.add_parser("start", help="start the server in the background")
447
+ start.add_argument("-f", "--foreground", action="store_true", help="run in this terminal")
448
+ start.add_argument("--host", help="bind address")
449
+ start.add_argument("--port", type=int, help="bind port")
450
+ start.set_defaults(func=cmd_start)
451
+
452
+ serve_cmd = sub.add_parser("serve", help="run the server in the foreground")
453
+ serve_cmd.add_argument("--host", help="bind address")
454
+ serve_cmd.add_argument("--port", type=int, help="bind port")
455
+ serve_cmd.set_defaults(func=cmd_serve)
456
+
457
+ stop = sub.add_parser("stop", help="stop the background server")
458
+ stop.set_defaults(func=cmd_stop)
459
+
460
+ status = sub.add_parser("status", help="show server status")
461
+ status.set_defaults(func=cmd_status)
462
+
463
+ logs = sub.add_parser("logs", help="show server logs")
464
+ logs.add_argument("-n", "--lines", type=int, default=50)
465
+ logs.add_argument("-f", "--follow", action="store_true")
466
+ logs.set_defaults(func=cmd_logs)
467
+
468
+ check = sub.add_parser("check", help="verify the saved credentials")
469
+ check.set_defaults(func=cmd_check)
470
+
471
+ config = sub.add_parser("config", help="show configuration")
472
+ config.set_defaults(func=cmd_config)
473
+
474
+ models = sub.add_parser("models", help="list model names")
475
+ models.set_defaults(func=cmd_models)
476
+
477
+ return parser
478
+
479
+
480
+ def main(argv: Optional[list] = None) -> int:
481
+ parser = build_parser()
482
+ args = parser.parse_args(argv)
483
+ if not getattr(args, "command", None):
484
+ parser.print_help()
485
+ return 0
486
+ return int(args.func(args))
487
+
488
+
489
+ if __name__ == "__main__":
490
+ raise SystemExit(main())