orivane-cli 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.
@@ -0,0 +1 @@
1
+ """Orivane's local developer CLI."""
@@ -0,0 +1,3 @@
1
+ from ._main import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,76 @@
1
+ """Small command operations; application output is separate from telemetry."""
2
+
3
+ import asyncio
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from ._config import load_config
8
+ from ._loader import load_runner, project_path
9
+ from ._trace import capture, format_spans
10
+
11
+ _TEMPLATES = {
12
+ "orivane.toml": 'schema_version = 1\n\n[app]\nfactory = "app:create_runner"\n',
13
+ ".gitignore": ".env\n.venv/\n__pycache__/\n*.pyc\n",
14
+ "app.py": """from collections.abc import Awaitable, Callable
15
+
16
+ from orivane_core import RunRequest
17
+ from orivane_pydantic import PydanticAgentBackend
18
+ from pydantic_ai.models.test import TestModel
19
+
20
+
21
+ def create_runner() -> Callable[[str], Awaitable[object]]:
22
+ # TestModel is an offline starter only.
23
+ # Replace it with a real PydanticAI Model in your application when ready.
24
+ backend: PydanticAgentBackend[None, str] = PydanticAgentBackend(
25
+ TestModel(custom_output_text="offline starter"), output_type=str
26
+ )
27
+
28
+ async def run(prompt: str) -> object:
29
+ result = await backend.run(RunRequest(prompt, None))
30
+ return result.output
31
+
32
+ return run
33
+ """,
34
+ }
35
+
36
+
37
+ class _InitError(ValueError):
38
+ pass
39
+
40
+
41
+ def initialize(root: Path) -> None:
42
+ if root.exists() and (not root.is_dir() or any(root.iterdir())):
43
+ raise _InitError("initialization requires a new or empty directory")
44
+ root.mkdir(parents=True, exist_ok=True)
45
+ created: list[Path] = []
46
+ try:
47
+ for name, content in _TEMPLATES.items():
48
+ path = root / name
49
+ with path.open("x", encoding="utf-8", newline="\n") as target:
50
+ created.append(path)
51
+ target.write(content)
52
+ except OSError:
53
+ # Only remove files exclusively created by this invocation, never user files.
54
+ for path in created:
55
+ path.unlink()
56
+ raise
57
+
58
+
59
+ async def _run(root: Path, factory: tuple[str, str], prompt: str) -> object:
60
+ with project_path(root.resolve()):
61
+ runner = load_runner(*factory)
62
+ return await runner(prompt)
63
+
64
+
65
+ def execute(root: Path, *, tracing: bool) -> None:
66
+ factory = load_config(root)
67
+ prompt = sys.stdin.read()
68
+ if tracing:
69
+ with capture() as exporter:
70
+ result = asyncio.run(_run(root, factory, prompt))
71
+ print(str(result))
72
+ print("TRACE")
73
+ print(format_spans(exporter.get_finished_spans()))
74
+ else:
75
+ result = asyncio.run(_run(root, factory, prompt))
76
+ print(str(result))
orivane_cli/_config.py ADDED
@@ -0,0 +1,35 @@
1
+ """Static, strict TOML validation; never imports application code."""
2
+
3
+ import keyword
4
+ import tomllib
5
+ from pathlib import Path
6
+
7
+
8
+ class _ConfigError(ValueError):
9
+ """Contains only messages authored by the CLI, never input contents."""
10
+
11
+
12
+ def load_config(root: Path) -> tuple[str, str]:
13
+ try:
14
+ with (root / "orivane.toml").open("rb") as source:
15
+ data = tomllib.load(source)
16
+ except (OSError, ValueError) as error:
17
+ raise _ConfigError("cannot read valid TOML") from error
18
+ if set(data) != {"schema_version", "app"}:
19
+ raise _ConfigError("expected only schema_version and app")
20
+ version = data["schema_version"]
21
+ if type(version) is not int or version != 1:
22
+ raise _ConfigError("unsupported schema_version")
23
+ app = data["app"]
24
+ if not isinstance(app, dict) or set(app) != {"factory"}:
25
+ raise _ConfigError("app must contain only factory")
26
+ factory = app["factory"]
27
+ if not isinstance(factory, str) or factory.count(":") != 1:
28
+ raise _ConfigError("factory must be module.path:callable_name")
29
+ module, attribute = factory.split(":")
30
+ if not all(
31
+ part.isidentifier() and not keyword.iskeyword(part)
32
+ for part in [*module.split("."), attribute]
33
+ ):
34
+ raise _ConfigError("factory must be module.path:callable_name")
35
+ return module, attribute
orivane_cli/_loader.py ADDED
@@ -0,0 +1,49 @@
1
+ """The sole dynamic application boundary; no reload system or Core-private imports."""
2
+
3
+ import importlib
4
+ import inspect
5
+ import sys
6
+ from collections.abc import Awaitable, Callable, Iterator
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ from typing import cast
10
+
11
+
12
+ class _LoadError(Exception):
13
+ def __init__(self, error_type: str) -> None:
14
+ self.error_type = error_type
15
+
16
+
17
+ @contextmanager
18
+ def project_path(root: Path) -> Iterator[None]:
19
+ original = sys.path[:]
20
+ sys.path.insert(0, str(root))
21
+ try:
22
+ yield
23
+ finally:
24
+ sys.path[:] = original
25
+
26
+
27
+ def load_runner(module: str, attribute: str) -> Callable[[str], Awaitable[object]]:
28
+ try:
29
+ factory: object = getattr(importlib.import_module(module), attribute)
30
+ if not callable(factory) or inspect.iscoroutinefunction(factory):
31
+ raise TypeError
32
+ runner: object = factory()
33
+ if inspect.iscoroutine(runner):
34
+ runner.close()
35
+ raise TypeError
36
+ if not callable(runner):
37
+ raise TypeError
38
+ except SystemExit:
39
+ raise _LoadError("SystemExit") from None
40
+ except Exception as error:
41
+ raise _LoadError(type(error).__name__) from None
42
+
43
+ async def invoke(prompt: str) -> object:
44
+ pending: object = runner(prompt)
45
+ if not inspect.isawaitable(pending):
46
+ raise TypeError
47
+ return await cast(Awaitable[object], pending)
48
+
49
+ return invoke
orivane_cli/_main.py ADDED
@@ -0,0 +1,67 @@
1
+ """argparse entry point with safe errors and stable exit codes."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ from importlib.metadata import version
7
+ from pathlib import Path
8
+ from typing import NoReturn
9
+
10
+ from ._commands import _InitError, execute, initialize
11
+ from ._config import _ConfigError, load_config
12
+ from ._loader import _LoadError
13
+ from ._trace import _ProviderConfiguredError
14
+
15
+
16
+ class _Parser(argparse.ArgumentParser):
17
+ def error(self, message: str) -> NoReturn:
18
+ # argparse's default text can echo rejected command-line values.
19
+ self.exit(2, "Invalid command usage; use --help.\n")
20
+
21
+
22
+ def main(argv: list[str] | None = None) -> int:
23
+ parser = _Parser(prog="orivane", description="Local Orivane developer commands")
24
+ parser.add_argument("--version", action="version", version=version("orivane-cli"))
25
+ commands = parser.add_subparsers(dest="command", required=True)
26
+ for name, help_text in (
27
+ ("init", "Create an offline starter in a new or empty directory"),
28
+ ("validate", "Statically validate TOML without importing application code"),
29
+ ("run", "Run an application once with the entire stdin as its prompt"),
30
+ ("trace", "Run once and display local allowlisted spans"),
31
+ ):
32
+ command = commands.add_parser(name, help=help_text, description=help_text)
33
+ command.add_argument("path", nargs="?", default=".")
34
+ args = parser.parse_args(argv)
35
+ root = Path(args.path)
36
+ try:
37
+ if args.command == "init":
38
+ try:
39
+ initialize(root)
40
+ except OSError as error:
41
+ print("Initialization failed: " + type(error).__name__, file=sys.stderr)
42
+ return 2
43
+ print("INITIALIZED")
44
+ elif args.command == "validate":
45
+ load_config(root)
46
+ print("VALID")
47
+ else:
48
+ execute(root, tracing=args.command == "trace")
49
+ return 0
50
+ except (_ConfigError, _InitError) as error:
51
+ print("Invalid configuration or usage: " + error.args[0], file=sys.stderr)
52
+ return 2
53
+ except _LoadError as error:
54
+ print("Application load failed: " + error.error_type, file=sys.stderr)
55
+ return 1
56
+ except _ProviderConfiguredError:
57
+ print("Trace provider already configured", file=sys.stderr)
58
+ return 1
59
+ except (KeyboardInterrupt, asyncio.CancelledError):
60
+ print("Interrupted", file=sys.stderr)
61
+ return 130
62
+ except SystemExit:
63
+ print("Run failed: SystemExit", file=sys.stderr)
64
+ return 1
65
+ except Exception as error:
66
+ print("Run failed: " + type(error).__name__, file=sys.stderr)
67
+ return 1
orivane_cli/_trace.py ADDED
@@ -0,0 +1,69 @@
1
+ """One-process, local SDK ownership and allowlisted structural formatting."""
2
+
3
+ import json
4
+ from collections.abc import Iterator, Sequence
5
+ from contextlib import contextmanager
6
+
7
+ from opentelemetry import trace
8
+ from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
9
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
10
+ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
11
+
12
+ _ATTRIBUTES = frozenset(
13
+ {
14
+ "orivane.component",
15
+ "orivane.operation",
16
+ "orivane.node.name",
17
+ "orivane.node.kind",
18
+ "orivane.backend.id",
19
+ "orivane.outcome",
20
+ "gen_ai.operation.name",
21
+ }
22
+ )
23
+
24
+
25
+ class _ProviderConfiguredError(Exception):
26
+ pass
27
+
28
+
29
+ @contextmanager
30
+ def capture() -> Iterator[InMemorySpanExporter]:
31
+ if not isinstance(trace.get_tracer_provider(), trace.ProxyTracerProvider):
32
+ raise _ProviderConfiguredError
33
+ provider = TracerProvider()
34
+ exporter = InMemorySpanExporter()
35
+ try:
36
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
37
+ trace.set_tracer_provider(provider)
38
+ yield exporter
39
+ finally:
40
+ try:
41
+ provider.force_flush()
42
+ finally:
43
+ provider.shutdown()
44
+
45
+
46
+ def format_spans(spans: Sequence[ReadableSpan]) -> str:
47
+ if not spans:
48
+ return "(no spans)"
49
+ rows = []
50
+ for span in sorted(spans, key=lambda item: (item.start_time or 0, item.name)):
51
+ context = span.context
52
+ rows.append(
53
+ json.dumps(
54
+ {
55
+ "name": span.name,
56
+ "trace_id": format(context.trace_id, "032x") if context else None,
57
+ "span_id": format(context.span_id, "016x") if context else None,
58
+ "parent_span_id": format(span.parent.span_id, "016x") if span.parent else None,
59
+ "status": span.status.status_code.name,
60
+ "attributes": {
61
+ key: value
62
+ for key, value in (span.attributes or {}).items()
63
+ if key in _ATTRIBUTES
64
+ },
65
+ },
66
+ sort_keys=True,
67
+ )
68
+ )
69
+ return "\n".join(rows)
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.5
2
+ Name: orivane-cli
3
+ Version: 0.1.0
4
+ Summary: Local developer CLI for Orivane
5
+ Project-URL: Repository, https://github.com/luyf579/orivane
6
+ Project-URL: Documentation, https://github.com/luyf579/orivane/tree/main/docs
7
+ Project-URL: Issues, https://github.com/luyf579/orivane/issues
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,cli,opentelemetry
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: opentelemetry-sdk<2,>=1.44
17
+ Requires-Dist: orivane-backend-pydantic==0.1.0
18
+ Requires-Dist: orivane-core==0.1.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # orivane-cli
22
+
23
+ The local Orivane CLI, version 0.1.0, under the MIT license. The source is public;
24
+ this is an early release and does not claim production readiness.
25
+
26
+ The `orivane` command provides deterministic offline init, static TOML
27
+ validate, stdin run and local structural trace. It uses a synchronous application
28
+ factory returning an async runner. No provider schema, persistent sessions, remote
29
+ exporter or automatic environment-file loading is included. Python 3.11/3.12 are
30
+ tested. This distribution has a command interface, not an intended typed library API;
31
+ it does not advertise PEP 561 support.
32
+
33
+ Install the CLI and create an offline starter project in PowerShell:
34
+
35
+ ```powershell
36
+ pipx install orivane-cli
37
+ orivane init demo
38
+ cd demo
39
+ orivane validate .
40
+ "hello" | orivane run .
41
+ "hello" | orivane trace .
42
+ ```
43
+
44
+ The generated starter uses offline TestModel and needs no API key. Installing the
45
+ CLI resolves Core and the backend at exactly 0.1.0. Alternatively, use
46
+ `pip install orivane-cli` inside a Python environment. For local development, use
47
+ `uv sync --locked --all-packages` from the repository or locally built wheels.
48
+
49
+ [Repository and documentation](https://github.com/luyf579/orivane) are public.
50
+
51
+ ## License
52
+
53
+ MIT. The included LICENSE is an exact copy of the repository root license.
@@ -0,0 +1,12 @@
1
+ orivane_cli/__init__.py,sha256=THiXg7nENuvKUQRn9KYKanuRggvFs09NyUQhJEsACGw,37
2
+ orivane_cli/__main__.py,sha256=VLqdG7fSvpLPDDXmeYtXBUmtt92f1aN1davbGhpo34Q,50
3
+ orivane_cli/_commands.py,sha256=2MOIS3Wk3kx4sAXysuf9Xte2z9DB0PlmH-qkOUKGJY4,2434
4
+ orivane_cli/_config.py,sha256=SoCbWkoW05LyJjxogu7283ZHTTOuyCOy26hAcPpQFc8,1345
5
+ orivane_cli/_loader.py,sha256=G-Z9sdaktdv_KXEEM23U6t2v4XGeh2E4Lx3ccPWNhY4,1446
6
+ orivane_cli/_main.py,sha256=8o2s0cyNf9si4zxXI0opBz9slSh5hS1S3L1XBRswE_A,2644
7
+ orivane_cli/_trace.py,sha256=AOlRyk668yX0PX6u1YIiPcLP4BR5hzb3ZeDdZIy9Tnk,2215
8
+ orivane_cli-0.1.0.dist-info/METADATA,sha256=xzpW8diAXgX8htP9WOxaTz7qucFE9RBoIwZqqNXBhD4,2056
9
+ orivane_cli-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
10
+ orivane_cli-0.1.0.dist-info/entry_points.txt,sha256=uUpwBQF1LAXWT611NgleVQNEFp0S5LS2Pn-N7A6gQRk,51
11
+ orivane_cli-0.1.0.dist-info/licenses/LICENSE,sha256=mXz7jOIJWuMFkIE1TjKNXQNqii060bxmUzFg4Ddk9vo,1077
12
+ orivane_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ orivane = orivane_cli._main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Orivane contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.