thzdaq-cli 0.0.6b3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
thzdaq_cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """The thzdaq command: arguments to calls of the thzdaq-api contract, results to text."""
thzdaq_cli/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from thzdaq_cli.app import main
4
+
5
+ sys.exit(main())
thzdaq_cli/agents.py ADDED
@@ -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)
thzdaq_cli/app.py ADDED
@@ -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)
thzdaq_cli/client.py ADDED
@@ -0,0 +1,140 @@
1
+ """What a command works with: the daemon (started when none runs), its
2
+ workspace, questions in the terminal, output as text or JSON, and the exit
3
+ codes.
4
+
5
+ The workspace is the folder given with --workspace, else the nearest one from
6
+ here up (thzdaq.toml), else none: the daemon writes to the program's. A daemon
7
+ the command starts loads the profile that workspace expects."""
8
+
9
+ import argparse
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Optional, TypeVar
13
+
14
+ from thzdaq_api import host
15
+ from thzdaq_api.errors import ErrorCode, LabError
16
+ from thzdaq_api.lab import Lab
17
+ from thzdaq_api.operation import Operation
18
+ from thzdaq_api.origins import AGENT_CLI, CLI, agent_shell
19
+ from thzdaq_api.terminal import yes
20
+ from thzdaq_api.station import GetStation
21
+ from thzdaq_api.workspace import (
22
+ chosen,
23
+ expected_profile,
24
+ profile_name,
25
+ profile_warning,
26
+ )
27
+
28
+ from thzdaq_cli import show
29
+
30
+ R = TypeVar("R")
31
+ PROG = "thzdaq" # the command, as people type it
32
+ KIND = CLI
33
+ OK, FAILED, USAGE, NO_DAEMON = 0, 1, 2, 3
34
+ # How --workspace defaults, as its help says
35
+ HERE = "default: the workspace here or above, else the program's"
36
+ THIS_FOLDER = "default: this folder" # of a command that writes into a folder
37
+
38
+
39
+ def origin() -> str:
40
+ """cli in a person's terminal, cli:agent in an agent's shell: what it
41
+ changes waits for a person in the window."""
42
+ return AGENT_CLI if agent_shell() else CLI
43
+
44
+
45
+ class Mistyped(Exception):
46
+ """What was typed does not fit (exit 2, as argparse does)."""
47
+
48
+
49
+ # The lab of the bench, or of its simulator, listened to as a kind of client;
50
+ # started when none runs (autostart) with a profile (station)
51
+ Connect = Callable[[bool, bool, str, Optional[str]], Lab]
52
+
53
+
54
+ def reach(simulate: bool, autostart: bool, kind: str, station: Optional[str]) -> Lab:
55
+ """The running daemon; started when none runs and autostart allows it."""
56
+ try:
57
+ return host.connect(simulate, origin(), kind)
58
+ except LabError as e:
59
+ if e.code != ErrorCode.UNREACHABLE or not autostart:
60
+ raise
61
+ lab = host.connect_or_start(simulate, station, origin(), kind)
62
+ print(f"daemon started (pid {lab.host.pid})", file=sys.stderr)
63
+ return lab
64
+
65
+
66
+ class Client:
67
+ """What a command works with: the lab, questions in the terminal, output."""
68
+
69
+ def __init__(self, args: argparse.Namespace, connect: Connect):
70
+ self.simulate: bool = args.simulate
71
+ self.json: bool = args.json
72
+ self.yes: bool = args.yes
73
+ self.autostart: bool = not args.no_autostart
74
+ self.kind: str = args.kind # cli; cli:answers while a person answers here
75
+ self.workspace: Optional[Path] = chosen(args.workspace)
76
+ self._connect = connect
77
+ self._lab: Optional[Lab] = None
78
+
79
+ @property
80
+ def lab(self) -> Lab:
81
+ if self._lab is None:
82
+ self._lab = self._connect(
83
+ self.simulate,
84
+ self.autostart,
85
+ self.kind,
86
+ expected_profile(self.workspace),
87
+ )
88
+ return self._lab
89
+
90
+ def running_lab(self) -> Lab:
91
+ """The daemon only when it runs already: LabError UNREACHABLE otherwise."""
92
+ if self._lab is None:
93
+ self._lab = self._connect(self.simulate, False, self.kind, None)
94
+ return self._lab
95
+
96
+ def daemons_profile(self) -> str:
97
+ """The name of the profile the running daemon works with; none when no
98
+ daemon runs (none is started for it)."""
99
+ try:
100
+ path = self.running_lab().call(GetStation()).path
101
+ except LabError as e:
102
+ if e.code != ErrorCode.UNREACHABLE:
103
+ raise
104
+ return ""
105
+ return profile_name(path) if path else ""
106
+
107
+ def folder(self) -> Optional[str]:
108
+ """The workspace as operations name it (None: the program's); a
109
+ person is warned when it expects another profile than the daemon's."""
110
+ warning = profile_warning(self.lab, self.workspace)
111
+ if warning:
112
+ print(f"{PROG}: {warning}", file=sys.stderr)
113
+ return str(self.workspace) if self.workspace else None
114
+
115
+ def call(self, operation: Operation[R]) -> R:
116
+ return self.lab.call(operation)
117
+
118
+ def ask(self, question: str) -> bool:
119
+ """yes or no in the terminal; --yes answers yes, no terminal answers no."""
120
+ if self.yes:
121
+ return True
122
+ if not sys.stdin.isatty():
123
+ print(f"{question} — not asked without a terminal: --yes", file=sys.stderr)
124
+ return False
125
+ return yes(input(f"{question} [y/N] "))
126
+
127
+ def shared(self, call: Callable[[bool], R]) -> Optional[R]:
128
+ """call(share=False); a conflict (a device another measurement sweeps)
129
+ is asked, and on yes called again with share. None when not."""
130
+ try:
131
+ return call(False)
132
+ except LabError as e:
133
+ if e.code != ErrorCode.CONFLICT:
134
+ raise
135
+ if not self.ask(f"{e.message}. Go on anyway (both note it)?"):
136
+ return None
137
+ return call(True)
138
+
139
+ def out(self, value: Any, human: Callable[[Any], str]) -> None:
140
+ print(show.as_json(value) if self.json else human(value))