cmdop 3.0.0__tar.gz
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.
- cmdop-3.0.0/.gitignore +2 -0
- cmdop-3.0.0/LICENSE +21 -0
- cmdop-3.0.0/PKG-INFO +35 -0
- cmdop-3.0.0/README.md +19 -0
- cmdop-3.0.0/pyproject.toml +34 -0
- cmdop-3.0.0/src/cmdop/__init__.py +36 -0
- cmdop-3.0.0/src/cmdop/_async.py +149 -0
- cmdop-3.0.0/src/cmdop/_client.py +243 -0
- cmdop-3.0.0/src/cmdop/_errors.py +23 -0
- cmdop-3.0.0/src/cmdop/_sealing.py +22 -0
- cmdop-3.0.0/src/cmdop/carriers/__init__.py +7 -0
- cmdop-3.0.0/src/cmdop/carriers/_carrier.py +47 -0
- cmdop-3.0.0/src/cmdop/carriers/http.py +136 -0
- cmdop-3.0.0/src/cmdop/carriers/memory.py +64 -0
- cmdop-3.0.0/src/cmdop/generated/__init__.py +1 -0
- cmdop-3.0.0/src/cmdop/generated/args.py +610 -0
- cmdop-3.0.0/src/cmdop/generated/call.py +224 -0
- cmdop-3.0.0/src/cmdop/generated/models.py +665 -0
- cmdop-3.0.0/src/cmdop/generated/tools.py +411 -0
- cmdop-3.0.0/src/cmdop/py.typed +0 -0
cmdop-3.0.0/.gitignore
ADDED
cmdop-3.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 CMDOP
|
|
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.
|
cmdop-3.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cmdop
|
|
3
|
+
Version: 3.0.0
|
|
4
|
+
Summary: Your machines' tools from a program: the same tools agents use through MCP, typed from Rust.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: httpx<1,>=0.28
|
|
9
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
10
|
+
Requires-Dist: typing-extensions>=4.12
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: cryptography>=44; extra == 'dev'
|
|
13
|
+
Requires-Dist: pyright>=1.1.400; extra == 'dev'
|
|
14
|
+
Requires-Dist: pytest>=8.3; extra == 'dev'
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# cmdop (Python)
|
|
18
|
+
|
|
19
|
+
Your machines' tools from a program: the same tools agents use through MCP, typed from Rust.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
import cmdop
|
|
23
|
+
|
|
24
|
+
with cmdop.connect() as c: # CMDOP_TOKEN, CMDOP_URL
|
|
25
|
+
box = c.machine("box")
|
|
26
|
+
print(box.run("uptime").stdout)
|
|
27
|
+
run = box.stream("make test")
|
|
28
|
+
for piece in run:
|
|
29
|
+
print(piece.data, end="")
|
|
30
|
+
print(run.result.exit_code)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`cmdop.connect_async()` is the same, awaited. `src/cmdop/generated/` is generated by `make sdk-generate`; never edit it.
|
|
34
|
+
|
|
35
|
+
Docs: https://docs.cmdop.ai · License: MIT
|
cmdop-3.0.0/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# cmdop (Python)
|
|
2
|
+
|
|
3
|
+
Your machines' tools from a program: the same tools agents use through MCP, typed from Rust.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import cmdop
|
|
7
|
+
|
|
8
|
+
with cmdop.connect() as c: # CMDOP_TOKEN, CMDOP_URL
|
|
9
|
+
box = c.machine("box")
|
|
10
|
+
print(box.run("uptime").stdout)
|
|
11
|
+
run = box.stream("make test")
|
|
12
|
+
for piece in run:
|
|
13
|
+
print(piece.data, end="")
|
|
14
|
+
print(run.result.exit_code)
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`cmdop.connect_async()` is the same, awaited. `src/cmdop/generated/` is generated by `make sdk-generate`; never edit it.
|
|
18
|
+
|
|
19
|
+
Docs: https://docs.cmdop.ai · License: MIT
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "cmdop"
|
|
3
|
+
version = "3.0.0"
|
|
4
|
+
description = "Your machines' tools from a program: the same tools agents use through MCP, typed from Rust."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
# The core stays two libraries (developer SDK plan, section 3): a carrier needing a runtime of its own is an extra.
|
|
10
|
+
dependencies = [
|
|
11
|
+
"httpx>=0.28,<1",
|
|
12
|
+
"pydantic>=2.10,<3",
|
|
13
|
+
"typing-extensions>=4.12",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
dev = ["pytest>=8.3", "pyright>=1.1.400", "cryptography>=44"]
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling>=1.27"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["src/cmdop"]
|
|
25
|
+
|
|
26
|
+
[tool.pyright]
|
|
27
|
+
include = ["src", "tests"]
|
|
28
|
+
typeCheckingMode = "strict"
|
|
29
|
+
pythonVersion = "3.10"
|
|
30
|
+
# Generated models are checked by their own generator; the methods that use them are checked here.
|
|
31
|
+
exclude = ["src/cmdop/generated/args.py", "src/cmdop/generated/models.py", "src/cmdop/generated/call.py"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""cmdop: your machines' tools from a program, the same tools agents use through MCP.
|
|
2
|
+
|
|
3
|
+
```python
|
|
4
|
+
import cmdop
|
|
5
|
+
with cmdop.connect() as c: # CMDOP_TOKEN, CMDOP_URL
|
|
6
|
+
box = c.machine("box")
|
|
7
|
+
print(box.run("uptime").stdout)
|
|
8
|
+
```
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._async import AsyncClient, AsyncMachine, AsyncRun, connect_async
|
|
12
|
+
from ._client import Client, Machine, Piece, Run, connect
|
|
13
|
+
from ._errors import CarrierError, CmdopError
|
|
14
|
+
from .carriers import AsyncMemoryCarrier, MemoryCarrier
|
|
15
|
+
from .generated.call import ENVELOPE_MAX_BYTES, ERROR_CODES, PIECE_MAX_BYTES
|
|
16
|
+
from .generated.tools import TOOLS
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ENVELOPE_MAX_BYTES",
|
|
20
|
+
"ERROR_CODES",
|
|
21
|
+
"PIECE_MAX_BYTES",
|
|
22
|
+
"TOOLS",
|
|
23
|
+
"AsyncClient",
|
|
24
|
+
"AsyncMachine",
|
|
25
|
+
"AsyncMemoryCarrier",
|
|
26
|
+
"AsyncRun",
|
|
27
|
+
"CarrierError",
|
|
28
|
+
"Client",
|
|
29
|
+
"CmdopError",
|
|
30
|
+
"Machine",
|
|
31
|
+
"MemoryCarrier",
|
|
32
|
+
"Piece",
|
|
33
|
+
"Run",
|
|
34
|
+
"connect",
|
|
35
|
+
"connect_async",
|
|
36
|
+
]
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""The cmdop client, awaited: the same calls as `_client.py` on an async carrier."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import AsyncIterator, Callable
|
|
7
|
+
from typing import Any, Generic, TypeVar
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
from typing_extensions import Unpack
|
|
11
|
+
|
|
12
|
+
from ._client import Piece, carrier_name, piece, request, settle, token_of, url_of
|
|
13
|
+
from ._errors import CarrierError, CmdopError
|
|
14
|
+
from ._sealing import Sealing
|
|
15
|
+
from .carriers import AsyncCarrier, AsyncHttpCarrier, Json
|
|
16
|
+
from .carriers._carrier import is_answer
|
|
17
|
+
from .generated import args as a
|
|
18
|
+
from .generated import models as m
|
|
19
|
+
from .generated.tools import AsyncTools
|
|
20
|
+
|
|
21
|
+
T = TypeVar("T", bound=BaseModel)
|
|
22
|
+
R = TypeVar("R")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AsyncRun(Generic[R]):
|
|
26
|
+
"""A call with its output followed: `async for` the pieces, then `await run.result()`. Leaving the loop early
|
|
27
|
+
stops the call, and `result()` then raises `cancelled`."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, lines: AsyncIterator[Json], parse: Callable[[Any], R]) -> None:
|
|
30
|
+
self._lines = lines
|
|
31
|
+
self._parse = parse
|
|
32
|
+
self._result: tuple[R] | None = None
|
|
33
|
+
self._error: BaseException | None = None
|
|
34
|
+
self._started = False
|
|
35
|
+
|
|
36
|
+
async def __aiter__(self) -> AsyncIterator[Piece]:
|
|
37
|
+
self._started = True
|
|
38
|
+
try:
|
|
39
|
+
async for line in self._lines:
|
|
40
|
+
if is_answer(line):
|
|
41
|
+
self._result = (self._parse(settle(line)),)
|
|
42
|
+
return
|
|
43
|
+
p = piece(line)
|
|
44
|
+
if p is not None:
|
|
45
|
+
yield p
|
|
46
|
+
raise CarrierError("stream", "the stream ended without an answer")
|
|
47
|
+
except BaseException as e:
|
|
48
|
+
if not isinstance(e, GeneratorExit):
|
|
49
|
+
self._error = e
|
|
50
|
+
raise
|
|
51
|
+
finally:
|
|
52
|
+
await self.cancel()
|
|
53
|
+
|
|
54
|
+
async def result(self) -> R:
|
|
55
|
+
"""The call's result. Awaiting it before iterating skips the pieces."""
|
|
56
|
+
if not self._started:
|
|
57
|
+
async for _ in self:
|
|
58
|
+
pass
|
|
59
|
+
if self._result is not None:
|
|
60
|
+
return self._result[0]
|
|
61
|
+
if self._error is not None:
|
|
62
|
+
raise self._error
|
|
63
|
+
raise CmdopError("cancelled", "the call was stopped by its caller")
|
|
64
|
+
|
|
65
|
+
async def cancel(self) -> None:
|
|
66
|
+
close = getattr(self._lines, "aclose", None)
|
|
67
|
+
if callable(close):
|
|
68
|
+
await close() # pyright: ignore[reportUnknownVariableType, reportGeneralTypeIssues]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class AsyncMachine(AsyncTools):
|
|
72
|
+
def __init__(self, client: AsyncClient, name: str | None) -> None:
|
|
73
|
+
self._client = client
|
|
74
|
+
self.name = name
|
|
75
|
+
|
|
76
|
+
async def _tool(self, name: str, args: dict[str, Any], out: type[T], deadline: float | None) -> T:
|
|
77
|
+
return out.model_validate(await self._client.call(name, args, machine=self.name, deadline=deadline))
|
|
78
|
+
|
|
79
|
+
async def run(self, command: str, /, *, deadline: float | None = None, **args: Unpack[a.ExecRunArgs]) -> m.ExecRunOut:
|
|
80
|
+
"""`exec_run` with a shell command line."""
|
|
81
|
+
return await self.exec_run(deadline=deadline, **{**args, "command": command})
|
|
82
|
+
|
|
83
|
+
def stream(self, command: str, /, *, deadline: float | None = None, **args: Unpack[a.ExecRunArgs]) -> AsyncRun[m.ExecRunOut]:
|
|
84
|
+
"""`exec_run` with its output as it comes."""
|
|
85
|
+
return self._client.stream("exec_run", {**args, "command": command}, machine=self.name, deadline=deadline, out=m.ExecRunOut)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class AsyncClient:
|
|
89
|
+
def __init__(self, carrier: AsyncCarrier, e2e: Sealing | None = None) -> None:
|
|
90
|
+
self.carrier_impl = carrier
|
|
91
|
+
self._sealer = e2e
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def carrier(self) -> str:
|
|
95
|
+
return self.carrier_impl.name
|
|
96
|
+
|
|
97
|
+
async def machines(self) -> list[Json]:
|
|
98
|
+
rows: list[Json] = settle(await self.carrier_impl.machines())
|
|
99
|
+
return rows
|
|
100
|
+
|
|
101
|
+
def machine(self, name: str | None = None) -> AsyncMachine:
|
|
102
|
+
return AsyncMachine(self, name)
|
|
103
|
+
|
|
104
|
+
async def call(self, tool: str, args: dict[str, Any], *, machine: str | None = None, deadline: float | None = None) -> Any:
|
|
105
|
+
req = request(tool, args, machine, deadline)
|
|
106
|
+
if self._sealer is None:
|
|
107
|
+
return settle(await self.carrier_impl.call(req))
|
|
108
|
+
sealed, replies = self._sealer.seal(req, await self.machines(), time.time())
|
|
109
|
+
return settle(self._sealer.open_answer(await self.carrier_impl.call(sealed), replies))
|
|
110
|
+
|
|
111
|
+
def stream(
|
|
112
|
+
self, tool: str, args: dict[str, Any], *, machine: str | None = None, deadline: float | None = None, out: type[T] | None = None
|
|
113
|
+
) -> AsyncRun[Any]:
|
|
114
|
+
"""Runs any tool by name as a streamed call, awaited."""
|
|
115
|
+
req = request(tool, args, machine, deadline)
|
|
116
|
+
if self._sealer is None:
|
|
117
|
+
return AsyncRun(self.carrier_impl.stream(req), out.model_validate if out is not None else (lambda v: v))
|
|
118
|
+
return AsyncRun(self._sealed_lines(req), out.model_validate if out is not None else (lambda v: v))
|
|
119
|
+
|
|
120
|
+
async def _sealed_lines(self, req: Json) -> AsyncIterator[Json]:
|
|
121
|
+
sealer = self._sealer
|
|
122
|
+
assert sealer is not None
|
|
123
|
+
sealed, replies = sealer.seal(req, await self.machines(), time.time())
|
|
124
|
+
async for line in self.carrier_impl.stream(sealed):
|
|
125
|
+
yield sealer.open_line(line, replies)
|
|
126
|
+
|
|
127
|
+
async def close(self) -> None:
|
|
128
|
+
await self.carrier_impl.close()
|
|
129
|
+
|
|
130
|
+
async def __aenter__(self) -> AsyncClient:
|
|
131
|
+
return self
|
|
132
|
+
|
|
133
|
+
async def __aexit__(self, *_: object) -> None:
|
|
134
|
+
await self.close()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def connect_async(
|
|
138
|
+
token: str | None = None,
|
|
139
|
+
url: str | None = None,
|
|
140
|
+
*,
|
|
141
|
+
contour: str | None = None,
|
|
142
|
+
carrier: str | AsyncCarrier | None = None,
|
|
143
|
+
e2e: Sealing | None = None,
|
|
144
|
+
) -> AsyncClient:
|
|
145
|
+
"""`connect`, awaited: `async with cmdop.connect_async() as c: ...`."""
|
|
146
|
+
if carrier is not None and not isinstance(carrier, str):
|
|
147
|
+
return AsyncClient(carrier, e2e)
|
|
148
|
+
carrier_name(carrier)
|
|
149
|
+
return AsyncClient(AsyncHttpCarrier(url_of(url, contour), token_of(token)), e2e)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""The cmdop client, sync (developer SDK plan, section 4). `_async.py` is the same, awaited.
|
|
2
|
+
|
|
3
|
+
Every tool, its arguments and result, the error codes and the call shapes come from `generated/`. This file speaks the
|
|
4
|
+
call contract only; which channel carries it is the carrier's business (`carriers/`), and nothing here knows it.
|
|
5
|
+
End-to-end calls come through a sealer (`e2e`, `_sealing.py`): this file holds no key and reads no sealed text.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Callable, Iterator
|
|
13
|
+
from typing import Any, Generic, TypeVar
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel
|
|
16
|
+
from typing_extensions import Unpack
|
|
17
|
+
|
|
18
|
+
from ._errors import CarrierError, CmdopError
|
|
19
|
+
from ._sealing import Sealing
|
|
20
|
+
from .carriers import Carrier, HttpCarrier, Json
|
|
21
|
+
from .carriers._carrier import is_answer
|
|
22
|
+
from .generated import args as a
|
|
23
|
+
from .generated import models as m
|
|
24
|
+
from .generated.call import OutputChunk
|
|
25
|
+
from .generated.tools import Tools
|
|
26
|
+
|
|
27
|
+
T = TypeVar("T", bound=BaseModel)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def url_of(url: str | None = None, contour: str | None = None) -> str:
|
|
31
|
+
"""`url` as given, else `https://<contour>.cmdop.dev`; `CMDOP_URL` when neither is given."""
|
|
32
|
+
if url and contour:
|
|
33
|
+
raise ValueError("connect: give url or contour, not both")
|
|
34
|
+
if contour is not None:
|
|
35
|
+
if not contour or not all(c.isascii() and (c.isalnum() or c == "-") and not c.isupper() for c in contour):
|
|
36
|
+
raise ValueError(f"connect: {contour!r} is not a contour address")
|
|
37
|
+
return f"https://{contour}.cmdop.dev"
|
|
38
|
+
url = url or os.environ.get("CMDOP_URL")
|
|
39
|
+
if not url:
|
|
40
|
+
raise ValueError("connect: no address; set CMDOP_URL (your page's address, https://<address>.cmdop.dev) or pass url")
|
|
41
|
+
return url.rstrip("/")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def token_of(token: str | None) -> str:
|
|
45
|
+
token = token or os.environ.get("CMDOP_TOKEN")
|
|
46
|
+
if not token:
|
|
47
|
+
raise ValueError("connect: no token; set CMDOP_TOKEN or pass token")
|
|
48
|
+
return token
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def carrier_name(carrier: str | None) -> str:
|
|
52
|
+
want = carrier or os.environ.get("CMDOP_CARRIER") or "auto"
|
|
53
|
+
# One door exists today, so `auto` is HTTP. A second carrier adds its probe here, never a branch in the client.
|
|
54
|
+
if want in ("auto", "http"):
|
|
55
|
+
return "http"
|
|
56
|
+
raise ValueError(f"connect: unknown carrier {want!r} (auto, http)")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def request(tool: str, args: dict[str, Any], machine: str | None, deadline: float | None) -> Json:
|
|
60
|
+
"""The contract's `CallRequest`. `deadline` is in seconds; the call keeps the shorter of it and the tool's time."""
|
|
61
|
+
req: Json = {"tool": tool, "args": args}
|
|
62
|
+
if machine is not None:
|
|
63
|
+
req["machine"] = machine
|
|
64
|
+
if deadline is not None:
|
|
65
|
+
req["deadline_ms"] = max(0, round(deadline * 1000))
|
|
66
|
+
return req
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def settle(answer: Json) -> Any:
|
|
70
|
+
"""The result of an answer, or its refusal as a `CmdopError`."""
|
|
71
|
+
if "ok" in answer:
|
|
72
|
+
return answer["ok"]
|
|
73
|
+
e = answer.get("error")
|
|
74
|
+
if isinstance(e, dict):
|
|
75
|
+
err: dict[str, Any] = e # pyright: ignore[reportUnknownVariableType]
|
|
76
|
+
details = err.get("details")
|
|
77
|
+
raise CmdopError(str(err.get("code", "other")), str(err.get("message", "")), details if isinstance(details, dict) else None) # pyright: ignore[reportUnknownArgumentType]
|
|
78
|
+
raise CmdopError("not_sealed", "a sealed answer reached a call that was not sealed")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Piece(OutputChunk):
|
|
82
|
+
"""One piece of a running command's output, with its place in the call."""
|
|
83
|
+
|
|
84
|
+
seq: int
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def piece(line: Json) -> Piece | None:
|
|
88
|
+
if "chunk" in line:
|
|
89
|
+
return Piece.model_validate({**line["chunk"], "seq": line["seq"]})
|
|
90
|
+
if "sealed_chunk" in line:
|
|
91
|
+
raise CmdopError("not_sealed", "a sealed piece reached a call that was not sealed")
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
R = TypeVar("R")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Run(Generic[R]):
|
|
99
|
+
"""A call with its output followed: iterate for the pieces, then read `result`. Leaving the loop early, or
|
|
100
|
+
`cancel()`, stops the call, and `result` then raises `cancelled`."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, lines: Iterator[Json], parse: Callable[[Any], R]) -> None:
|
|
103
|
+
self._lines = lines
|
|
104
|
+
self._parse = parse
|
|
105
|
+
self._result: tuple[R] | None = None
|
|
106
|
+
self._error: BaseException | None = None
|
|
107
|
+
self._started = False
|
|
108
|
+
|
|
109
|
+
def __iter__(self) -> Iterator[Piece]:
|
|
110
|
+
self._started = True
|
|
111
|
+
try:
|
|
112
|
+
for line in self._lines:
|
|
113
|
+
if is_answer(line):
|
|
114
|
+
self._result = (self._parse(settle(line)),)
|
|
115
|
+
return
|
|
116
|
+
p = piece(line)
|
|
117
|
+
if p is not None:
|
|
118
|
+
yield p
|
|
119
|
+
raise CarrierError("stream", "the stream ended without an answer")
|
|
120
|
+
except BaseException as e:
|
|
121
|
+
if not isinstance(e, GeneratorExit):
|
|
122
|
+
self._error = e
|
|
123
|
+
raise
|
|
124
|
+
finally:
|
|
125
|
+
self.cancel()
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def result(self) -> R:
|
|
129
|
+
"""The call's result. Reading it before iterating skips the pieces."""
|
|
130
|
+
if not self._started:
|
|
131
|
+
for _ in self:
|
|
132
|
+
pass
|
|
133
|
+
if self._result is not None:
|
|
134
|
+
return self._result[0]
|
|
135
|
+
if self._error is not None:
|
|
136
|
+
raise self._error
|
|
137
|
+
raise CmdopError("cancelled", "the call was stopped by its caller")
|
|
138
|
+
|
|
139
|
+
def cancel(self) -> None:
|
|
140
|
+
close = getattr(self._lines, "close", None)
|
|
141
|
+
if callable(close):
|
|
142
|
+
close()
|
|
143
|
+
|
|
144
|
+
def __enter__(self) -> Run[R]:
|
|
145
|
+
return self
|
|
146
|
+
|
|
147
|
+
def __exit__(self, *_: object) -> None:
|
|
148
|
+
self.cancel()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class Machine(Tools):
|
|
152
|
+
"""One machine: every tool as a method (`box.fs_read(path=...)`) and two short forms."""
|
|
153
|
+
|
|
154
|
+
def __init__(self, client: Client, name: str | None) -> None:
|
|
155
|
+
self._client = client
|
|
156
|
+
self.name = name
|
|
157
|
+
|
|
158
|
+
def _tool(self, name: str, args: dict[str, Any], out: type[T], deadline: float | None) -> T:
|
|
159
|
+
return out.model_validate(self._client.call(name, args, machine=self.name, deadline=deadline))
|
|
160
|
+
|
|
161
|
+
def run(self, command: str, /, *, deadline: float | None = None, **args: Unpack[a.ExecRunArgs]) -> m.ExecRunOut:
|
|
162
|
+
"""`exec_run` with a shell command line."""
|
|
163
|
+
return self.exec_run(deadline=deadline, **{**args, "command": command})
|
|
164
|
+
|
|
165
|
+
def stream(self, command: str, /, *, deadline: float | None = None, **args: Unpack[a.ExecRunArgs]) -> Run[m.ExecRunOut]:
|
|
166
|
+
"""`exec_run` with its output as it comes."""
|
|
167
|
+
return self._client.stream("exec_run", {**args, "command": command}, machine=self.name, deadline=deadline, out=m.ExecRunOut)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class Client:
|
|
171
|
+
"""Your machines. Use `cmdop.connect()`; close it, or use it as a context manager."""
|
|
172
|
+
|
|
173
|
+
def __init__(self, carrier: Carrier, e2e: Sealing | None = None) -> None:
|
|
174
|
+
self.carrier_impl = carrier
|
|
175
|
+
self._sealer = e2e
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def carrier(self) -> str:
|
|
179
|
+
"""Which carrier is in use (`"http"`, …): what `auto` picked."""
|
|
180
|
+
return self.carrier_impl.name
|
|
181
|
+
|
|
182
|
+
def machines(self) -> list[Json]:
|
|
183
|
+
"""The contour's machines: name, id, online, os, tools."""
|
|
184
|
+
rows: list[Json] = settle(self.carrier_impl.machines())
|
|
185
|
+
return rows
|
|
186
|
+
|
|
187
|
+
def machine(self, name: str | None = None) -> Machine:
|
|
188
|
+
"""One machine; no name: the one online machine (the server decides)."""
|
|
189
|
+
return Machine(self, name)
|
|
190
|
+
|
|
191
|
+
def call(self, tool: str, args: dict[str, Any], *, machine: str | None = None, deadline: float | None = None) -> Any:
|
|
192
|
+
"""Runs any tool by name; the result as JSON."""
|
|
193
|
+
req = request(tool, args, machine, deadline)
|
|
194
|
+
if self._sealer is None:
|
|
195
|
+
return settle(self.carrier_impl.call(req))
|
|
196
|
+
sealed, replies = self._sealer.seal(req, self.machines(), time.time())
|
|
197
|
+
return settle(self._sealer.open_answer(self.carrier_impl.call(sealed), replies))
|
|
198
|
+
|
|
199
|
+
def stream(
|
|
200
|
+
self, tool: str, args: dict[str, Any], *, machine: str | None = None, deadline: float | None = None, out: type[T] | None = None
|
|
201
|
+
) -> Run[Any]:
|
|
202
|
+
"""Runs any tool by name as a streamed call: its pieces as they come (only `exec_run` sends any), then its
|
|
203
|
+
result, as `out` when given, else as JSON."""
|
|
204
|
+
req = request(tool, args, machine, deadline)
|
|
205
|
+
if self._sealer is None:
|
|
206
|
+
lines = iter(self.carrier_impl.stream(req))
|
|
207
|
+
else:
|
|
208
|
+
sealer = self._sealer
|
|
209
|
+
sealed, replies = sealer.seal(req, self.machines(), time.time())
|
|
210
|
+
lines = (sealer.open_line(line, replies) for line in self.carrier_impl.stream(sealed))
|
|
211
|
+
return Run(lines, out.model_validate if out is not None else (lambda v: v))
|
|
212
|
+
|
|
213
|
+
def public_key(self) -> str:
|
|
214
|
+
"""With `e2e`: this client's public key, for `cmdop pair <key>` on each machine."""
|
|
215
|
+
if self._sealer is None:
|
|
216
|
+
raise CmdopError("bad_args", "this client was made without e2e")
|
|
217
|
+
return self._sealer.public_key()
|
|
218
|
+
|
|
219
|
+
def close(self) -> None:
|
|
220
|
+
self.carrier_impl.close()
|
|
221
|
+
|
|
222
|
+
def __enter__(self) -> Client:
|
|
223
|
+
return self
|
|
224
|
+
|
|
225
|
+
def __exit__(self, *_: object) -> None:
|
|
226
|
+
self.close()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def connect(
|
|
230
|
+
token: str | None = None,
|
|
231
|
+
url: str | None = None,
|
|
232
|
+
*,
|
|
233
|
+
contour: str | None = None,
|
|
234
|
+
carrier: str | Carrier | None = None,
|
|
235
|
+
e2e: Sealing | None = None,
|
|
236
|
+
) -> Client:
|
|
237
|
+
"""Connect to your contour: the token from `CMDOP_TOKEN`, the address from `CMDOP_URL` unless given. `carrier` is
|
|
238
|
+
`"auto"` (default, or `CMDOP_CARRIER`), `"http"`, or a carrier of your own (tests: `MemoryCarrier`). With `e2e`
|
|
239
|
+
every call is sealed for the machine by that sealer."""
|
|
240
|
+
if carrier is not None and not isinstance(carrier, str):
|
|
241
|
+
return Client(carrier, e2e)
|
|
242
|
+
carrier_name(carrier)
|
|
243
|
+
return Client(HttpCarrier(url_of(url, contour), token_of(token)), e2e)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""The one error a call raises. Decide by `code`, never by the message."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CmdopError(Exception):
|
|
9
|
+
"""A call returned no result: refused, failed, timed out, cancelled. `code` is one of `ERROR_CODES`."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, code: str, message: str, details: dict[str, Any] | None = None) -> None:
|
|
12
|
+
super().__init__(f"{code}: {message}")
|
|
13
|
+
self.code = code
|
|
14
|
+
self.message = message
|
|
15
|
+
self.details = details
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class CarrierError(Exception):
|
|
19
|
+
"""A carrier could not reach the door or read what came back: not a contract answer."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, carrier: str, message: str) -> None:
|
|
22
|
+
super().__init__(f"{carrier}: {message}")
|
|
23
|
+
self.carrier = carrier
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""The seam for end-to-end calls: `connect(e2e=...)` takes any object with these methods. The client sends what it is
|
|
2
|
+
given and hands back what comes for it to open; it holds no key and never reads the sealed text itself."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from .carriers import Json
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Sealing(Protocol):
|
|
12
|
+
def seal(self, req: Json, rows: list[Json], now: float) -> tuple[Json, Any]:
|
|
13
|
+
"""The request to send for one call (`rows`: the contour's machines), and how to open what comes back."""
|
|
14
|
+
...
|
|
15
|
+
|
|
16
|
+
def open_answer(self, answer: Json, replies: Any) -> Json: ...
|
|
17
|
+
|
|
18
|
+
def open_line(self, line: Json, replies: Any) -> Json: ...
|
|
19
|
+
|
|
20
|
+
def public_key(self) -> str:
|
|
21
|
+
"""This client's public key, for `cmdop pair <key>` on each machine."""
|
|
22
|
+
...
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Carriers: HTTP + NDJSON (the first), in-memory (tests and the conformance suite)."""
|
|
2
|
+
|
|
3
|
+
from ._carrier import AsyncCarrier, Carrier, Json
|
|
4
|
+
from .http import AsyncHttpCarrier, HttpCarrier
|
|
5
|
+
from .memory import AsyncMemoryCarrier, MemoryCarrier
|
|
6
|
+
|
|
7
|
+
__all__ = ["AsyncCarrier", "AsyncHttpCarrier", "AsyncMemoryCarrier", "Carrier", "HttpCarrier", "Json", "MemoryCarrier"]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The client-door seam (developer SDK plan, section 4), the same as the TypeScript one.
|
|
2
|
+
|
|
3
|
+
The client speaks the call contract (`cmdop.generated.call`) and nothing else; an adapter moves the contract's shapes
|
|
4
|
+
over one channel. A carrier defines no semantics: codes, deadlines, cancel and the order of pieces come from the
|
|
5
|
+
contract. Requests and lines are plain JSON values (dicts), exactly as the contract's schemas describe them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import AsyncIterator, Iterator
|
|
11
|
+
from typing import Any, Protocol
|
|
12
|
+
|
|
13
|
+
Json = dict[str, Any]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Carrier(Protocol):
|
|
17
|
+
name: str
|
|
18
|
+
|
|
19
|
+
def call(self, req: Json) -> Json:
|
|
20
|
+
"""One call, answered once. A refusal is an answer with `error`, never an exception."""
|
|
21
|
+
...
|
|
22
|
+
|
|
23
|
+
def stream(self, req: Json) -> Iterator[Json]:
|
|
24
|
+
"""One call: its pieces as they come, its answer as the last line. Closing the iterator cancels the call."""
|
|
25
|
+
...
|
|
26
|
+
|
|
27
|
+
def machines(self) -> Json:
|
|
28
|
+
"""The contour's machines, a server-answered operation: `ok` is a list of rows."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def close(self) -> None: ...
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AsyncCarrier(Protocol):
|
|
35
|
+
name: str
|
|
36
|
+
|
|
37
|
+
async def call(self, req: Json) -> Json: ...
|
|
38
|
+
|
|
39
|
+
def stream(self, req: Json) -> AsyncIterator[Json]: ...
|
|
40
|
+
|
|
41
|
+
async def machines(self) -> Json: ...
|
|
42
|
+
|
|
43
|
+
async def close(self) -> None: ...
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def is_answer(line: Json) -> bool:
|
|
47
|
+
return "ok" in line or "error" in line or "sealed" in line
|