cli-contracts-runtime 0.36.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: cli-contracts-runtime
3
+ Version: 0.36.0
4
+ Summary: Python runtime for the programs and command wrappers cli-contracts generates from a CLI contract: commander-compatible argument parsing, help, policy derivation and the built-in extract command.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/foo-log-inc/cli-contracts
7
+ Project-URL: Repository, https://github.com/foo-log-inc/cli-contracts
8
+ Keywords: cli,contract,codegen,argument-parsing
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+
12
+ # cli-contracts-runtime
13
+
14
+ The runtime for the Python programs and command wrappers that [cli-contracts](https://github.com/foo-log-inc/cli-contracts) generates from a CLI contract (`templates: builtin:python`). A generated program holds its command tree and handler protocol; this package parses an invocation over the tree by the same rules as the TypeScript program generated from the same contract (which uses commander), and writes the same help, errors, `--introspect` policy and `extract` output.
15
+
16
+ ```bash
17
+ pip install cli-contracts-runtime
18
+ ```
19
+
20
+ Python 3.10 or later. The package uses the standard library only.
21
+
22
+ ## Usage
23
+
24
+ Generate the package (`cli-contracts.config.yaml`):
25
+
26
+ ```yaml
27
+ generators:
28
+ python:
29
+ enabled: true
30
+ output: ./tool/cli
31
+ templates: builtin:python
32
+ ```
33
+
34
+ Implement the handlers and run the program:
35
+
36
+ ```python
37
+ import sys
38
+
39
+ import cli_contracts_runtime
40
+
41
+ from tool import cli
42
+
43
+
44
+ class Handlers:
45
+ # One method per command of the contract; it returns the exit code (None for 0).
46
+ def users_import(self, file, options, parent_opts):
47
+ if options.get("dryRun"):
48
+ print("dry run:", file)
49
+ return 0
50
+
51
+
52
+ def on_usage_error(err, command):
53
+ # Optional: for an invocation the program rejects, writes what the contract declares for invalid arguments and returns the exit code.
54
+ sys.stderr.write('{"code":"INVALID_ARGS","message":%s}\n' % cli_contracts_runtime.quote(err.message))
55
+ return 2
56
+
57
+
58
+ if __name__ == "__main__":
59
+ cli.create_program(Handlers(), "1.0.0", on_usage_error).main()
60
+ ```
61
+
62
+ The options a handler receives are a dict of the options given or defaulted, keyed as the program keys them (`dry-run` → `dryRun`); `parent_opts` holds those of the command and its ancestors. A command that takes `--adapter` may return the prompt it built, or `(exit_code, prompt)`; the program writes the prompt with `--show-prompt`.
63
+
64
+ `create_program` returns a `cli_contracts_runtime.Program`; its `run(argv, stdout, stderr)` runs an invocation (`argv` without the program name) without exiting and returns its exit code.
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,57 @@
1
+ # cli-contracts-runtime
2
+
3
+ The runtime for the Python programs and command wrappers that [cli-contracts](https://github.com/foo-log-inc/cli-contracts) generates from a CLI contract (`templates: builtin:python`). A generated program holds its command tree and handler protocol; this package parses an invocation over the tree by the same rules as the TypeScript program generated from the same contract (which uses commander), and writes the same help, errors, `--introspect` policy and `extract` output.
4
+
5
+ ```bash
6
+ pip install cli-contracts-runtime
7
+ ```
8
+
9
+ Python 3.10 or later. The package uses the standard library only.
10
+
11
+ ## Usage
12
+
13
+ Generate the package (`cli-contracts.config.yaml`):
14
+
15
+ ```yaml
16
+ generators:
17
+ python:
18
+ enabled: true
19
+ output: ./tool/cli
20
+ templates: builtin:python
21
+ ```
22
+
23
+ Implement the handlers and run the program:
24
+
25
+ ```python
26
+ import sys
27
+
28
+ import cli_contracts_runtime
29
+
30
+ from tool import cli
31
+
32
+
33
+ class Handlers:
34
+ # One method per command of the contract; it returns the exit code (None for 0).
35
+ def users_import(self, file, options, parent_opts):
36
+ if options.get("dryRun"):
37
+ print("dry run:", file)
38
+ return 0
39
+
40
+
41
+ def on_usage_error(err, command):
42
+ # Optional: for an invocation the program rejects, writes what the contract declares for invalid arguments and returns the exit code.
43
+ sys.stderr.write('{"code":"INVALID_ARGS","message":%s}\n' % cli_contracts_runtime.quote(err.message))
44
+ return 2
45
+
46
+
47
+ if __name__ == "__main__":
48
+ cli.create_program(Handlers(), "1.0.0", on_usage_error).main()
49
+ ```
50
+
51
+ The options a handler receives are a dict of the options given or defaulted, keyed as the program keys them (`dry-run` → `dryRun`); `parent_opts` holds those of the command and its ancestors. A command that takes `--adapter` may return the prompt it built, or `(exit_code, prompt)`; the program writes the prompt with `--show-prompt`.
52
+
53
+ `create_program` returns a `cli_contracts_runtime.Program`; its `run(argv, stdout, stderr)` runs an invocation (`argv` without the program name) without exiting and returns its exit code.
54
+
55
+ ## License
56
+
57
+ MIT
@@ -0,0 +1,54 @@
1
+ """The runtime of the Python programs and command wrappers cli-contracts
2
+ generates from a CLI contract. A generated program holds its command tree
3
+ and dispatches to its handlers; this package parses an invocation over the
4
+ tree by commander's rules, so the program behaves as the TypeScript program
5
+ generated from the same contract."""
6
+
7
+ from .client import ExecResult, arg_string, exec_cli, format_number
8
+ from .extract import ExtractSet, ExtractSpec
9
+ from .jsonvalue import Number, quote, stringify
10
+ from .policy import introspect
11
+ from .typing_compat import NotRequired
12
+ from .program import (
13
+ FLAG,
14
+ NEGATE,
15
+ TAKES_VALUE,
16
+ Action,
17
+ Argument,
18
+ Command,
19
+ Invocation,
20
+ Option,
21
+ Outcome,
22
+ Program,
23
+ UsageError,
24
+ outcome,
25
+ )
26
+
27
+ __version__ = "0.36.0"
28
+
29
+ __all__ = [
30
+ "FLAG",
31
+ "NEGATE",
32
+ "TAKES_VALUE",
33
+ "Action",
34
+ "Argument",
35
+ "Command",
36
+ "ExecResult",
37
+ "ExtractSet",
38
+ "ExtractSpec",
39
+ "Invocation",
40
+ "NotRequired",
41
+ "Number",
42
+ "Option",
43
+ "Outcome",
44
+ "Program",
45
+ "UsageError",
46
+ "arg_string",
47
+ "exec_cli",
48
+ "format_number",
49
+ "introspect",
50
+ "outcome",
51
+ "quote",
52
+ "stringify",
53
+ "__version__",
54
+ ]
@@ -0,0 +1,86 @@
1
+ """The command wrappers' side: running a CLI with the arguments a wrapper
2
+ built, and writing a number as an argument the way the TypeScript wrapper's
3
+ ``String(value)`` does."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import subprocess
9
+ from decimal import Decimal
10
+ from dataclasses import dataclass
11
+ from typing import List
12
+
13
+
14
+ @dataclass
15
+ class ExecResult:
16
+ exit_code: int
17
+ stdout: str
18
+ stderr: str
19
+
20
+
21
+ def exec_cli(executable: str, args: List[str]) -> ExecResult:
22
+ """Runs an executable with arguments. A CLI that cannot be started, or is
23
+ ended by a signal, has exit code 1."""
24
+ try:
25
+ done = subprocess.run([executable, *args], capture_output=True, check=False)
26
+ except OSError:
27
+ return ExecResult(exit_code=1, stdout="", stderr="")
28
+ code = done.returncode if done.returncode >= 0 else 1
29
+ return ExecResult(
30
+ exit_code=code,
31
+ stdout=done.stdout.decode("utf-8", "replace"),
32
+ stderr=done.stderr.decode("utf-8", "replace"),
33
+ )
34
+
35
+
36
+ def format_number(f: float) -> str:
37
+ """Writes a number as JavaScript's ``String(n)`` does (Number::toString:
38
+ the shortest digits that read back as the number, in fixed notation from
39
+ 1e-7 up to 1e21 and exponential notation outside)."""
40
+ f = float(f)
41
+ if math.isnan(f):
42
+ return "NaN"
43
+ if math.isinf(f):
44
+ return "Infinity" if f > 0 else "-Infinity"
45
+ if f == 0:
46
+ return "0"
47
+ sign = "-" if f < 0 else ""
48
+ # repr writes the shortest digits that read back as the number.
49
+ _, digit_tuple, exponent = Decimal(repr(abs(f))).as_tuple()
50
+ digits = "".join(map(str, digit_tuple))
51
+ stripped = digits.rstrip("0")
52
+ exponent += len(digits) - len(stripped)
53
+ digits = stripped.lstrip("0")
54
+ k = len(digits)
55
+ n = k + int(exponent)
56
+ if k <= n <= 21:
57
+ out = digits + "0" * (n - k)
58
+ elif 0 < n <= 21:
59
+ out = digits[:n] + "." + digits[n:]
60
+ elif -6 < n <= 0:
61
+ out = "0." + "0" * (-n) + digits
62
+ else:
63
+ m = digits[0] + ("." + digits[1:] if k > 1 else "")
64
+ out = f"{m}e{'-' if n - 1 < 0 else '+'}{abs(n - 1)}"
65
+ return sign + out
66
+
67
+
68
+ def arg_string(value: object) -> str:
69
+ """Writes a value as an argument the way JavaScript's ``String(value)``
70
+ does: a number in JavaScript's notation, a list as its items joined by
71
+ commas (None as nothing), an object as ``[object Object]``."""
72
+ if value is None:
73
+ return "null"
74
+ if value is True:
75
+ return "true"
76
+ if value is False:
77
+ return "false"
78
+ if isinstance(value, int):
79
+ return str(value)
80
+ if isinstance(value, float):
81
+ return format_number(value)
82
+ if isinstance(value, str):
83
+ return value
84
+ if isinstance(value, (list, tuple)):
85
+ return ",".join("" if item is None else arg_string(item) for item in value)
86
+ return "[object Object]"
@@ -0,0 +1,87 @@
1
+ """The built-in extract command.
2
+
3
+ Its output is computed when the program is generated (cli-contracts
4
+ ``src/generators/runtime-spec.ts``, ExtractSpec); what depends on the
5
+ invocation is filled in here: the time, and which commands the given IDs
6
+ select.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from datetime import datetime, timezone
13
+ from typing import Any, Dict, List, Tuple
14
+
15
+ EXTRACTED_AT = "\x00cli-contracts:extractedAt\x00"
16
+ """Stands where the time of the invocation goes in the output."""
17
+ _EXTRACTED_AT_JSON = "\\u0000cli-contracts:extractedAt\\u0000"
18
+
19
+
20
+ @dataclass
21
+ class ExtractSet:
22
+ """A command set of the embedded contract; ``commands`` holds each command's ID and its JSON at its depth."""
23
+
24
+ id: str
25
+ key: str
26
+ before: List[str] = field(default_factory=list)
27
+ after: List[str] = field(default_factory=list)
28
+ commands: List[Tuple[str, str]] = field(default_factory=list)
29
+
30
+
31
+ @dataclass
32
+ class ExtractSpec:
33
+ yaml_with_meta: str
34
+ yaml_without_meta: str
35
+ json_with_meta: str
36
+ json_without_meta: str
37
+ filter_head: str
38
+ filter_tail: str
39
+ sets: List[ExtractSet] = field(default_factory=list)
40
+
41
+
42
+ def _iso_now() -> str:
43
+ """The time as JavaScript's ``Date.prototype.toISOString`` writes it."""
44
+ now = datetime.now(timezone.utc)
45
+ return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"
46
+
47
+
48
+ def _truthy(values: Dict[str, Any], key: str) -> bool:
49
+ v = values.get(key)
50
+ if v is None or v is False:
51
+ return False
52
+ if isinstance(v, str):
53
+ return v != ""
54
+ return True
55
+
56
+
57
+ def run_extract(spec: ExtractSpec, args: List[Any], opts: Dict[str, Any]) -> Tuple[int, str, str]:
58
+ """Runs the built-in extract command: the exit code, stdout and stderr."""
59
+ commands = list(args[0]) if args and isinstance(args[0], list) else []
60
+ all_ = _truthy(opts, "all")
61
+ if not commands and not all_:
62
+ return 2, "", '{"code":"INVALID_ARGS","message":"Specify command IDs or use --all"}\n'
63
+ fmt = opts.get("format") if _truthy(opts, "format") else "yaml"
64
+ ids = [] if all_ else commands
65
+ include_meta = _truthy(opts, "includeMeta")
66
+ now = _iso_now()
67
+ if not ids:
68
+ if fmt == "json":
69
+ text = spec.json_with_meta if include_meta else spec.json_without_meta
70
+ return 0, text.replace(_EXTRACTED_AT_JSON, now), ""
71
+ text = spec.yaml_with_meta if include_meta else spec.yaml_without_meta
72
+ return 0, text.replace(EXTRACTED_AT, now), ""
73
+
74
+ def selected(set_id: str, cmd_id: str) -> bool:
75
+ return any(i == cmd_id or i == f"{set_id}.{cmd_id}" or cmd_id.startswith(i + ".") for i in ids)
76
+
77
+ sets: List[str] = []
78
+ for s in spec.sets:
79
+ matched = [text for cmd_id, text in s.commands if selected(s.id, cmd_id)]
80
+ if not matched:
81
+ continue
82
+ entries = list(s.before)
83
+ entries.append(' "commands": {\n' + ",\n".join(matched) + "\n }")
84
+ entries.extend(s.after)
85
+ sets.append(s.key + "{\n" + ",\n".join(entries) + "\n }")
86
+ command_sets = "{\n" + ",\n".join(sets) + "\n }" if sets else "{}"
87
+ return 0, spec.filter_head + command_sets + spec.filter_tail, ""
@@ -0,0 +1,102 @@
1
+ """JSON values and a writer that writes them as ``JSON.stringify`` does.
2
+
3
+ A JSON object is a ``dict`` (it keeps its keys in insertion order, as a
4
+ JavaScript object does); a number is a :class:`Number`, which holds the text
5
+ JavaScript writes for it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+
13
+ class Number:
14
+ """A JSON number, held as the text JavaScript writes for it."""
15
+
16
+ __slots__ = ("text",)
17
+
18
+ def __init__(self, text: str) -> None:
19
+ self.text = text
20
+
21
+ def __eq__(self, other: object) -> bool:
22
+ return isinstance(other, Number) and other.text == self.text
23
+
24
+ def __hash__(self) -> int:
25
+ return hash(self.text)
26
+
27
+ def __repr__(self) -> str:
28
+ return f"Number({self.text!r})"
29
+
30
+
31
+ _ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
32
+
33
+
34
+ def quote(s: str) -> str:
35
+ """A string as ``JSON.stringify`` writes it."""
36
+ out = ['"']
37
+ for c in s:
38
+ escaped = _ESCAPES.get(c)
39
+ if escaped is not None:
40
+ out.append(escaped)
41
+ elif ord(c) < 0x20:
42
+ out.append("\\u%04x" % ord(c))
43
+ else:
44
+ out.append(c)
45
+ out.append('"')
46
+ return "".join(out)
47
+
48
+
49
+ def stringify(value: Any, indent: int = 0) -> str:
50
+ """Writes a value as ``JSON.stringify(value, null, indent)`` does; an
51
+ indent of 0 writes it on one line."""
52
+ out: list[str] = []
53
+ _write(out, value, indent, 0)
54
+ return "".join(out)
55
+
56
+
57
+ def _newline(out: list[str], indent: int, depth: int) -> None:
58
+ if indent > 0:
59
+ out.append("\n" + " " * (indent * depth))
60
+
61
+
62
+ def _write(out: list[str], value: Any, indent: int, depth: int) -> None:
63
+ if value is None:
64
+ out.append("null")
65
+ elif value is True:
66
+ out.append("true")
67
+ elif value is False:
68
+ out.append("false")
69
+ elif isinstance(value, Number):
70
+ out.append(value.text)
71
+ elif isinstance(value, int):
72
+ out.append(str(value))
73
+ elif isinstance(value, str):
74
+ out.append(quote(value))
75
+ elif isinstance(value, (list, tuple)):
76
+ if not value:
77
+ out.append("[]")
78
+ return
79
+ out.append("[")
80
+ for i, item in enumerate(value):
81
+ if i > 0:
82
+ out.append(",")
83
+ _newline(out, indent, depth + 1)
84
+ _write(out, item, indent, depth + 1)
85
+ _newline(out, indent, depth)
86
+ out.append("]")
87
+ elif isinstance(value, dict):
88
+ if not value:
89
+ out.append("{}")
90
+ return
91
+ out.append("{")
92
+ for i, (k, v) in enumerate(value.items()):
93
+ if i > 0:
94
+ out.append(",")
95
+ _newline(out, indent, depth + 1)
96
+ out.append(quote(k))
97
+ out.append(": " if indent > 0 else ":")
98
+ _write(out, v, indent, depth + 1)
99
+ _newline(out, indent, depth)
100
+ out.append("}")
101
+ else:
102
+ raise TypeError(f"not a JSON value: {value!r}")
@@ -0,0 +1,237 @@
1
+ """The policy derivation of ``--introspect``.
2
+
3
+ The derivation is defined by cli-contracts ``src/policy-runtime.ts``
4
+ (introspectCommand, derivePolicy, isOptionActive); this is its port, and
5
+ test/conformance compares the two. A definition is the command's
6
+ CommandPolicyDefinition as JSON.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from .jsonvalue import Number
14
+
15
+ _RISK_ORDER = {"low": 0, "medium": 1, "high": 2, "critical": 3}
16
+ _ABSENT = object()
17
+
18
+
19
+ def _truthy(v: Any) -> bool:
20
+ """JavaScript's truthiness of a JSON value; absent is falsy."""
21
+ if v is _ABSENT or v is None or v is False:
22
+ return False
23
+ if isinstance(v, str):
24
+ return v != ""
25
+ if isinstance(v, Number):
26
+ return v.text not in ("0", "-0", "NaN")
27
+ return True
28
+
29
+
30
+ def _get(v: Any, key: str) -> Any:
31
+ if isinstance(v, dict) and key in v:
32
+ return v[key]
33
+ return _ABSENT
34
+
35
+
36
+ def _risk_level(effects: Any) -> Any:
37
+ level = _get(effects, "risk_level")
38
+ return "low" if level is _ABSENT or level is None else level
39
+
40
+
41
+ def _risk(level: Any) -> Optional[int]:
42
+ return _RISK_ORDER.get(level) if isinstance(level, str) else None
43
+
44
+
45
+ def _source_requires_confirmation(effects: Any) -> bool:
46
+ """The source's explicit requires_confirmation, or else its own risk level at high or above."""
47
+ explicit = _get(effects, "requires_confirmation")
48
+ if explicit is not _ABSENT and explicit is not None:
49
+ return _truthy(explicit)
50
+ n = _risk(_risk_level(effects))
51
+ return n is not None and n >= _RISK_ORDER["high"]
52
+
53
+
54
+ def camel_case(name: str) -> str:
55
+ """Joins the ``-``-separated words of a name in camelCase, as commander keys an option's value."""
56
+ words = name.split("-")
57
+ return words[0] + "".join(w[:1].upper() + w[1:] for w in words[1:])
58
+
59
+
60
+ def _is_option_active(definition: Any, value: Any, specified: bool) -> bool:
61
+ if _get(_get(definition, "schema"), "type") == "boolean":
62
+ return value is True
63
+ if _truthy(_get(definition, "repeatable")):
64
+ return specified and isinstance(value, list) and len(value) > 0
65
+ return specified and value is not None and value is not _ABSENT
66
+
67
+
68
+ def _copy(out: Dict[str, Any], key: str, src: Any) -> None:
69
+ v = _get(src, key)
70
+ if v is not _ABSENT:
71
+ out[key] = v
72
+
73
+
74
+ def _copy_if_truthy(out: Dict[str, Any], key: str, src: Any) -> None:
75
+ v = _get(src, key)
76
+ if _truthy(v):
77
+ out[key] = v
78
+
79
+
80
+ def _semantic_read(r: Any, source: str) -> Dict[str, Any]:
81
+ read = {"target": r} if isinstance(r, str) else r
82
+ out: Dict[str, Any] = {"kind": "semantic"}
83
+ _copy(out, "target", read)
84
+ _copy(out, "description", read)
85
+ out["source"] = source
86
+ return out
87
+
88
+
89
+ def _semantic_write(w: Any, source: str) -> Dict[str, Any]:
90
+ write = {"target": w} if isinstance(w, str) else w
91
+ out: Dict[str, Any] = {"kind": "semantic"}
92
+ for key in ("target", "description", "overwrite", "destructive", "idempotent"):
93
+ _copy(out, key, write)
94
+ _copy_if_truthy(out, "idempotency_key", write)
95
+ _copy_if_truthy(out, "idempotent_note", write)
96
+ out["source"] = source
97
+ return out
98
+
99
+
100
+ def _network_effect(network: Any, source: str) -> Dict[str, Any]:
101
+ out: Dict[str, Any] = {}
102
+ _copy_if_truthy(out, "description", network)
103
+ _copy_if_truthy(out, "domains", network)
104
+ _copy(out, "idempotent", network)
105
+ _copy_if_truthy(out, "idempotency_key", network)
106
+ _copy_if_truthy(out, "idempotent_note", network)
107
+ out["source"] = source
108
+ return out
109
+
110
+
111
+ class _Derivation:
112
+ def __init__(self) -> None:
113
+ self.side_effects: List[str] = []
114
+ self.reads: List[Any] = []
115
+ self.writes: List[Any] = []
116
+ self.network: List[Any] = []
117
+ self.risk_levels: List[Any] = []
118
+ self.execution_mode: Any = None
119
+ self.confirmation = False
120
+
121
+ def add_side_effect(self, effect: str) -> None:
122
+ if effect not in self.side_effects:
123
+ self.side_effects.append(effect)
124
+
125
+ def add_write(self, write: Dict[str, Any]) -> None:
126
+ # Every derived write, and only a write, puts file_write among the side effects.
127
+ self.add_side_effect("file_write")
128
+ self.writes.append(write)
129
+
130
+ def add_effects(self, effects: Any, source: str, is_command: bool) -> None:
131
+ self.risk_levels.append(_risk_level(effects))
132
+ if _source_requires_confirmation(effects):
133
+ self.confirmation = True
134
+ writes = _get(effects, "writes")
135
+ if _truthy(writes) and isinstance(writes, list):
136
+ for w in writes:
137
+ self.add_write(_semantic_write(w, source))
138
+ reads = _get(effects, "reads")
139
+ if _truthy(reads) and isinstance(reads, list):
140
+ for r in reads:
141
+ self.reads.append(_semantic_read(r, source))
142
+ network = _get(effects, "network")
143
+ if _truthy(network):
144
+ self.add_side_effect("network")
145
+ if isinstance(network, dict):
146
+ self.network.append(_network_effect(network, source))
147
+ mode = _get(effects, "execution_mode")
148
+ if _truthy(mode) and (is_command or self.execution_mode is None):
149
+ self.execution_mode = mode
150
+
151
+
152
+ def _derive_policy(command_id: str, definition: Any, options: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
153
+ d = _Derivation()
154
+ effects = _get(definition, "effects")
155
+ if _truthy(effects):
156
+ d.add_effects(effects, f"command:{command_id}", True)
157
+
158
+ for name, inp in options.items():
159
+ if not _is_option_active(inp["definition"], inp["value"], inp["specified"]):
160
+ continue
161
+ source = f"option:{name}"
162
+ file = _get(inp["definition"], "file")
163
+ if _truthy(file):
164
+ value = inp["value"]
165
+ mode = _get(file, "mode")
166
+ if mode in ("read", "readWrite"):
167
+ read: Dict[str, Any] = {"kind": "option-file", "option": name}
168
+ if isinstance(value, str):
169
+ read["path"] = value
170
+ read["source"] = source
171
+ d.reads.append(read)
172
+ if mode in ("write", "append", "readWrite"):
173
+ write: Dict[str, Any] = {"kind": "option-file", "option": name}
174
+ if isinstance(value, str):
175
+ write["path"] = value
176
+ write["mode"] = mode
177
+ write["source"] = source
178
+ d.add_write(write)
179
+ option_effects = _get(inp["definition"], "effects")
180
+ if _truthy(option_effects):
181
+ d.add_effects(option_effects, source, False)
182
+
183
+ final_risk: Any = "low"
184
+ max_order = 0
185
+ for level in d.risk_levels:
186
+ n = _risk(level)
187
+ if n is not None and n > max_order:
188
+ max_order = n
189
+ final_risk = level
190
+
191
+ secrets: List[str] = []
192
+ env = _get(definition, "env")
193
+ if isinstance(env, dict):
194
+ for env_name, var in env.items():
195
+ if _truthy(_get(var, "sensitive")):
196
+ secrets.append(env_name)
197
+
198
+ idempotent = all(w.get("idempotent") is True for w in d.writes if w.get("kind") == "semantic") and all(
199
+ n.get("idempotent") is True for n in d.network
200
+ )
201
+
202
+ policy: Dict[str, Any] = {
203
+ "risk_level": final_risk,
204
+ "requires_confirmation": d.confirmation,
205
+ "idempotent": idempotent,
206
+ "side_effects": list(d.side_effects),
207
+ "reads": d.reads,
208
+ "writes": d.writes,
209
+ }
210
+ if d.network:
211
+ policy["network"] = d.network
212
+ if d.execution_mode is not None:
213
+ policy["execution_mode"] = d.execution_mode
214
+ if secrets:
215
+ policy["requires_secrets"] = secrets
216
+ return policy
217
+
218
+
219
+ def introspect(command_id: str, definition: Any, option_values: Dict[str, Any]) -> Dict[str, Any]:
220
+ """Derives a command's policy from the option values the program parsed for it (introspectCommand)."""
221
+ options: Dict[str, Dict[str, Any]] = {}
222
+ active: List[str] = []
223
+ defs = _get(definition, "options")
224
+ for opt in defs if isinstance(defs, list) else []:
225
+ name = _get(opt, "name")
226
+ name = name if isinstance(name, str) else ""
227
+ key = camel_case(name)
228
+ value = option_values.get(key)
229
+ specified = key in option_values and value is not None
230
+ options[name] = {"definition": opt, "value": value, "specified": specified}
231
+ if _is_option_active(opt, value, specified):
232
+ active.append(name)
233
+ return {
234
+ "command": command_id,
235
+ "active_options": active,
236
+ "policy": _derive_policy(command_id, definition, options),
237
+ }