Pyrophone 0.1.0__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.
pyrophone/_schema.py ADDED
@@ -0,0 +1,197 @@
1
+ """Immutable declaration metadata and shared runtime type operations."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass
5
+ from enum import Enum, auto
6
+ from functools import reduce
7
+ from operator import or_
8
+ from types import MappingProxyType, UnionType
9
+ from typing import Any, TypeVar, Union, get_args, get_origin
10
+
11
+ from ._exceptions import ConfigurationError, SchemaError
12
+
13
+
14
+ class _Missing(Enum):
15
+ TOKEN = auto()
16
+
17
+
18
+ _MISSING = _Missing.TOKEN
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class PropertySchema:
23
+ name: str
24
+ type: object
25
+ default: object = _MISSING
26
+ title: str | None = None
27
+ description: str | None = None
28
+ minimum: int | float | None = None
29
+ maximum: int | float | None = None
30
+ step: int | float | None = None
31
+
32
+ @property
33
+ def required(self) -> bool:
34
+ return self.default is _MISSING
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class PortSchema:
39
+ name: str
40
+ type: object
41
+ description: str | None = None
42
+ default: bool = False
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class NodeTypeSchema:
47
+ name: str
48
+ description: str | None
49
+ properties: Mapping[str, PropertySchema]
50
+ inputs: Mapping[str, PortSchema]
51
+ outputs: Mapping[str, PortSchema]
52
+
53
+ def __post_init__(self) -> None:
54
+ # Own each mapping: subsequent changes to a caller's dictionary cannot
55
+ # mutate a registered schema.
56
+ object.__setattr__(self, "properties", MappingProxyType(dict(self.properties)))
57
+ object.__setattr__(self, "inputs", MappingProxyType(dict(self.inputs)))
58
+ object.__setattr__(self, "outputs", MappingProxyType(dict(self.outputs)))
59
+
60
+
61
+ _CONTAINERS = (list, dict, tuple, set, frozenset)
62
+
63
+
64
+ def substitute_type(spec: object, substitutions: Mapping[TypeVar, object]) -> object:
65
+ """Resolve type variables recursively, preserving parameterized containers."""
66
+ if isinstance(spec, TypeVar):
67
+ return substitutions.get(spec, spec)
68
+ origin = get_origin(spec)
69
+ if origin not in (*_CONTAINERS, Union, UnionType):
70
+ # Leave unsupported forms intact so validate_type reports a contextual
71
+ # SchemaError rather than leaking an error from alias reconstruction.
72
+ return spec
73
+ args = tuple(substitute_type(arg, substitutions) for arg in get_args(spec))
74
+ if origin in (Union, UnionType):
75
+ # Dynamic type construction is intentionally confined to this boundary.
76
+ return _make_union(args)
77
+ return _parameterize(spec, origin, args)
78
+
79
+
80
+ def _make_union(args: tuple[object, ...]) -> object:
81
+ dynamic_args: Any = args
82
+ return reduce(or_, dynamic_args)
83
+
84
+
85
+ def _parameterize(spec: object, origin: object, args: tuple[object, ...]) -> object:
86
+ # typing aliases expose copy_with; builtin GenericAlias uses subscription.
87
+ dynamic_spec: Any = spec
88
+ dynamic_origin: Any = origin
89
+ if hasattr(spec, "copy_with"):
90
+ return dynamic_spec.copy_with(args)
91
+ return dynamic_origin[args]
92
+
93
+
94
+ def validate_type(spec: object, name: str = "type") -> None:
95
+ """Reject types for which value validation has no well-defined behavior."""
96
+ if spec is Any:
97
+ return
98
+ if isinstance(spec, TypeVar):
99
+ raise SchemaError(f"{name}: unresolved type variable {spec}")
100
+ origin = get_origin(spec)
101
+ args = get_args(spec)
102
+ if origin in (Union, UnionType):
103
+ for arg in args:
104
+ validate_type(arg, name)
105
+ return
106
+ if origin in _CONTAINERS:
107
+ if origin is dict and len(args) != 2:
108
+ raise SchemaError(f"{name}: unsupported dictionary type {spec}")
109
+ if origin in (list, set, frozenset) and len(args) != 1:
110
+ raise SchemaError(f"{name}: unsupported container type {spec}")
111
+ if (
112
+ origin is tuple
113
+ and Ellipsis in args
114
+ and not (len(args) == 2 and args[1] is Ellipsis)
115
+ ):
116
+ raise SchemaError(f"{name}: unsupported tuple type {spec}")
117
+ for index, arg in enumerate(args):
118
+ if origin is tuple and index == 1 and arg is Ellipsis:
119
+ continue
120
+ validate_type(arg, name)
121
+ return
122
+ if origin is None and isinstance(spec, type):
123
+ if getattr(spec, "_is_protocol", False):
124
+ raise SchemaError(f"{name}: unsupported protocol type {spec}")
125
+ try:
126
+ isinstance(None, spec)
127
+ except TypeError as error:
128
+ raise SchemaError(f"{name}: unsupported runtime type {spec}") from error
129
+ return
130
+ raise SchemaError(f"{name}: unsupported type {spec!r}")
131
+
132
+
133
+ def _matches(value: object, spec: object) -> bool:
134
+ if spec is Any:
135
+ return True
136
+ origin = get_origin(spec)
137
+ args = get_args(spec)
138
+ if origin in (Union, UnionType):
139
+ return any(_matches(value, arg) for arg in args)
140
+ if origin is dict:
141
+ return isinstance(value, dict) and all(
142
+ _matches(key, args[0]) and _matches(item, args[1])
143
+ for key, item in value.items()
144
+ )
145
+ if origin is tuple:
146
+ if not isinstance(value, tuple):
147
+ return False
148
+ if len(args) == 2 and args[1] is Ellipsis:
149
+ return all(_matches(item, args[0]) for item in value)
150
+ return len(value) == len(args) and all(
151
+ _matches(item, arg) for item, arg in zip(value, args, strict=True)
152
+ )
153
+ if origin in (list, set, frozenset):
154
+ return isinstance(value, origin) and all(
155
+ _matches(item, args[0]) for item in value
156
+ )
157
+ return isinstance(spec, type) and isinstance(value, spec)
158
+
159
+
160
+ def validate_value(value: object, spec: object, name: str) -> None:
161
+ validate_type(spec, name)
162
+ if not _matches(value, spec):
163
+ raise ConfigurationError(f"{name}: expected {spec}, got {type(value).__name__}")
164
+
165
+
166
+ def is_type_compatible(source: object, destination: object) -> bool:
167
+ """Conservatively decide whether every source value fits the destination."""
168
+ validate_type(source, "source")
169
+ validate_type(destination, "destination")
170
+ if source == destination or destination is Any:
171
+ return True
172
+ if source is Any:
173
+ return False
174
+ source_origin, destination_origin = get_origin(source), get_origin(destination)
175
+ if source_origin in (Union, UnionType):
176
+ return all(is_type_compatible(arg, destination) for arg in get_args(source))
177
+ if destination_origin in (Union, UnionType):
178
+ return any(is_type_compatible(source, arg) for arg in get_args(destination))
179
+ # Parameterized containers are invariant. A container itself may still flow
180
+ # to an ordinary superclass such as object.
181
+ if destination_origin is not None:
182
+ return False
183
+ nominal_source = source_origin or source
184
+ return (
185
+ isinstance(nominal_source, type)
186
+ and isinstance(destination, type)
187
+ and issubclass(nominal_source, destination)
188
+ )
189
+
190
+
191
+ def validate_property(value: object, schema: PropertySchema) -> None:
192
+ validate_value(value, schema.type, schema.name)
193
+ if isinstance(value, (int, float)):
194
+ if schema.minimum is not None and value < schema.minimum:
195
+ raise ConfigurationError(f"{schema.name}: below minimum {schema.minimum}")
196
+ if schema.maximum is not None and value > schema.maximum:
197
+ raise ConfigurationError(f"{schema.name}: above maximum {schema.maximum}")
pyrophone/_shell.py ADDED
@@ -0,0 +1,130 @@
1
+ """Async stdio inspection of a running graph."""
2
+
3
+ import asyncio
4
+ import builtins
5
+ import signal
6
+ import sys
7
+ from contextlib import closing
8
+ from typing import TextIO
9
+
10
+ from aioconsole import AsynchronousConsole # type: ignore[import-untyped]
11
+ from prompt_toolkit import PromptSession
12
+ from prompt_toolkit.application import create_app_session
13
+ from prompt_toolkit.input import create_input
14
+ from prompt_toolkit.output import create_output
15
+
16
+ from ._compile import CompiledGraph
17
+ from ._control import Runtime
18
+ from ._graph import Graph
19
+ from ._terminal import coordinated_output
20
+
21
+
22
+ class _ConsoleWriter:
23
+ def __init__(self, stream: TextIO) -> None:
24
+ self.stream = stream
25
+
26
+ def write(self, data: bytes) -> None:
27
+ self.stream.write(data.decode())
28
+
29
+ async def drain(self) -> None:
30
+ self.stream.flush()
31
+
32
+
33
+ class _Console(AsynchronousConsole): # type: ignore[misc]
34
+ def __init__(
35
+ self,
36
+ namespace: dict[str, object],
37
+ prompt: PromptSession[str] | None = None,
38
+ output: TextIO | None = None,
39
+ ) -> None:
40
+ self._prompt = prompt
41
+ self._output = output
42
+ # In terminal mode prompt-toolkit exclusively owns stdin. Do not let
43
+ # aioconsole also attach a read transport to the same descriptor.
44
+ streams = (None, _ConsoleWriter(output)) if output is not None else None
45
+ super().__init__(locals=namespace, streams=streams)
46
+ if prompt is not None:
47
+ self.locals["ainput"] = self.raw_input
48
+
49
+ def print(
50
+ self,
51
+ *values: object,
52
+ sep: str | None = " ",
53
+ end: str | None = "\n",
54
+ file: TextIO | None = None,
55
+ flush: bool = False,
56
+ ) -> None:
57
+ # A shell print function may be retained by a trace callback. During
58
+ # input, use the coordinated stream; between prompts, write directly.
59
+ if file is None:
60
+ editing = self._prompt is not None and self._prompt.app.is_running
61
+ file = sys.stderr if editing or self._output is None else self._output
62
+ builtins.print(*values, sep=sep, end=end, file=file, flush=flush)
63
+
64
+ async def raw_input(self, prompt: str = "") -> str:
65
+ if self._prompt is None:
66
+ result: str = await super().raw_input(prompt)
67
+ return result
68
+ try:
69
+ return await self._prompt.prompt_async(prompt, handle_sigint=False)
70
+ except KeyboardInterrupt:
71
+ # Let aioconsole reset multiline input using its usual Ctrl-C path.
72
+ self._sigint_received = True
73
+ raise asyncio.CancelledError from None
74
+
75
+ def showtraceback(self) -> None:
76
+ # aioconsole catches BaseException during evaluation. Let cancellation
77
+ # reach its input loop so graph shutdown cannot get stuck at a new prompt.
78
+ error = sys.exception()
79
+ if isinstance(error, asyncio.CancelledError):
80
+ raise error
81
+ super().showtraceback()
82
+
83
+
84
+ async def run_shell(
85
+ graph: Graph,
86
+ compiled_graph: CompiledGraph,
87
+ graph_task: asyncio.Task[None],
88
+ runtime: Runtime,
89
+ ) -> None:
90
+ """Read stdin and write prompts/results to stderr without blocking the graph.
91
+
92
+ Ctrl-C interrupts a command; EOF, exit(), and quit() return to the runtime,
93
+ which cancels the graph and awaits its cleanup.
94
+ """
95
+ from . import script
96
+
97
+ namespace = {name: getattr(script, name) for name in script.__all__}
98
+ namespace.update(
99
+ graph=graph,
100
+ compiled_graph=compiled_graph,
101
+ graph_task=graph_task,
102
+ runtime=runtime,
103
+ )
104
+ if sys.stdin.isatty() and sys.stderr.isatty():
105
+ with closing(create_input(stdin=sys.stdin)) as terminal_input:
106
+ with create_app_session(
107
+ input=terminal_input, output=create_output(stdout=sys.stderr)
108
+ ):
109
+ prompt = PromptSession[str]()
110
+ output = sys.stderr
111
+ with coordinated_output():
112
+ await _interact(_Console(namespace, prompt, output))
113
+ else:
114
+ await _interact(_Console(namespace))
115
+
116
+
117
+ async def _interact(console: _Console) -> None:
118
+ previous_sigint = signal.getsignal(signal.SIGINT)
119
+ try:
120
+ await console.interact(
121
+ banner=(
122
+ "Pyrophone shell (top-level await supported).\n"
123
+ "Available: runtime, graph, compiled_graph, graph_task, asyncio, loop, "
124
+ "and pyrophone.script names.\n"
125
+ "Ctrl-C interrupts a command; Ctrl-D or exit() stops the graph."
126
+ ),
127
+ stop=False,
128
+ )
129
+ finally:
130
+ signal.signal(signal.SIGINT, previous_sigint)
pyrophone/_terminal.py ADDED
@@ -0,0 +1,73 @@
1
+ """Coordinate terminal writes with the active input editor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextvars
7
+ import logging
8
+ import sys
9
+ from collections.abc import Iterator
10
+ from contextlib import contextmanager
11
+ from typing import TextIO, cast
12
+
13
+ from prompt_toolkit.patch_stdout import StdoutProxy
14
+
15
+
16
+ class _SessionOutputProxy(StdoutProxy):
17
+ def __init__(self) -> None:
18
+ self._context = contextvars.copy_context()
19
+ super().__init__()
20
+
21
+ def _write_and_flush(
22
+ self, loop: asyncio.AbstractEventLoop | None, text: str
23
+ ) -> None:
24
+ # The flush worker is a thread. Its callbacks must enter the shell's
25
+ # app session, or run_in_terminal cannot find the prompt to redraw.
26
+ self._context.copy().run(super()._write_and_flush, loop, text)
27
+
28
+
29
+ def _stream_handlers() -> set[logging.StreamHandler[TextIO]]:
30
+ loggers = [logging.getLogger()]
31
+ loggers.extend(
32
+ logger
33
+ for logger in logging.Logger.manager.loggerDict.copy().values()
34
+ if isinstance(logger, logging.Logger)
35
+ )
36
+ return {
37
+ handler
38
+ for logger in loggers
39
+ for handler in logger.handlers[:]
40
+ if isinstance(handler, logging.StreamHandler)
41
+ }
42
+
43
+
44
+ @contextmanager
45
+ def coordinated_output() -> Iterator[None]:
46
+ """Redraw around terminal writes, including already-configured log handlers.
47
+
48
+ An active prompt-toolkit app session selects the terminal output. Preserve
49
+ redirected stdout and file handlers, and restore streams when the shell ends.
50
+ """
51
+ stdout, stderr = sys.stdout, sys.stderr
52
+ terminal_streams = [stderr]
53
+ if stdout.isatty():
54
+ terminal_streams.append(stdout)
55
+ with _SessionOutputProxy() as output:
56
+ proxy = cast(TextIO, output)
57
+ original_streams = {}
58
+ try:
59
+ sys.stderr = proxy
60
+ if stdout.isatty():
61
+ sys.stdout = proxy
62
+ for handler in _stream_handlers():
63
+ if any(handler.stream is stream for stream in terminal_streams):
64
+ original_streams[handler] = handler.stream
65
+ handler.setStream(proxy)
66
+ yield
67
+ finally:
68
+ # Include handlers created during the session, whose default stream
69
+ # is the proxy. Do not overwrite an explicitly changed destination.
70
+ for handler in _stream_handlers() | original_streams.keys():
71
+ if handler.stream is proxy:
72
+ handler.setStream(original_streams.get(handler, stderr))
73
+ sys.stdout, sys.stderr = stdout, stderr
pyrophone/_trace.py ADDED
@@ -0,0 +1,93 @@
1
+ """Synchronous observers of accepted channel handoffs."""
2
+
3
+ import asyncio
4
+ import inspect
5
+ import logging
6
+ from collections.abc import Callable
7
+ from typing import cast
8
+
9
+ _logger = logging.getLogger(__name__)
10
+
11
+
12
+ class Trace:
13
+ """A port trace registration. close() removes it synchronously and idempotently."""
14
+
15
+ def __init__(
16
+ self, callback: Callable[[object], None], remove: Callable[[], object]
17
+ ) -> None:
18
+ self._callback: Callable[[object], None] | None = callback
19
+ self._remove = remove
20
+ self._loop = asyncio.get_running_loop()
21
+
22
+ @property
23
+ def active(self) -> bool:
24
+ return self._callback is not None
25
+
26
+ def close(self) -> None:
27
+ """Stop future notifications; call from the runtime's event loop."""
28
+ if not self.active:
29
+ return
30
+ try:
31
+ loop = asyncio.get_running_loop()
32
+ except RuntimeError:
33
+ loop = None
34
+ if loop is not self._loop:
35
+ raise RuntimeError("trace changes must run on the node's event loop")
36
+ self._remove()
37
+ self._deactivate()
38
+
39
+ def _deactivate(self) -> None:
40
+ self._callback = None
41
+
42
+ def __repr__(self) -> str:
43
+ return f"Trace(active={self.active})"
44
+
45
+
46
+ class _TraceCallbacks[T]:
47
+ def __init__(self) -> None:
48
+ self._traces: dict[object, Trace] = {}
49
+ self._closed = False
50
+
51
+ def add(self, callback: Callable[[T], None]) -> Trace:
52
+ if self._closed:
53
+ raise RuntimeError("port has closed")
54
+ call = getattr(callback, "__call__", None) # noqa: B004 - inspect async callable objects
55
+ if not callable(callback) or any(
56
+ inspect.iscoroutinefunction(fn) or inspect.isasyncgenfunction(fn)
57
+ for fn in (callback, call)
58
+ ):
59
+ raise TypeError("trace callbacks must be synchronous callables")
60
+ token = object()
61
+ trace = Trace(
62
+ cast(Callable[[object], None], callback),
63
+ lambda: self._traces.pop(token, None),
64
+ )
65
+ self._traces[token] = trace
66
+ return trace
67
+
68
+ def snapshot(self) -> tuple[Callable[[object], None], ...]:
69
+ return tuple(
70
+ trace._callback
71
+ for trace in self._traces.values()
72
+ if trace._callback is not None
73
+ )
74
+
75
+ def close(self) -> None:
76
+ self._closed = True
77
+ for trace in self._traces.values():
78
+ trace._deactivate()
79
+ self._traces.clear()
80
+
81
+
82
+ def _notify(callbacks: tuple[Callable[[object], None], ...], value: object) -> None:
83
+ for callback in callbacks:
84
+ try:
85
+ result: object = callback(value)
86
+ if inspect.isawaitable(result) or inspect.isasyncgen(result):
87
+ if inspect.iscoroutine(result):
88
+ result.close()
89
+ raise TypeError(
90
+ "trace callback returned an awaitable or async generator"
91
+ )
92
+ except Exception:
93
+ _logger.exception("Port trace callback failed")