thzdaq-api 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.
Files changed (57) hide show
  1. thzdaq_api/__init__.py +1 -0
  2. thzdaq_api/analysis.py +62 -0
  3. thzdaq_api/approvals.py +87 -0
  4. thzdaq_api/assistant/agents.md +202 -0
  5. thzdaq_api/assistant/assistant.md +23 -0
  6. thzdaq_api/assistant/hints.md +15 -0
  7. thzdaq_api/atomic.py +79 -0
  8. thzdaq_api/catalog.py +131 -0
  9. thzdaq_api/console.py +70 -0
  10. thzdaq_api/custom.py +326 -0
  11. thzdaq_api/daemon.py +183 -0
  12. thzdaq_api/data.py +55 -0
  13. thzdaq_api/declare.py +193 -0
  14. thzdaq_api/declaring.py +125 -0
  15. thzdaq_api/devices.py +307 -0
  16. thzdaq_api/errors.py +47 -0
  17. thzdaq_api/events.py +224 -0
  18. thzdaq_api/examples/hot_cold.py +67 -0
  19. thzdaq_api/examples/hot_cold_grid.py +74 -0
  20. thzdaq_api/examples/iv_analysis.py +34 -0
  21. thzdaq_api/examples/map.py +42 -0
  22. thzdaq_api/examples/monitor.py +35 -0
  23. thzdaq_api/examples/raw_instrument.py +37 -0
  24. thzdaq_api/examples/sweep.py +38 -0
  25. thzdaq_api/examples.py +79 -0
  26. thzdaq_api/guides.py +61 -0
  27. thzdaq_api/host.py +494 -0
  28. thzdaq_api/interpreters.py +422 -0
  29. thzdaq_api/kernel.py +137 -0
  30. thzdaq_api/lab.py +562 -0
  31. thzdaq_api/lanes.py +170 -0
  32. thzdaq_api/leases.py +29 -0
  33. thzdaq_api/lock.py +65 -0
  34. thzdaq_api/measurement_file.py +459 -0
  35. thzdaq_api/measurements.py +433 -0
  36. thzdaq_api/operation.py +52 -0
  37. thzdaq_api/origins.py +86 -0
  38. thzdaq_api/present.py +376 -0
  39. thzdaq_api/procedures.py +124 -0
  40. thzdaq_api/raw.py +272 -0
  41. thzdaq_api/remote.py +267 -0
  42. thzdaq_api/rights.py +81 -0
  43. thzdaq_api/script.py +382 -0
  44. thzdaq_api/scripts.py +133 -0
  45. thzdaq_api/sessions.py +176 -0
  46. thzdaq_api/station.py +192 -0
  47. thzdaq_api/terminal.py +66 -0
  48. thzdaq_api/tools.py +275 -0
  49. thzdaq_api/transport.py +93 -0
  50. thzdaq_api/ui.py +152 -0
  51. thzdaq_api/windows.py +192 -0
  52. thzdaq_api/wire.py +35 -0
  53. thzdaq_api/workspace.py +239 -0
  54. thzdaq_api-0.0.6b3.dist-info/METADATA +30 -0
  55. thzdaq_api-0.0.6b3.dist-info/RECORD +57 -0
  56. thzdaq_api-0.0.6b3.dist-info/WHEEL +4 -0
  57. thzdaq_api-0.0.6b3.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,433 @@
