Coverage for little_loops / fsm / executor.py: 84%
365 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
1"""FSM Executor - Runtime engine for FSM loop execution.
3This module provides the execution engine that runs FSM loops:
4- Executes actions (shell commands or slash commands)
5- Evaluates results using appropriate evaluators
6- Routes to next states based on verdicts
7- Tracks iteration count and enforces limits
8- Manages captured variables and context
9"""
11from __future__ import annotations
13import json
14import subprocess
15import sys
16import threading
17import time
18from collections.abc import Callable
19from dataclasses import dataclass, field
20from datetime import UTC, datetime
21from typing import Any, Protocol
23from little_loops.fsm.evaluators import (
24 EvaluationResult,
25 evaluate,
26 evaluate_exit_code,
27 evaluate_llm_structured,
28 evaluate_mcp_result,
29)
30from little_loops.fsm.handoff_handler import HandoffHandler
31from little_loops.fsm.interpolation import (
32 InterpolationContext,
33 InterpolationError,
34 interpolate,
35 interpolate_dict,
36)
37from little_loops.fsm.schema import FSMLoop, StateConfig
38from little_loops.fsm.signal_detector import DetectedSignal, SignalDetector
39from little_loops.session_log import get_current_session_jsonl
42@dataclass
43class ExecutionResult:
44 """Result from FSM execution.
46 Attributes:
47 final_state: Name of the state when execution stopped
48 iterations: Total iterations executed
49 terminated_by: Reason for termination (terminal, max_iterations, timeout, signal, error, handoff)
50 duration_ms: Total execution time in milliseconds
51 captured: All captured variable values
52 error: Error message if terminated_by is "error"
53 handoff: True if execution stopped due to handoff signal
54 continuation_prompt: Continuation context from handoff signal
55 """
57 final_state: str
58 iterations: int
59 terminated_by: str # "terminal", "max_iterations", "timeout", "signal", "error", "handoff"
60 duration_ms: int
61 captured: dict[str, dict[str, Any]]
62 error: str | None = None
63 handoff: bool = False
64 continuation_prompt: str | None = None
66 def to_dict(self) -> dict[str, Any]:
67 """Convert to dictionary for JSON serialization."""
68 result: dict[str, Any] = {
69 "final_state": self.final_state,
70 "iterations": self.iterations,
71 "terminated_by": self.terminated_by,
72 "duration_ms": self.duration_ms,
73 "captured": self.captured,
74 }
75 if self.error is not None:
76 result["error"] = self.error
77 if self.handoff:
78 result["handoff"] = self.handoff
79 if self.continuation_prompt is not None:
80 result["continuation_prompt"] = self.continuation_prompt
81 return result
84@dataclass
85class ActionResult:
86 """Result from action execution.
88 Attributes:
89 output: stdout from the action
90 stderr: stderr from the action
91 exit_code: Exit code from the action
92 duration_ms: Execution time in milliseconds
93 """
95 output: str
96 stderr: str
97 exit_code: int
98 duration_ms: int
101# Type for event callback
102EventCallback = Callable[[dict[str, Any]], None]
105class ActionRunner(Protocol):
106 """Protocol for action execution."""
108 def run(
109 self,
110 action: str,
111 timeout: int,
112 is_slash_command: bool,
113 on_output_line: Callable[[str], None] | None = None,
114 ) -> ActionResult:
115 """Execute an action and return the result.
117 Args:
118 action: The command to execute
119 timeout: Timeout in seconds
120 is_slash_command: True if this is a slash command (starts with /)
121 on_output_line: Optional callback invoked for each output line
123 Returns:
124 ActionResult with output, stderr, exit_code, duration_ms
125 """
126 ...
129class DefaultActionRunner:
130 """Execute actions via subprocess or Claude CLI."""
132 def __init__(self) -> None:
133 self._current_process: subprocess.Popen[str] | None = None
135 def run(
136 self,
137 action: str,
138 timeout: int,
139 is_slash_command: bool,
140 on_output_line: Callable[[str], None] | None = None,
141 ) -> ActionResult:
142 """Execute action and return result, streaming output line by line.
144 Args:
145 action: The command to execute
146 timeout: Timeout in seconds
147 is_slash_command: True if action starts with /
148 on_output_line: Optional callback invoked for each stdout line
150 Returns:
151 ActionResult with execution details
152 """
153 start = _now_ms()
155 if is_slash_command:
156 # Execute via Claude CLI
157 cmd = [
158 "claude",
159 "--dangerously-skip-permissions",
160 "--no-session-persistence",
161 "-p",
162 action,
163 ]
164 else:
165 # Shell command
166 cmd = ["bash", "-c", action]
168 process = subprocess.Popen(
169 cmd,
170 stdout=subprocess.PIPE,
171 stderr=subprocess.PIPE,
172 text=True,
173 )
174 self._current_process = process
175 output_chunks: list[str] = []
176 stderr_chunks: list[str] = []
178 def _drain_stderr() -> None:
179 assert process.stderr is not None
180 for line in process.stderr:
181 stderr_chunks.append(line)
183 stderr_thread = threading.Thread(target=_drain_stderr, daemon=True)
184 stderr_thread.start()
186 try:
187 for line in process.stdout: # type: ignore[union-attr]
188 output_chunks.append(line)
189 if on_output_line:
190 on_output_line(line.rstrip())
191 process.wait(timeout=timeout)
192 except subprocess.TimeoutExpired:
193 process.kill()
194 process.wait()
195 stderr_thread.join(timeout=5)
196 return ActionResult(
197 output="".join(output_chunks),
198 stderr="".join(stderr_chunks) or "Action timed out",
199 exit_code=124,
200 duration_ms=timeout * 1000,
201 )
202 finally:
203 self._current_process = None
204 stderr_thread.join(timeout=5)
205 stderr = "".join(stderr_chunks)
206 return ActionResult(
207 output="".join(output_chunks),
208 stderr=stderr,
209 exit_code=process.returncode,
210 duration_ms=_now_ms() - start,
211 )
214@dataclass
215class SimulationActionRunner:
216 """Action runner for simulation mode - prompts user instead of executing.
218 This runner allows users to trace through FSM logic without executing
219 real commands. It can either prompt interactively for results or use
220 predefined scenarios.
222 Attributes:
223 scenario: Predefined result pattern ("all-pass", "all-fail", "first-fail", "alternating")
224 call_count: Number of actions simulated so far
225 calls: List of all actions that would have been executed
226 """
228 scenario: str | None = None
229 call_count: int = 0
230 calls: list[str] = field(default_factory=list)
232 def run(
233 self,
234 action: str,
235 timeout: int,
236 is_slash_command: bool,
237 on_output_line: Callable[[str], None] | None = None,
238 ) -> ActionResult:
239 """Prompt user for simulated result instead of executing.
241 Args:
242 action: The command that would be executed
243 timeout: Timeout (ignored in simulation)
244 is_slash_command: Whether this is a slash command
245 on_output_line: Ignored in simulation
247 Returns:
248 ActionResult with simulated exit code
249 """
250 del timeout, on_output_line # unused in simulation
251 self.calls.append(action)
252 self.call_count += 1
254 cmd_type = "slash command" if is_slash_command else "shell command"
255 print(f" [SIMULATED] Would execute ({cmd_type}): {action}")
257 if self.scenario:
258 exit_code = self._scenario_result()
259 scenario_label = {
260 "all-pass": "Success (scenario: all-pass)",
261 "all-fail": "Failure (scenario: all-fail)",
262 "all-error": "Error (scenario: all-error)",
263 "first-fail": "Failure" if self.call_count == 1 else "Success",
264 "alternating": "Failure" if self.call_count % 2 == 1 else "Success",
265 }.get(self.scenario, "Success")
266 print(f" [AUTO] Result: {scenario_label}")
267 else:
268 exit_code = self._prompt_result()
270 return ActionResult(
271 output=f"[simulated output for: {action}]",
272 stderr="",
273 exit_code=exit_code,
274 duration_ms=0,
275 )
277 def _scenario_result(self) -> int:
278 """Return exit code based on scenario pattern.
280 Returns:
281 0 for success, 1 for failure, 2 for error based on scenario logic
282 """
283 if self.scenario == "all-pass":
284 return 0
285 elif self.scenario == "all-fail":
286 return 1
287 elif self.scenario == "all-error":
288 return 2
289 elif self.scenario == "first-fail":
290 # First call fails, rest pass
291 return 1 if self.call_count == 1 else 0
292 elif self.scenario == "alternating":
293 # Odd calls fail, even calls pass
294 return 1 if self.call_count % 2 == 1 else 0
295 return 0
297 def _prompt_result(self) -> int:
298 """Prompt user for simulated exit code.
300 Returns:
301 Exit code based on user selection
302 """
303 print()
304 print(" ? What should the simulated result be?")
305 print(" 1) Success (exit 0) [default]")
306 print(" 2) Failure (exit 1)")
307 print(" 3) Error (exit 2)")
309 while True:
310 try:
311 sys.stdout.write(" > ")
312 sys.stdout.flush()
313 choice = sys.stdin.readline().strip()
314 if choice in ("1", ""):
315 return 0
316 elif choice == "2":
317 return 1
318 elif choice == "3":
319 return 2
320 print(" Invalid choice. Enter 1, 2, or 3.")
321 except (EOFError, KeyboardInterrupt):
322 print()
323 return 0
326def _now_ms() -> int:
327 """Get current time in milliseconds."""
328 return int(time.time() * 1000)
331def _iso_now() -> str:
332 """Get current time as ISO 8601 string."""
333 return datetime.now(UTC).isoformat()
336class FSMExecutor:
337 """Execute an FSM loop.
339 The executor runs an FSM from its initial state until:
340 - A terminal state is reached
341 - max_iterations is exceeded
342 - A timeout occurs
343 - A shutdown signal is received
344 - An unrecoverable error occurs
346 Events are emitted via the callback for observability.
347 """
349 def __init__(
350 self,
351 fsm: FSMLoop,
352 event_callback: EventCallback | None = None,
353 action_runner: ActionRunner | None = None,
354 signal_detector: SignalDetector | None = None,
355 handoff_handler: HandoffHandler | None = None,
356 ):
357 """Initialize the executor.
359 Args:
360 fsm: The FSM loop to execute
361 event_callback: Optional callback for events
362 action_runner: Optional custom action runner (for testing)
363 signal_detector: Optional signal detector for output parsing
364 handoff_handler: Optional handler for handoff signals
365 """
366 self.fsm = fsm
367 self.event_callback = event_callback or (lambda _: None)
368 self.action_runner: ActionRunner = action_runner or DefaultActionRunner()
369 self.signal_detector = signal_detector
370 self.handoff_handler = handoff_handler
372 # Runtime state
373 self.current_state = fsm.initial
374 self.iteration = 0
375 self.captured: dict[str, dict[str, Any]] = {}
376 self.prev_result: dict[str, Any] | None = None
377 self.started_at = ""
378 self.start_time_ms = 0
379 self.elapsed_offset_ms = (
380 0 # milliseconds from segments before current run (set by PersistentExecutor on resume)
381 )
383 # Shutdown flag for graceful signal handling
384 self._shutdown_requested = False
386 # Pending handoff signal (set by _run_action, checked by main loop)
387 self._pending_handoff: DetectedSignal | None = None
389 # Pending error payload from FATAL_ERROR signal (set by _run_action, checked by main loop)
390 self._pending_error: str | None = None
392 # Per-state retry tracking for max_retries support.
393 # _retry_counts[state_name] = number of consecutive re-entries into that state.
394 # Incremented each time we enter the same state as the previous iteration.
395 # Reset when a different state is entered, or after retry exhaustion.
396 self._retry_counts: dict[str, int] = {}
397 # State entered in the previous iteration (None on first iteration or after resume).
398 self._prev_state: str | None = None
400 def request_shutdown(self) -> None:
401 """Request graceful shutdown of the executor.
403 Sets a flag that will be checked at the start of each iteration,
404 allowing the loop to exit cleanly after the current state completes.
405 """
406 self._shutdown_requested = True
408 def run(self) -> ExecutionResult:
409 """Execute the FSM until terminal state or limits reached.
411 Returns:
412 ExecutionResult with final state and execution metadata
413 """
414 self.started_at = _iso_now()
415 self.start_time_ms = _now_ms()
417 self._emit("loop_start", {"loop": self.fsm.name})
419 try:
420 while True:
421 # Check shutdown request (signal handling)
422 if self._shutdown_requested:
423 return self._finish("signal")
425 # Check iteration limit
426 if self.iteration >= self.fsm.max_iterations:
427 return self._finish("max_iterations")
429 # Check timeout
430 if self.fsm.timeout:
431 elapsed = _now_ms() - self.start_time_ms + self.elapsed_offset_ms
432 if elapsed > self.fsm.timeout * 1000:
433 return self._finish("timeout")
435 # Get current state config
436 state_config = self.fsm.states[self.current_state]
438 # Update per-state retry tracking based on transition from previous iteration.
439 # If re-entering the same state consecutively, increment retry count.
440 # If entering a different state, clear the previous state's retry count.
441 if self._prev_state is not None:
442 if self.current_state == self._prev_state:
443 self._retry_counts[self.current_state] = (
444 self._retry_counts.get(self.current_state, 0) + 1
445 )
446 else:
447 self._retry_counts.pop(self._prev_state, None)
449 # Check terminal
450 if state_config.terminal:
451 # Handle maintain mode - restart loop instead of terminating
452 if self.fsm.maintain:
453 self.iteration += 1
454 maintain_target = state_config.on_maintain or self.fsm.initial
455 self._emit(
456 "route",
457 {
458 "from": self.current_state,
459 "to": maintain_target,
460 "reason": "maintain",
461 },
462 )
463 self._prev_state = self.current_state
464 self.current_state = maintain_target
465 continue
466 return self._finish("terminal")
468 # Check per-state retry limit. If the consecutive re-entry count exceeds
469 # max_retries, skip execution and route to on_retry_exhausted instead.
470 if state_config.max_retries is not None:
471 retry_count = self._retry_counts.get(self.current_state, 0)
472 if retry_count > state_config.max_retries:
473 # on_retry_exhausted is guaranteed non-None by validation when
474 # max_retries is set, but we fall back to an error if misconfigured.
475 exhausted_state: str = state_config.on_retry_exhausted or ""
476 if not exhausted_state:
477 return self._finish(
478 "error",
479 error=f"State '{self.current_state}' exceeded max_retries "
480 "but on_retry_exhausted is not set",
481 )
482 self._emit(
483 "retry_exhausted",
484 {
485 "state": self.current_state,
486 "retries": retry_count,
487 "next": exhausted_state,
488 },
489 )
490 self._retry_counts.pop(self.current_state, None)
491 self._prev_state = self.current_state
492 self.current_state = exhausted_state
493 continue
495 self.iteration += 1
496 self._emit(
497 "state_enter",
498 {
499 "state": self.current_state,
500 "iteration": self.iteration,
501 },
502 )
504 # Execute state
505 next_state = self._execute_state(state_config)
507 # Check for pending error signal (FATAL_ERROR)
508 if self._pending_error is not None:
509 return self._finish("error", error=self._pending_error)
511 # Check for pending handoff signal
512 if self._pending_handoff:
513 return self._handle_handoff(self._pending_handoff)
515 # Handle maintain mode
516 if next_state is None and self.fsm.maintain:
517 next_state = state_config.on_maintain or self.fsm.initial
519 # SIGKILL in _execute_state sets shutdown flag and returns None
520 if next_state is None and self._shutdown_requested:
521 return self._finish("signal")
523 if next_state is None:
524 return self._finish("error", error="No valid transition")
526 # At this point next_state is guaranteed to be str
527 resolved_next: str = next_state
529 self._emit(
530 "route",
531 {
532 "from": self.current_state,
533 "to": resolved_next,
534 },
535 )
537 self._prev_state = self.current_state
538 self.current_state = resolved_next
540 # Interruptible backoff sleep between iterations
541 if self.fsm.backoff and self.fsm.backoff > 0:
542 deadline = time.time() + self.fsm.backoff
543 while time.time() < deadline:
544 if self._shutdown_requested:
545 break
546 time.sleep(min(0.1, deadline - time.time()))
548 except Exception as exc:
549 return self._finish("error", error=str(exc))
551 def _execute_state(self, state: StateConfig) -> str | None:
552 """Execute a single state and return next state name.
554 Args:
555 state: The state configuration to execute
557 Returns:
558 Next state name, or None if no valid transition
559 """
560 # Build interpolation context
561 ctx = self._build_context()
563 # Handle unconditional transition
564 if state.next:
565 if state.action:
566 result = self._run_action(state.action, state, ctx)
567 self.prev_result = {
568 "output": result.output,
569 "exit_code": result.exit_code,
570 "state": self.current_state,
571 }
572 if result.exit_code is not None and result.exit_code < 0:
573 # Process killed by signal — do not silently advance via next
574 if state.on_error:
575 return interpolate(state.on_error, ctx)
576 self.request_shutdown()
577 return None
578 return interpolate(state.next, ctx)
580 # Execute action if present
581 action_result = None
582 if state.action:
583 action_result = self._run_action(state.action, state, ctx)
585 # Evaluate
586 eval_result = self._evaluate(state, action_result, ctx)
587 self.prev_result = {
588 "output": action_result.output if action_result else "",
589 "exit_code": action_result.exit_code if action_result else 0,
590 "state": self.current_state,
591 }
593 # Update context with result for routing interpolation
594 if eval_result:
595 ctx.result = {
596 "verdict": eval_result.verdict,
597 "details": eval_result.details,
598 }
600 # Route based on verdict
601 verdict = eval_result.verdict if eval_result else "yes"
602 return self._route(state, verdict, ctx)
604 def _run_action(
605 self,
606 action_template: str,
607 state: StateConfig,
608 ctx: InterpolationContext,
609 ) -> ActionResult:
610 """Execute action and optionally capture result.
612 Args:
613 action_template: Action string (may contain variables)
614 state: State configuration
615 ctx: Interpolation context
617 Returns:
618 ActionResult with output and exit code
619 """
620 action = interpolate(action_template, ctx)
621 action_mode = self._action_mode(state)
623 self._emit("action_start", {"action": action, "is_prompt": action_mode == "prompt"})
625 def _on_line(line: str) -> None:
626 self._emit("action_output", {"line": line})
628 if action_mode == "mcp_tool":
629 # Direct MCP tool call — bypass action_runner entirely
630 interpolated_params = interpolate_dict(state.params, ctx) if state.params else {}
631 cmd = ["mcp-call", action, json.dumps(interpolated_params)]
632 result = self._run_subprocess(cmd, timeout=state.timeout or 30, on_output_line=_on_line)
633 else:
634 result = self.action_runner.run(
635 action,
636 timeout=state.timeout or 120,
637 is_slash_command=action_mode == "prompt",
638 on_output_line=_on_line,
639 )
641 preview = result.output[-2000:].strip() if result.output else None
642 payload: dict[str, Any] = {
643 "exit_code": result.exit_code,
644 "duration_ms": result.duration_ms,
645 "output_preview": preview,
646 "is_prompt": action_mode == "prompt",
647 }
648 if action_mode == "prompt":
649 session_jsonl = get_current_session_jsonl()
650 payload["session_jsonl"] = str(session_jsonl) if session_jsonl else None
651 self._emit("action_complete", payload)
653 # Capture if requested
654 if state.capture:
655 self.captured[state.capture] = {
656 "output": result.output,
657 "stderr": result.stderr,
658 "exit_code": result.exit_code,
659 "duration_ms": result.duration_ms,
660 }
662 # Check for signals in output
663 if self.signal_detector:
664 signal = self.signal_detector.detect_first(result.output)
665 if signal:
666 if signal.signal_type == "handoff":
667 self._pending_handoff = signal
668 elif signal.signal_type == "error":
669 self._pending_error = signal.payload
670 elif signal.signal_type == "stop":
671 self.request_shutdown()
673 return result
675 def _run_subprocess(
676 self,
677 cmd: list[str],
678 timeout: int,
679 on_output_line: Any | None = None,
680 ) -> ActionResult:
681 """Run a subprocess directly and return ActionResult.
683 Follows the same Popen + stderr-drain-thread pattern as DefaultActionRunner.
685 Args:
686 cmd: Command and arguments to execute
687 timeout: Timeout in seconds
688 on_output_line: Optional callback for each stdout line
690 Returns:
691 ActionResult with output, stderr, exit_code, duration_ms
692 """
693 start = _now_ms()
694 process = subprocess.Popen(
695 cmd,
696 stdout=subprocess.PIPE,
697 stderr=subprocess.PIPE,
698 text=True,
699 )
700 output_chunks: list[str] = []
701 stderr_chunks: list[str] = []
703 def _drain_stderr() -> None:
704 assert process.stderr is not None
705 for line in process.stderr:
706 stderr_chunks.append(line)
708 stderr_thread = threading.Thread(target=_drain_stderr, daemon=True)
709 stderr_thread.start()
711 try:
712 for line in process.stdout: # type: ignore[union-attr]
713 output_chunks.append(line)
714 if on_output_line:
715 on_output_line(line.rstrip())
716 process.wait(timeout=timeout)
717 except subprocess.TimeoutExpired:
718 process.kill()
719 process.wait()
720 stderr_thread.join(timeout=5)
721 return ActionResult(
722 output="".join(output_chunks),
723 stderr="".join(stderr_chunks) or "MCP call timed out",
724 exit_code=124,
725 duration_ms=timeout * 1000,
726 )
727 finally:
728 pass
729 stderr_thread.join(timeout=5)
730 return ActionResult(
731 output="".join(output_chunks),
732 stderr="".join(stderr_chunks),
733 exit_code=process.returncode,
734 duration_ms=_now_ms() - start,
735 )
737 def _evaluate(
738 self,
739 state: StateConfig,
740 action_result: ActionResult | None,
741 ctx: InterpolationContext,
742 ) -> EvaluationResult | None:
743 """Evaluate action result.
745 Args:
746 state: State configuration
747 action_result: Result from action execution (may be None)
748 ctx: Interpolation context
750 Returns:
751 EvaluationResult, or None if no evaluation needed
752 """
753 if state.evaluate is None:
754 # Default evaluation based on action type
755 if action_result:
756 action_mode = self._action_mode(state)
758 if action_mode == "mcp_tool":
759 # MCP tool call: use mcp_result evaluator
760 result = evaluate_mcp_result(action_result.output, action_result.exit_code)
761 elif action_mode == "prompt":
762 # Slash command or prompt: use LLM evaluation
763 if not self.fsm.llm.enabled:
764 result = EvaluationResult(
765 verdict="error",
766 details={"error": "LLM evaluation disabled via --no-llm"},
767 )
768 else:
769 result = evaluate_llm_structured(
770 action_result.output,
771 model=self.fsm.llm.model,
772 max_tokens=self.fsm.llm.max_tokens,
773 timeout=self.fsm.llm.timeout,
774 )
775 else:
776 # Shell command: use exit code
777 result = evaluate_exit_code(action_result.exit_code)
779 self._emit(
780 "evaluate",
781 {
782 "type": "default",
783 "verdict": result.verdict,
784 **result.details,
785 },
786 )
787 return result
788 return None
790 # Explicit evaluation config
791 raw_output = action_result.output if action_result else ""
792 if state.evaluate.source:
793 try:
794 eval_input = interpolate(state.evaluate.source, ctx)
795 except InterpolationError:
796 eval_input = raw_output
797 else:
798 eval_input = raw_output
800 if state.evaluate.type == "llm_structured" and not self.fsm.llm.enabled:
801 result = EvaluationResult(
802 verdict="error",
803 details={"error": "LLM evaluation disabled via --no-llm"},
804 )
805 else:
806 result = evaluate(
807 config=state.evaluate,
808 output=eval_input,
809 exit_code=action_result.exit_code if action_result else 0,
810 context=ctx,
811 )
813 self._emit(
814 "evaluate",
815 {
816 "type": state.evaluate.type,
817 "verdict": result.verdict,
818 **result.details,
819 },
820 )
822 return result
824 def _route(
825 self,
826 state: StateConfig,
827 verdict: str,
828 ctx: InterpolationContext,
829 ) -> str | None:
830 """Determine next state from verdict.
832 Resolution order (from design doc):
833 1. next (unconditional) - handled before this method
834 2. route (full routing table)
835 3. on_success/on_failure/on_error (shorthand)
836 4. terminal - handled in main loop
837 5. error
839 Args:
840 state: State configuration
841 verdict: Verdict string from evaluation
842 ctx: Interpolation context
844 Returns:
845 Next state name, or None if no valid route
846 """
847 if state.route:
848 routes = state.route.routes
849 if verdict in routes:
850 return self._resolve_route(routes[verdict], ctx)
851 if state.route.default:
852 return self._resolve_route(state.route.default, ctx)
853 if verdict == "error" and state.route.error:
854 return self._resolve_route(state.route.error, ctx)
855 return None
857 # Shorthand routing
858 if verdict == "yes" and state.on_yes:
859 return self._resolve_route(state.on_yes, ctx)
860 if verdict == "no" and state.on_no:
861 return self._resolve_route(state.on_no, ctx)
862 if verdict == "error" and state.on_error:
863 return self._resolve_route(state.on_error, ctx)
864 if verdict == "partial" and state.on_partial:
865 return self._resolve_route(state.on_partial, ctx)
867 return None
869 def _resolve_route(self, route: str, ctx: InterpolationContext) -> str:
870 """Resolve route target, handling special tokens.
872 Args:
873 route: Route target string
874 ctx: Interpolation context
876 Returns:
877 Resolved state name
878 """
879 if route == "$current":
880 return self.current_state
881 return interpolate(route, ctx)
883 def _action_mode(self, state: StateConfig) -> str:
884 """Return execution mode for the state: 'prompt', 'shell', or 'mcp_tool'."""
885 if state.action_type == "mcp_tool":
886 return "mcp_tool"
887 if state.action_type in ("prompt", "slash_command"):
888 return "prompt"
889 if state.action_type == "shell":
890 return "shell"
891 # Heuristic: / prefix = slash_command (prompt mode)
892 if state.action is not None and state.action.startswith("/"):
893 return "prompt"
894 return "shell"
896 def _build_context(self) -> InterpolationContext:
897 """Build interpolation context for current state.
899 Returns:
900 InterpolationContext with all runtime values
901 """
902 return InterpolationContext(
903 context=self.fsm.context,
904 captured=self.captured,
905 prev=self.prev_result,
906 result=None,
907 state_name=self.current_state,
908 iteration=self.iteration,
909 loop_name=self.fsm.name,
910 started_at=self.started_at,
911 elapsed_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms,
912 )
914 def _emit(self, event: str, data: dict[str, Any]) -> None:
915 """Emit an event via the callback."""
916 self.event_callback(
917 {
918 "event": event,
919 "ts": _iso_now(),
920 **data,
921 }
922 )
924 def _finish(self, terminated_by: str, error: str | None = None) -> ExecutionResult:
925 """Finalize execution and return result."""
926 self._emit(
927 "loop_complete",
928 {
929 "final_state": self.current_state,
930 "iterations": self.iteration,
931 "terminated_by": terminated_by,
932 },
933 )
935 return ExecutionResult(
936 final_state=self.current_state,
937 iterations=self.iteration,
938 terminated_by=terminated_by,
939 duration_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms,
940 captured=self.captured,
941 error=error,
942 )
944 def _handle_handoff(self, signal: DetectedSignal) -> ExecutionResult:
945 """Handle a detected handoff signal.
947 Emits a handoff_detected event and optionally invokes the handoff handler.
949 Args:
950 signal: The detected handoff signal
952 Returns:
953 ExecutionResult with handoff information
954 """
955 self._emit(
956 "handoff_detected",
957 {
958 "state": self.current_state,
959 "iteration": self.iteration,
960 "continuation": signal.payload,
961 },
962 )
964 # Invoke handler if configured
965 if self.handoff_handler:
966 result = self.handoff_handler.handle(self.fsm.name, signal.payload)
967 if result.spawned_process is not None:
968 self._emit(
969 "handoff_spawned",
970 {
971 "pid": result.spawned_process.pid,
972 "state": self.current_state,
973 },
974 )
976 return ExecutionResult(
977 final_state=self.current_state,
978 iterations=self.iteration,
979 terminated_by="handoff",
980 duration_ms=_now_ms() - self.start_time_ms + self.elapsed_offset_ms,
981 captured=self.captured,
982 handoff=True,
983 continuation_prompt=signal.payload,
984 )