clicodemode 0.6.1__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.
- clicodemode-0.6.1/.gitignore +10 -0
- clicodemode-0.6.1/LICENSE +21 -0
- clicodemode-0.6.1/PKG-INFO +249 -0
- clicodemode-0.6.1/README.md +211 -0
- clicodemode-0.6.1/examples/argparse_cli.py +67 -0
- clicodemode-0.6.1/examples/click_cli.py +83 -0
- clicodemode-0.6.1/examples/typer_cli.py +61 -0
- clicodemode-0.6.1/pyproject.toml +59 -0
- clicodemode-0.6.1/scripts/build_wasm.sh +15 -0
- clicodemode-0.6.1/scripts/check_python.sh +43 -0
- clicodemode-0.6.1/src/clicodemode/__init__.py +46 -0
- clicodemode-0.6.1/src/clicodemode/_codemode.wasm +0 -0
- clicodemode-0.6.1/src/clicodemode/_guest.py +366 -0
- clicodemode-0.6.1/src/clicodemode/adapters.py +455 -0
- clicodemode-0.6.1/src/clicodemode/core.py +473 -0
- clicodemode-0.6.1/src/clicodemode/errors.py +19 -0
- clicodemode-0.6.1/src/clicodemode/py.typed +0 -0
- clicodemode-0.6.1/src/clicodemode/types.py +147 -0
- clicodemode-0.6.1/tests/conformance_runner.py +268 -0
- clicodemode-0.6.1/tests/conftest.py +26 -0
- clicodemode-0.6.1/tests/test_adapters.py +232 -0
- clicodemode-0.6.1/tests/test_conformance.py +29 -0
- clicodemode-0.6.1/tests/test_engine.py +535 -0
- clicodemode-0.6.1/tests/test_examples.py +136 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muthukumaran Navaneethakrishnan
|
|
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.
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: clicodemode
|
|
3
|
+
Version: 0.6.1
|
|
4
|
+
Summary: Code Mode for Python CLIs: run agent-written JavaScript-like programs against your existing handlers, on the Go engine compiled to WebAssembly.
|
|
5
|
+
Project-URL: Homepage, https://github.com/muthuishere/clicodemode
|
|
6
|
+
Project-URL: Source, https://github.com/muthuishere/clicodemode/tree/main/python
|
|
7
|
+
Author: Muthukumaran Navaneethakrishnan
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,argparse,cli,click,codemode,mcp,typer,wasm
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
16
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Requires-Dist: wasmtime~=51.0
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
29
|
+
Requires-Dist: click>=8.1; extra == 'dev'
|
|
30
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
32
|
+
Requires-Dist: typer>=0.12; extra == 'dev'
|
|
33
|
+
Provides-Extra: test
|
|
34
|
+
Requires-Dist: click>=8.1; extra == 'test'
|
|
35
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
36
|
+
Requires-Dist: typer>=0.12; extra == 'test'
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
# clicodemode for Python (experimental)
|
|
40
|
+
|
|
41
|
+
Register the commands your Python CLI already has as Code Mode operations, then
|
|
42
|
+
let an agent run small JavaScript-like programs that call them.
|
|
43
|
+
|
|
44
|
+
**Go is the primary library.** This package is an experimental thin wrapper
|
|
45
|
+
around the Go engine compiled to WebAssembly (`GOOS=wasip1`) and run by
|
|
46
|
+
[wasmtime](https://github.com/bytecodealliance/wasmtime-py). The engine owns
|
|
47
|
+
parsing, language semantics and portable validation; Python never interprets
|
|
48
|
+
the language and nothing is reimplemented. The host (your Python code) owns
|
|
49
|
+
authorization and path/exec security. Version 0.6.1 matches the Go library
|
|
50
|
+
version; `cm.engine_version()` reports the engine that is embedded.
|
|
51
|
+
|
|
52
|
+
## Install (no package registry needed; not on PyPI)
|
|
53
|
+
|
|
54
|
+
**a) From a GitHub release asset** (the URL is valid once the v0.6.1 release exists):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
python3 -m venv .venv && . .venv/bin/activate
|
|
58
|
+
pip install https://github.com/muthuishere/clicodemode/releases/download/v0.6.1/clicodemode-0.6.1-py3-none-any.whl
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The wheel is pure Python plus the embedded engine (`_codemode.wasm`); the only
|
|
62
|
+
dependency, `wasmtime`, is installed from its own wheels. Needs Python >= 3.9.
|
|
63
|
+
|
|
64
|
+
**b) From source** (needs Go and Python >= 3.9; Python 3.10+ for the check script):
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
git clone https://github.com/muthuishere/clicodemode && cd clicodemode
|
|
68
|
+
bash python/scripts/check_python.sh # venv, build wasm, pytest, mypy --strict, wheel in python/dist/
|
|
69
|
+
# or just the two commands it wraps for a wheel:
|
|
70
|
+
bash python/scripts/build_wasm.sh && python3 -m pip install build && python3 -m build python
|
|
71
|
+
pip install python/dist/clicodemode-0.6.1-py3-none-any.whl
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Quickstart (a Click CLI, copy-paste and run)
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import click
|
|
78
|
+
from clicodemode import CodeMode, Policy
|
|
79
|
+
|
|
80
|
+
@click.group()
|
|
81
|
+
def inventory() -> None:
|
|
82
|
+
"""Existing CLI; nothing here knows about Code Mode."""
|
|
83
|
+
|
|
84
|
+
@inventory.command()
|
|
85
|
+
@click.argument("sku")
|
|
86
|
+
@click.option("--qty", type=int, default=1)
|
|
87
|
+
def add(sku: str, qty: int) -> dict:
|
|
88
|
+
"""Add stock; returns the new level."""
|
|
89
|
+
return {"sku": sku, "qty": qty}
|
|
90
|
+
|
|
91
|
+
cm = CodeMode("1.0.0", policy=Policy(allow=lambda op: op.side_effects != "external"))
|
|
92
|
+
cm.register_click(inventory, "inv") # becomes ops.inv.add
|
|
93
|
+
|
|
94
|
+
r = cm.run("""
|
|
95
|
+
export default async () => {
|
|
96
|
+
const a = await ops.inv.add({ sku: "apple", qty: 5 });
|
|
97
|
+
return { a, total: a.qty + 2 };
|
|
98
|
+
}""")
|
|
99
|
+
print(r.ok, r.value) # True {'a': {'qty': 5, 'sku': 'apple'}, 'total': 7}
|
|
100
|
+
print(cm.engine_version())
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Limitations at a glance (measured: Apple M-series, Python 3.12, wasmtime 51)
|
|
104
|
+
|
|
105
|
+
| Area | Status |
|
|
106
|
+
|---|---|
|
|
107
|
+
| `exec` / `execStream` / `shell` | denied (the guest has no processes) |
|
|
108
|
+
| Module imports | not available (no filesystem in the guest) |
|
|
109
|
+
| Handlers | synchronous; a running handler cannot be pre-empted, so timeout and cancel apply after it returns. This is **partial** coverage of SPEC LIM-2/LIM-3; a test (`test_slow_handler_is_not_cut_off_by_timeout`) pins it so nobody relies on it |
|
|
110
|
+
| Click / Typer | leaf commands only; group callbacks and group-level options do not run |
|
|
111
|
+
| argparse | leaf (sub-)parsers become operations, nested sub-parsers included; options on a parent parser that precede the sub-command do not apply |
|
|
112
|
+
| Parallelism | `Promise.all` calls are answered one after another by the host |
|
|
113
|
+
| Security | the Go engine owns parsing, semantics and portable validation (syntax, static checks, operation-input schemas). Authorization and filesystem/path/exec security are enforced by your Python host (`Policy.allow`, handler code); WebAssembly does not sandbox them |
|
|
114
|
+
| Cold vs warm | cold: first engine in a process about 300 ms; warm: later engines about 6 ms, a steady `run` with one host call about 0.3 ms (details under "Measured") |
|
|
115
|
+
|
|
116
|
+
## Who does what
|
|
117
|
+
|
|
118
|
+
| Go engine (in WASM) | Python layer (this package) |
|
|
119
|
+
|---|---|
|
|
120
|
+
| JS parser/AST, language and evaluation semantics | operation registration |
|
|
121
|
+
| portable core validation: syntax and static checks, diagnostics (`file:line:col`), operation-input schema checks, limits (steps, call depth, concurrency) | calling your Python handlers, JSON in/out |
|
|
122
|
+
| capability fingerprint, docs, generated skill | policy gate (`Policy.allow`), timeouts/cancellation, I/O |
|
|
123
|
+
| | host authorization and filesystem/path security |
|
|
124
|
+
|
|
125
|
+
Authorization that depends on the host (who may call what, which paths a
|
|
126
|
+
handler may touch) is enforced in Python, in your handlers and your `Policy`.
|
|
127
|
+
Nothing about paths or files is validated or sandboxed by the WASM engine:
|
|
128
|
+
the guest has no filesystem at all, but your handlers do, with your privileges.
|
|
129
|
+
If a handler takes a path, validate it in the handler (resolve it, check it
|
|
130
|
+
stays under an allowed directory) and deny the operation in `Policy` when in doubt.
|
|
131
|
+
|
|
132
|
+
## Develop: build and test
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
# from the repository root; needs Go (to build the engine) and Python >= 3.9 (tested 3.9-3.15)
|
|
136
|
+
python/scripts/build_wasm.sh # Go -> python/src/clicodemode/_codemode.wasm (git-ignored)
|
|
137
|
+
cd python
|
|
138
|
+
python3.13 -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
|
139
|
+
.venv/bin/python -m pytest # unit tests + examples + the conformance suite
|
|
140
|
+
.venv/bin/python tests/conformance_runner.py # conformance report only
|
|
141
|
+
.venv/bin/python -m mypy # strict
|
|
142
|
+
python -m build # wheel + sdist in dist/ (contains the wasm)
|
|
143
|
+
scripts/check_python.sh # the whole clean sequence in one go
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The wasm is a build output (about 7.1 MB, about 2.1 MB inside the wheel). It is
|
|
147
|
+
never committed: `build_wasm.sh` produces it and `python -m build` packages it.
|
|
148
|
+
Building a wheel without running the script first fails the wasm check in
|
|
149
|
+
`check_python.sh` and raises a clear error at first use.
|
|
150
|
+
|
|
151
|
+
Runtime dependency: `wasmtime~=51.0` (Apache-2.0 WITH LLVM-exception). Test extras: `click`, `typer`, `pytest`.
|
|
152
|
+
|
|
153
|
+
## API tour
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from clicodemode import CodeMode, Limits, Policy
|
|
157
|
+
|
|
158
|
+
cm = CodeMode("1.0.0",
|
|
159
|
+
limits=Limits(max_steps=1_000_000, timeout_ms=2000),
|
|
160
|
+
policy=Policy(allow=lambda op: op.side_effects != "external"))
|
|
161
|
+
|
|
162
|
+
@cm.operation("health.check", description="Report health.", side_effects="none", idempotent=True,
|
|
163
|
+
input_schema={"type": "object", "properties": {}, "additionalProperties": False})
|
|
164
|
+
def health(args):
|
|
165
|
+
return {"ok": True}
|
|
166
|
+
|
|
167
|
+
r = cm.run("export default async () => await ops.health.check({})", timeout=5)
|
|
168
|
+
r.ok, r.value, r.error, r.diagnostics, r.stdout, r.ms
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`cm.run(src, input=..., file=..., timeout=<seconds>, cancel=<threading.Event>)`,
|
|
172
|
+
`cm.eval(expr)`, `cm.check(src)`, `cm.compile(src)`, `cm.capabilities()`,
|
|
173
|
+
`cm.operations()`, `cm.describe(name)`, `cm.docs()`, `cm.skill()`, `cm.cancel()`, `cm.close()`.
|
|
174
|
+
A program that throws, is rejected or times out is a `Result(ok=False)`, not an exception.
|
|
175
|
+
|
|
176
|
+
### Existing functions and CLIs
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
cm.register_function("util.greet", greet) # schema from the signature and type hints
|
|
180
|
+
cm.register_click(group, "inv", exclude=["code"]) # every leaf command becomes inv.<cmd> (sub-groups: inv.<sub>.<cmd>)
|
|
181
|
+
cm.register_typer(app, exclude=["code"]) # via the command Typer builds
|
|
182
|
+
cm.register_argparse(parser, exclude=["code"]) # sub-parsers with set_defaults(func=handler)
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The wrapped command runs in-process, with its own argument parsing, so Click,
|
|
186
|
+
Typer and argparse validation and errors apply. Its return value is the result;
|
|
187
|
+
if it returns `None`, what it printed is the result (JSON-decoded when it is
|
|
188
|
+
JSON). Click/Typer errors and argparse usage errors become rejected calls with
|
|
189
|
+
the original message. Only leaf commands run: group callbacks and group-level
|
|
190
|
+
options do not (use `obj=` for `ctx.obj`). Stdout capture is process-wide, so
|
|
191
|
+
wrapped commands are serialised by a lock.
|
|
192
|
+
|
|
193
|
+
Complete, tested examples, each a real CLI with an extra `code run` command:
|
|
194
|
+
[`examples/click_cli.py`](examples/click_cli.py),
|
|
195
|
+
[`examples/typer_cli.py`](examples/typer_cli.py),
|
|
196
|
+
[`examples/argparse_cli.py`](examples/argparse_cli.py).
|
|
197
|
+
|
|
198
|
+
```bash
|
|
199
|
+
python examples/click_cli.py code run -e 'await call("inventory.add", {sku: "apple", qty: 5})'
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
(The examples only read a program file the user names on the command line; they expose no file operations as operations.)
|
|
203
|
+
|
|
204
|
+
## Behaviour, honestly
|
|
205
|
+
|
|
206
|
+
* **Handlers are synchronous** and run in-process on the thread that called `run`, when the engine emits a call. Calls from `Promise.all` are all issued by the program but **answered one after another** by the host.
|
|
207
|
+
* **Handler errors** reject the call inside the program (catchable; message preserved). **Policy denial** rejects it with `"<op>: denied by policy"`; the handler never runs. A raising policy denies, with its message.
|
|
208
|
+
* **Result conversion**: JSON both ways, `None` is `null`, Unicode is preserved. A handler result that is not JSON-serialisable (dataclass, set, NaN) rejects that call with a message naming the operation.
|
|
209
|
+
* **Input checks**: arguments are validated against `input_schema` by the engine before your handler is reached (the schemas derived for functions/Click/Typer/argparse use `additionalProperties: false`).
|
|
210
|
+
* **Timeout and cancellation** really stop runaway code: the guest is interrupted (wasmtime epoch interruption) and **restarted**; the next call transparently starts a fresh engine (about 6 ms, program state is per run anyway). Engine-side limits (`max_steps`, `max_call_depth`) end the run without a restart. `Limits.timeout_ms` is enforced by the engine; the host adds a 1 s backstop. A Python handler that is *executing* cannot be pre-empted: timeout/cancel apply when it returns.
|
|
211
|
+
* **Thread-safety**: one `CodeMode` serialises its calls with a lock, so sharing it is safe but one run at a time; `cancel()` is the only call meant for another thread. Use one instance per thread for parallel runs. A handler cannot re-enter its own engine (raises `UsageError`).
|
|
212
|
+
* **Isolation**: every `CodeMode` has its own WebAssembly instance and its own operations. The compiled module is shared per process.
|
|
213
|
+
* **exec / execStream / shell are denied** (the guest has no processes); programs get a "not permitted" diagnostic or error.
|
|
214
|
+
|
|
215
|
+
### Differences from native Go
|
|
216
|
+
|
|
217
|
+
No claim of parity. Known differences: no module imports (no filesystem in the guest); CPU-bound code is slower (a 1M-iteration loop took ~0.5 s here); handlers are sync Python, so a blocked handler cannot be cancelled mid-call; `exec`/`shell` are denied; key order of operation results and `input` is not preserved by the Go engine (fixture `lang6-*`); the engine's own known deviations (conformance `known_deviation`) apply as they do in Go; only one engine per WASM instance, started lazily and restarted after registration changes or interruption.
|
|
218
|
+
|
|
219
|
+
## Measured (Apple M-series, Python 3.12, wasmtime 51)
|
|
220
|
+
|
|
221
|
+
| | |
|
|
222
|
+
|---|---|
|
|
223
|
+
| first engine in a process (Cranelift compile of the 7.1 MB module + run) | ~300 ms |
|
|
224
|
+
| new engine afterwards (module deserialized from the process cache) + first run | ~6 ms |
|
|
225
|
+
| steady `run` with one host call | ~0.3 ms |
|
|
226
|
+
| 500 parallel calls in one `Promise.all` | ~50 ms |
|
|
227
|
+
| interrupted run + restart + next run (200 ms budget) | ~230 ms |
|
|
228
|
+
|
|
229
|
+
## Conformance
|
|
230
|
+
|
|
231
|
+
`tests/conformance_runner.py` drives `../conformance/cases/*.json` (250 cases)
|
|
232
|
+
through this API. Cases flagged `known_deviation` are reported as skipped, never
|
|
233
|
+
as passed; cases the wrapper cannot express are listed as unsupported
|
|
234
|
+
(currently one: an operation that never settles, which a synchronous handler
|
|
235
|
+
cannot model). `Policy` maps the fixtures' `deny_side_effects`.
|
|
236
|
+
|
|
237
|
+
## Security
|
|
238
|
+
|
|
239
|
+
The engine is an interpreter, **not a sandbox for hostile code**. Programs can
|
|
240
|
+
only reach what you register, but registered handlers run with the host
|
|
241
|
+
process's full privileges, and a program can call them in any order and
|
|
242
|
+
quantity. `Policy.allow` is the gate: deny what an agent must not do, validate
|
|
243
|
+
every argument that reaches files, processes or the network inside the
|
|
244
|
+
handler, and keep `side_effects` honest. Resource limits (`Limits`, timeouts)
|
|
245
|
+
bound compute, not what handlers do.
|
|
246
|
+
|
|
247
|
+
## License
|
|
248
|
+
|
|
249
|
+
MIT (see `LICENSE`).
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# clicodemode for Python (experimental)
|
|
2
|
+
|
|
3
|
+
Register the commands your Python CLI already has as Code Mode operations, then
|
|
4
|
+
let an agent run small JavaScript-like programs that call them.
|
|
5
|
+
|
|
6
|
+
**Go is the primary library.** This package is an experimental thin wrapper
|
|
7
|
+
around the Go engine compiled to WebAssembly (`GOOS=wasip1`) and run by
|
|
8
|
+
[wasmtime](https://github.com/bytecodealliance/wasmtime-py). The engine owns
|
|
9
|
+
parsing, language semantics and portable validation; Python never interprets
|
|
10
|
+
the language and nothing is reimplemented. The host (your Python code) owns
|
|
11
|
+
authorization and path/exec security. Version 0.6.1 matches the Go library
|
|
12
|
+
version; `cm.engine_version()` reports the engine that is embedded.
|
|
13
|
+
|
|
14
|
+
## Install (no package registry needed; not on PyPI)
|
|
15
|
+
|
|
16
|
+
**a) From a GitHub release asset** (the URL is valid once the v0.6.1 release exists):
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
python3 -m venv .venv && . .venv/bin/activate
|
|
20
|
+
pip install https://github.com/muthuishere/clicodemode/releases/download/v0.6.1/clicodemode-0.6.1-py3-none-any.whl
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The wheel is pure Python plus the embedded engine (`_codemode.wasm`); the only
|
|
24
|
+
dependency, `wasmtime`, is installed from its own wheels. Needs Python >= 3.9.
|
|
25
|
+
|
|
26
|
+
**b) From source** (needs Go and Python >= 3.9; Python 3.10+ for the check script):
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
git clone https://github.com/muthuishere/clicodemode && cd clicodemode
|
|
30
|
+
bash python/scripts/check_python.sh # venv, build wasm, pytest, mypy --strict, wheel in python/dist/
|
|
31
|
+
# or just the two commands it wraps for a wheel:
|
|
32
|
+
bash python/scripts/build_wasm.sh && python3 -m pip install build && python3 -m build python
|
|
33
|
+
pip install python/dist/clicodemode-0.6.1-py3-none-any.whl
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quickstart (a Click CLI, copy-paste and run)
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import click
|
|
40
|
+
from clicodemode import CodeMode, Policy
|
|
41
|
+
|
|
42
|
+
@click.group()
|
|
43
|
+
def inventory() -> None:
|
|
44
|
+
"""Existing CLI; nothing here knows about Code Mode."""
|
|
45
|
+
|
|
46
|
+
@inventory.command()
|
|
47
|
+
@click.argument("sku")
|
|
48
|
+
@click.option("--qty", type=int, default=1)
|
|
49
|
+
def add(sku: str, qty: int) -> dict:
|
|
50
|
+
"""Add stock; returns the new level."""
|
|
51
|
+
return {"sku": sku, "qty": qty}
|
|
52
|
+
|
|
53
|
+
cm = CodeMode("1.0.0", policy=Policy(allow=lambda op: op.side_effects != "external"))
|
|
54
|
+
cm.register_click(inventory, "inv") # becomes ops.inv.add
|
|
55
|
+
|
|
56
|
+
r = cm.run("""
|
|
57
|
+
export default async () => {
|
|
58
|
+
const a = await ops.inv.add({ sku: "apple", qty: 5 });
|
|
59
|
+
return { a, total: a.qty + 2 };
|
|
60
|
+
}""")
|
|
61
|
+
print(r.ok, r.value) # True {'a': {'qty': 5, 'sku': 'apple'}, 'total': 7}
|
|
62
|
+
print(cm.engine_version())
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Limitations at a glance (measured: Apple M-series, Python 3.12, wasmtime 51)
|
|
66
|
+
|
|
67
|
+
| Area | Status |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `exec` / `execStream` / `shell` | denied (the guest has no processes) |
|
|
70
|
+
| Module imports | not available (no filesystem in the guest) |
|
|
71
|
+
| Handlers | synchronous; a running handler cannot be pre-empted, so timeout and cancel apply after it returns. This is **partial** coverage of SPEC LIM-2/LIM-3; a test (`test_slow_handler_is_not_cut_off_by_timeout`) pins it so nobody relies on it |
|
|
72
|
+
| Click / Typer | leaf commands only; group callbacks and group-level options do not run |
|
|
73
|
+
| argparse | leaf (sub-)parsers become operations, nested sub-parsers included; options on a parent parser that precede the sub-command do not apply |
|
|
74
|
+
| Parallelism | `Promise.all` calls are answered one after another by the host |
|
|
75
|
+
| Security | the Go engine owns parsing, semantics and portable validation (syntax, static checks, operation-input schemas). Authorization and filesystem/path/exec security are enforced by your Python host (`Policy.allow`, handler code); WebAssembly does not sandbox them |
|
|
76
|
+
| Cold vs warm | cold: first engine in a process about 300 ms; warm: later engines about 6 ms, a steady `run` with one host call about 0.3 ms (details under "Measured") |
|
|
77
|
+
|
|
78
|
+
## Who does what
|
|
79
|
+
|
|
80
|
+
| Go engine (in WASM) | Python layer (this package) |
|
|
81
|
+
|---|---|
|
|
82
|
+
| JS parser/AST, language and evaluation semantics | operation registration |
|
|
83
|
+
| portable core validation: syntax and static checks, diagnostics (`file:line:col`), operation-input schema checks, limits (steps, call depth, concurrency) | calling your Python handlers, JSON in/out |
|
|
84
|
+
| capability fingerprint, docs, generated skill | policy gate (`Policy.allow`), timeouts/cancellation, I/O |
|
|
85
|
+
| | host authorization and filesystem/path security |
|
|
86
|
+
|
|
87
|
+
Authorization that depends on the host (who may call what, which paths a
|
|
88
|
+
handler may touch) is enforced in Python, in your handlers and your `Policy`.
|
|
89
|
+
Nothing about paths or files is validated or sandboxed by the WASM engine:
|
|
90
|
+
the guest has no filesystem at all, but your handlers do, with your privileges.
|
|
91
|
+
If a handler takes a path, validate it in the handler (resolve it, check it
|
|
92
|
+
stays under an allowed directory) and deny the operation in `Policy` when in doubt.
|
|
93
|
+
|
|
94
|
+
## Develop: build and test
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
# from the repository root; needs Go (to build the engine) and Python >= 3.9 (tested 3.9-3.15)
|
|
98
|
+
python/scripts/build_wasm.sh # Go -> python/src/clicodemode/_codemode.wasm (git-ignored)
|
|
99
|
+
cd python
|
|
100
|
+
python3.13 -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
|
101
|
+
.venv/bin/python -m pytest # unit tests + examples + the conformance suite
|
|
102
|
+
.venv/bin/python tests/conformance_runner.py # conformance report only
|
|
103
|
+
.venv/bin/python -m mypy # strict
|
|
104
|
+
python -m build # wheel + sdist in dist/ (contains the wasm)
|
|
105
|
+
scripts/check_python.sh # the whole clean sequence in one go
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
The wasm is a build output (about 7.1 MB, about 2.1 MB inside the wheel). It is
|
|
109
|
+
never committed: `build_wasm.sh` produces it and `python -m build` packages it.
|
|
110
|
+
Building a wheel without running the script first fails the wasm check in
|
|
111
|
+
`check_python.sh` and raises a clear error at first use.
|
|
112
|
+
|
|
113
|
+
Runtime dependency: `wasmtime~=51.0` (Apache-2.0 WITH LLVM-exception). Test extras: `click`, `typer`, `pytest`.
|
|
114
|
+
|
|
115
|
+
## API tour
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from clicodemode import CodeMode, Limits, Policy
|
|
119
|
+
|
|
120
|
+
cm = CodeMode("1.0.0",
|
|
121
|
+
limits=Limits(max_steps=1_000_000, timeout_ms=2000),
|
|
122
|
+
policy=Policy(allow=lambda op: op.side_effects != "external"))
|
|
123
|
+
|
|
124
|
+
@cm.operation("health.check", description="Report health.", side_effects="none", idempotent=True,
|
|
125
|
+
input_schema={"type": "object", "properties": {}, "additionalProperties": False})
|
|
126
|
+
def health(args):
|
|
127
|
+
return {"ok": True}
|
|
128
|
+
|
|
129
|
+
r = cm.run("export default async () => await ops.health.check({})", timeout=5)
|
|
130
|
+
r.ok, r.value, r.error, r.diagnostics, r.stdout, r.ms
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`cm.run(src, input=..., file=..., timeout=<seconds>, cancel=<threading.Event>)`,
|
|
134
|
+
`cm.eval(expr)`, `cm.check(src)`, `cm.compile(src)`, `cm.capabilities()`,
|
|
135
|
+
`cm.operations()`, `cm.describe(name)`, `cm.docs()`, `cm.skill()`, `cm.cancel()`, `cm.close()`.
|
|
136
|
+
A program that throws, is rejected or times out is a `Result(ok=False)`, not an exception.
|
|
137
|
+
|
|
138
|
+
### Existing functions and CLIs
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
cm.register_function("util.greet", greet) # schema from the signature and type hints
|
|
142
|
+
cm.register_click(group, "inv", exclude=["code"]) # every leaf command becomes inv.<cmd> (sub-groups: inv.<sub>.<cmd>)
|
|
143
|
+
cm.register_typer(app, exclude=["code"]) # via the command Typer builds
|
|
144
|
+
cm.register_argparse(parser, exclude=["code"]) # sub-parsers with set_defaults(func=handler)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The wrapped command runs in-process, with its own argument parsing, so Click,
|
|
148
|
+
Typer and argparse validation and errors apply. Its return value is the result;
|
|
149
|
+
if it returns `None`, what it printed is the result (JSON-decoded when it is
|
|
150
|
+
JSON). Click/Typer errors and argparse usage errors become rejected calls with
|
|
151
|
+
the original message. Only leaf commands run: group callbacks and group-level
|
|
152
|
+
options do not (use `obj=` for `ctx.obj`). Stdout capture is process-wide, so
|
|
153
|
+
wrapped commands are serialised by a lock.
|
|
154
|
+
|
|
155
|
+
Complete, tested examples, each a real CLI with an extra `code run` command:
|
|
156
|
+
[`examples/click_cli.py`](examples/click_cli.py),
|
|
157
|
+
[`examples/typer_cli.py`](examples/typer_cli.py),
|
|
158
|
+
[`examples/argparse_cli.py`](examples/argparse_cli.py).
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
python examples/click_cli.py code run -e 'await call("inventory.add", {sku: "apple", qty: 5})'
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
(The examples only read a program file the user names on the command line; they expose no file operations as operations.)
|
|
165
|
+
|
|
166
|
+
## Behaviour, honestly
|
|
167
|
+
|
|
168
|
+
* **Handlers are synchronous** and run in-process on the thread that called `run`, when the engine emits a call. Calls from `Promise.all` are all issued by the program but **answered one after another** by the host.
|
|
169
|
+
* **Handler errors** reject the call inside the program (catchable; message preserved). **Policy denial** rejects it with `"<op>: denied by policy"`; the handler never runs. A raising policy denies, with its message.
|
|
170
|
+
* **Result conversion**: JSON both ways, `None` is `null`, Unicode is preserved. A handler result that is not JSON-serialisable (dataclass, set, NaN) rejects that call with a message naming the operation.
|
|
171
|
+
* **Input checks**: arguments are validated against `input_schema` by the engine before your handler is reached (the schemas derived for functions/Click/Typer/argparse use `additionalProperties: false`).
|
|
172
|
+
* **Timeout and cancellation** really stop runaway code: the guest is interrupted (wasmtime epoch interruption) and **restarted**; the next call transparently starts a fresh engine (about 6 ms, program state is per run anyway). Engine-side limits (`max_steps`, `max_call_depth`) end the run without a restart. `Limits.timeout_ms` is enforced by the engine; the host adds a 1 s backstop. A Python handler that is *executing* cannot be pre-empted: timeout/cancel apply when it returns.
|
|
173
|
+
* **Thread-safety**: one `CodeMode` serialises its calls with a lock, so sharing it is safe but one run at a time; `cancel()` is the only call meant for another thread. Use one instance per thread for parallel runs. A handler cannot re-enter its own engine (raises `UsageError`).
|
|
174
|
+
* **Isolation**: every `CodeMode` has its own WebAssembly instance and its own operations. The compiled module is shared per process.
|
|
175
|
+
* **exec / execStream / shell are denied** (the guest has no processes); programs get a "not permitted" diagnostic or error.
|
|
176
|
+
|
|
177
|
+
### Differences from native Go
|
|
178
|
+
|
|
179
|
+
No claim of parity. Known differences: no module imports (no filesystem in the guest); CPU-bound code is slower (a 1M-iteration loop took ~0.5 s here); handlers are sync Python, so a blocked handler cannot be cancelled mid-call; `exec`/`shell` are denied; key order of operation results and `input` is not preserved by the Go engine (fixture `lang6-*`); the engine's own known deviations (conformance `known_deviation`) apply as they do in Go; only one engine per WASM instance, started lazily and restarted after registration changes or interruption.
|
|
180
|
+
|
|
181
|
+
## Measured (Apple M-series, Python 3.12, wasmtime 51)
|
|
182
|
+
|
|
183
|
+
| | |
|
|
184
|
+
|---|---|
|
|
185
|
+
| first engine in a process (Cranelift compile of the 7.1 MB module + run) | ~300 ms |
|
|
186
|
+
| new engine afterwards (module deserialized from the process cache) + first run | ~6 ms |
|
|
187
|
+
| steady `run` with one host call | ~0.3 ms |
|
|
188
|
+
| 500 parallel calls in one `Promise.all` | ~50 ms |
|
|
189
|
+
| interrupted run + restart + next run (200 ms budget) | ~230 ms |
|
|
190
|
+
|
|
191
|
+
## Conformance
|
|
192
|
+
|
|
193
|
+
`tests/conformance_runner.py` drives `../conformance/cases/*.json` (250 cases)
|
|
194
|
+
through this API. Cases flagged `known_deviation` are reported as skipped, never
|
|
195
|
+
as passed; cases the wrapper cannot express are listed as unsupported
|
|
196
|
+
(currently one: an operation that never settles, which a synchronous handler
|
|
197
|
+
cannot model). `Policy` maps the fixtures' `deny_side_effects`.
|
|
198
|
+
|
|
199
|
+
## Security
|
|
200
|
+
|
|
201
|
+
The engine is an interpreter, **not a sandbox for hostile code**. Programs can
|
|
202
|
+
only reach what you register, but registered handlers run with the host
|
|
203
|
+
process's full privileges, and a program can call them in any order and
|
|
204
|
+
quantity. `Policy.allow` is the gate: deny what an agent must not do, validate
|
|
205
|
+
every argument that reaches files, processes or the network inside the
|
|
206
|
+
handler, and keep `side_effects` honest. Resource limits (`Limits`, timeouts)
|
|
207
|
+
bound compute, not what handlers do.
|
|
208
|
+
|
|
209
|
+
## License
|
|
210
|
+
|
|
211
|
+
MIT (see `LICENSE`).
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""An argparse CLI whose existing handlers are also available to agent-written programs.
|
|
2
|
+
|
|
3
|
+
python examples/argparse_cli.py notes add "buy milk" --tag home
|
|
4
|
+
python examples/argparse_cli.py code run -e 'await ops.notes.search({text: "milk"})'
|
|
5
|
+
|
|
6
|
+
The handlers are ordinary argparse handlers (``parser.set_defaults(func=...)``) that
|
|
7
|
+
print their output; Code Mode runs the same handlers in-process.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Any, Dict, List, Optional
|
|
16
|
+
|
|
17
|
+
from clicodemode import CodeMode
|
|
18
|
+
|
|
19
|
+
NOTES: List[Dict[str, Any]] = []
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def cmd_add(ns: argparse.Namespace) -> None:
|
|
23
|
+
NOTES.append({"text": ns.text, "tags": ns.tag})
|
|
24
|
+
print(json.dumps({"count": len(NOTES)}))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def cmd_search(ns: argparse.Namespace) -> None:
|
|
28
|
+
print(json.dumps([n for n in NOTES if ns.text in n["text"]]))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def cmd_code_run(ns: argparse.Namespace) -> None:
|
|
32
|
+
cm = CodeMode("1.0.0")
|
|
33
|
+
cm.register_argparse(build_parser(), exclude=["code"])
|
|
34
|
+
r = cm.run(ns.src)
|
|
35
|
+
print(json.dumps({"ok": r.ok, "value": r.value, "error": r.error}))
|
|
36
|
+
if not r.ok:
|
|
37
|
+
sys.exit(1)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
41
|
+
p = argparse.ArgumentParser(prog="notes-cli")
|
|
42
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
43
|
+
|
|
44
|
+
notes = sub.add_parser("notes", help="note commands").add_subparsers(dest="sub", required=True)
|
|
45
|
+
add = notes.add_parser("add", description="Add a note.")
|
|
46
|
+
add.add_argument("text")
|
|
47
|
+
add.add_argument("--tag", action="append", default=[], help="repeatable")
|
|
48
|
+
add.set_defaults(func=cmd_add)
|
|
49
|
+
search = notes.add_parser("search", description="Find notes containing text.")
|
|
50
|
+
search.add_argument("text")
|
|
51
|
+
search.set_defaults(func=cmd_search)
|
|
52
|
+
|
|
53
|
+
code = sub.add_parser("code", help="run programs").add_subparsers(dest="sub", required=True)
|
|
54
|
+
run = code.add_parser("run", description="Run a program.")
|
|
55
|
+
run.add_argument("-e", "--eval", dest="src", required=True)
|
|
56
|
+
run.set_defaults(func=cmd_code_run)
|
|
57
|
+
return p
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
61
|
+
ns = build_parser().parse_args(argv)
|
|
62
|
+
ns.func(ns)
|
|
63
|
+
return 0
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
if __name__ == "__main__":
|
|
67
|
+
sys.exit(main())
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""A Click CLI whose existing commands are also available to agent-written programs.
|
|
2
|
+
|
|
3
|
+
python examples/click_cli.py inventory stock --sku apple
|
|
4
|
+
python examples/click_cli.py code run -e 'await ops.inventory.add({sku: "apple", qty: 5})'
|
|
5
|
+
python examples/click_cli.py code docs
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from typing import Any, Dict
|
|
13
|
+
|
|
14
|
+
import click
|
|
15
|
+
|
|
16
|
+
from clicodemode import CodeMode, Policy
|
|
17
|
+
|
|
18
|
+
STOCK: Dict[str, int] = {"apple": 3, "pear": 0}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@click.group()
|
|
22
|
+
def inventory() -> None:
|
|
23
|
+
"""Inventory commands (these are the existing CLI; nothing here knows about Code Mode)."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@inventory.command()
|
|
27
|
+
@click.option("--sku", required=True, help="item code")
|
|
28
|
+
def stock(sku: str) -> None:
|
|
29
|
+
"""Show the stock level of one item."""
|
|
30
|
+
click.echo(json.dumps({"sku": sku, "qty": STOCK.get(sku, 0)}))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@inventory.command()
|
|
34
|
+
@click.argument("sku")
|
|
35
|
+
@click.option("--qty", type=int, default=1, help="how many to add")
|
|
36
|
+
def add(sku: str, qty: int) -> Dict[str, Any]:
|
|
37
|
+
"""Add stock; returns the new level."""
|
|
38
|
+
if qty <= 0:
|
|
39
|
+
raise click.BadParameter("qty must be positive")
|
|
40
|
+
STOCK[sku] = STOCK.get(sku, 0) + qty
|
|
41
|
+
return {"sku": sku, "qty": STOCK[sku]}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def make_codemode() -> CodeMode:
|
|
45
|
+
# the policy is the gate: here nothing that touches the outside world may run
|
|
46
|
+
cm = CodeMode("1.0.0", policy=Policy(allow=lambda op: op.side_effects != "external"))
|
|
47
|
+
cm.register_click(main, exclude=["code"]) # every command except Code Mode itself
|
|
48
|
+
return cm
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@click.group()
|
|
52
|
+
def code() -> None:
|
|
53
|
+
"""Run agent-written programs against this CLI's commands."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@code.command("run")
|
|
57
|
+
@click.argument("file", required=False, type=click.Path(exists=True))
|
|
58
|
+
@click.option("-e", "--eval", "src", help="program text instead of a file")
|
|
59
|
+
@click.option("--input", "input_json", default=None, help="JSON exposed to the program as `input`")
|
|
60
|
+
def code_run(file: str, src: str, input_json: str) -> None:
|
|
61
|
+
"""Run a program; prints the result as JSON, exits 1 if it failed."""
|
|
62
|
+
program = src if src is not None else open(file, encoding="utf-8").read()
|
|
63
|
+
r = make_codemode().run(program, input=json.loads(input_json) if input_json else None)
|
|
64
|
+
click.echo(json.dumps({"ok": r.ok, "value": r.value, "error": r.error}))
|
|
65
|
+
sys.exit(0 if r.ok else 1)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@code.command("docs")
|
|
69
|
+
def code_docs() -> None:
|
|
70
|
+
"""Print the generated language and operation reference."""
|
|
71
|
+
click.echo(make_codemode().docs())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@click.group()
|
|
75
|
+
def main() -> None:
|
|
76
|
+
"""Inventory CLI with Code Mode."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
main.add_command(inventory)
|
|
80
|
+
main.add_command(code)
|
|
81
|
+
|
|
82
|
+
if __name__ == "__main__":
|
|
83
|
+
main()
|