1
+ """Procedures and the measurements running in the daemon."""
2
+
3
+ import json
4
+ import re
5
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple
6
+
7
+ import msgspec
8
+
9
+ from thzdaq_api.devices import DeviceInfo, Prefix, Value
10
+ from thzdaq_api.measurement_file import PLOTS, Measurement
11
+ from thzdaq_api.operation import Operation, Rights
12
+ from thzdaq_api.procedures import current_name
13
+
14
+ DATA = "data" # the folder of a workspace that holds its measurements
15
+ PLANNED = "planned" # a run as a dry run of start_measurement says it would go
16
+
17
+ # Items of a list parameter typed as text: "4, 6; 8"
18
+ LIST_SEPARATORS = re.compile(r"[,;\s]+")
19
+
20
+
21
+ def split_list(text: str) -> List[str]:
22
+ """ "4, 6; 8" -> ["4", "6", "8"]"""
23
+ return [item for item in LIST_SEPARATORS.split(str(text).strip()) if item]
24
+
25
+
26
+ class Condition(msgspec.Struct, frozen=True):
27
+ """Holds while the parameter named has one of the values (as JSON)."""
28
+
29
+ parameter: str
30
+ values: Tuple[Any, ...]
31
+
32
+ def holds(self, values: Mapping[str, Any]) -> bool:
33
+ return values.get(self.parameter) in self.values
34
+
35
+ def __str__(self) -> str:
36
+ """hot_cold=true; detector=spectrum|power_meter"""
37
+ shown = "|".join(
38
+ json.dumps(v) if isinstance(v, bool) else f"{v}" for v in self.values
39
+ )
40
+ return f"{self.parameter}={shown}"
41
+
42
+
43
+ class ParameterInfo(msgspec.Struct, frozen=True):
44
+ """A parameter of a procedure; values in SI units, shown in display units
45
+ (value / display_scale). A form shows it under its group, and only while
46
+ all of shown_if hold (hot and cold load with hot/cold on): otherwise the
47
+ run does not use it."""
48
+
49
+ name: str
50
+ label: str
51
+ kind: str # float, int, bool, choice, sweep, float_list, string_list, ...
52
+ unit: str = ""
53
+ display_unit: str = ""
54
+ display_scale: float = 1.0
55
+ default: Any = None # as JSON: a sweep is {start, stop, points}
56
+ required: bool = False
57
+ help: str = ""
58
+ minimum: Optional[float] = None
59
+ maximum: Optional[float] = None
60
+ choices: Tuple[Any, ...] = ()
61
+ max_points: Optional[int] = None # of a sweep
62
+ group: str = "" # the title of the part of a form it is in
63
+ shown_if: Tuple[Condition, ...] = ()
64
+
65
+ def shown(self, values: Mapping[str, Any]) -> bool:
66
+ """Used with the parameters' values (as JSON) given."""
67
+ return all(condition.holds(values) for condition in self.shown_if)
68
+
69
+ def used_when(self) -> str:
70
+ """Its conditions as text: "hot_cold=true"; empty when it is always used."""
71
+ return ", ".join(f"{condition}" for condition in self.shown_if)
72
+
73
+ def typed(self, value: Any) -> str:
74
+ """A value as people type it (typed): in the display unit, a sweep
75
+ start:stop:points, a list comma separated."""
76
+ scale = self.display_scale
77
+ if value is None:
78
+ return "--"
79
+ if isinstance(value, dict):
80
+ return f"{value['start'] / scale:g}:{value['stop'] / scale:g}:{value['points']}"
81
+ if isinstance(value, list):
82
+ return ", ".join(self.typed(item) for item in value)
83
+ if isinstance(value, float):
84
+ return f"{value / scale:g}"
85
+ return f"{value}"
86
+
87
+
88
+ class SlotInfo(msgspec.Struct, frozen=True):
89
+ """A device a procedure needs, by the capabilities it must have (none: any
90
+ device)."""
91
+
92
+ name: str
93
+ title: str
94
+ capabilities: Tuple[str, ...]
95
+ # The device kind preferred: sis_bias, or the type of an instrument
96
+ # (generic: one without a driver of its own)
97
+ kind: Optional[str] = None
98
+
99
+ def suits(self, device: DeviceInfo) -> bool:
100
+ return set(self.capabilities) <= set(device.capabilities)
101
+
102
+ def candidates(self, devices: Iterable[DeviceInfo]) -> List[DeviceInfo]:
103
+ """Devices that suit it; only those of the preferred kind when there
104
+ are any (a SIS bias slot lists SIS biases, not every supply channel)."""
105
+ suitable = [device for device in devices if self.suits(device)]
106
+ preferred = [d for d in suitable if self.kind in (d.kind, d.type)]
107
+ return preferred or suitable
108
+
109
+
110
+ def fill_slots(
111
+ slots: Iterable[SlotInfo], bench: Iterable[DeviceInfo], given: Mapping[str, str]
112
+ ) -> Tuple[Dict[str, str], Dict[str, List[str]]]:
113
+ """The devices given, and for a slot without one the only device that
114
+ suits it; besides, the slots several devices suit, with those devices."""
115
+ devices, choices = dict(given), {}
116
+ bench = list(bench)
117
+ for slot in slots:
118
+ if slot.name in devices:
119
+ continue
120
+ suitable = [device.ref for device in slot.candidates(bench)]
121
+ if len(suitable) == 1:
122
+ devices[slot.name] = suitable[0]
123
+ elif suitable:
124
+ choices[slot.name] = suitable
125
+ return devices, choices
126
+
127
+
128
+ GroupKey = Tuple[Any, ...]
129
+ LABEL_UNIT = ", " # "Voltage, V": the unit of an axis after its title
130
+ CAPTION_GAP = " " # "p–t Pressure (time)": the symbols, then the words
131
+
132
+
133
+ def plot_caption(symbols: str, words: str) -> str:
134
+ """What people read as a graph's name: ("p–t", "Pressure (time)") ->
135
+ "p–t Pressure (time)"."""
136
+ return f"{symbols}{CAPTION_GAP}{words}"
137
+
138
+
139
+ def unit_of(label: str) -> str:
140
+ """ "Voltage, V" -> "V"; "" for a label without a unit."""
141
+ title, separator, unit = label.rpartition(LABEL_UNIT)
142
+ return unit if separator else ""
143
+
144
+
145
+ class PlotInfo(msgspec.Struct, frozen=True):
146
+ """A plot of the records of one table, independent of any plotting library.
147
+
148
+ Values in records are SI; x_scale / y_scale convert them for display
149
+ (value / scale), e.g. x_scale=1e9 shows Hz as GHz. Records with different
150
+ values of the group_by keys form separate curves; kind="map" draws z over
151
+ x and y. A procedure declares its plots so; a viewer draws them so.
152
+
153
+ title names the graph it is drawn in: layouts, into= of scripts and files
154
+ hold it, so it never changes. caption is what people read as the graph's
155
+ name (plot_caption: its quantities' symbols and what they are), free to
156
+ change; empty: the title.
157
+ """
158
+
159
+ key: str
160
+ title: str
161
+ table: str
162
+ x: str
163
+ y: str
164
+ x_label: str = ""
165
+ y_label: str = ""
166
+ x_scale: float = 1.0
167
+ y_scale: float = 1.0
168
+ group_by: Tuple[str, ...] = ()
169
+ kind: str = "line" # line, scatter or map (z over x and y)
170
+ z: Optional[str] = None
171
+ z_label: str = ""
172
+ z_scale: float = 1.0
173
+ analysis: Optional[str] = None # an analysis a viewer may offer: iv
174
+ # Only records with these values: (("plot", "P-t"),) in a monitor table
175
+ where: Tuple[Tuple[str, Any], ...] = ()
176
+ # The graph of a window it is drawn into (its title), with the curves of
177
+ # other measurements; None, or a graph there is not or of other units:
178
+ # a graph of its own
179
+ into: Optional[str] = None
180
+ caption: str = ""
181
+
182
+ def shown_title(self) -> str:
183
+ """The graph's name as people read it."""
184
+ return self.caption or self.title
185
+
186
+ def accepts(self, record: Mapping[str, Any]) -> bool:
187
+ return all(record.get(key) == value for key, value in self.where)
188
+
189
+ def group_key(self, record: Mapping[str, Any]) -> GroupKey:
190
+ return tuple(record.get(key) for key in self.group_by)
191
+
192
+ def label(self, group: GroupKey) -> str:
193
+ return " ".join(f"{value}" for value in group if value is not None)
194
+
195
+ def units(self) -> Tuple[str, str]:
196
+ """The units of its axes, by their labels ("Voltage, V" -> V)."""
197
+ return unit_of(self.x_label), unit_of(self.y_label)
198
+
199
+ def point(self, record: Mapping[str, Any]) -> Optional[Tuple[float, ...]]:
200
+ """Display coordinates of a record, None when a value is missing."""
201
+ if not self.accepts(record):
202
+ return None
203
+ keys = (self.x, self.y) + ((self.z,) if self.kind == "map" else ())
204
+ scales = (self.x_scale, self.y_scale) + (
205
+ (self.z_scale,) if self.kind == "map" else ()
206
+ )
207
+ values = []
208
+ for key, scale in zip(keys, scales):
209
+ value = record.get(key)
210
+ if value is None:
211
+ return None
212
+ values.append(value / scale)
213
+ return tuple(values)
214
+
215
+ def curves(
216
+ self, records: Iterable[Mapping[str, Any]]
217
+ ) -> Dict[GroupKey, List[Tuple[float, ...]]]:
218
+ """Points per group in record order."""
219
+ result: Dict[GroupKey, List[Tuple[float, ...]]] = {}
220
+ for record in records:
221
+ point = self.point(record)
222
+ if point is not None:
223
+ result.setdefault(self.group_key(record), []).append(point)
224
+ return result
225
+
226
+
227
+ class ProcedureSummary(msgspec.Struct, frozen=True):
228
+ name: str
229
+ title: str
230
+ description: str
231
+ plots: Tuple[PlotInfo, ...] = () # every plot it may fill
232
+ # Why the bench's own measurement (custom.<name>) cannot run: its script
233
+ # is not described (a syntax error, a declaration after connect()), with
234
+ # its traceback; empty when it can
235
+ error: str = ""
236
+
237
+
238
+ def kept_plots(measurement: Measurement) -> Tuple[PlotInfo, ...]:
239
+ """The plots a measurement keeps with it (none in files written before)."""
240
+ return tuple(msgspec.convert(plot, PlotInfo) for plot in measurement.plots or ())
241
+
242
+
243
+ def saved_plots(
244
+ measurement: Measurement, procedures: Iterable[ProcedureSummary]
245
+ ) -> Tuple[PlotInfo, ...]:
246
+ """The plots a saved measurement is drawn with: those its file keeps; of
247
+ a file written before, those of its procedure (list_procedures, by its
248
+ name now), then those it added while it ran (a script's m.plot)."""
249
+ if measurement.plots is not None:
250
+ return kept_plots(measurement)
251
+ name = current_name(measurement.procedure)
252
+ own = next((p.plots for p in procedures if p.name == name), ())
253
+ added = measurement.metadata.get(PLOTS, ())
254
+ return tuple(own) + tuple(msgspec.convert(plot, PlotInfo) for plot in added)
255
+
256
+
257
+ class ProcedureInfo(msgspec.Struct, frozen=True):
258
+ """A procedure as a run with the parameters (and devices) described goes:
259
+ the slots it needs, the plots it fills, its steps (None: no end known) and
260
+ the seconds of x its live plots keep (None: all of it)."""
261
+
262
+ name: str
263
+ title: str
264
+ description: str
265
+ parameters: Tuple[ParameterInfo, ...]
266
+ slots: Tuple[SlotInfo, ...]
267
+ plots: Tuple[PlotInfo, ...]
268
+ steps: Optional[int] = None
269
+ plot_window: Optional[float] = None
270
+ # How to measure with it: what to do first, what to look at in the result
271
+ guide: str = ""
272
+
273
+
274
+ class RunInfo(msgspec.Struct, frozen=True):
275
+ """A measurement started in the daemon: running or how it ended."""
276
+
277
+ id: int
278
+ procedure: str
279
+ title: str
280
+ status: str # running, completed, cancelled, failed; planned for a dry run
281
+ devices: Dict[str, str] # slot -> device
282
+ origin: str # who started it
283
+ comment: str = ""
284
+ done: int = 0
285
+ total: Optional[int] = None # steps; None: no end known
286
+ started: str = ""
287
+ finished: Optional[str] = None
288
+ error: Optional[str] = None
289
+ path: Optional[str] = None # the file it is saved in
290
+ workspace: Optional[str] = None # the folder whose data/ holds it
291
+ # Conflicts accepted with share, as the measurement notes them
292
+ conflicts: Tuple[Dict[str, Any], ...] = ()
293
+
294
+
295
+ class ListProcedures(Operation[Tuple[ProcedureSummary, ...]]):
296
+ """Every procedure the bench can run, with what it measures."""
297
+
298
+
299
+ class DescribeProcedure(Operation[ProcedureInfo]):
300
+ """A procedure's parameters (units, defaults, limits), the devices it needs,
301
+ its plots and steps. Slots, plots and steps depend on the parameters, a
302
+ monitor's plots on its devices (the units they read): pass them to see
303
+ those of a run. Invalid parameters are refused, each one named."""
304
+
305
+ procedure: str
306
+ parameters: Dict[str, Any] = {}
307
+ devices: Dict[str, str] = {} # slot -> device
308
+ typed: Dict[str, str] = {} # parameters as people type them, as in start
309
+
310
+
311
+ class StartMeasurement(Operation[RunInfo]):
312
+ """Start a procedure. parameters in SI units as describe_procedure lists
313
+ them (a sweep: {"start", "stop", "points"}); devices maps slots to device
314
+ refs. Returns at once; wait_measurement follows it. A device another
315
+ measurement sweeps (or one this one sweeps that another uses) is a
316
+ conflict unless share is true; both measurements record it. workspace is
317
+ the folder of the experiment: the file goes to its data/ (the daemon's own
318
+ folder when not given). dry_run checks all a start checks (parameters,
319
+ devices, the limits of what it sets, conflicts) without opening an
320
+ instrument or writing a file, and returns the run it would be, planned,
321
+ with number 0. typed gives parameters as people type them, in the units
322
+ they are shown in: a sweep as start:stop:points ("0:7:351" for mV), a list
323
+ comma separated; the daemon parses them."""
324
+
325
+ rights = Rights.RUN
326
+ procedure: str
327
+ parameters: Dict[str, Any] = {}
328
+ devices: Dict[str, str] = {}
329
+ comment: str = ""
330
+ share: bool = False
331
+ workspace: Optional[str] = None
332
+ dry_run: bool = False
333
+ typed: Dict[str, str] = {}
334
+
335
+
336
+ class ListRuns(Operation[Tuple[RunInfo, ...]]):
337
+ """Measurements started in the daemon: those running and those that ended
338
+ lately."""
339
+
340
+
341
+ class RunSnapshot(msgspec.Struct, frozen=True):
342
+ """The published state of a run; follow events after seq to continue it.
343
+
344
+ Rows use the same value encoding as MeasurementRecords. Pending batches
345
+ are excluded: they will arrive in events after this snapshot.
346
+ """
347
+
348
+ run: RunInfo
349
+ plots: Tuple[PlotInfo, ...]
350
+ rows: Dict[str, Tuple[Dict[str, Any], ...]]
351
+ seq: int
352
+
353
+
354
+ class GetRunSnapshot(Operation[RunSnapshot]):
355
+ """Catch up with a running or recently finished measurement, including
356
+ its published records and the plots of this particular run."""
357
+
358
+ id: int
359
+
360
+
361
+ class WaitMeasurement(Operation[RunInfo]):
362
+ """Wait until a measurement ends, at most `timeout` seconds (up to 60);
363
+ returns how it stands. Call again while it runs."""
364
+
365
+ long = True
366
+ id: int
367
+ timeout: float = 30.0
368
+
369
+
370
+ class CancelMeasurement(Operation[RunInfo]):
371
+ """Stop a measurement: it ends after the step it is in and restores what
372
+ it changed."""
373
+
374
+ rights = Rights.STOP
375
+ id: int
376
+
377
+
378
+ class ColumnSummary(msgspec.Struct, frozen=True):
379
+ """A column of a table: what it holds and the range of its numbers (SI)."""
380
+
381
+ key: str
382
+ title: str
383
+ unit: str = ""
384
+ minimum: Optional[float] = None # None when it holds no number
385
+ maximum: Optional[float] = None
386
+ prefixes: Tuple[Prefix, ...] = () # to show it in
387
+
388
+ @property
389
+ def label(self) -> str:
390
+ return f"{self.title}, {self.unit}" if self.unit else self.title
391
+
392
+
393
+ class TableSummary(msgspec.Struct, frozen=True):
394
+ name: str
395
+ title: str
396
+ records: int
397
+ columns: Tuple[ColumnSummary, ...]
398
+
399
+
400
+ class MeasurementSummary(msgspec.Struct, frozen=True):
401
+ """What a measurement holds, without its arrays: each table with its number
402
+ of records and the range of each column, the results that are single
403
+ values, and the length of those that are lists (the file has them)."""
404
+
405
+ run: RunInfo
406
+ tables: Tuple[TableSummary, ...]
407
+ results: Dict[str, Value] = {}
408
+ series: Dict[str, int] = {} # a list result -> its length
409
+
410
+
411
+ class SummarizeMeasurement(Operation[MeasurementSummary]):
412
+ """What a running or ended measurement holds so far, without its arrays:
413
+ the records of each table, the range of each column with its unit, and its
414
+ results. The full data are in its file (run.path)."""
415
+
416
+ id: int
417
+
418
+
419
+ class SetComment(Operation[None]):
420
+ """The comment of a measurement, by its file: a running one keeps it and
421
+ saves it with its data; a file that ended is written with it."""
422
+
423
+ rights = Rights.RUN
424
+ path: str
425
+ comment: str
426
+
427
+
428
+ class AbortMeasurement(Operation[RunInfo]):
429
+ """Stop a measurement that waits for a device that does not answer: breaks
430
+ the connections of its devices (they reconnect on the next command)."""
431
+
432
+ rights = Rights.STOP
433
+ id: int
@@ -0,0 +1,52 @@
1
+ """An operation of the bench: a Struct of its arguments whose class says what it is.
2
+
3
+ The class name gives the operation's name (SetQuantity -> set_quantity), its
4
+ docstring tells people and models what it does (it becomes the description in
5
+ the JSON schema), the generic parameter is the type of the result, and two
6
+ class variables classify it: the rights it needs and whether it takes long.
7
+ """
8
+
9
+ import re
10
+ import typing
11
+ from enum import Enum
12
+ from typing import ClassVar, Generic, TypeVar
13
+
14
+ import msgspec
15
+
16
+ R = TypeVar("R")
17
+
18
+
19
+ class Rights(str, Enum):
20
+ """What an operation may change; agents and scripts get rights by these."""
21
+
22
+ READ = "read" # looks, changes nothing
23
+ SET = "set" # changes a device
24
+ RUN = "run" # starts measurements, notes on them
25
+ STOP = "stop" # ends measurements, brings devices to their safe state
26
+ STATION = "station" # changes the profile, or what agents may do
27
+ DAEMON = "daemon" # stops or restarts the daemon
28
+ ANSWER = "answer" # answers for a person what waits for one
29
+ RAW_QUERY = "raw_query" # asks an instrument a raw command (with ?)
30
+ RAW_WRITE = "raw_write" # sends an instrument a raw command nothing checks
31
+ LIBRARY = "library" # writes the bench's own measurements (measurements/)
32
+
33
+
34
+ class Operation(
35
+ msgspec.Struct, Generic[R], kw_only=True, frozen=True, forbid_unknown_fields=True
36
+ ):
37
+ # Arguments cannot be called name, rights or long: these describe the class
38
+ name: ClassVar[str] = ""
39
+ rights: ClassVar[Rights] = Rights.READ
40
+ long: ClassVar[bool] = False # may take minutes: started, then waited for apart
41
+
42
+ def __init_subclass__(cls, **kwargs):
43
+ super().__init_subclass__(**kwargs)
44
+ if "name" not in vars(cls):
45
+ cls.name = re.sub(r"(?<!^)(?=[A-Z])", "_", cls.__name__).lower()
46
+
47
+ @classmethod
48
+ def result_type(cls) -> type:
49
+ for base in getattr(cls, "__orig_bases__", ()):
50
+ if typing.get_origin(base) is Operation:
51
+ return typing.get_args(base)[0]
52
+ raise TypeError(f"{cls.__name__} does not say what it returns")
thzdaq_api/origins.py ADDED
@@ -0,0 +1,86 @@
1
+ """Who calls the daemon: the origin each operation carries, the kind of a client
2
+ that listens. People do what they ask and answer for agents; agents ask a
3
+ person before they change the bench (thzdaq_core's Policy).
4
+
5
+ A script has the rights of whoever started it: one a person started (in a
6
+ window, their terminal) a person's, asked only what may harm the bench; one an
7
+ agent started an agent's. A script run in a shell an agent drives names itself
8
+ so (script:agent:<name>); the daemon knows who started the scripts it runs. A
9
+ console of a window runs code a person types: its kernel calls as console,
10
+ with the rights of a person's script."""
11
+
12
+ import os
13
+ from typing import Optional
14
+
15
+ GUI = "gui" # a window: people answer in it
16
+ CLI = "cli" # the command line in a terminal of a person
17
+ AGENT_CLI = "cli:agent" # the command line in a shell an agent runs
18
+ ASSISTANT = "assistant" # the chat in the window: an agent
19
+ ASSISTANT_CLIENT = "assistant" # the kind of client the chat listens as
20
+ MCP = "mcp:" # mcp:<the agent's name> (Claude Code, Codex)
21
+ MCP_CLIENT = "mcp" # the kind of client an MCP server listens as
22
+ SCRIPT = "script:" # script:<its name>
23
+ AGENT_SCRIPT = f"{SCRIPT}agent:" # script:agent:<its name>: an agent's script
24
+ NUMBERED = "@" # script:<its name>@<number>: one the daemon runs
25
+ SCRIPT_CLIENT = "script" # the kind of client a script listens as
26
+ PLOTS = "plots" # a plots window: it only shows, nobody answers in it
27
+ CONSOLE = "console" # the kernel of a console of a window: a person types its code
28
+ CONSOLE_CLIENT = "console" # the kind of client a console's kernel listens as
29
+
30
+ # The kind of a CLI that asks a person in its terminal what waits (approvals watch)
31
+ ANSWERING_CLI = "cli:answers"
32
+ ANSWERING = (GUI, ANSWERING_CLI) # the kinds of client a person answers in
33
+
34
+ # Set by the daemon in a script an agent started: it is the agent's
35
+ AGENT_ENV = "THZDAQ_AGENT"
36
+ # Set by a window in the kernel of its console: the kernel calls as console
37
+ CONSOLE_ENV = "THZDAQ_CONSOLE"
38
+ # Set in the shells agents run commands in (Claude Code, Codex): a command or
39
+ # a script started there is the agent's, so no person answers in its terminal
40
+ AGENT_SHELLS = (
41
+ "CLAUDECODE",
42
+ "CODEX_SANDBOX",
43
+ "CODEX_SANDBOX_NETWORK_DISABLED",
44
+ AGENT_ENV,
45
+ )
46
+
47
+
48
+ def agent(origin: str) -> bool:
49
+ """An agent, or a script that names itself an agent's: what it changes
50
+ waits for a person. The daemon knows besides who started the scripts it
51
+ runs."""
52
+ return origin in (AGENT_CLI, ASSISTANT) or origin.startswith((MCP, AGENT_SCRIPT))
53
+
54
+
55
+ def answers(kind: str, origin: str) -> bool:
56
+ """A client a person answers in: a window, or a terminal that asks; never
57
+ one an agent runs."""
58
+ return kind in ANSWERING and not agent(origin)
59
+
60
+
61
+ def scripted(origin: str) -> bool:
62
+ """Code that drives the bench, by its origin: a script, or a console of a
63
+ window. A person's goes by its own rights (thzdaq_api.rights.PERSON_SCRIPTS):
64
+ what a dock confirms waits for a person; an agent's by an agent's."""
65
+ return origin.startswith(SCRIPT) or origin == CONSOLE
66
+
67
+
68
+ def script(name: str, number: Optional[int] = None, by_agent: bool = False) -> str:
69
+ """The origin of a script: script:<its name> (script:agent:<its name>
70
+ when an agent started it), and @<number> for one the daemon runs
71
+ (thzdaq script start)."""
72
+ head = AGENT_SCRIPT if by_agent else SCRIPT
73
+ return f"{head}{name}" + ("" if number is None else f"{NUMBERED}{number}")
74
+
75
+
76
+ def script_number(origin: str) -> Optional[int]:
77
+ """The number of a script the daemon runs, by its origin; None for others."""
78
+ head, numbered, number = origin.rpartition(NUMBERED)
79
+ if not head.startswith(SCRIPT) or not numbered or not number.isdigit():
80
+ return None
81
+ return int(number)
82
+
83
+
84
+ def agent_shell() -> bool:
85
+ """This process runs in a shell an agent drives (Claude Code, Codex)."""
86
+ return any(os.environ.get(name) for name in AGENT_SHELLS)