function-sequence 0.2.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.
@@ -0,0 +1,302 @@
1
+ """A shared sequential state machine with calls at explicit yield boundaries."""
2
+
3
+ from contextlib import contextmanager, nullcontext
4
+ from dataclasses import dataclass, replace
5
+ from enum import StrEnum
6
+ import inspect
7
+ from typing import Any, Callable
8
+ from uuid import uuid4
9
+
10
+ from .control import Control, _current
11
+ from ._budget import execution_scope
12
+ from .definitions import Script, resolve, _is_async_callable
13
+ from .errors import (
14
+ BusyError, CheckpointError, DefinitionError, DefinitionMismatchError,
15
+ RecoveryRequiredError, StepFailedError, ResolutionError,
16
+ )
17
+ from .storage import CheckpointStore
18
+ from .values import copy_json, encode_json
19
+
20
+
21
+ class Status(StrEnum):
22
+ READY = "ready"
23
+ RUNNING = "running"
24
+ PAUSED = "paused"
25
+ COMPLETED = "completed"
26
+ FAILED = "failed"
27
+ INTERRUPTED = "interrupted"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class RunResult:
32
+ status: Status
33
+ next_step: int
34
+ completed: tuple[str, ...]
35
+ results: dict[str, Any]
36
+ run_id: str
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Event:
41
+ kind: str
42
+ script: str
43
+ step_id: str | None
44
+ next_step: int
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class _State:
49
+ fingerprint: str
50
+ run_id: str
51
+ status: Status = Status.READY
52
+ cursor: int = 0
53
+ active_step: str | None = None
54
+ results: dict | None = None
55
+ error_type: str | None = None
56
+
57
+ def __post_init__(self):
58
+ if self.results is None:
59
+ object.__setattr__(self, "results", {})
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class _Call:
64
+ function: Callable
65
+ args: tuple
66
+ kwargs: dict
67
+
68
+
69
+ def _result(script: Script, state: _State) -> RunResult:
70
+ return RunResult(state.status, state.cursor, script.step_ids[:state.cursor],
71
+ copy_json(state.results), state.run_id)
72
+
73
+
74
+ def _options(pace, control, observer, console_log):
75
+ if pace not in ("auto", "function", "pause"):
76
+ raise ValueError("pace must be 'auto', 'function' or 'pause'; line stepping is unsupported")
77
+ if control is not None and not isinstance(control, Control):
78
+ raise TypeError("control must be a Control")
79
+ if observer is not None and not callable(observer):
80
+ raise TypeError("observer must be callable")
81
+ if observer is not None and inspect.iscoroutinefunction(observer):
82
+ raise TypeError("observer must be synchronous")
83
+ if type(console_log) is not bool:
84
+ raise TypeError("console_log must be bool")
85
+ return control if control is not None else Control()
86
+
87
+
88
+ def _drive(script, state, persist, *, pace, control, observer, console_log, retry):
89
+ def emit(kind, step_id=None):
90
+ event = Event(kind, script.name, step_id, state.cursor)
91
+ if console_log:
92
+ print(f"{event.script}: {event.kind}" + (f" {step_id}" if step_id else ""))
93
+ if observer is not None:
94
+ observed = observer(event)
95
+ if inspect.isawaitable(observed):
96
+ if inspect.iscoroutine(observed):
97
+ observed.close()
98
+ raise TypeError("observer must be synchronous")
99
+
100
+ if state.active_step is not None:
101
+ if not retry:
102
+ raise RecoveryRequiredError("An uncertain step requires retry=True or restart=True")
103
+ state = replace(state, active_step=None, status=Status.PAUSED, error_type=None)
104
+ persist(state)
105
+ while state.cursor < len(script._steps):
106
+ if control.pause_requested:
107
+ state = replace(state, status=Status.PAUSED)
108
+ persist(state)
109
+ emit("paused")
110
+ return _result(script, state)
111
+ step = script._steps[state.cursor]
112
+ # Resolve and notify before creating uncertainty about an external call.
113
+ try:
114
+ args = tuple(resolve(value, state.results) for value in step.args)
115
+ kwargs = {key: resolve(value, state.results) for key, value in step.kwargs.items()}
116
+ except ResolutionError as error:
117
+ error.step_id = step.step_id
118
+ raise
119
+ emit("starting", step.step_id)
120
+ # Observers may also request STOP; honor it before the callable starts.
121
+ if control.pause_requested:
122
+ continue
123
+ active = replace(state, status=Status.RUNNING, active_step=step.step_id, error_type=None)
124
+ persist(active)
125
+ state = active
126
+ # A disk write may take long enough for STOP to arrive after the first
127
+ # check. No callable has run yet, so this is still a safe pause boundary.
128
+ if control.pause_requested:
129
+ state = replace(state, status=Status.PAUSED, active_step=None)
130
+ persist(state)
131
+ emit("paused")
132
+ return _result(script, state)
133
+ try:
134
+ token = _current.set((control, pace))
135
+ try:
136
+ output = None if step.function is None else (yield _Call(step.function, args, kwargs))
137
+ finally:
138
+ _current.reset(token)
139
+ encode_json(output)
140
+ committed = replace(state, cursor=state.cursor + 1, active_step=None,
141
+ results={**state.results, step.step_id: copy_json(output)})
142
+ persist(committed)
143
+ state = committed
144
+ except BaseException as error:
145
+ failed = replace(state, status=Status.FAILED if isinstance(error, Exception)
146
+ else Status.INTERRUPTED, error_type=type(error).__name__[:128])
147
+ try:
148
+ persist(failed)
149
+ except BaseException:
150
+ # The pre-call marker still records uncertainty if storage fails.
151
+ pass
152
+ if not isinstance(error, Exception):
153
+ raise
154
+ raise StepFailedError(step.step_id) from error
155
+ emit("finished", step.step_id)
156
+ if state.cursor < len(script._steps) and (
157
+ control.pause_requested or (pace == "function" and step.function is not None)
158
+ or (pace == "pause" and step.function is None)
159
+ ):
160
+ state = replace(state, status=Status.PAUSED)
161
+ persist(state)
162
+ emit("paused")
163
+ return _result(script, state)
164
+ state = replace(state, status=Status.COMPLETED)
165
+ persist(state)
166
+ emit("completed")
167
+ return _result(script, state)
168
+
169
+
170
+ def _call_sync(call):
171
+ output = call.function(*call.args, **call.kwargs)
172
+ if inspect.isawaitable(output):
173
+ if inspect.iscoroutine(output):
174
+ output.close()
175
+ raise DefinitionError("Synchronous run cannot await this step; use arun()")
176
+ return output
177
+
178
+
179
+ def _pump_sync(driver):
180
+ try:
181
+ call = next(driver)
182
+ while True:
183
+ try:
184
+ output = _call_sync(call)
185
+ except BaseException as error:
186
+ call = driver.throw(error)
187
+ else:
188
+ call = driver.send(output)
189
+ except StopIteration as done:
190
+ return done.value
191
+ finally:
192
+ driver.close()
193
+
194
+
195
+ def _document(state):
196
+ return {"schema": 1, "fingerprint": state.fingerprint, "run_id": state.run_id,
197
+ "status": str(state.status), "cursor": state.cursor,
198
+ "active_step": state.active_step, "results": state.results,
199
+ "error_type": state.error_type}
200
+
201
+
202
+ def _restore(script, data):
203
+ if data["fingerprint"] != script.fingerprint:
204
+ raise DefinitionMismatchError("Checkpoint belongs to a different script definition")
205
+ cursor = data["cursor"]
206
+ if cursor > len(script._steps) or set(data["results"]) != set(script.step_ids[:cursor]):
207
+ raise CheckpointError("Checkpoint outputs are not the completed prefix")
208
+ if data["active_step"] is not None and (
209
+ cursor == len(script._steps) or data["active_step"] != script.step_ids[cursor]
210
+ ):
211
+ raise CheckpointError("Checkpoint active step is inconsistent")
212
+ if data["status"] == "completed" and cursor != len(script._steps):
213
+ raise CheckpointError("Checkpoint completion is inconsistent")
214
+ if any(step.function is None and data["results"][step.step_id] is not None
215
+ for step in script._steps[:cursor]):
216
+ raise CheckpointError("Pause marker output must be null")
217
+ return _State(data["fingerprint"], data["run_id"], Status(data["status"]), cursor,
218
+ data["active_step"], data["results"], data["error_type"])
219
+
220
+
221
+ @contextmanager
222
+ def _session(script, checkpoint, restart, retry):
223
+ if type(restart) is not bool or type(retry) is not bool or (restart and retry):
224
+ raise ValueError("restart and retry must be booleans and cannot both be true")
225
+ if not script._lock.acquire(blocking=False):
226
+ raise BusyError("Script is already executing")
227
+ try:
228
+ store = CheckpointStore(checkpoint) if checkpoint is not None else None
229
+ selected = str(store.path) if store is not None else None
230
+ if script._state is not None and script._checkpoint_path != selected and not restart:
231
+ raise DefinitionError("Use a fresh Script or restart=True to select different progress storage")
232
+ with store.owned() if store is not None else nullcontext():
233
+ state = None if restart else script._state
234
+ if store is not None and not restart:
235
+ data = store.read()
236
+ if data is None and script._state is not None:
237
+ raise CheckpointError("Progress disappeared; explicit restart is required")
238
+ state = _restore(script, data) if data is not None else None
239
+ if state is None:
240
+ state = _State(script.fingerprint, str(uuid4()))
241
+
242
+ def persist(updated):
243
+ if store is not None:
244
+ store.save(_document(updated))
245
+ script._state = updated
246
+ script._checkpoint_path = selected
247
+
248
+ persist(state)
249
+ yield state, persist
250
+ finally:
251
+ script._lock.release()
252
+
253
+
254
+ def run(script: Script, *, pace="auto", control=None, observer=None,
255
+ console_log=False, restart=False, retry=False, checkpoint=None) -> RunResult:
256
+ control = _options(pace, control, observer, console_log)
257
+ if any(_is_async_callable(step.function) for step in script._steps):
258
+ raise DefinitionError("Script contains asynchronous functions; use arun()")
259
+ with execution_scope(), _session(script, checkpoint, restart, retry) as (state, persist):
260
+ return _pump_sync(_drive(script, state, persist, pace=pace, control=control,
261
+ observer=observer, console_log=console_log, retry=retry))
262
+
263
+
264
+ async def _pump_async(driver):
265
+ try:
266
+ call = next(driver)
267
+ while True:
268
+ try:
269
+ output = call.function(*call.args, **call.kwargs)
270
+ if inspect.isawaitable(output):
271
+ output = await output
272
+ except BaseException as error:
273
+ call = driver.throw(error)
274
+ else:
275
+ call = driver.send(output)
276
+ except StopIteration as done:
277
+ return done.value
278
+ finally:
279
+ driver.close()
280
+
281
+
282
+ async def arun(script: Script, *, pace="auto", control=None, observer=None,
283
+ console_log=False, restart=False, retry=False, checkpoint=None) -> RunResult:
284
+ """Await a sequential queue; synchronous functions execute on the calling thread."""
285
+ control = _options(pace, control, observer, console_log)
286
+ with execution_scope(), _session(script, checkpoint, restart, retry) as (state, persist):
287
+ return await _pump_async(_drive(script, state, persist, pace=pace, control=control,
288
+ observer=observer, console_log=console_log, retry=retry))
289
+
290
+
291
+ def delete_progress(script, checkpoint=None):
292
+ if not script._lock.acquire(blocking=False):
293
+ raise BusyError("Script is already executing")
294
+ try:
295
+ selected = checkpoint if checkpoint is not None else script._checkpoint_path
296
+ removed = CheckpointStore(selected).delete() if selected is not None else script._state is not None
297
+ if selected is None or str(CheckpointStore(selected).path) == script._checkpoint_path:
298
+ script._state = None
299
+ script._checkpoint_path = None
300
+ return removed
301
+ finally:
302
+ script._lock.release()
@@ -0,0 +1,164 @@
1
+ """Passive bounded checkpoints on a caller-selected local filesystem path."""
2
+
3
+ from contextlib import contextmanager
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import stat
8
+ import tempfile
9
+ from uuid import UUID
10
+
11
+ from .errors import BusyError, CheckpointError, InvalidValueError
12
+ from .values import MAX_BYTES, decode_json, encode_json
13
+
14
+ _FIELDS = {"schema", "fingerprint", "run_id", "status", "cursor", "active_step",
15
+ "results", "error_type"}
16
+ _STATUSES = {"ready", "running", "paused", "completed", "failed", "interrupted"}
17
+
18
+
19
+ def validate_document(data: dict) -> dict:
20
+ """Validate the storage schema without importing any script code."""
21
+ def require(condition):
22
+ if not condition:
23
+ raise CheckpointError("Checkpoint schema or progress is invalid")
24
+
25
+ require(type(data) is dict and set(data) == _FIELDS)
26
+ require(type(data["schema"]) is int and data["schema"] == 1)
27
+ require(type(data["fingerprint"]) is str and
28
+ re.fullmatch(r"[0-9a-f]{64}", data["fingerprint"]) is not None)
29
+ require(type(data["run_id"]) is str)
30
+ try:
31
+ run_id = UUID(data["run_id"])
32
+ require(str(run_id) == data["run_id"] and run_id.version == 4)
33
+ except ValueError:
34
+ raise CheckpointError("Checkpoint run identity is invalid") from None
35
+ require(type(data["status"]) is str and data["status"] in _STATUSES)
36
+ require(type(data["cursor"]) is int and data["cursor"] >= 0)
37
+ require(type(data["results"]) is dict and len(data["results"]) == data["cursor"])
38
+ require(all(type(key) is str and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", key)
39
+ for key in data["results"]))
40
+ active = data["active_step"]
41
+ require(active is None or (type(active) is str and
42
+ re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", active) is not None))
43
+ require(active is None or (active not in data["results"] and
44
+ data["status"] in {"running", "failed", "interrupted"}))
45
+ error = data["error_type"]
46
+ if data["status"] in {"failed", "interrupted"}:
47
+ require(active is not None and type(error) is str and 0 < len(error) <= 128
48
+ and all(ord(char) >= 32 for char in error))
49
+ else:
50
+ require(error is None)
51
+ if data["status"] == "ready":
52
+ require(data["cursor"] == 0 and active is None)
53
+ # Callers may pass raw data directly, so validate every value too.
54
+ try:
55
+ return decode_json(encode_json(data))
56
+ except InvalidValueError:
57
+ raise CheckpointError("Checkpoint contains invalid or excessive JSON data") from None
58
+
59
+
60
+ def _regular(path: Path):
61
+ try:
62
+ info = path.lstat()
63
+ except FileNotFoundError:
64
+ return None
65
+ if not stat.S_ISREG(info.st_mode):
66
+ raise CheckpointError("Checkpoint and lock paths must be regular files")
67
+ return info
68
+
69
+
70
+ class CheckpointStore:
71
+ """Explicit JSON storage. Parent directories must already exist."""
72
+
73
+ def __init__(self, path: str | os.PathLike) -> None:
74
+ self.path = Path(path).absolute()
75
+ self.lock_path = self.path.with_name(self.path.name + ".lock")
76
+ self._owned = False
77
+
78
+ @contextmanager
79
+ def owned(self):
80
+ """Acquire exclusive ownership. Stale locks require manual inspection."""
81
+ if self._owned:
82
+ raise BusyError("Checkpoint is already owned")
83
+ try:
84
+ fd = os.open(self.lock_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL
85
+ | getattr(os, "O_NOFOLLOW", 0), 0o600)
86
+ except FileExistsError:
87
+ raise BusyError("Checkpoint lock exists; verify its owner before removing it") from None
88
+ except OSError as error:
89
+ raise CheckpointError("Checkpoint lock could not be created") from error
90
+ identity = os.fstat(fd)
91
+ self._owned = True
92
+ try:
93
+ with os.fdopen(fd, "wb") as stream:
94
+ stream.write(f"pid={os.getpid()}\n".encode("ascii"))
95
+ stream.flush()
96
+ os.fsync(stream.fileno())
97
+ yield self
98
+ finally:
99
+ self._owned = False
100
+ try:
101
+ current = _regular(self.lock_path)
102
+ if current is None or (current.st_dev, current.st_ino) != (identity.st_dev, identity.st_ino):
103
+ raise CheckpointError("Checkpoint lock ownership changed")
104
+ self.lock_path.unlink()
105
+ except OSError as error:
106
+ raise CheckpointError("Checkpoint lock could not be released") from error
107
+
108
+ def read(self) -> dict | None:
109
+ """Read passive metadata without importing code or creating a lock."""
110
+ try:
111
+ before = _regular(self.path)
112
+ if before is None:
113
+ return None
114
+ fd = os.open(self.path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
115
+ with os.fdopen(fd, "rb") as stream:
116
+ actual = os.fstat(stream.fileno())
117
+ if not stat.S_ISREG(actual.st_mode) or (before.st_dev, before.st_ino) != (actual.st_dev, actual.st_ino):
118
+ raise CheckpointError("Checkpoint changed while opening it")
119
+ payload = stream.read(MAX_BYTES + 1)
120
+ return validate_document(decode_json(payload))
121
+ except InvalidValueError:
122
+ raise CheckpointError("Checkpoint is not valid bounded JSON") from None
123
+ except OSError as error:
124
+ raise CheckpointError("Checkpoint could not be read") from error
125
+
126
+ def save(self, data: dict) -> None:
127
+ if not self._owned:
128
+ raise BusyError("Saving progress requires checkpoint ownership")
129
+ payload = encode_json(validate_document(data))
130
+ temporary = None
131
+ try:
132
+ _regular(self.path)
133
+ fd, name = tempfile.mkstemp(prefix=f".{self.path.name}.", suffix=".tmp", dir=self.path.parent)
134
+ temporary = Path(name)
135
+ with os.fdopen(fd, "wb") as stream:
136
+ stream.write(payload)
137
+ stream.flush()
138
+ os.fsync(stream.fileno())
139
+ # Recheck before replacement; hostile directory mutation is out of scope.
140
+ _regular(self.path)
141
+ os.replace(temporary, self.path)
142
+ temporary = None
143
+ if os.name == "posix":
144
+ directory = os.open(self.path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
145
+ try:
146
+ os.fsync(directory)
147
+ finally:
148
+ os.close(directory)
149
+ except OSError as error:
150
+ raise CheckpointError("Checkpoint could not be atomically saved") from error
151
+ finally:
152
+ if temporary is not None:
153
+ temporary.unlink(missing_ok=True)
154
+
155
+ def delete(self) -> bool:
156
+ """Explicitly remove this progress file under exclusive ownership."""
157
+ with self.owned():
158
+ try:
159
+ if _regular(self.path) is None:
160
+ return False
161
+ self.path.unlink()
162
+ return True
163
+ except OSError as error:
164
+ raise CheckpointError("Checkpoint could not be deleted") from error
@@ -0,0 +1,193 @@
1
+ """Optional Carets frontend over the same passive workflow/application API."""
2
+
3
+ import sys
4
+
5
+ if sys.version_info < (3, 14):
6
+ raise ImportError("The workflow terminal requires the terminal profile on Python 3.14+")
7
+
8
+ import contextlib
9
+ from dataclasses import dataclass, replace
10
+ import io
11
+ import json
12
+
13
+ from carets import Command, CommandErrorMsg, FocusManager, Form, Group, KeyMsg, Msg, Program, TerminalOptions, TerminalSession, TypedField, WindowSizeMsg
14
+ from carets.components import TextInput
15
+ from carets.renderer import CellDiffRenderer
16
+ from carets.style import truncate_ansi
17
+ from function_sequence import Control
18
+
19
+ from .application import execute
20
+ from .workflow import decode_json
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ProgressMsg(Msg):
25
+ kind: str
26
+ step_id: str | None
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class OutcomeMsg(Msg):
31
+ outcome: dict
32
+
33
+
34
+ def _input_values(text):
35
+ envelope = decode_json(text, source="terminal inputs")
36
+ if type(envelope) is not dict or set(envelope) != {"schema", "inputs"} or type(envelope["schema"]) is not int or envelope["schema"] != 1 or type(envelope["inputs"]) is not dict:
37
+ raise ValueError("Use a schema-1 inputs object")
38
+ return envelope["inputs"]
39
+
40
+
41
+ def _visible(text):
42
+ return "".join(char if char.isprintable() else f"\\u{ord(char):04x}" for char in str(text))
43
+
44
+
45
+ class WorkflowTerminal:
46
+ """A testable update/view model. The host supplies resolver and resource policy."""
47
+
48
+ def __init__(self, workflow, resolver, *, resolver_version, checkpoint, inputs=None):
49
+ self.workflow, self.resolver = workflow, resolver
50
+ self.resolver_version, self.checkpoint = resolver_version, checkpoint
51
+ self.names = tuple(dict.fromkeys(step.operation for step in workflow.definition.steps))
52
+ self.checked = set()
53
+ self.selected_index = 0
54
+ initial = json.dumps({"schema": 1, "inputs": inputs if inputs is not None else {}}, ensure_ascii=False)
55
+ self.input = TextInput(initial, cursor=len(initial))
56
+ self.form = Form([Group([TypedField("inputs", "Inputs", _input_values, default=initial)])])
57
+ self.focus = FocusManager()
58
+ for name in ("inputs", "operations", "actions"):
59
+ self.focus.register(name)
60
+ self.width, self.height = 80, 24
61
+ self.status, self.progress = "ready", ""
62
+ self.outcome = None
63
+ self.control = Control()
64
+ self.program = None
65
+ self.exit_requested = False
66
+ self._layout()
67
+
68
+ def attach(self, program):
69
+ self.program = program
70
+
71
+ def _layout(self):
72
+ for name, y in (("inputs", 1), ("operations", 2), ("actions", max(0, self.height - 2))):
73
+ self.focus.zones.define(name, 0, min(y, self.height - 1), self.width, 1)
74
+
75
+ def start(self, *, resume=False, retry=False, restart=False):
76
+ if self.status == "running":
77
+ return None
78
+ if self.checked != set(self.names):
79
+ self.progress = "Select every required operation before execution"
80
+ return None
81
+ self.form.update("inputs", self.input.value)
82
+ result = self.form.submit()
83
+ if result.status != "valid":
84
+ self.progress = "Inputs must be valid schema-1 JSON"
85
+ return None
86
+ if self.program is None:
87
+ raise RuntimeError("Attach this model to a Program before execution")
88
+ self.status, self.progress, self.outcome = "running", "starting", None
89
+ self.control = Control()
90
+
91
+ def observe(event):
92
+ self.program.post(ProgressMsg(event.kind, event.step_id))
93
+
94
+ async def produce():
95
+ outcome = await execute(self.workflow, self.resolver, resolver_version=self.resolver_version,
96
+ inputs=result.values["inputs"], checkpoint=self.checkpoint, resume=resume,
97
+ retry=retry, restart=restart, control=self.control, observer=observe)
98
+ return OutcomeMsg(outcome)
99
+ return Command(produce)
100
+
101
+ def update(self, message):
102
+ if isinstance(message, WindowSizeMsg):
103
+ self.width, self.height = max(1, message.width), max(1, message.height)
104
+ self._layout()
105
+ elif isinstance(message, ProgressMsg):
106
+ self.progress = message.kind + (f" {message.step_id}" if message.step_id else "")
107
+ elif isinstance(message, OutcomeMsg):
108
+ self.outcome = message.outcome
109
+ self.status = self.outcome["status"]
110
+ if self.exit_requested:
111
+ self.program.stop()
112
+ elif isinstance(message, CommandErrorMsg):
113
+ self.status = "error"
114
+ self.progress = type(message.error).__name__ + "; resume/retry/restart are explicit choices"
115
+ self.outcome = {"schema": 1, "status": "error", "error": type(message.error).__name__}
116
+ if self.exit_requested:
117
+ self.program.stop()
118
+ elif isinstance(message, KeyMsg):
119
+ if message.key == "ctrl-c" or (message.key == "q" and (self.focus.focused != "inputs" or self.status == "running")):
120
+ if self.status == "running":
121
+ self.exit_requested = True
122
+ self.control.request_pause()
123
+ elif self.program is not None:
124
+ self.program.stop()
125
+ elif message.key == "p" and self.status == "running":
126
+ self.control.request_pause()
127
+ self.progress = "pause requested at the next cooperative boundary"
128
+ elif message.key in ("tab", "backtab", "shift-tab"):
129
+ self.focus.route(message)
130
+ elif self.status != "running" and self.focus.focused == "inputs":
131
+ self.input = replace(self.input, focused=True).update(message)
132
+ elif self.status != "running" and self.focus.focused == "operations":
133
+ if message.key in ("up", "down"):
134
+ self.selected_index = (self.selected_index + (1 if message.key == "down" else -1)) % len(self.names)
135
+ elif message.key == " ":
136
+ name = self.names[self.selected_index]
137
+ self.checked.symmetric_difference_update({name})
138
+ elif self.focus.focused == "actions":
139
+ if message.key == "enter":
140
+ return self.start()
141
+ if message.key in ("r", "t", "R"):
142
+ return self.start(resume=True, retry=message.key == "t", restart=message.key == "R")
143
+
144
+ def view(self):
145
+ count = max(1, self.height - 6)
146
+ offset = max(0, self.selected_index - count + 1)
147
+ names = self.names[offset:offset + count]
148
+ lines = [f"Workflow: {self.workflow.definition.name}",
149
+ f"{self.focus.indicator('inputs')} Inputs: {_visible(replace(self.input, focused=self.focus.focused == 'inputs').view())}",
150
+ f"{self.focus.indicator('operations')} Required operations (space selects)"]
151
+ for index, name in enumerate(names, offset):
152
+ lines.append(f" {'>' if index == self.selected_index else ' '} [{'x' if name in self.checked else ' '}] {_visible(name)}")
153
+ lines += [f"{self.focus.indicator('actions')} Enter run | r resume | t retry | R restart | p pause | q quit",
154
+ f"Status: {self.status} {_visible(self.progress)}"]
155
+ return "\n".join(truncate_ansi(line, self.width) for line in lines[:self.height])
156
+
157
+
158
+ class _Renderer:
159
+ def __init__(self, model):
160
+ self.model = model
161
+ self.size = None
162
+ self.renderer = None
163
+
164
+ def render(self, view):
165
+ size = self.model.width, self.model.height
166
+ if size != self.size:
167
+ self.size = size
168
+ self.renderer = CellDiffRenderer(*size)
169
+ return self.renderer.render(view)
170
+
171
+
172
+ async def run_terminal(workflow, resolver, *, resolver_version, checkpoint, inputs=None,
173
+ input_stream=None, output_stream=None, diagnostics=None, messages=None):
174
+ """Select terminal ownership explicitly; flush trusted diagnostics after teardown."""
175
+ input_stream = input_stream if input_stream is not None else sys.stdin.buffer
176
+ output_stream = output_stream if output_stream is not None else sys.stderr
177
+ diagnostics = diagnostics if diagnostics is not None else sys.stderr
178
+ session = TerminalSession(input_stream, output_stream,
179
+ options=TerminalOptions(alternate_screen=True, bracketed_paste=True))
180
+ if messages is None and (not session.capabilities.raw or not session.capabilities.tty):
181
+ raise ValueError("Interactive input requires a supported POSIX TTY; library/CLI execution remains available")
182
+ model = WorkflowTerminal(workflow, resolver, resolver_version=resolver_version, checkpoint=checkpoint, inputs=inputs)
183
+ program = Program(model, input_stream=input_stream, output_stream=output_stream,
184
+ renderer=_Renderer(model), terminal=session)
185
+ model.attach(program)
186
+ buffer = io.StringIO()
187
+ try:
188
+ with contextlib.redirect_stdout(buffer), contextlib.redirect_stderr(buffer):
189
+ await program.run(messages, stop_on_eof=messages is None)
190
+ finally:
191
+ diagnostics.write(buffer.getvalue())
192
+ diagnostics.flush()
193
+ return model.outcome if model.outcome is not None else {"schema": 1, "status": "closed"}