Python
run: the task can be piped in on standard input
Rohit C Prasad07cc4a3caa5d
diff --git a/coworker/headless/runner.py b/coworker/headless/runner.pyindex 46b97912..540cb500 100644--- a/coworker/headless/runner.py+++ b/coworker/headless/runner.py@@ -57,9 +57,12 @@ def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:prog="openworker run",description="Run one task with no human present, and record it.",)- src = p.add_mutually_exclusive_group(required=True)+ # With neither flag, the task is read from standard input when it is piped in.+ src = p.add_mutually_exclusive_group()src.add_argument("--prompt", "--prompt-text", dest="prompt_text", help="the task text")- src.add_argument("--prompt-file", help="file containing the task text (UTF-8)")+ src.add_argument(+ "--prompt-file", help="file containing the task text (UTF-8); - reads standard input"+ )p.add_argument("--workspace", default=".", help="folder the agent works in (default: the current folder)")@@ -580,10 +583,23 @@ def _preview(value: Any, limit: int = 400) -> str:# -- the run ------------------------------------------------------------------------------+class NoPrompt(Exception):+ pass++def _read_prompt(args: argparse.Namespace) -> str:if args.prompt_text is not None:return args.prompt_text- return Path(args.prompt_file).read_text(encoding="utf-8")+ if args.prompt_file not in (None, "-"):+ return Path(args.prompt_file).read_text(encoding="utf-8")+ # Piped in: `cat task.md | openworker run`. A terminal is not read: the command would+ # sit waiting for typing with nothing on screen saying so.+ if args.prompt_file is None and sys.stdin.isatty():+ raise NoPrompt("give the task with --prompt, --prompt-file, or pipe it in on standard input")+ text = sys.stdin.buffer.read().decode("utf-8", errors="replace")+ if not text.strip():+ raise NoPrompt("standard input was empty; give the task with --prompt or --prompt-file")+ return textdef _agent_version(explicit: Optional[str]) -> str:@@ -656,7 +672,11 @@ def run(args: argparse.Namespace) -> int:model = normalize_model(args.model)mode = Mode(args.mode)run_id = uuid.uuid4().hex[:12]- prompt = _read_prompt(args)+ try:+ prompt = _read_prompt(args)+ except NoPrompt as exc:+ print(f"openworker run: {exc}", file=sys.stderr)+ return 2answers = Answers()secrets = SecretStore(state_dir() / "secrets.json")diff --git a/docs/headless.md b/docs/headless.mdindex c9af329a..c51d647e 100644--- a/docs/headless.md+++ b/docs/headless.md@@ -69,7 +69,7 @@ Options:| Flag | Meaning ||---|---|-| `--prompt TEXT` / `--prompt-file PATH` | the task |+| `--prompt TEXT` / `--prompt-file PATH` | the task. With neither flag, the task is read from standard input when it is piped in (`cat task.md \| openworker run …`); `--prompt-file -` does the same || `--workspace DIR` | the folder the agent works in; the current folder when left out || `--add-dir DIR` | an extra folder the agent may read and write, beside the workspace (repeatable), for a harness whose output contract lives outside the workspace — e.g. `--add-dir /output`. The file tools only write inside the session's folders, in every mode; the shell is not scoped, so without this a delivery would depend on which tool the model happened to pick. Recorded under `args.extra_dirs` in `summary.json`. || `--model ID` | `provider:model` or `provider/model` (first slash splits) |diff --git a/tests/test_headless_run.py b/tests/test_headless_run.pyindex 87819a0e..c3653815 100644--- a/tests/test_headless_run.py+++ b/tests/test_headless_run.py@@ -386,3 +386,42 @@ def test_the_workspace_defaults_to_the_current_folder(tmp_path: Path) -> None:proc = subprocess.run(cmd, env=_env(None), cwd=here, capture_output=True, text=True, timeout=300)assert proc.returncode == 0, proc.stderrassert _summary(out)["args"]["workspace"] == str(here.resolve())+++def _first_user_text(out: Path) -> str:+ return next(m["content"] for m in _messages(out) if m["role"] == "user")+++def _run_piped(tmp_path: Path, stdin: str, extra: list[str] | None = None) -> tuple[subprocess.CompletedProcess, Path]:+ ws = tmp_path / "ws"+ ws.mkdir(exist_ok=True)+ out = tmp_path / "out"+ script = tmp_path / "script.json"+ script.write_text(json.dumps(SCRIPT), encoding="utf-8")+ cmd = [+ sys.executable, "-m", "coworker.cli", "run", "--workspace", str(ws),+ "--model", "anthropic/claude-sonnet-5", "--mode", "bypass-approvals",+ "--out", str(out), "--scripted", str(script), "--timeout-seconds", "120",+ *(extra or []),+ ]+ proc = subprocess.run(cmd, env=_env(None), input=stdin, capture_output=True, text=True, timeout=300)+ return proc, out+++def test_the_task_can_be_piped_in_on_standard_input(tmp_path: Path) -> None:+ task = "First line of the task.\nSecond line of the task.\n"+ proc, out = _run_piped(tmp_path, task)+ assert proc.returncode == 0, proc.stderr+ assert _first_user_text(out) == task++ proc, out = _run_piped(tmp_path, task, extra=["--prompt-file", "-"])+ assert proc.returncode == 0, proc.stderr+ assert _first_user_text(out) == task+++def test_an_empty_standard_input_stops_the_run(tmp_path: Path) -> None:+ proc, out = _run_piped(tmp_path, "")+ assert proc.returncode == 2+ assert "--prompt" in proc.stderr+ assert not (out / "summary.json").exists()+