nodehop 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,209 @@
1
+ """OpenAI Codex CLI module.
2
+
3
+ Codex keeps each conversation as a "rollout" file,
4
+ ~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<uuid>.jsonl, whose first line
5
+ (`session_meta`) records the working directory. Unlike Claude Code, sessions
6
+ are filed by date, not by project: NodeHop picks this project's files by their
7
+ `cwd`, sends only those, and puts them in the same dated place on the other
8
+ machine, with every `cwd` rewritten to the local path. `codex resume <id>`
9
+ finds a copied rollout even on a machine that never saw it (checked against a
10
+ fresh CODEX_HOME). Folder trust lives in ~/.codex/config.toml.
11
+
12
+ Like Claude Code's files, this layout is Codex's own and may change.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import shutil
20
+ from pathlib import Path
21
+ from typing import Iterable, List, Optional, Tuple
22
+
23
+ from nodehop.config import Project, home_dir
24
+ from nodehop.modules.base import Module
25
+ from nodehop.modules.claude_code import _epoch, rewrite_session_file
26
+
27
+ # What Codex's terminal shows while it works or waits on an approval.
28
+ BUSY_MARKERS = ("esc to interrupt", "allow command", "approve", "would you like to run")
29
+
30
+
31
+ def codex_home() -> Path:
32
+ return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
33
+
34
+
35
+ def _meta(path: Path) -> dict:
36
+ try:
37
+ with open(path, encoding="utf-8", errors="replace") as fh:
38
+ first = json.loads(fh.readline() or "{}")
39
+ except (OSError, ValueError):
40
+ return {}
41
+ return first.get("payload") or {} if first.get("type") == "session_meta" else {}
42
+
43
+
44
+ def session_files(project_path: str, home: Optional[Path] = None) -> List[Path]:
45
+ """This project's rollout files, oldest first."""
46
+ root = (home or codex_home()) / "sessions"
47
+ if not root.is_dir():
48
+ return []
49
+ wanted = os.path.normpath(project_path)
50
+ found = [f for f in root.rglob("rollout-*.jsonl")
51
+ if os.path.normpath(_meta(f).get("cwd") or "") == wanted]
52
+ return sorted(found, key=lambda f: f.stat().st_mtime)
53
+
54
+
55
+ def config_toml() -> Path:
56
+ return codex_home() / "config.toml"
57
+
58
+
59
+ def _toml_key(path: str) -> str:
60
+ return '[projects."' + path.replace("\\", "\\\\").replace('"', '\\"') + '"]'
61
+
62
+
63
+ def is_trusted(project_path: str) -> bool:
64
+ try:
65
+ text = config_toml().read_text()
66
+ except OSError:
67
+ return False
68
+ head = _toml_key(project_path)
69
+ if head not in text:
70
+ return False
71
+ block = text.split(head, 1)[1].split("\n[", 1)[0]
72
+ return 'trust_level = "trusted"' in block
73
+
74
+
75
+ def mark_trusted(project_path: str) -> bool:
76
+ if is_trusted(project_path):
77
+ return False
78
+ path = config_toml()
79
+ text = path.read_text() if path.exists() else ""
80
+ if _toml_key(project_path) in text: # present but not trusted: leave the person's choice alone
81
+ return False
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ path.write_text(text + ("" if text.endswith("\n") or not text else "\n")
84
+ + f'\n{_toml_key(project_path)}\ntrust_level = "trusted"\n')
85
+ return True
86
+
87
+
88
+ def _texts(content) -> Iterable[str]:
89
+ for block in content or []:
90
+ if isinstance(block, dict) and isinstance(block.get("text"), str):
91
+ yield block["text"]
92
+
93
+
94
+ class CodexModule(Module):
95
+ name = "codex"
96
+
97
+ # ---- what travels ---------------------------------------------------------------
98
+ def stage(self, project: Project) -> Path:
99
+ return home_dir() / "outbox" / project.name / "codex"
100
+
101
+ def snapshot(self, project: Project) -> dict:
102
+ files = session_files(project.path)
103
+ meta = {"path": project.path, "trusted": is_trusted(project.path),
104
+ "session_id": _meta(files[-1]).get("id") if files else None, "codex_stage": None}
105
+ if files and not self.runner.dry_run:
106
+ stage = self.stage(project)
107
+ shutil.rmtree(stage, ignore_errors=True)
108
+ root = codex_home() / "sessions"
109
+ for f in files: # only this project's conversations leave the machine
110
+ dest = stage / f.relative_to(root)
111
+ dest.parent.mkdir(parents=True, exist_ok=True)
112
+ shutil.copy2(f, dest)
113
+ meta["codex_stage"] = str(stage)
114
+ return meta
115
+
116
+ def payload(self, project: Project, meta: dict) -> List[Tuple[str, Path]]:
117
+ stage = meta.get("codex_stage")
118
+ return [("codex", Path(stage))] if stage else []
119
+
120
+ def accept_payload(self, project: Project, inbox: Path, meta: dict) -> None:
121
+ source = inbox / "codex"
122
+ if not source.is_dir():
123
+ return
124
+ if self.runner.dry_run:
125
+ self.runner.log(f"[dry-run] would place {source} under {codex_home() / 'sessions'}")
126
+ return
127
+ old_root = meta.get("path") or project.path
128
+ root = codex_home() / "sessions"
129
+ changed = 0
130
+ for f in source.rglob("rollout-*.jsonl"):
131
+ dest = root / f.relative_to(source)
132
+ dest.parent.mkdir(parents=True, exist_ok=True)
133
+ shutil.copy2(f, dest)
134
+ changed += rewrite_session_file(dest, old_root, project.path)
135
+ if meta.get("trusted") and mark_trusted(project.path):
136
+ self.runner.log(f"{project.name}: folder trusted on the sending machine, trusted here too")
137
+ if changed:
138
+ self.runner.log(f"{project.name}: session paths moved from {old_root} to {project.path}")
139
+
140
+ # ---- running it -------------------------------------------------------------------
141
+ def command(self, project: Project, meta: dict, resume: bool) -> List[str]:
142
+ argv = [self.config.codex_bin]
143
+ if not resume:
144
+ return argv + list(self.config.codex_args)
145
+ session_id = meta.get("session_id")
146
+ if not session_id:
147
+ return argv + list(self.config.codex_args)
148
+ argv += ["resume", *self.config.codex_args, session_id]
149
+ if not meta.get("was_busy", True):
150
+ return argv # idle: reopen the conversation, no turn spent
151
+ prompt = self.config.resume_prompt
152
+ if meta.get("failover"):
153
+ prompt = ("NodeHop fallback: the machine you were working on stopped responding, so you were restarted "
154
+ f"on another machine from a copy taken at {meta.get('copy_time', 'its last sync')}. Anything "
155
+ "done after that copy is missing. Check the actual state of the project before continuing.")
156
+ old_path = meta.get("path")
157
+ if old_path and old_path != project.path:
158
+ prompt += f" Note: the project folder is now {project.path} on this machine (it was {old_path})."
159
+ return argv + [prompt]
160
+
161
+ def is_busy(self, project: Project) -> bool:
162
+ screen = self.screen(project).lower()
163
+ return any(marker in screen for marker in BUSY_MARKERS)
164
+
165
+ def progress(self, project: Project, since: float) -> dict:
166
+ info = super().progress(project, since)
167
+ files = session_files(project.path)
168
+ if not files:
169
+ return info
170
+ tools, texts, first, last, task, last_action = 0, [], None, None, None, None
171
+ with open(files[-1], encoding="utf-8", errors="replace") as fh:
172
+ for line in fh:
173
+ try:
174
+ o = json.loads(line)
175
+ except ValueError:
176
+ continue
177
+ p = o.get("payload") or {}
178
+ if o.get("type") != "response_item":
179
+ continue
180
+ kind = p.get("type")
181
+ if kind == "message" and p.get("role") == "user":
182
+ for t in _texts(p.get("content")):
183
+ if t.strip() and not t.lstrip().startswith(("<", "NodeHop")):
184
+ task = t.strip()
185
+ ts = _epoch(o.get("timestamp"))
186
+ if ts is None or ts < since:
187
+ continue
188
+ if kind in ("function_call", "custom_tool_call", "local_shell_call"):
189
+ tools += 1
190
+ raw = p.get("arguments") or p.get("input") or ""
191
+ try:
192
+ args = json.loads(raw) if isinstance(raw, str) and raw.startswith("{") else {}
193
+ except ValueError:
194
+ args = {}
195
+ cmd = args.get("command") if isinstance(args, dict) else None
196
+ if isinstance(cmd, list):
197
+ cmd = " ".join(str(c) for c in cmd)
198
+ last_action = " ".join(str(cmd or raw or p.get("name", "tool")).split())[:120]
199
+ elif kind == "message" and p.get("role") == "assistant":
200
+ texts += [t.strip() for t in _texts(p.get("content")) if t.strip()]
201
+ else:
202
+ continue
203
+ first = first or ts
204
+ last = ts
205
+ info.update(actions=tools, tool_calls=tools, messages=len(texts), task=task, last_action=last_action,
206
+ first_activity=first, last_message=(texts[-1] if texts else None))
207
+ if last and (info["last_activity"] is None or last > info["last_activity"]):
208
+ info["last_activity"] = last
209
+ return info
@@ -0,0 +1,81 @@
1
+ """Generic module: any long-running command (a training script, a simulation, a build).
2
+
3
+ The command runs in NodeHop's tmux session. To stop it, NodeHop sends one
4
+ Ctrl-C (SIGINT) and waits up to `stop_grace` seconds for it to save its state
5
+ and exit; then it kills the session. On the other machine the same command is
6
+ started again with NODEHOP_RESUMED=1: the program resumes from its own
7
+ checkpoints, which live in the project folder and travel with it.
8
+ `nodehop.train` gives Python scripts all of this in a few lines.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ from typing import List
17
+
18
+ import nodehop
19
+ from nodehop.config import Project
20
+ from nodehop.modules.base import Module, tmux
21
+
22
+
23
+ class CommandModule(Module):
24
+ name = "command"
25
+ stop_grace = 45.0 # seconds to write a checkpoint before being killed
26
+
27
+ def snapshot(self, project: Project) -> dict:
28
+ return {"path": project.path, "command": project.command}
29
+
30
+ def should_resume(self, meta: dict) -> bool:
31
+ return bool(meta.get("was_busy", True)) # a finished job is not started again
32
+
33
+ def command(self, project: Project, meta: dict, resume: bool) -> List[str]:
34
+ if not project.command:
35
+ raise RuntimeError(f"{project.name}: no command set (nodehop on --command '...')")
36
+ # The pane stays open after the command ends, so its last lines can still be read.
37
+ return ["sh", "-c", f"{project.command}; echo; echo '[nodehop] command finished (exit '$?')'; exec sleep 86400"]
38
+
39
+ def environment(self, project: Project, meta: dict, resume: bool) -> dict:
40
+ env = super().environment(project, meta, resume)
41
+ # `from nodehop import train` works in any virtualenv the command uses.
42
+ package_root = str(Path(nodehop.__file__).resolve().parent.parent)
43
+ env["PYTHONPATH"] = package_root + (":" + os.environ["PYTHONPATH"] if os.environ.get("PYTHONPATH") else "")
44
+ env["PYTHONUNBUFFERED"] = "1"
45
+ return env
46
+
47
+ def is_busy(self, project: Project) -> bool:
48
+ # Busy while the command itself runs (not just the pane that shows its last words).
49
+ # A session that is gone is not busy: on Linux, the Ctrl-C also ends the wrapping shell.
50
+ if not self.is_running(project):
51
+ return False
52
+ return "[nodehop] command finished" not in self.screen(project)
53
+
54
+ def stop(self, project: Project, attempts: int = 1, interval: float = 0.5, grace_seconds: float = 0.0) -> bool:
55
+ if not self.is_running(project):
56
+ return False
57
+ target = f"={self.session(project)}"
58
+ if self.is_busy(project):
59
+ self.runner.run(tmux("send-keys", "-t", f"{target}:", "C-c"), check=False)
60
+ waited = 0.0
61
+ while waited < self.stop_grace and not self.runner.dry_run and self.is_running(project) \
62
+ and self.is_busy(project):
63
+ self.runner.sleep(0.5)
64
+ waited += 0.5
65
+ if self.is_running(project):
66
+ self.runner.run(tmux("kill-session", "-t", target), check=False)
67
+ self.runner.log(f"{project.name}: stopped")
68
+ return True
69
+
70
+ def progress(self, project: Project, since: float) -> dict:
71
+ info = super().progress(project, since)
72
+ path = Path(project.path) / ".nodehop" / "progress.json"
73
+ try:
74
+ data = json.loads(path.read_text())
75
+ except (OSError, ValueError):
76
+ return info
77
+ bits = [f"{k} {data[k]}" for k in ("step", "total", "loss", "epoch") if k in data]
78
+ info.update(task=project.command, last_action=", ".join(bits) or None,
79
+ last_activity=max(filter(None, [info.get("last_activity"), data.get("time")]), default=None),
80
+ training=data)
81
+ return info
nodehop/onboard.py ADDED
@@ -0,0 +1,210 @@
1
+ """`nodehop onboard`: from nothing to working, one step at a time.
2
+
3
+ It looks at what is already done on this machine and returns the next step:
4
+ the questions to ask the person (with choices and defaults) and the command
5
+ to run once they answered. An agent loops on `nodehop onboard --json` until
6
+ `complete` is true; a person runs `nodehop onboard` in a terminal and gets the
7
+ same steps as an interactive wizard.
8
+
9
+ Steps: this machine (name, role) → the other machine (install and pair over
10
+ SSH) → background jobs → projects to protect → unattended agents → check.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import getpass
16
+ import shlex
17
+ import socket
18
+ from pathlib import Path
19
+ from typing import Callable, Dict, List, Optional, Sequence
20
+
21
+ from nodehop import doctor, pairing
22
+ from nodehop.config import Config
23
+ from nodehop.runner import Runner
24
+
25
+
26
+ def _q(qid: str, ask: str, default: Optional[str] = None, choices: Optional[List[dict]] = None,
27
+ when: Optional[Dict[str, str]] = None, optional: bool = False) -> dict:
28
+ q = {"id": qid, "ask": ask}
29
+ if default is not None:
30
+ q["default"] = default
31
+ if choices:
32
+ q["choices"] = choices
33
+ if when:
34
+ q["when"] = when # only ask if an earlier answer has this value
35
+ if optional:
36
+ q["optional"] = True
37
+ return q
38
+
39
+
40
+ def _computer_name(runner: Runner) -> str:
41
+ name = runner.run(["scutil", "--get", "ComputerName"], check=False, mutating=False).stdout.strip()
42
+ return pairing.suggested_name(name or socket.gethostname() or "machine")
43
+
44
+
45
+ def _ok(checks: List[dict], cid: str) -> bool:
46
+ return any(c["id"] == cid and c["status"] == "ok" for c in checks)
47
+
48
+
49
+ def plan(runner: Runner, cfg: Optional[Config] = None, checks: Optional[List[dict]] = None,
50
+ skip: Sequence[str] = ()) -> dict:
51
+ cfg = cfg if cfg is not None else doctor.load_config()
52
+ steps: List[dict] = []
53
+ nxt: Optional[dict] = None
54
+
55
+ def step(sid: str, title: str, done: bool, todo: Optional[Callable[[], dict]] = None, person: bool = False) -> None:
56
+ nonlocal nxt
57
+ status = "done" if done else "skipped" if sid in skip else ("needs-person" if person else "todo")
58
+ steps.append({"id": sid, "title": title, "status": status})
59
+ if status in ("todo", "needs-person") and nxt is None and todo is not None:
60
+ nxt = dict(todo(), id=sid, title=title)
61
+
62
+ # 1. this machine ---------------------------------------------------------------
63
+ step("machine", "Set up this machine", cfg is not None, lambda: {
64
+ "why": "NodeHop needs a name and a role for this machine.",
65
+ "questions": [
66
+ _q("role", "Is this the machine you work on and close (primary), or the always-on machine "
67
+ "that takes over (server)?", "primary",
68
+ [{"value": "primary", "label": "Primary: the Mac I work on (usually a laptop)"},
69
+ {"value": "server", "label": "Server: always on (a Mac mini or a Linux server), takes over "
70
+ "while the laptop sleeps"}]),
71
+ _q("name", "Short name for this machine?", _computer_name(runner)),
72
+ ],
73
+ "command": "nodehop setup --name {name} {role_flag} --json",
74
+ "fill": {"role_flag": {"role=primary": "--primary", "role=server": ""}},
75
+ })
76
+ if cfg is None:
77
+ return _result(steps, nxt)
78
+
79
+ is_primary = cfg.primary == cfg.machine
80
+ checks = checks if checks is not None else doctor.run_checks(cfg, runner, peers=False)
81
+
82
+ # 2. the other machine -------------------------------------------------------------
83
+ def pair_step() -> dict:
84
+ peers = pairing.tailnet_peers(runner)
85
+ choices = [{"value": p["host"], "label": f"{p['name']} ({p['host']}, {p['os'] or '?'}, "
86
+ f"{'online' if p['online'] else 'offline'})"} for p in peers]
87
+ other = "server (always on)" if is_primary else "primary (the laptop)"
88
+ return {
89
+ "why": f"NodeHop installs itself on the {other} over SSH and pairs both machines. "
90
+ + ("" if is_primary else "Running this from the primary is better: it connects to the server, "
91
+ "never the reverse."),
92
+ "questions": [
93
+ _q("host", f"Which machine is the {other}? (a Tailscale name, host name or IP)",
94
+ choices[0]["value"] if choices else None, choices or None),
95
+ _q("user", "Your user name on that machine?", getpass.getuser()),
96
+ _q("other_name", "Short name for that machine?", None),
97
+ ],
98
+ "command": "nodehop deploy {user}@{host} --name {other_name} --json",
99
+ "defaults_from": {"other_name": "host"},
100
+ "if_it_fails": "If it says there is no SSH access yet, the person runs once, in their own terminal: "
101
+ f"ssh-copy-id -i {cfg.ssh_key_path()}.pub USER@HOST (they type that machine's password; "
102
+ "never type it for them). If the SSH server is off there, give them the `fix` it prints.",
103
+ }
104
+ step("pair", "Install NodeHop on the other machine and pair them", bool(cfg.peers), pair_step)
105
+
106
+ # 3. background jobs here --------------------------------------------------------------
107
+ if is_primary:
108
+ hooks_done = _ok(checks, "lid-hooks") and _ok(checks, "pre-sync")
109
+ why = ("Closing the lid must hand work off, opening it must bring it back, and a pre-sync keeps the "
110
+ "server's copy fresh. On macOS this installs SleepWatcher with Homebrew.")
111
+ else:
112
+ hooks_done = _ok(checks, "fallback")
113
+ why = "The server takes over if the primary disappears without going to sleep."
114
+ step("hooks", "Install the background jobs", hooks_done, lambda: {
115
+ "why": why,
116
+ "questions": [_q("go", "Install them now?", "yes", [{"value": "yes", "label": "Yes"},
117
+ {"value": "no", "label": "Not now"}])],
118
+ "command": "nodehop install-hooks --apply --json",
119
+ "skip_if": {"go": "no"},
120
+ "then": "Any command listed under `left` needs an administrator: give it to the person.",
121
+ })
122
+
123
+ # 4. projects ---------------------------------------------------------------------
124
+ if is_primary:
125
+ active = [n for n, p in cfg.projects.items() if p.active]
126
+ step("projects", "Choose a project to protect", bool(active), lambda: {
127
+ "why": "Only the projects you switch on are copied, handed off and covered by the fallback.",
128
+ "questions": [
129
+ _q("path", "Which project folder should NodeHop protect? (you can add more later with "
130
+ "`nodehop on <folder>`)", str(Path.cwd()) if _looks_like_project(Path.cwd()) else None),
131
+ _q("kind", "What runs in it?", "claude",
132
+ [{"value": "claude", "label": "Claude Code (resumed with its conversation)"},
133
+ {"value": "codex", "label": "Codex (resumed with its conversation)"},
134
+ {"value": "command", "label": "A long command, e.g. a training script"}]),
135
+ _q("command_line", "Which command? (e.g. .venv/bin/python train.py)", None,
136
+ when={"kind": "command"}),
137
+ ],
138
+ "command": "nodehop on {path} {command_flag}",
139
+ "fill": {"command_flag": {"kind=claude": "--agent claude", "kind=codex": "--agent codex",
140
+ "kind=command": "--command {command_line}"}},
141
+ })
142
+
143
+ # 5. agents with nobody in front of them ------------------------------------------
144
+ unattended = cfg.unattended is not None or "--permission-mode" in " ".join(cfg.claude_args)
145
+ step("unattended", "Agents resumed with nobody there", unattended, lambda: {
146
+ "why": "A resumed agent that stops on a permission prompt waits until someone answers.",
147
+ "questions": [
148
+ _q("mode", "When NodeHop resumes an agent on the other machine with nobody there, how may it "
149
+ "handle permission prompts?", "auto",
150
+ [{"value": "auto", "label": "Auto mode (recommended): Claude Code's auto mode decides by itself, "
151
+ "so the work never stalls; Codex runs sandboxed to the project"},
152
+ {"value": "acceptEdits", "label": "Accept file edits only: anything else waits for you"},
153
+ {"value": "default", "label": "Ask as usual: the agent waits for you"}]),
154
+ _q("remote", "Also make NodeHop's Claude Code sessions visible in the Claude app (Remote Control), "
155
+ "to follow them and answer from your phone?", "yes",
156
+ [{"value": "yes", "label": "Yes"}, {"value": "no", "label": "No"}]),
157
+ ],
158
+ "command": "nodehop config set unattended {mode} && nodehop config set remote_control {remote_bool}",
159
+ "fill": {"remote_bool": {"remote=yes": "true", "remote=no": "false"}},
160
+ })
161
+
162
+ # 6. check --------------------------------------------------------------------------
163
+ healthy = doctor.healthy(checks) and bool(cfg.peers)
164
+ step("check", "Final check", healthy, lambda: {
165
+ "why": "Everything should be green on this machine.",
166
+ "questions": [],
167
+ "command": "nodehop doctor --json",
168
+ "then": "Relay every `fail` with its `fix` to the person.",
169
+ }, person=not healthy and any(c["status"] == "fail" for c in checks))
170
+ return _result(steps, nxt, cfg, is_primary)
171
+
172
+
173
+ def _looks_like_project(path: Path) -> bool:
174
+ markers = (".git", "pyproject.toml", "package.json", "Cargo.toml", "go.mod", "CLAUDE.md", "README.md")
175
+ return path != Path.home() and len(path.parts) > 3 and any((path / m).exists() for m in markers)
176
+
177
+
178
+ def _result(steps: List[dict], nxt: Optional[dict], cfg: Optional[Config] = None, is_primary: bool = False) -> dict:
179
+ complete = all(s["status"] in ("done", "skipped") for s in steps)
180
+ out = {"complete": complete, "steps": steps, "next": nxt}
181
+ if complete and cfg is not None:
182
+ out["summary"] = (
183
+ [f"{cfg.machine} is the primary; work goes to {', '.join(cfg.peers)} when the lid closes and comes "
184
+ "back when it opens.",
185
+ "Daily use: `nodehop on` in a project folder, `nodehop start <project>`, `nodehop status`, "
186
+ "`nodehop attach <project>`; if two agents ever work in parallel, a window asks which to keep."]
187
+ if is_primary else
188
+ [f"{cfg.machine} is a server for {cfg.primary}: nothing to do here day to day."]
189
+ )
190
+ return out
191
+
192
+
193
+ def fill_command(step: dict, answers: Dict[str, str]) -> Optional[str]:
194
+ """Turn a step's command template and the person's answers into the command to run (None = skipped)."""
195
+ for qid, value in (step.get("skip_if") or {}).items():
196
+ if answers.get(qid) == value:
197
+ return None
198
+ values = {k: shlex.quote(v) for k, v in answers.items() if v}
199
+ for target, source in (step.get("defaults_from") or {}).items():
200
+ if not answers.get(target) and answers.get(source):
201
+ values[target] = shlex.quote(pairing.suggested_name(answers[source]))
202
+ for field, mapping in (step.get("fill") or {}).items():
203
+ chosen = ""
204
+ for key, text in mapping.items():
205
+ if "=" in key:
206
+ qid, val = key.split("=", 1)
207
+ if answers.get(qid) == val:
208
+ chosen = text
209
+ values[field] = chosen.format(**values) if chosen else ""
210
+ return " ".join(step["command"].format(**values).split())