liwenjson 1.5.2__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.
liwenjson/__init__.py ADDED
@@ -0,0 +1,67 @@
1
+ """liwenjson — the MoonBit JSON engine as a Python client.
2
+
3
+ The engine ships as a single native binary; this package speaks the versioned
4
+ stdio protocol (`liwenjson serve`) rather than reimplementing JSON
5
+ repair. That keeps one implementation of the semantics and gives Python the
6
+ same decision fields the CLI and the MoonBit library produce.
7
+
8
+ from liwenjson import Client
9
+
10
+ with Client() as jm:
11
+ plan = jm.analyze(model_output, profile="agent", schema_json=tool["inputSchema"])
12
+ if plan["executable"]:
13
+ # `value` is the parsed document; `text` is its rendered form and is
14
+ # only present when the caller asks for it (`with_text`), so reading
15
+ # `plan["text"]` raised `KeyError` on the default path.
16
+ args = plan["value"]
17
+
18
+ `find_binary()` resolves the engine: `LIWENJSON_BIN`, then `PATH`, then a
19
+ bundled `liwenjson/bin/`, then the development build in this repository.
20
+ """
21
+
22
+ from pathlib import Path
23
+
24
+ from .client import Client, LIWENJSONError, find_binary, repair, analyze, validate
25
+
26
+ __all__ = [
27
+ "Client",
28
+ "LIWENJSONError",
29
+ "find_binary",
30
+ "repair",
31
+ "analyze",
32
+ "validate",
33
+ "__version__",
34
+ ]
35
+
36
+ def _declared_version() -> str:
37
+ """The version this package declares.
38
+
39
+ `pyproject.toml` is the declaration, so it is read directly. When the
40
+ package is installed rather than used from a source checkout, the
41
+ installed metadata is the authority instead. A literal here went stale
42
+ once already -- it said 1.1.0 while the package was 1.1.1 -- and nothing
43
+ noticed, because the tests pinned the same stale literal.
44
+ """
45
+ import re
46
+
47
+ pyproject = Path(__file__).resolve().parents[1] / "pyproject.toml"
48
+ try:
49
+ text = pyproject.read_text(encoding="utf-8")
50
+ except OSError:
51
+ text = ""
52
+ match = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)
53
+ if match:
54
+ return match.group(1)
55
+ from importlib.metadata import PackageNotFoundError
56
+ from importlib.metadata import version as _metadata_version
57
+
58
+ try:
59
+ return _metadata_version("liwenjson")
60
+ except PackageNotFoundError:
61
+ raise RuntimeError(
62
+ "cannot determine the liwenjson version: no pyproject.toml next to "
63
+ "the package and no installed metadata"
64
+ )
65
+
66
+
67
+ __version__ = _declared_version()
liwenjson/__main__.py ADDED
@@ -0,0 +1,38 @@
1
+ """`python -m liwenjson` — small dispatcher.
2
+
3
+ python -m liwenjson mcp # MCP stdio server (replaces the process)
4
+ python -m liwenjson http --port 8080
5
+ python -m liwenjson version
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+
12
+ from . import __version__
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> None:
16
+ args = list(sys.argv[1:] if argv is None else argv)
17
+ if not args or args[0] in ("-h", "--help", "help"):
18
+ print(__doc__)
19
+ return
20
+ command, rest = args[0], args[1:]
21
+ if command == "mcp":
22
+ from .mcp import main as mcp_main
23
+
24
+ # `mcp_main` reads sys.argv; pass the extra arguments through.
25
+ sys.argv = ["liwenjson-mcp", *rest]
26
+ mcp_main()
27
+ elif command == "http":
28
+ from .http import main as http_main
29
+
30
+ http_main(rest)
31
+ elif command in ("version", "--version", "-V"):
32
+ print(f"liwenjson {__version__}")
33
+ else:
34
+ raise SystemExit(f"unknown command `{command}`; use mcp, http or version")
35
+
36
+
37
+ if __name__ == "__main__":
38
+ main()
Binary file
Binary file
Binary file
liwenjson/client.py ADDED
@@ -0,0 +1,477 @@
1
+ """A thin, dependency-free client for the `liwenjson serve` protocol.
2
+
3
+ The server is a child process speaking one JSON object per line on stdin and
4
+ stdout. A reader thread turns stdout into a queue so a request can time out
5
+ without depending on `select` and buffered pipes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import queue
13
+ import shutil
14
+ import subprocess
15
+ import threading
16
+ import time
17
+ from pathlib import Path
18
+ from typing import Any, Iterable
19
+
20
+ __all__ = ["Client", "LIWENJSONError", "find_binary", "repair", "analyze", "validate"]
21
+
22
+ _EOF = object()
23
+
24
+
25
+ class LIWENJSONError(RuntimeError):
26
+ """A structured refusal from the engine (`E010`, `E011`, `E070`, ...)."""
27
+
28
+ def __init__(self, error: dict[str, Any]) -> None:
29
+ self.code = str(error.get("code", "E000"))
30
+ self.message = str(error.get("message", ""))
31
+ self.exit_code = int(error.get("exit", 1))
32
+ self.retry_hint = error.get("retry_hint")
33
+ self.offset = error.get("offset")
34
+ super().__init__(f"{self.code} {self.message}")
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ out: dict[str, Any] = {"code": self.code, "message": self.message, "exit": self.exit_code}
38
+ if self.retry_hint is not None:
39
+ out["retry_hint"] = self.retry_hint
40
+ if self.offset is not None:
41
+ out["offset"] = self.offset
42
+ return out
43
+
44
+
45
+ def _platform_key() -> str | None:
46
+ """The release platform this interpreter can run, or None.
47
+
48
+ The wheel carries one binary per release platform, so the choice is made
49
+ here rather than by installing four different wheels: one wheel works on
50
+ every platform the release supports, and the cost is a few unused
51
+ megabytes.
52
+
53
+ The keys are the release asset names with the `liwenjson-` prefix removed,
54
+ so a wheel and a release can be compared by eye. There is deliberately no
55
+ Intel-macOS key: the MoonBit toolchain publishes no `darwin-x86_64`
56
+ target, so there is no binary to name.
57
+ """
58
+
59
+ import platform as _platform
60
+ import sys
61
+
62
+ machine = (_platform.machine() or "").lower()
63
+ if sys.platform == "darwin":
64
+ return "macos-arm64" if machine in ("arm64", "aarch64") else None
65
+ if sys.platform.startswith("linux"):
66
+ if machine in ("x86_64", "amd64"):
67
+ return "linux-x86_64"
68
+ if machine in ("aarch64", "arm64"):
69
+ return "linux-arm64"
70
+ return None
71
+ if sys.platform in ("win32", "cygwin"):
72
+ return "windows-x86_64"
73
+ return None
74
+
75
+
76
+ def _make_executable(path: Path) -> None:
77
+ """The executable bit survives a wheel install on most platforms, not all.
78
+
79
+ A binary that is present but not executable turns every call into a
80
+ `PermissionError` that names a file the user did not install by hand, so
81
+ the bit is restored once, quietly, before the path is returned.
82
+ """
83
+
84
+ try:
85
+ mode = path.stat().st_mode
86
+ if not mode & 0o111:
87
+ path.chmod(mode | 0o755)
88
+ except OSError:
89
+ pass
90
+
91
+
92
+ def find_binary() -> str:
93
+ """Locate the engine.
94
+
95
+ Order: `LIWENJSON_BIN`, `PATH`, the binary this wheel carries for this
96
+ platform, a binary placed directly in `bin/`, then the development build
97
+ inside this repository.
98
+
99
+ An explicit path or a `PATH` entry wins over the bundled binary on purpose:
100
+ a caller who has installed a newer CLI should not silently get whichever
101
+ engine happened to be current when the Python package was built.
102
+ """
103
+
104
+ env = os.environ.get("LIWENJSON_BIN")
105
+ if env:
106
+ return env
107
+ found = shutil.which("liwenjson")
108
+ if found:
109
+ return found
110
+ here = Path(__file__).resolve().parent
111
+ key = _platform_key()
112
+ if key is not None:
113
+ for name in ("liwenjson", "liwenjson.exe"):
114
+ candidate = here / "bin" / key / name
115
+ if candidate.is_file():
116
+ _make_executable(candidate)
117
+ return str(candidate)
118
+ for name in ("liwenjson", "liwenjson.exe"):
119
+ candidate = here / "bin" / name
120
+ if candidate.is_file():
121
+ _make_executable(candidate)
122
+ return str(candidate)
123
+ # Development checkout: code/python/liwenjson/client.py -> code/
124
+ code_dir = here.parents[1]
125
+ for target in ("native",):
126
+ candidate = (
127
+ code_dir
128
+ / "_build"
129
+ / target
130
+ / "release"
131
+ / "build"
132
+ / "cmd"
133
+ / "liwenjson"
134
+ / "liwenjson.exe"
135
+ )
136
+ if candidate.is_file():
137
+ return str(candidate)
138
+ raise FileNotFoundError(_not_found_message(here, key))
139
+
140
+
141
+ def _not_found_message(here: Path, key: str | None) -> str:
142
+ """Say what is missing in terms of what this installation actually has.
143
+
144
+ Three different situations used to produce the same sentence, and only one
145
+ of them was fixed by setting `LIWENJSON_BIN`:
146
+
147
+ * a source checkout with no build -- "build it";
148
+ * a wheel installed for a platform the release does not cover, such as
149
+ Intel macOS -- "there is no binary for this platform", which no amount
150
+ of `pip install` will change;
151
+ * a wheel whose bundled directory was stripped by a repackager.
152
+ """
153
+
154
+ import platform as _platform
155
+ import sys
156
+
157
+ bundled = sorted(
158
+ p.name for p in (here / "bin").iterdir() if p.is_dir()
159
+ ) if (here / "bin").is_dir() else []
160
+ where = f"{_platform.system()} {_platform.machine() or 'unknown'} ({sys.platform})"
161
+ if bundled and key is None:
162
+ return (
163
+ f"the liwenjson engine is not available for {where}: the package "
164
+ f"carries {', '.join(bundled)}. Set LIWENJSON_BIN to a binary built "
165
+ "for this platform, or build one with "
166
+ "`moon build cmd/liwenjson --target native --release`."
167
+ )
168
+ return (
169
+ "the liwenjson engine was not found. Reinstall `liwenjson` from "
170
+ "PyPI to get the bundled binary, or set LIWENJSON_BIN, put `liwenjson` on "
171
+ "PATH, or build it with `moon build cmd/liwenjson --target native --release`"
172
+ )
173
+
174
+
175
+ class Client:
176
+ """A long-lived `liwenjson serve` process.
177
+
178
+ Use it as a context manager, or call `close()`. One client is not shared
179
+ between threads; a lock serialises requests so a caller that does share one
180
+ still gets correct `id` matching.
181
+ """
182
+
183
+ def __init__(
184
+ self,
185
+ binary: str | None = None,
186
+ *,
187
+ args: Iterable[str] = (),
188
+ timeout: float = 30.0,
189
+ stderr: int | None = None,
190
+ ) -> None:
191
+ self.binary = binary or find_binary()
192
+ self.timeout = timeout
193
+ self._lock = threading.Lock()
194
+ self._next_id = 0
195
+ self._responses: "queue.Queue[Any]" = queue.Queue()
196
+ self._stderr_lines: list[str] = []
197
+ # `stderr` defaults to a pipe rather than DEVNULL. The engine writes
198
+ # its diagnostics there, and `stderr=DEVNULL` meant that every error
199
+ # message the client raised about a dead or misbehaving process ended
200
+ # with an empty `stderr:` field -- the one piece of evidence that says
201
+ # *why* the engine exited was thrown away by default. Pass
202
+ # `stderr=subprocess.DEVNULL` to opt out.
203
+ self.proc = subprocess.Popen(
204
+ [self.binary, "serve", *args],
205
+ stdin=subprocess.PIPE,
206
+ stdout=subprocess.PIPE,
207
+ stderr=subprocess.PIPE if stderr is None else stderr,
208
+ text=True,
209
+ encoding="utf-8",
210
+ bufsize=1,
211
+ )
212
+ self._reader = threading.Thread(target=self._read_stdout, daemon=True)
213
+ self._reader.start()
214
+ if stderr is None:
215
+ self._err_reader = threading.Thread(target=self._read_stderr, daemon=True)
216
+ self._err_reader.start()
217
+
218
+ # -- plumbing ---------------------------------------------------------
219
+
220
+ def _read_stdout(self) -> None:
221
+ assert self.proc.stdout is not None
222
+ for line in self.proc.stdout:
223
+ line = line.strip()
224
+ if not line:
225
+ continue
226
+ try:
227
+ self._responses.put(json.loads(line))
228
+ except json.JSONDecodeError:
229
+ self._responses.put({"ok": False, "error": {"code": "E030", "message": line}})
230
+ self._responses.put(_EOF)
231
+
232
+ def _read_stderr(self) -> None:
233
+ assert self.proc.stderr is not None
234
+ for line in self.proc.stderr:
235
+ self._stderr_lines.append(line.rstrip())
236
+ if len(self._stderr_lines) > 100:
237
+ del self._stderr_lines[:50]
238
+
239
+ def _resync(self) -> None:
240
+ """Drop every buffered answer.
241
+
242
+ The reader thread is left alone: starting a second one would let two
243
+ threads feed the same queue, and the answers would interleave. What
244
+ matters is that a *late* answer cannot be mistaken for the next
245
+ request's answer, which `request` handles by matching ids.
246
+ """
247
+ while True:
248
+ try:
249
+ self._responses.get_nowait()
250
+ except queue.Empty:
251
+ break
252
+
253
+ def request(self, method: str, **params: Any) -> Any:
254
+ """Send one request and return its `result`, or raise `LIWENJSONError`."""
255
+ with self._lock:
256
+ if self.proc.poll() is not None:
257
+ raise RuntimeError(
258
+ f"liwenjson exited with {self.proc.returncode}; "
259
+ f"stderr: {' | '.join(self._stderr_lines[-3:])}"
260
+ )
261
+ self._next_id += 1
262
+ request_id = self._next_id
263
+ payload = {"id": request_id, "method": method}
264
+ if params:
265
+ payload["params"] = params
266
+ assert self.proc.stdin is not None
267
+ self.proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
268
+ self.proc.stdin.flush()
269
+ # Wait for *this* request's answer, discarding anything else.
270
+ #
271
+ # A timed-out request leaves its answer in flight: the reader
272
+ # thread delivers it after the caller has given up, and it then
273
+ # sits at the head of the queue. Reading it as the next request's
274
+ # answer either raised a confusing id mismatch or, when the ids
275
+ # happened to line up, returned the wrong result. Matching on the
276
+ # id is what makes a late answer harmless.
277
+ deadline = time.monotonic() + self.timeout
278
+ while True:
279
+ remaining = deadline - time.monotonic()
280
+ if remaining <= 0:
281
+ self._resync()
282
+ raise TimeoutError(
283
+ f"liwenjson did not answer `{method}` in {self.timeout}s"
284
+ )
285
+ try:
286
+ response = self._responses.get(timeout=remaining)
287
+ except queue.Empty:
288
+ self._resync()
289
+ raise TimeoutError(
290
+ f"liwenjson did not answer `{method}` in {self.timeout}s"
291
+ )
292
+ if response is _EOF:
293
+ raise RuntimeError(
294
+ f"liwenjson closed the stream; "
295
+ f"stderr: {' | '.join(self._stderr_lines[-3:])}"
296
+ )
297
+ if response.get("id") != request_id:
298
+ # An answer to an abandoned request. Drop it and keep
299
+ # waiting for the one this call is owed.
300
+ continue
301
+ if response.get("ok"):
302
+ return response["result"]
303
+ raise LIWENJSONError(response.get("error") or {})
304
+
305
+ # -- methods ----------------------------------------------------------
306
+
307
+ def hello(self) -> dict[str, Any]:
308
+ """Handshake: name, engine version, registry version, protocol, capabilities."""
309
+ return self.request("hello")
310
+
311
+ def repair(
312
+ self,
313
+ text: str,
314
+ *,
315
+ profile: str | None = None,
316
+ schema: str | None = None,
317
+ schema_json: Any = None,
318
+ skip_prose: bool | None = None,
319
+ max_loss: str | None = None,
320
+ ) -> dict[str, Any]:
321
+ return self.request("repair", **self._params(text, profile, schema, schema_json, skip_prose, max_loss))
322
+
323
+ def analyze(
324
+ self,
325
+ text: str,
326
+ *,
327
+ profile: str | None = None,
328
+ schema: str | None = None,
329
+ schema_json: Any = None,
330
+ skip_prose: bool | None = None,
331
+ max_loss: str | None = None,
332
+ with_text: bool | None = None,
333
+ ) -> dict[str, Any]:
334
+ """The decision plan: `decision`, `executable`, `exactness`, `retry`, ...
335
+
336
+ The plan carries `value`, the parsed document. `text`, its rendered form,
337
+ is only present when `with_text=True` is asked for, because sending both
338
+ puts two copies of the document on the wire.
339
+ """
340
+ params = self._params(text, profile, schema, schema_json, skip_prose, max_loss)
341
+ if with_text is not None:
342
+ params["with_text"] = with_text
343
+ return self.request("analyze", **params)
344
+
345
+ def validate(
346
+ self,
347
+ text: str,
348
+ *,
349
+ schema: str | None = None,
350
+ schema_json: Any = None,
351
+ ) -> dict[str, Any]:
352
+ params: dict[str, Any] = {"text": text}
353
+ if schema is not None:
354
+ params["schema"] = schema
355
+ if schema_json is not None:
356
+ params["schema_json"] = schema_json
357
+ return self.request("validate", **params)
358
+
359
+ def readiness(
360
+ self,
361
+ text: str,
362
+ *,
363
+ schema: str | None = None,
364
+ schema_json: Any = None,
365
+ step: int | None = None,
366
+ ) -> dict[str, Any]:
367
+ params: dict[str, Any] = {"text": text}
368
+ if schema is not None:
369
+ params["schema"] = schema
370
+ if schema_json is not None:
371
+ params["schema_json"] = schema_json
372
+ if step is not None:
373
+ params["step"] = step
374
+ return self.request("readiness", **params)
375
+
376
+ def watch_start(
377
+ self,
378
+ *,
379
+ schema: str | None = None,
380
+ schema_json: Any = None,
381
+ profile: str | None = None,
382
+ ) -> dict[str, Any]:
383
+ params: dict[str, Any] = {}
384
+ if schema is not None:
385
+ params["schema"] = schema
386
+ if schema_json is not None:
387
+ params["schema_json"] = schema_json
388
+ if profile is not None:
389
+ params["profile"] = profile
390
+ return self.request("watch.start", **params)
391
+
392
+ def watch_feed(self, chunk: str) -> dict[str, Any]:
393
+ return self.request("watch.feed", chunk=chunk)
394
+
395
+ def watch_finish(self) -> dict[str, Any]:
396
+ return self.request("watch.finish")
397
+
398
+ def llm_open(self, provider: str = "anthropic") -> dict[str, Any]:
399
+ return self.request("llm.open", provider=provider)
400
+
401
+ def llm_feed(self, event: str) -> dict[str, Any]:
402
+ return self.request("llm.feed", event=event)
403
+
404
+ def llm_close(self) -> dict[str, Any]:
405
+ return self.request("llm.close")
406
+
407
+ @staticmethod
408
+ def _params(
409
+ text: str,
410
+ profile: str | None,
411
+ schema: str | None,
412
+ schema_json: Any,
413
+ skip_prose: bool | None,
414
+ max_loss: str | None,
415
+ ) -> dict[str, Any]:
416
+ params: dict[str, Any] = {"text": text}
417
+ if profile is not None:
418
+ params["profile"] = profile
419
+ if schema is not None:
420
+ params["schema"] = schema
421
+ if schema_json is not None:
422
+ params["schema_json"] = schema_json
423
+ if skip_prose is not None:
424
+ params["skip_prose"] = skip_prose
425
+ if max_loss is not None:
426
+ params["max_loss"] = max_loss
427
+ return params
428
+
429
+ # -- lifecycle --------------------------------------------------------
430
+
431
+ def close(self) -> None:
432
+ if self.proc.poll() is None:
433
+ try:
434
+ self.request("shutdown")
435
+ except Exception:
436
+ pass
437
+ try:
438
+ self.proc.wait(timeout=5)
439
+ except subprocess.TimeoutExpired:
440
+ self.proc.kill()
441
+ self.proc.wait(timeout=5)
442
+ for stream in (self.proc.stdin, self.proc.stdout, self.proc.stderr):
443
+ try:
444
+ if stream is not None:
445
+ stream.close()
446
+ except Exception:
447
+ pass
448
+
449
+ def __enter__(self) -> "Client":
450
+ return self
451
+
452
+ def __exit__(self, *_exc: object) -> None:
453
+ self.close()
454
+
455
+ def __del__(self) -> None: # pragma: no cover - best effort
456
+ try:
457
+ self.close()
458
+ except Exception:
459
+ pass
460
+
461
+
462
+ def repair(text: str, **kwargs: Any) -> dict[str, Any]:
463
+ """One-shot repair. Reuse a `Client` in a loop; this spawns a process."""
464
+ with Client() as client:
465
+ return client.repair(text, **kwargs)
466
+
467
+
468
+ def analyze(text: str, **kwargs: Any) -> dict[str, Any]:
469
+ """One-shot analyze. Reuse a `Client` in a loop; this spawns a process."""
470
+ with Client() as client:
471
+ return client.analyze(text, **kwargs)
472
+
473
+
474
+ def validate(text: str, **kwargs: Any) -> dict[str, Any]:
475
+ """One-shot validate. Reuse a `Client` in a loop; this spawns a process."""
476
+ with Client() as client:
477
+ return client.validate(text, **kwargs)