thzdaq-cli 0.0.6b4__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.
- thzdaq_cli-0.0.6b4/.gitignore +25 -0
- thzdaq_cli-0.0.6b4/LICENSE +21 -0
- thzdaq_cli-0.0.6b4/PKG-INFO +27 -0
- thzdaq_cli-0.0.6b4/README.md +5 -0
- thzdaq_cli-0.0.6b4/pyproject.toml +40 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/__init__.py +1 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/__main__.py +5 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/agents.py +259 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/app.py +100 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/approvals.py +150 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/client.py +140 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/daemon.py +266 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/devices.py +262 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/measurements.py +383 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/scripts.py +167 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/show.py +71 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/station.py +72 -0
- thzdaq_cli-0.0.6b4/src/thzdaq_cli/workspaces.py +177 -0
- thzdaq_cli-0.0.6b4/tests/conftest.py +72 -0
- thzdaq_cli-0.0.6b4/tests/test_cli.py +604 -0
- thzdaq_cli-0.0.6b4/tests/test_workspaces.py +234 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
.idea
|
|
2
|
+
venv
|
|
3
|
+
.venv
|
|
4
|
+
.uv-cache
|
|
5
|
+
build
|
|
6
|
+
dist
|
|
7
|
+
*__pycache__
|
|
8
|
+
*.log
|
|
9
|
+
*.DS_Store
|
|
10
|
+
*.spec
|
|
11
|
+
!ThzDAQ.spec
|
|
12
|
+
*.ipynb
|
|
13
|
+
.env
|
|
14
|
+
/data/
|
|
15
|
+
# What a daemon run from sources keeps between runs
|
|
16
|
+
/daemon.json
|
|
17
|
+
/daemon-sim.json
|
|
18
|
+
# Window layout and perspectives of a local run
|
|
19
|
+
/settings.ini
|
|
20
|
+
# What a daemon run from sources keeps of instruments (a grid's angle)
|
|
21
|
+
/state.json
|
|
22
|
+
/state-sim.json
|
|
23
|
+
# The program's own measurements and the profiles' previous versions
|
|
24
|
+
/measurements/
|
|
25
|
+
stations/.history/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 yarvod
|
|
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,27 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: thzdaq-cli
|
|
3
|
+
Version: 0.0.6b4
|
|
4
|
+
Summary: ThzDAQ command line: a client of the bench daemon
|
|
5
|
+
Project-URL: Homepage, https://github.com/yarvod/ThzDAQ
|
|
6
|
+
Project-URL: Documentation, https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md
|
|
7
|
+
Project-URL: Issues, https://github.com/yarvod/ThzDAQ/issues
|
|
8
|
+
Project-URL: Releases, https://github.com/yarvod/ThzDAQ/releases
|
|
9
|
+
Author: yarvod
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: thzdaq-api==0.0.6b4
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# thzdaq-cli
|
|
24
|
+
|
|
25
|
+
The `thzdaq` command: a client of the bench daemon through `thzdaq-api`, like the GUI and
|
|
26
|
+
the MCP server. It starts the daemon's executable when needed and never imports it.
|
|
27
|
+
Install it with [`thzdaq`](https://pypi.org/project/thzdaq/).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "thzdaq-cli"
|
|
3
|
+
version = "0.0.6b4"
|
|
4
|
+
description = "ThzDAQ command line: a client of the bench daemon"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "yarvod" }]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Development Status :: 3 - Alpha",
|
|
12
|
+
"Intended Audience :: Science/Research",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
16
|
+
"Programming Language :: Python :: 3.11",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Physics",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"thzdaq-api==0.0.6b4",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/yarvod/ThzDAQ"
|
|
25
|
+
Documentation = "https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md"
|
|
26
|
+
Issues = "https://github.com/yarvod/ThzDAQ/issues"
|
|
27
|
+
Releases = "https://github.com/yarvod/ThzDAQ/releases"
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
thzdaq = "thzdaq_cli.app:main"
|
|
31
|
+
|
|
32
|
+
[tool.uv.sources]
|
|
33
|
+
thzdaq-api = { workspace = true }
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["hatchling>=1.27"]
|
|
37
|
+
build-backend = "hatchling.build"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/thzdaq_cli"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The thzdaq command: arguments to calls of the thzdaq-api contract, results to text."""
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""thzdaq mcp, thzdaq agent-setup: the bench for agents (Claude Code, Codex)
|
|
2
|
+
that work in a folder next to the window.
|
|
3
|
+
|
|
4
|
+
thzdaq mcp serves MCP on stdin and stdout when the thzdaq-mcp package is
|
|
5
|
+
installed (the build has it): the package adds the command through an entry
|
|
6
|
+
point, so the command line never imports it. agent-setup writes into a folder
|
|
7
|
+
what the agents read there: the MCP server as this very command starts it
|
|
8
|
+
from any folder (.mcp.json for Claude Code, .codex/config.toml for Codex),
|
|
9
|
+
and the guide for agents (AGENTS.md, CLAUDE.md refers to it); the folder
|
|
10
|
+
becomes a workspace (thzdaq.toml) when it is none. Agents write only in the
|
|
11
|
+
folder they work in, and the bench's own measurements live in the program's
|
|
12
|
+
folder (measurements/): it is opened to them (additionalDirectories of
|
|
13
|
+
.claude/settings.json, writable_roots of Codex). Files a person wrote stay:
|
|
14
|
+
our entries are added to theirs.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import shutil
|
|
19
|
+
import sys
|
|
20
|
+
import tomllib
|
|
21
|
+
from importlib.metadata import entry_points
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, List
|
|
24
|
+
|
|
25
|
+
from thzdaq_api import guides, host
|
|
26
|
+
from thzdaq_api.custom import ListCustom
|
|
27
|
+
from thzdaq_api.workspace import FILE, create
|
|
28
|
+
|
|
29
|
+
from thzdaq_cli.client import (
|
|
30
|
+
FAILED,
|
|
31
|
+
HERE,
|
|
32
|
+
OK,
|
|
33
|
+
PROG,
|
|
34
|
+
THIS_FOLDER,
|
|
35
|
+
Client,
|
|
36
|
+
Mistyped,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
PLUGINS = "thzdaq.cli" # entry points of the packages that add a command
|
|
40
|
+
MCP = "mcp"
|
|
41
|
+
SERVER = "thzdaq" # the MCP server's name in the agents' configs
|
|
42
|
+
INSTALL = "thzdaq mcp needs the thzdaq-mcp package: uv tool install 'thzdaq[mcp]'"
|
|
43
|
+
|
|
44
|
+
CLAUDE_CONFIG = ".mcp.json"
|
|
45
|
+
CLAUDE_SETTINGS = Path(".claude") / "settings.json"
|
|
46
|
+
CODEX_CONFIG = Path(".codex") / "config.toml"
|
|
47
|
+
CODEX_SANDBOX = "sandbox_workspace_write" # the table of what Codex may write
|
|
48
|
+
GUIDE = "AGENTS.md"
|
|
49
|
+
CLAUDE_GUIDE = "CLAUDE.md"
|
|
50
|
+
REFERENCE = f"@{GUIDE}" # how CLAUDE.md takes another file in
|
|
51
|
+
# A call waits up to 50 s for a person and a wait up to 60 s: more than the
|
|
52
|
+
# 60 s Codex gives a tool by default
|
|
53
|
+
TOOL_TIMEOUT_S = 120
|
|
54
|
+
|
|
55
|
+
WRITTEN, ADDED, KEPT = "written", "added to", "kept"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def add(commands) -> None:
|
|
59
|
+
serve = commands.add_parser(
|
|
60
|
+
MCP, help="the MCP server for agents, on stdin and stdout"
|
|
61
|
+
)
|
|
62
|
+
serve.add_argument(
|
|
63
|
+
"--workspace", help=f"its measurements go to data/ there ({HERE})"
|
|
64
|
+
)
|
|
65
|
+
serve.set_defaults(run=serve_mcp)
|
|
66
|
+
setup = commands.add_parser(
|
|
67
|
+
"agent-setup", help="let Claude Code and Codex measure in a folder"
|
|
68
|
+
)
|
|
69
|
+
setup.add_argument("folder", nargs="?", default=".", help=THIS_FOLDER)
|
|
70
|
+
setup.add_argument(
|
|
71
|
+
"--force", action="store_true", help=f"replace {GUIDE} with this version's"
|
|
72
|
+
)
|
|
73
|
+
setup.set_defaults(run=agent_setup)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def serve_mcp(args, client: Client) -> int:
|
|
77
|
+
found = entry_points(group=PLUGINS, name=MCP)
|
|
78
|
+
if not found:
|
|
79
|
+
print(f"{PROG}: {INSTALL}", file=sys.stderr)
|
|
80
|
+
return FAILED
|
|
81
|
+
(plugin,) = found
|
|
82
|
+
return plugin.load()(simulate=args.simulate, workspace=args.workspace)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def command() -> List[str]:
|
|
86
|
+
"""This very command as another program starts it from any folder: the
|
|
87
|
+
build's thzdaq-cli, the thzdaq of an environment (uv run, uv tool, pip),
|
|
88
|
+
else this Python with the package."""
|
|
89
|
+
if host.frozen():
|
|
90
|
+
return [sys.executable]
|
|
91
|
+
found = shutil.which(sys.argv[0])
|
|
92
|
+
if found is not None and Path(found).stem == PROG:
|
|
93
|
+
return [str(Path(found).absolute())]
|
|
94
|
+
return [sys.executable, "-m", __package__]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def server_command(simulate: bool, folder: Path) -> List[str]:
|
|
98
|
+
"""thzdaq [--simulate] mcp --workspace FOLDER, absolute."""
|
|
99
|
+
options = ["--simulate"] if simulate else []
|
|
100
|
+
return [*command(), *options, MCP, "--workspace", str(folder)]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def claude_config(path: Path, started: List[str]) -> str:
|
|
104
|
+
"""The server among those the folder's .mcp.json has."""
|
|
105
|
+
told = ADDED if path.exists() else WRITTEN
|
|
106
|
+
try:
|
|
107
|
+
config: Dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
|
|
108
|
+
except FileNotFoundError:
|
|
109
|
+
config = {}
|
|
110
|
+
except json.JSONDecodeError as e:
|
|
111
|
+
raise Mistyped(f"{path} is not JSON ({e}): fix it, then run again") from None
|
|
112
|
+
servers = config.setdefault("mcpServers", {})
|
|
113
|
+
servers[SERVER] = {"command": started[0], "args": started[1:]}
|
|
114
|
+
path.write_text(json.dumps(config, indent=2, ensure_ascii=False) + "\n", "utf-8")
|
|
115
|
+
return told
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def claude_settings(path: Path, library: Path) -> str:
|
|
119
|
+
"""The library among the folders Claude Code may work in besides this one."""
|
|
120
|
+
told = ADDED if path.exists() else WRITTEN
|
|
121
|
+
try:
|
|
122
|
+
config: Dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
|
|
123
|
+
except FileNotFoundError:
|
|
124
|
+
config = {}
|
|
125
|
+
except json.JSONDecodeError as e:
|
|
126
|
+
raise Mistyped(f"{path} is not JSON ({e}): fix it, then run again") from None
|
|
127
|
+
permissions = config.setdefault("permissions", {})
|
|
128
|
+
folders = permissions.setdefault("additionalDirectories", [])
|
|
129
|
+
if str(library) in folders:
|
|
130
|
+
return KEPT
|
|
131
|
+
folders.append(str(library))
|
|
132
|
+
path.parent.mkdir(exist_ok=True)
|
|
133
|
+
path.write_text(json.dumps(config, indent=2, ensure_ascii=False) + "\n", "utf-8")
|
|
134
|
+
return told
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def codex_block(started: List[str]) -> str:
|
|
138
|
+
"""The server's table of config.toml (JSON strings are TOML strings)."""
|
|
139
|
+
return (
|
|
140
|
+
f"[mcp_servers.{SERVER}]\n"
|
|
141
|
+
f"command = {json.dumps(started[0], ensure_ascii=False)}\n"
|
|
142
|
+
f"args = {json.dumps(started[1:], ensure_ascii=False)}\n"
|
|
143
|
+
f"tool_timeout_sec = {TOOL_TIMEOUT_S}\n"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def sandbox_block(library: Path) -> str:
|
|
148
|
+
"""What Codex may write besides the folder: the library."""
|
|
149
|
+
roots = json.dumps([str(library)], ensure_ascii=False)
|
|
150
|
+
return f"[{CODEX_SANDBOX}]\nwritable_roots = {roots}\n"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def codex_config(path: Path, started: List[str], library: Path) -> str:
|
|
154
|
+
"""The server and the library added to the folder's config where it has
|
|
155
|
+
none of them. A table of what Codex may write that a person wrote stays
|
|
156
|
+
as it is (agent_setup tells when the library is not in it)."""
|
|
157
|
+
if not path.exists():
|
|
158
|
+
path.parent.mkdir(exist_ok=True)
|
|
159
|
+
path.write_text(
|
|
160
|
+
f"{codex_block(started)}\n{sandbox_block(library)}", encoding="utf-8"
|
|
161
|
+
)
|
|
162
|
+
return WRITTEN
|
|
163
|
+
text = path.read_text(encoding="utf-8")
|
|
164
|
+
try:
|
|
165
|
+
config = tomllib.loads(text)
|
|
166
|
+
except tomllib.TOMLDecodeError as e:
|
|
167
|
+
raise Mistyped(f"{path} is not TOML ({e}): fix it, then run again") from None
|
|
168
|
+
blocks = []
|
|
169
|
+
if SERVER not in config.get("mcp_servers", {}):
|
|
170
|
+
blocks.append(codex_block(started))
|
|
171
|
+
if CODEX_SANDBOX not in config:
|
|
172
|
+
blocks.append(sandbox_block(library))
|
|
173
|
+
if not blocks:
|
|
174
|
+
return KEPT
|
|
175
|
+
path.write_text("\n".join([text.rstrip() + "\n", *blocks]), encoding="utf-8")
|
|
176
|
+
return ADDED
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def codex_writes(path: Path, library: Path) -> bool:
|
|
180
|
+
"""Codex may write the library, by the folder's config."""
|
|
181
|
+
roots = tomllib.loads(path.read_text(encoding="utf-8")).get(CODEX_SANDBOX, {})
|
|
182
|
+
return str(library) in roots.get("writable_roots", ())
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def guide(path: Path, force: bool) -> str:
|
|
186
|
+
if path.exists() and not force:
|
|
187
|
+
return KEPT
|
|
188
|
+
path.write_text(guides.guide(guides.AGENTS), encoding="utf-8")
|
|
189
|
+
return WRITTEN
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def claude_guide(path: Path) -> str:
|
|
193
|
+
"""CLAUDE.md takes AGENTS.md in."""
|
|
194
|
+
if not path.exists():
|
|
195
|
+
path.write_text(f"{REFERENCE}\n", encoding="utf-8")
|
|
196
|
+
return WRITTEN
|
|
197
|
+
text = path.read_text(encoding="utf-8")
|
|
198
|
+
if REFERENCE in text:
|
|
199
|
+
return KEPT
|
|
200
|
+
path.write_text(f"{text.rstrip()}\n\n{REFERENCE}\n", encoding="utf-8")
|
|
201
|
+
return ADDED
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def setup(
|
|
205
|
+
folder: Path, simulate: bool, library: Path, force: bool = False
|
|
206
|
+
) -> Dict[str, Any]:
|
|
207
|
+
"""The files agents read, written into folder: what became of each.
|
|
208
|
+
library: the bench's own measurements, which agents may write too."""
|
|
209
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
210
|
+
started = server_command(simulate, folder)
|
|
211
|
+
files = {
|
|
212
|
+
CLAUDE_CONFIG: claude_config(folder / CLAUDE_CONFIG, started),
|
|
213
|
+
str(CLAUDE_SETTINGS): claude_settings(folder / CLAUDE_SETTINGS, library),
|
|
214
|
+
str(CODEX_CONFIG): codex_config(folder / CODEX_CONFIG, started, library),
|
|
215
|
+
GUIDE: guide(folder / GUIDE, force),
|
|
216
|
+
CLAUDE_GUIDE: claude_guide(folder / CLAUDE_GUIDE),
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
"folder": str(folder),
|
|
220
|
+
"server": started,
|
|
221
|
+
"files": files,
|
|
222
|
+
"library": str(library),
|
|
223
|
+
"codex_writes_library": codex_writes(folder / CODEX_CONFIG, library),
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def library(client: Client) -> Path:
|
|
228
|
+
"""The bench's own measurements: the folder the daemon keeps them in."""
|
|
229
|
+
return Path(client.call(ListCustom()).folder)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def agent_setup(args, client: Client) -> int:
|
|
233
|
+
"""The folder becomes a workspace too (thzdaq.toml, for the daemon's
|
|
234
|
+
profile): what the agent runs there with thzdaq measures there as well."""
|
|
235
|
+
folder = Path(args.folder).resolve()
|
|
236
|
+
made = create(folder, client.daemons_profile())
|
|
237
|
+
told = setup(folder, args.simulate, library(client), args.force)
|
|
238
|
+
told["files"] = {FILE: WRITTEN if made else KEPT, **told["files"]}
|
|
239
|
+
client.out(told, setup_text)
|
|
240
|
+
return OK
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def setup_text(told: Dict[str, Any]) -> str:
|
|
244
|
+
lines = [f"{state} {name}" for name, state in told["files"].items()]
|
|
245
|
+
lines += [
|
|
246
|
+
"",
|
|
247
|
+
f"MCP server: {' '.join(told['server'])}",
|
|
248
|
+
f"Claude Code reads {CLAUDE_CONFIG} when it starts in {told['folder']}; "
|
|
249
|
+
f"Codex reads {CODEX_CONFIG} of a trusted project (or copy its table "
|
|
250
|
+
"into ~/.codex/config.toml).",
|
|
251
|
+
f"Agents may write the bench's own measurements in {told['library']}.",
|
|
252
|
+
"What agents change waits for a person in the ThzDAQ window.",
|
|
253
|
+
]
|
|
254
|
+
if not told["codex_writes_library"]:
|
|
255
|
+
lines.append(
|
|
256
|
+
f"Codex: add {told['library']} to writable_roots of [{CODEX_SANDBOX}]"
|
|
257
|
+
f" in {CODEX_CONFIG}."
|
|
258
|
+
)
|
|
259
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""thzdaq: the bench from the terminal, a client of the daemon as the GUI is.
|
|
2
|
+
|
|
3
|
+
Every command calls the daemon of the instruments (--simulate: of their
|
|
4
|
+
simulator) and starts it when none runs, saying so in one line on stderr. A
|
|
5
|
+
change that may harm the bench, or that touches a device a measurement sweeps,
|
|
6
|
+
is asked in the terminal; --yes answers yes, and without a terminal the
|
|
7
|
+
answer is no. --json prints what the daemon answered, as JSON.
|
|
8
|
+
|
|
9
|
+
Arguments after -- are not thzdaq's: they go to the script a command runs.
|
|
10
|
+
|
|
11
|
+
Exit codes: 0 done, 1 refused or failed, 2 wrong arguments, 3 no daemon runs.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import sys
|
|
16
|
+
from typing import List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
from thzdaq_api.errors import ErrorCode, LabError
|
|
19
|
+
from thzdaq_api.host import PASSED
|
|
20
|
+
|
|
21
|
+
from thzdaq_cli import (
|
|
22
|
+
agents,
|
|
23
|
+
approvals,
|
|
24
|
+
daemon,
|
|
25
|
+
devices,
|
|
26
|
+
measurements,
|
|
27
|
+
scripts,
|
|
28
|
+
station,
|
|
29
|
+
workspaces,
|
|
30
|
+
)
|
|
31
|
+
from thzdaq_cli.client import (
|
|
32
|
+
FAILED,
|
|
33
|
+
KIND,
|
|
34
|
+
NO_DAEMON,
|
|
35
|
+
PROG,
|
|
36
|
+
USAGE,
|
|
37
|
+
Client,
|
|
38
|
+
Connect,
|
|
39
|
+
Mistyped,
|
|
40
|
+
reach,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def parser() -> argparse.ArgumentParser:
|
|
45
|
+
found = argparse.ArgumentParser(
|
|
46
|
+
prog=PROG,
|
|
47
|
+
description="The ThzDAQ bench from the terminal (a client of its daemon)",
|
|
48
|
+
epilog="Exit codes: 0 done, 1 refused or failed, 2 wrong arguments, "
|
|
49
|
+
"3 no daemon runs.",
|
|
50
|
+
)
|
|
51
|
+
found.add_argument("--simulate", action="store_true", help="the simulator's daemon")
|
|
52
|
+
found.add_argument("--json", action="store_true", help="answers as JSON")
|
|
53
|
+
found.add_argument(
|
|
54
|
+
"-y", "--yes", action="store_true", help="answer yes to questions"
|
|
55
|
+
)
|
|
56
|
+
found.add_argument(
|
|
57
|
+
"--no-autostart",
|
|
58
|
+
action="store_true",
|
|
59
|
+
help="do not start the daemon when none runs",
|
|
60
|
+
)
|
|
61
|
+
# Commands that work in a workspace take --workspace; the others the one here
|
|
62
|
+
found.set_defaults(kind=KIND, workspace=None)
|
|
63
|
+
commands = found.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
64
|
+
for area in (
|
|
65
|
+
daemon,
|
|
66
|
+
devices,
|
|
67
|
+
measurements,
|
|
68
|
+
scripts,
|
|
69
|
+
station,
|
|
70
|
+
approvals,
|
|
71
|
+
agents,
|
|
72
|
+
workspaces,
|
|
73
|
+
):
|
|
74
|
+
area.add(commands)
|
|
75
|
+
return found
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def passed_on(argv: List[str]) -> Tuple[List[str], List[str]]:
|
|
79
|
+
"""thzdaq's own arguments, and those after -- for the script it runs."""
|
|
80
|
+
if PASSED not in argv:
|
|
81
|
+
return argv, []
|
|
82
|
+
at = argv.index(PASSED)
|
|
83
|
+
return argv[:at], argv[at + 1 :]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def main(argv: Optional[List[str]] = None, connect: Connect = reach) -> int:
|
|
87
|
+
own, passed = passed_on(sys.argv[1:] if argv is None else list(argv))
|
|
88
|
+
args = parser().parse_args(own)
|
|
89
|
+
args.passed = passed
|
|
90
|
+
client = Client(args, connect)
|
|
91
|
+
try:
|
|
92
|
+
return args.run(args, client)
|
|
93
|
+
except LabError as e:
|
|
94
|
+
print(f"{PROG}: {e}", file=sys.stderr)
|
|
95
|
+
return NO_DAEMON if e.code == ErrorCode.UNREACHABLE else FAILED
|
|
96
|
+
except Mistyped as e:
|
|
97
|
+
print(f"{PROG}: {e}", file=sys.stderr)
|
|
98
|
+
return USAGE
|
|
99
|
+
except KeyboardInterrupt:
|
|
100
|
+
return 130
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""thzdaq approvals [answer|watch]: what waits for a person in the daemon (an
|
|
2
|
+
agent's operation, or its question) and the answers. watch asks the person at
|
|
3
|
+
this terminal about each one as it comes, as the window's dialog does; the
|
|
4
|
+
first answer, here or in a window, closes it everywhere. Only people answer:
|
|
5
|
+
the daemon refuses an agent's shell, and --yes answers nothing here."""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from thzdaq_api.approvals import AnswerApproval, Approval, ListApprovals
|
|
11
|
+
from thzdaq_api.errors import ErrorCode, LabError
|
|
12
|
+
from thzdaq_api.events import ApprovalAnswered, ApprovalRequested
|
|
13
|
+
from thzdaq_api.origins import ANSWERING_CLI, agent
|
|
14
|
+
from thzdaq_api.terminal import ALLOW, yes
|
|
15
|
+
|
|
16
|
+
from thzdaq_cli import show
|
|
17
|
+
from thzdaq_cli.client import FAILED, OK, Client, origin
|
|
18
|
+
from thzdaq_cli.measurements import Heard
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def add(commands) -> None:
|
|
22
|
+
group = commands.add_parser(
|
|
23
|
+
"approvals", help="what waits for a person: list it, answer it, watch"
|
|
24
|
+
)
|
|
25
|
+
group.set_defaults(run=list_approvals)
|
|
26
|
+
actions = group.add_subparsers(dest="action", metavar="ACTION")
|
|
27
|
+
answer = actions.add_parser("answer", help="allow what waits, or not")
|
|
28
|
+
answer.add_argument("id", type=int)
|
|
29
|
+
verdict = answer.add_mutually_exclusive_group(required=True)
|
|
30
|
+
verdict.add_argument(
|
|
31
|
+
"--allow", action="store_true", help="allow it; answer a question"
|
|
32
|
+
)
|
|
33
|
+
verdict.add_argument("--deny", action="store_true", help="refuse it")
|
|
34
|
+
answer.add_argument(
|
|
35
|
+
"--value", help='allow it with another value, in its unit ("2.2 mV")'
|
|
36
|
+
)
|
|
37
|
+
answer.add_argument(
|
|
38
|
+
"--text", default="", help="words for the agent: why not, what instead"
|
|
39
|
+
)
|
|
40
|
+
answer.add_argument(
|
|
41
|
+
"--confirm", default="", metavar="REF",
|
|
42
|
+
help="the device a dangerous step asks to type",
|
|
43
|
+
) # fmt: skip
|
|
44
|
+
answer.add_argument("--choice", help="one of a question's options")
|
|
45
|
+
answer.set_defaults(run=answer_approval)
|
|
46
|
+
actions.add_parser(
|
|
47
|
+
"watch", help="ask about each one in this terminal as it comes (Ctrl+C ends)"
|
|
48
|
+
).set_defaults(run=watch_approvals, kind=ANSWERING_CLI)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def list_approvals(args, client: Client) -> int:
|
|
52
|
+
found = client.call(ListApprovals())
|
|
53
|
+
client.out(
|
|
54
|
+
found, lambda a: "\n\n".join(show.approval(i) for i in a) or "nothing waits"
|
|
55
|
+
)
|
|
56
|
+
return OK
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def answer_approval(args, client: Client) -> int:
|
|
60
|
+
client.call(
|
|
61
|
+
AnswerApproval(
|
|
62
|
+
id=args.id, allowed=args.allow, text=args.text, value=args.value,
|
|
63
|
+
choice=args.choice, confirm=args.confirm,
|
|
64
|
+
)
|
|
65
|
+
) # fmt: skip
|
|
66
|
+
print(f"#{args.id} {'allowed' if args.allow else 'denied'}")
|
|
67
|
+
return OK
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def watch_approvals(args, client: Client) -> int:
|
|
71
|
+
if agent(origin()):
|
|
72
|
+
print("thzdaq: an agent's shell does not answer for a person", file=sys.stderr)
|
|
73
|
+
return FAILED
|
|
74
|
+
if not sys.stdin.isatty():
|
|
75
|
+
print(
|
|
76
|
+
"thzdaq: watch asks in a terminal; without one: approvals answer",
|
|
77
|
+
file=sys.stderr,
|
|
78
|
+
)
|
|
79
|
+
return FAILED
|
|
80
|
+
heard = Heard(client.lab) # from now on a person answers here
|
|
81
|
+
print("answering for agents here; Ctrl+C ends", file=sys.stderr)
|
|
82
|
+
try:
|
|
83
|
+
seen = set()
|
|
84
|
+
for approval in client.call(ListApprovals()):
|
|
85
|
+
seen.add(approval.id)
|
|
86
|
+
ask(client, approval)
|
|
87
|
+
for body in heard.bodies():
|
|
88
|
+
if isinstance(body, ApprovalRequested) and body.approval.id not in seen:
|
|
89
|
+
seen.add(body.approval.id)
|
|
90
|
+
ask(client, body.approval)
|
|
91
|
+
elif isinstance(body, ApprovalAnswered):
|
|
92
|
+
print(show.answer(body.id, body.answer))
|
|
93
|
+
except (KeyboardInterrupt, EOFError):
|
|
94
|
+
print(file=sys.stderr)
|
|
95
|
+
return OK
|
|
96
|
+
finally:
|
|
97
|
+
heard.stop()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def ask(client: Client, approval: Approval) -> None:
|
|
101
|
+
"""Until the daemon takes the answer, or it was answered elsewhere."""
|
|
102
|
+
if approval.id not in {a.id for a in client.call(ListApprovals())}:
|
|
103
|
+
return # answered in a window, or nobody did in time
|
|
104
|
+
print()
|
|
105
|
+
print(show.approval(approval))
|
|
106
|
+
while True:
|
|
107
|
+
answer = questioned(approval) if not approval.operation else decided(approval)
|
|
108
|
+
try:
|
|
109
|
+
client.call(answer)
|
|
110
|
+
return
|
|
111
|
+
except LabError as e:
|
|
112
|
+
if e.code != ErrorCode.INVALID_ARGUMENTS:
|
|
113
|
+
print(f"thzdaq: {e}", file=sys.stderr)
|
|
114
|
+
return
|
|
115
|
+
print(f"thzdaq: {e}: again", file=sys.stderr)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def decided(approval: Approval) -> AnswerApproval:
|
|
119
|
+
"""An operation: allow it (another value, the device typed for a dangerous
|
|
120
|
+
step) or not, with words for the agent."""
|
|
121
|
+
if not yes(input(ALLOW)):
|
|
122
|
+
words = input("why not, what instead (Enter: nothing): ").strip()
|
|
123
|
+
return AnswerApproval(id=approval.id, allowed=False, text=words)
|
|
124
|
+
value: Optional[str] = None
|
|
125
|
+
if approval.value is not None:
|
|
126
|
+
typed = input(f"value [{approval.value}]: ").strip()
|
|
127
|
+
value = typed if typed and typed != approval.value else None
|
|
128
|
+
confirm = ""
|
|
129
|
+
if approval.confirm:
|
|
130
|
+
confirm = input(f"type {approval.confirm} to allow it: ").strip()
|
|
131
|
+
words = input("words for the agent (Enter: none): ").strip()
|
|
132
|
+
return AnswerApproval(
|
|
133
|
+
id=approval.id, allowed=True, text=words, value=value, confirm=confirm
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def questioned(approval: Approval) -> AnswerApproval:
|
|
138
|
+
"""A question: one of its options, words, or both; nothing declines it."""
|
|
139
|
+
choice: Optional[str] = None
|
|
140
|
+
if approval.options:
|
|
141
|
+
for number, option in enumerate(approval.options, 1):
|
|
142
|
+
print(f" {number}) {option}")
|
|
143
|
+
typed = input(f"choice [1-{len(approval.options)}, Enter: none]: ").strip()
|
|
144
|
+
if typed.isdigit() and 1 <= int(typed) <= len(approval.options):
|
|
145
|
+
choice = approval.options[int(typed) - 1]
|
|
146
|
+
elif typed:
|
|
147
|
+
choice = typed # an option typed as it is; the daemon checks it
|
|
148
|
+
words = input("answer (Enter: none): ").strip()
|
|
149
|
+
given = choice is not None or bool(words)
|
|
150
|
+
return AnswerApproval(id=approval.id, allowed=given, text=words, choice=choice)
|