Python
run: uses this computer's settings, asks in the terminal, and saves the session
Rohit C Prasad25c9e0ba2df6
diff --git a/coworker/cli.py b/coworker/cli.pyindex 66ae7718..04d1ecb9 100644--- a/coworker/cli.py+++ b/coworker/cli.py@@ -32,7 +32,7 @@ commands:(the link comes from the app: Settings > Machines > Add a machine;give the controller's address instead to approve a code there)up serve again with the stored identity- run <task> run one task with no human and exit (writes a record and a trajectory)+ run run one task to the end and exit (--prompt "..."; see run --help)machine manage this machinestatus show enrollment and the sealing-key fingerprint (--json)keys manage provider keys stored on this machinediff --git a/coworker/engine.py b/coworker/engine.pyindex 488a4a0b..870c14fb 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -222,6 +222,10 @@ class TurnEngine:# the engine answers questions, folder requests and pinned installs itself by fixed# rule, and refuses any approval card only a person could clear — never a hang.self.attendance: Optional[Callable[[], str]] = None+ # Approvals are separate from questions. A surface that answers questions by rule+ # (attendance "auto") while a person still answers approval cards sets this: a+ # terminal run with --auto-answer. Unset, attendance "auto" covers both.+ self.cards_reach_person: Optional[Callable[[], bool]] = Noneself._dangerous_warned = False# Session facts (spec Part 0 / §2.4) — the known world frozen at session start, plus# the per-turn ingestion record. Set post-construction by the surface, same as@@ -1225,6 +1229,17 @@ class TurnEngine:except Exception: # noqa: BLE001 - a broken getter must read as attendedreturn False+ def _nobody_answers_cards(self) -> bool:+ """No person can answer an approval card: attendance "auto", unless the surface+ says cards still reach a person."""+ if self.cards_reach_person is not None:+ try:+ if self.cards_reach_person():+ return False+ except Exception: # noqa: BLE001 - a broken getter must not open a card nobody sees+ pass+ return self._auto_answering()+def _reviewer_active(self) -> bool:"""The reviewer is consulted only when ALL of these hold. Any miss ⇒ today'sbehaviour (the card). Someone must be accountable for the asks it cannot clear:@@ -1716,7 +1731,7 @@ class TurnEngine:self._reviewer_denials = 0 # streak semantics: any non-deny resetsunsure_note = verdict.reason- if not allowed and decision.needs_user and self._auto_answering():+ if not allowed and decision.needs_user and self._nobody_answers_cards():# Attendance "auto": nobody can answer a card, and the mode did not allow# the call — so the answer is no, recorded, never a hang. (The dangerous mode# never reaches here: it grants the floors before a card exists.)diff --git a/coworker/headless/runner.py b/coworker/headless/runner.pyindex 55e2acfd..2c304b1d 100644--- a/coworker/headless/runner.py+++ b/coworker/headless/runner.py@@ -1,15 +1,20 @@-"""`openworker run`: run ONE task with no human present, and record it.+"""`openworker run`: run ONE task to the end, and record it.- openworker run --prompt "..." --workspace /path/to/project --model anthropic/claude-sonnet-5 \- --mode bypass-approvals --out ./run-record --trajectory-atif ./run-record/trajectory.json+ openworker run --prompt "..." # here, with this computer's settings+ openworker run --isolated --prompt "..." --workspace /path/to/project \+ --model anthropic/claude-sonnet-5 --mode bypass-approvals --out ./run-record-The model id is accepted in OpenWorker's `provider:model` form or the `provider/model`-form other tools use. Nothing waits for a person: attendance is `auto`-(coworker/unattended.py), so the engine answers questions with the least-destructive-default, declines folder requests with guidance, installs pinned catalog tools itself,-and refuses any approval card only a person could clear unless the mode grants it.+Each run is its own process with its own engine. It reads this computer's settings (the+default model, stored keys, the sandbox and its allowed sites) and changes none of them;+`--isolated` reads nothing at all, for benchmark runs. The model id is accepted in+OpenWorker's `provider:model` form or the `provider/model` form other tools use.-Writes into --out:+Approvals and questions are separate. An approval follows `--mode`: asked in the terminal+(headless/terminal.py), refused and recorded when there is none. A question is asked in the+terminal, or answered by rule with `--auto-answer` or no terminal (coworker/unattended.py).+Nothing hangs.++Writes into --out (default: sessions/<workspace path>/<session id> in the state folder):events.jsonl every engine event, with a timestampmessages.json the final conversation (OpenWorker's own persisted shape)summary.json outcome, counts, tokens, cost, wall-clock, arguments@@ -20,11 +25,13 @@ Writes into --out:trajectory.json the ATIF trajectory (also copied to --trajectory-atif when given)The trajectory and the exit code are the stable contract; the other files are internal-and may change. Exit code 0 whenever a trajectory was written (completed, iteration cap,-timeout, model error); 1 only when the run crashed before producing one.+and may change. Exit code 0 when the task finished, 3 when the run stopped early with its+record written (timeout, model error, iteration cap), 1 when it crashed before producing+one, 2 for a command line that cannot be run.-OpenWorker's state and scratch folders are pointed under --out before the engine is-built, so a run never touches the machine's real conversations, keys or settings.+With --isolated, OpenWorker's state and scratch folders are pointed under --out before+the engine is built, so the run never touches the machine's real conversations, keys or+settings. Without it the state folder is read, and the run writes only its own record."""from __future__ import annotations@@ -33,6 +40,7 @@ import argparseimport asyncioimport jsonimport os+import reimport sysimport timeimport traceback@@ -85,7 +93,9 @@ def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:"which tool the model happened to pick.",)p.add_argument(- "--model", required=True, help="provider:model (OpenWorker) or provider/model"+ "--model", default=None,+ help="provider:model (OpenWorker) or provider/model (default: this computer's "+ "setting; required with --isolated)",)p.add_argument("--coworker", dest="persona", default="cowork", metavar="ID",@@ -94,14 +104,31 @@ def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:# The flag's first name; kept so an existing harness command still works.p.add_argument("--persona", dest="persona", default=argparse.SUPPRESS, help=argparse.SUPPRESS)p.add_argument(- "--mode", default="bypass-approvals", type=_mode_arg, metavar="MODE",- help="how tool calls are approved: " + ", ".join(MODES) + " (default: bypass-approvals)",+ "--mode", default="interactive", type=_mode_arg, metavar="MODE",+ help="how tool calls are approved: " + ", ".join(MODES) + " (default: ask). At a "+ "terminal an approval is asked there; with no terminal it is refused and recorded.",+ )+ p.add_argument(+ "--auto-answer", action="store_true",+ help="nobody will answer the coworker's questions: it is told so and carries on. "+ "Without this, a question is asked in the terminal. Implied when no terminal is "+ "attached. Approvals are separate: see --mode.",+ )+ # The flag --auto-answer replaced; `--attendance auto` still means it.+ p.add_argument("--attendance", default=None, choices=ATTENDANCE, help=argparse.SUPPRESS)+ p.add_argument(+ "--allow-site", dest="allow_site", action="append", default=None, metavar="HOST[:PORT]",+ help="a site this run's commands and web tools may reach, beside this computer's "+ "allowed sites (repeatable). For this run only.",+ )+ p.add_argument(+ "--allow-sites-file", default=None, metavar="FILE",+ help="a file of sites to allow for this run, one HOST[:PORT] per line (# starts a comment)",)p.add_argument(- "--attendance",- default="auto",- choices=ATTENDANCE,- help="who answers when the agent asks; `auto` = the engine, by fixed rule (default)",+ "--isolated", action="store_true",+ help="read nothing from this computer (no settings, no stored keys, no sandbox) and "+ "keep everything under --out. For benchmark and evaluation runs. Needs --out and --model.",)p.add_argument("--max-iterations", type=int, default=None, help="default: OpenWorker config (150)"@@ -145,7 +172,11 @@ def parse_args(argv: Optional[list[str]] = None) -> argparse.Namespace:default=1800.0,help="the run's own limit; 0 disables it (use 0 when an outer runner enforces one)",)- p.add_argument("--out", required=True, help="folder for the run record")+ p.add_argument(+ "--out", default=None,+ help="folder for the run record (default: sessions/<workspace path>/<session id> "+ "in OpenWorker's state folder)",+ )p.add_argument("--trajectory-atif", default=None, help="also write the ATIF trajectory here")p.add_argument("--agent-version", default=None, help="label for the trajectory's agent.version")p.add_argument(@@ -641,13 +672,95 @@ def _extra_dirs(args: argparse.Namespace, workspace: Path) -> list:return found+class UsageError(Exception):+ """The command line cannot be run as given: said on standard error, exit code 2."""+++def workspace_folder_name(workspace: Path) -> str:+ """The workspace's folder under sessions/: its full path with every character that is+ not a letter or a digit turned into a dash (`/Users/me/src/app` gives+ `-Users-me-src-app`), so one workspace's runs sit together and are found by path."""+ name = re.sub(r"[^A-Za-z0-9]", "-", str(workspace))+ if len(name) > 180: # a file name's limit is 255 on the common filesystems+ import hashlib++ name = name[:160] + "-" + hashlib.sha256(str(workspace).encode("utf-8")).hexdigest()[:12]+ return name+++def session_folder(workspace: Path, run_id: str) -> Path:+ from ..secrets import state_dir++ return state_dir() / "sessions" / workspace_folder_name(workspace) / run_id+++def allowed_sites(args: argparse.Namespace) -> list[str]:+ """`--allow-site` and `--allow-sites-file` as "host:port" entries. Exact host names,+ as on the network-access card; anything else stops the run before it starts."""+ from ..permissions import network_request_hosts++ wanted = list(args.allow_site or [])+ if args.allow_sites_file:+ try:+ text = Path(args.allow_sites_file).expanduser().read_text(encoding="utf-8")+ except OSError as exc:+ raise UsageError(f"cannot read --allow-sites-file: {exc}") from exc+ for line in text.splitlines():+ line = line.split("#", 1)[0].strip()+ if line:+ wanted.append(line)+ good, bad = network_request_hosts({"hosts": wanted})+ if bad:+ raise UsageError(+ "not a site name: " + ", ".join(bad) + ". Give exact host names, with a port "+ "only when it is not 443 (no wildcards, no addresses)."+ )+ return good+++# Exit codes. 0 only when the task finished; a run that stopped early still left its record.+EXIT_FINISHED = 0+EXIT_CRASHED = 1 # no usable record+EXIT_USAGE = 2+EXIT_STOPPED = 3 # timeout, model error, iteration cap, interrupted: the record is written++def run(args: argparse.Namespace) -> int:- out = Path(args.out).resolve()- out.mkdir(parents=True, exist_ok=True)- isolation = isolate_environment(out)+ try:+ return _run(args)+ except UsageError as exc:+ print(f"openworker run: {exc}", file=sys.stderr)+ return EXIT_USAGE+++def _run(args: argparse.Namespace) -> int:+ if args.isolated and not args.out:+ raise UsageError("--isolated needs --out: an isolated run keeps everything in that folder")+ if args.isolated and not args.model:+ raise UsageError("--isolated needs --model: an isolated run reads no settings from this computer")+ try:+ prompt = _read_prompt(args)+ except NoPrompt as exc:+ raise UsageError(str(exc)) from exc+ sites = allowed_sites(args)+ workspace = Path(args.workspace).resolve()+ run_id = uuid.uuid4().hex[:12]++ # Where OpenWorker's state is read from, set BEFORE the engine is built. Isolated: a+ # fresh folder under --out, so nothing of this computer is read or written. Otherwise+ # this computer's own state folder, read for its settings, keys, sandbox and allowed+ # sites; what the run writes goes to its own record folder.+ if args.isolated:+ out = Path(args.out).resolve()+ out.mkdir(parents=True, exist_ok=True)+ isolation = isolate_environment(out)+ else:+ out = Path(args.out).resolve() if args.out else session_folder(workspace, run_id)+ os.environ["COWORKER_SCRATCH_BASE"] = str(out / "scratch")+ isolation = {"COWORKER_SCRATCH_BASE": str(out / "scratch")}cleaned_keys = sanitize_key_env()if cleaned_keys:- print(f"openworker run: stripped stray whitespace from {', '.join(cleaned_keys)}")+ print(f"openworker run: stripped stray whitespace from {', '.join(cleaned_keys)}", file=sys.stderr)# Build the engine only now, after the isolation variables are set.from ..agent import build_engine@@ -665,29 +778,43 @@ def run(args: argparse.Namespace) -> int:known = get_registry().ids()if args.persona not in known:- print(- f"openworker run: no coworker has the id {args.persona!r}. Known ids: {', '.join(sorted(known))}",- file=sys.stderr,- )- return 2+ raise UsageError(f"no coworker has the id {args.persona!r}. Known ids: {', '.join(sorted(known))}")- workspace = Path(args.workspace).resolve()+ out.mkdir(parents=True, exist_ok=True)+ # Made now, not on first use: a sandbox is given the run's folders when it starts, and+ # it cannot be given one that does not exist yet.+ for name in ("scratch", "tool-output"):+ (out / name).mkdir(parents=True, exist_ok=True)workspace.mkdir(parents=True, exist_ok=True)# `--add-dir DIR`: extra writable folders. An explicit list replaces the engine's# default single-workspace root, so the workspace goes first and stays the folder# that relative paths resolve against.extra_dirs = _extra_dirs(args, workspace)roots = [RootDir(path=workspace, writable=True), *extra_dirs] if extra_dirs else None+ if not args.model:+ from ..config import load_config++ args.model = load_config(workspace).modelmodel = normalize_model(args.model)mode = Mode(args.mode)- run_id = uuid.uuid4().hex[:12]- try:- prompt = _read_prompt(args)- except NoPrompt as exc:- print(f"openworker run: {exc}", file=sys.stderr)- return 2answers = Answers()+ # Who answers. Approvals and questions are separate: an approval is the person's at a+ # terminal and refused without one; a question is the person's at a terminal unless+ # --auto-answer says nobody will answer, and answered by rule without a terminal.+ from .terminal import Terminal++ terminal = Terminal.attached(cwd=workspace)+ auto_answer = bool(args.auto_answer) or args.attendance == "auto" or terminal is None+ args.attendance = "auto" if auto_answer else "attended"+ if terminal is None and mode is Mode.INTERACTIVE:+ print(+ "openworker run: no terminal is attached, so every approval is refused in mode "+ "ask. For a run with nobody present use --mode auto-approve or --mode bypass-approvals.",+ file=sys.stderr,+ flush=True,+ )+secrets = SecretStore(state_dir() / "secrets.json")if args.scripted:provider = scripted_provider(Path(args.scripted))@@ -720,9 +847,31 @@ def run(args: argparse.Namespace) -> int:secrets=secrets,# The reviewer only exists in auto-approve mode; elsewhere leave the config default.auto_approve=True if mode is Mode.AUTO_APPROVE else None,+ approver=terminal.approve if terminal is not None else None,+ question_asker=terminal.ask if terminal is not None and not auto_answer else None,+ directory_requester=terminal.directory if terminal is not None and not auto_answer else None,+ tool_requester=terminal.tool if terminal is not None and not auto_answer else None,+ # A run reads this computer's settings and changes none of them. A connector+ # refreshes its stored sign-in as it works, so connectors stay out of a run for+ # now. (An isolated run has none to begin with.)+ connector_filter=None if args.isolated else set(),)- # Nobody is present: the engine answers by rule (coworker/unattended.py).+ # Questions: answered by rule when nobody will (coworker/unattended.py). Approvals:+ # with a terminal they reach the person whatever --auto-answer says.engine.attendance = lambda: args.attendance+ if terminal is not None:+ engine.cards_reach_person = lambda: True+ engine.is_attended = lambda: True+ if sites:+ if engine.permissions.sandbox_sites is None:+ print(+ "openworker run: --allow-site has no effect here: this run's commands are "+ "not held to a list of allowed sites.",+ file=sys.stderr,+ flush=True,+ )+ else:+ engine.permissions.allow_network_hosts(sites, always=False)if mode is Mode.DANGEROUSLY_BYPASS_APPROVALS:print(f"openworker run: {DANGEROUS_MODE_WARNING}", file=sys.stderr, flush=True)@@ -798,6 +947,10 @@ def run(args: argparse.Namespace) -> int:events.append(rec)events_fh.write(json.dumps(rec, default=str) + "\n")last_type, last_data = ev.type, ev.data+ if ev.type == EventType.PERMISSION_REQUIRED and terminal is not None:+ terminal.card = dict(ev.data) # the approver is asked next+ elif ev.type == EventType.TOOL_PROPOSED:+ _progress(ev.data)if ev.type == EventType.ITERATION_END:flush_provisional("in_progress")# A transient provider failure ended the turn: wait, then re-enter the same@@ -894,6 +1047,13 @@ def run(args: argparse.Namespace) -> int:executor.close()except Exception: # noqa: BLE001pass+ # The run's sandbox ends with the run.+ sandbox = getattr(engine, "sandbox_workspace", None)+ if sandbox is not None:+ try:+ sandbox.close()+ except Exception: # noqa: BLE001+ passwall = time.time() - startedtry:events_fh.close()@@ -930,13 +1090,53 @@ def run(args: argparse.Namespace) -> int:trajectory_extra_path=args.trajectory_atif,)tokens = summary["tokens"]+ # Standard output is the coworker's answer and nothing else; the rest is standard error.+ answer = _final_answer(engine)+ if answer:+ sys.stdout.write(answer if answer.endswith("\n") else answer + "\n")+ sys.stdout.flush()print(f"openworker run: outcome={outcome} iterations={summary['iterations']} "f"tool_calls={summary['tool_calls']} refused={summary['answers']['cards_refused']} "f"tokens_in={tokens['input']} tokens_out={tokens['output']} "- f"cost={summary['cost_usd']} wall={wall:.0f}s out={out}"+ f"cost={summary['cost_usd']} wall={wall:.0f}s out={out}",+ file=sys.stderr,+ flush=True,)- return 1 if outcome == "crash" else 0+ if outcome == "crash":+ return EXIT_CRASHED+ if outcome != "completed" and error_text:+ # Why it stopped, in a line: the full text is in the record.+ print(f"openworker run: {redact(error_text.strip().splitlines()[-1])[:600]}", file=sys.stderr, flush=True)+ return EXIT_FINISHED if outcome == "completed" else EXIT_STOPPED+++def _progress(data: dict[str, Any]) -> None:+ """One line per tool call on standard error, so a person watching sees the run move."""+ name = str(data.get("name") or "")+ args = data.get("arguments") if isinstance(data.get("arguments"), dict) else {}+ detail = ""+ for key in ("command", "path", "url", "query", "pattern"):+ if isinstance(args.get(key), str) and args[key].strip():+ detail = " ".join(args[key].split())+ break+ line = f" {name}" + (f": {detail}" if detail else "")+ print(line if len(line) <= 160 else line[:159] + "…", file=sys.stderr, flush=True)+++def _final_answer(engine: Any) -> str:+ """The text of the coworker's last reply."""+ for message in reversed(getattr(engine, "messages", None) or []):+ if message.get("role") != "assistant":+ continue+ content = message.get("content")+ if isinstance(content, list):+ content = "".join(+ str(part.get("text", "")) for part in content if isinstance(part, dict) and part.get("type") == "text"+ )+ if isinstance(content, str) and content.strip():+ return content.strip()+ return ""def _model_settings(args: argparse.Namespace) -> Optional[dict[str, Any]]:@@ -1081,6 +1281,7 @@ def _write_records("persona": args.persona,"mode": args.mode,"attendance": args.attendance,+ "isolated": bool(args.isolated),"max_iterations": args.max_iterations,"max_output_tokens": args.max_output_tokens,"reasoning_effort": args.reasoning_effort,diff --git a/coworker/headless/terminal.py b/coworker/headless/terminal.pynew file mode 100644index 00000000..c7c0ff04--- /dev/null+++ b/coworker/headless/terminal.py@@ -0,0 +1,303 @@+"""`openworker run` at a terminal: approval cards and questions as plain prompts.++A run with a person at the keyboard asks there, on standard error, so standard output+stays the coworker's answer and nothing else. Approvals and questions are separate+(coworker/unattended.py): `--auto-answer` answers the questions by rule and leaves the+approvals with the person.++ Approval needed: run a command+ npm install+ in ~/src/project+ [y] yes, once [s] yes, for this session [n] no+ >++The network card has no "always": a run reads this computer's allowed sites and never+changes them.+"""++from __future__ import annotations++import asyncio+import json+import os+import sys+from pathlib import Path+from typing import Any, Callable, Optional++from ..engine import ApprovalOutcome, PermissionRequest+from ..permissions import NETWORK_ACCESS_TOOL++_VALUE_LIMIT = 400+++def _short(text: str, limit: int = _VALUE_LIMIT) -> str:+ text = str(text)+ return text if len(text) <= limit else text[: limit - 1] + "…"+++def _home_relative(path: str) -> str:+ try:+ home = str(Path.home())+ except Exception: # noqa: BLE001+ return path+ return "~" + path[len(home):] if path == home or path.startswith(home + os.sep) else path+++def _ago(seconds: Any) -> str:+ try:+ n = int(float(seconds))+ except (TypeError, ValueError):+ return ""+ if n < 60:+ return f"{n} second{'' if n == 1 else 's'} ago"+ minutes = n // 60+ return f"{minutes} minute{'' if minutes == 1 else 's'} ago"+++def _site(entry: str) -> str:+ return entry[: -len(":443")] if entry.endswith(":443") else entry+++def session_outcome(request: PermissionRequest) -> Optional[ApprovalOutcome]:+ """The grant "[s] yes, for this session" stands for on this card: the narrowest one the+ app's card would offer (this command, this site, this tool). None when the card has no+ session choice, and then the prompt offers yes and no only."""+ from ..server.manager import _grant_offered++ for outcome in (+ ApprovalOutcome.ALWAYS_COMMAND,+ ApprovalOutcome.ALWAYS_DOMAIN,+ ApprovalOutcome.THIS_RUN,+ ApprovalOutcome.ALWAYS_TOOL,+ ):+ if _grant_offered(outcome, request):+ return outcome+ return None+++def _option_label(option: Any) -> str:+ if isinstance(option, dict):+ return str(option.get("label") or option.get("value") or "").strip()+ return str(option).strip()+++class Terminal:+ """The prompts. `read_line` returns the typed line without its newline, or None at end+ of input; `write` prints one piece of text. Both are plain blocking calls."""++ def __init__(+ self,+ read_line: Callable[[], Optional[str]],+ write: Callable[[str], None],+ *,+ cwd: Optional[Path] = None,+ ) -> None:+ self._read_line = read_line+ self._write = write+ self.cwd = cwd+ # The card the engine announced last (PERMISSION_REQUIRED): what the approver is+ # about to be asked. It carries what the request alone does not: the network+ # request's sites and whether the sandbox blocked them.+ self.card: dict[str, Any] = {}+ self._lock = asyncio.Lock()++ @classmethod+ def attached(cls, cwd: Optional[Path] = None) -> Optional["Terminal"]:+ """A terminal the person can be asked on, or None (a pipe, a CI job, a harness)."""+ try:+ if not (sys.stdin.isatty() and sys.stderr.isatty()):+ return None+ except Exception: # noqa: BLE001 - a closed stream is not a terminal+ return None++ def read_line() -> Optional[str]:+ line = sys.stdin.readline()+ return line.rstrip("\r\n") if line else None++ def write(text: str) -> None:+ sys.stderr.write(text)+ sys.stderr.flush()++ return cls(read_line, write, cwd=cwd)++ # -- plumbing -------------------------------------------------------------------------++ async def _prompt(self) -> Optional[str]:+ self._write("> ")+ return await asyncio.to_thread(self._read_line)++ def _say(self, *lines: str) -> None:+ self._write("\n".join(lines) + "\n")++ # -- approvals ------------------------------------------------------------------------++ def _describe(self, request: PermissionRequest) -> tuple[str, list[str]]:+ """The card's heading and body lines."""+ args = request.arguments or {}+ name = request.tool_name+ network = self.card.get("network_request") if name == NETWORK_ACCESS_TOOL else None+ if network:+ hosts = [h for h in network.get("hosts") or [] if isinstance(h, dict)]+ names = ", ".join(_site(str(h.get("host", ""))) for h in hosts)+ body = []+ if network.get("reason"):+ body.append(f"Reason: {_short(network['reason'])}")+ for h in hosts:+ seen = _ago(h.get("blocked_seconds_ago")) if h.get("blocked_seconds_ago") is not None else ""+ site = _site(str(h.get("host", "")))+ if seen:+ body.append(f"The sandbox blocked {site} {seen}." if len(hosts) > 1 else f"The sandbox blocked this site {seen}.")+ elif network.get("evidence"):+ body.append(f"No command has tried {site} yet." if len(hosts) > 1 else "No command has tried this site yet.")+ return f"let commands reach {names}", body+ wall = self.card.get("site_wall")+ if wall:+ body = [f"{name}: {_short(args.get('url') or args.get('query') or '')}".rstrip(": ")]+ body.append("This site is not on the sandbox's allowed sites.")+ return f"reach {_site(str(wall))}", body+ command = args.get("command")+ if isinstance(command, str) and command.strip():+ body = [_short(command.strip())]+ where = args.get("cwd") or (str(self.cwd) if self.cwd else "")+ if where:+ body.append(f"in {_home_relative(str(where))}")+ return "run a command", body+ body = []+ for key, value in args.items():+ text = value if isinstance(value, str) else json.dumps(value, default=str)+ body.append(f"{key}: {_short(text, 200)}")+ return f"use {name}", body[:8]++ async def approve(self, request: PermissionRequest) -> ApprovalOutcome:+ async with self._lock:+ heading, body = self._describe(request)+ reason = (request.reason or "").strip()+ network = request.tool_name == NETWORK_ACCESS_TOOL+ session = ApprovalOutcome.ALWAYS_DOMAIN if network else session_outcome(request)+ lines = ["", f"Approval needed: {heading}", *[f" {line}" for line in body]]+ if reason and reason != "requires approval" and not network:+ lines.append(f" Why it asks: {_short(reason, 200)}")+ if network:+ lines.append(" [s] yes, for this run [n] no")+ elif session is not None:+ lines.append(" [y] yes, once [s] yes, for this session [n] no")+ else:+ lines.append(" [y] yes [n] no")+ self._say(*lines)+ self.card = {}+ while True:+ typed = await self._prompt()+ if typed is None: # the terminal went away: nobody can say yes+ return ApprovalOutcome.DENY+ choice = typed.strip().lower()+ if choice in ("n", "no"):+ return ApprovalOutcome.DENY+ if choice in ("s", "session") and session is not None:+ return session+ if choice in ("y", "yes"):+ # The network card's only yes is "for this run".+ return session if network and session is not None else ApprovalOutcome.ONCE+ self._say(" Type " + ("s or n." if network else "y, s or n." if session is not None else "y or n."))++ # -- questions ------------------------------------------------------------------------++ async def _one_question(self, entry: dict[str, Any]) -> str:+ question = str(entry.get("question") or "").strip()+ options = [label for label in (_option_label(o) for o in entry.get("options") or []) if label]+ multi = bool(entry.get("multi") or entry.get("multiSelect"))+ free_text = entry.get("allow_text", True) is not False+ lines = [f" {question}"]+ for i, label in enumerate(options, 1):+ lines.append(f" {i}. {label}")+ if options and multi:+ lines.append(" Type the numbers, separated by commas" + (", or your own answer:" if free_text else ":"))+ elif options:+ lines.append(" Type a number" + (", or your own answer:" if free_text else ":"))+ else:+ lines.append(" Type your answer:")+ self._say(*lines)+ while True:+ typed = await self._prompt()+ if typed is None:+ return ""+ text = typed.strip()+ if not text:+ continue+ if options:+ picks = [p.strip() for p in text.split(",")] if multi else [text]+ if all(p.isdigit() and 1 <= int(p) <= len(options) for p in picks):+ return ", ".join(options[int(p) - 1] for p in picks)+ if not free_text:+ self._say(f" Type a number from 1 to {len(options)}.")+ continue+ return text++ async def ask(self, args: dict[str, Any], _call_id: Optional[str] = None) -> dict[str, Any]:+ """The engine's question hook: `{"answer": …}` for one question, `{"answers": {…}}`+ for a group, keyed by header or question as the other surfaces key them."""+ async with self._lock:+ grouped = [+ entry+ for entry in (args.get("questions") or [])+ if isinstance(entry, dict) and str(entry.get("question", "")).strip()+ ]+ self._say("", "The coworker asks:")+ if grouped:+ answers: dict[str, str] = {}+ for entry in grouped:+ answers[str(entry.get("header") or entry.get("question"))] = await self._one_question(entry)+ return {"answers": answers}+ return {"answer": await self._one_question(args)}++ # -- folders and tool installs --------------------------------------------------------++ async def directory(self, args: dict[str, Any], _call_id: Optional[str] = None) -> dict[str, Any]:+ """The engine's folder-request hook. A run's folders are fixed when it starts+ (`--workspace`, `--add-dir`), so the person is told what was asked for and the+ coworker is told to work with what it has."""+ async with self._lock:+ path = str(args.get("path") or "").strip()+ reason = str(args.get("reason") or "").strip()+ lines = ["", "The coworker asked for a folder" + (f": {_home_relative(path)}" if path else "") + "."]+ if reason:+ lines.append(f" Reason: {_short(reason, 200)}")+ lines.append(" A run's folders are set when it starts. To give this one, run again with --add-dir.")+ self._say(*lines)+ return {+ "granted": False,+ "error": (+ "This run's folders were set when it started and cannot be added to now. Work "+ "inside the current workspace. If the task cannot continue without that folder, "+ "stop and say which folder is needed, so the user can start the run again with it."+ ),+ }++ async def tool(self, args: dict[str, Any], _call_id: Optional[str] = None) -> dict[str, Any]:+ """The engine's tool-install hook: only reached for a tool in the pinned catalog,+ so yes installs the verified build."""+ from .. import toolchain++ name = str(args.get("name") or "").strip()+ info = toolchain.describe(name) or {}+ async with self._lock:+ lines = ["", f"The coworker asks to install a tool: {name}" + (f" {info['version']}" if info.get("version") else "")]+ if info.get("summary"):+ lines.append(f" {_short(info['summary'], 200)}")+ if args.get("reason"):+ lines.append(f" Reason: {_short(args['reason'], 200)}")+ lines.append(" [y] install it [n] no")+ self._say(*lines)+ while True:+ typed = await self._prompt()+ choice = (typed or "n").strip().lower() if typed is not None else "n"+ if choice in ("n", "no"):+ return {"installed": False, "error": "the user declined the install"}+ if choice in ("y", "yes"):+ break+ self._say(" Type y or n.")+ try:+ path = await asyncio.to_thread(toolchain.install, name)+ except Exception as exc: # noqa: BLE001 - the coworker must hear why+ self._say(f" The install failed: {exc}")+ return {"installed": False, "error": f"install failed: {exc}"}+ return {"installed": True, "path": path, "version": info.get("version", "")}diff --git a/docs/headless.md b/docs/headless.mdindex 9fda6ac8..10af71d6 100644--- a/docs/headless.md+++ b/docs/headless.md@@ -5,7 +5,7 @@ OpenWorker has two headless modes. They answer different questions.| Command | What it does | Who drives it ||---|---|---|| `openworker up` (after `openworker join`) | Keeps this computer serving as a machine the desktop app controls, forever | The desktop app: tasks and chat arrive over its channel |-| `openworker run` | Runs one task to the end and exits, leaving a record behind | A script, a CI job, an evaluation harness |+| `openworker run` | Runs one task to the end and exits, leaving a record behind | You at a terminal, a script, a CI job, an evaluation harness |This page is about `openworker run` and the two switches that decide what happens whenthe agent would normally stop and ask.@@ -53,39 +53,102 @@ In `auto`:verified installer, same version and checksum as the desktop card would use;- an approval card that would have needed a person is refused, never parked. Nothing hangs.-`openworker run` always uses `auto`. The desktop app offers it as the third position of the-Unattended toggle ("Answer for me while I'm away"); there it can only combine with modes-that keep the checks, so the worst case is a refused card.+The desktop app offers `auto` as the third position of the Unattended toggle ("Answer for+me while I'm away"); there it can only combine with modes that keep the checks, so the+worst case is a refused card.## `openworker run````-openworker run --prompt "Fix the failing test in tests/test_parser.py" \- --workspace ~/src/project --model anthropic/claude-sonnet-5 \- --mode bypass-approvals --out ./run-record+cd ~/src/project+openworker run --prompt "Fix the failing test in tests/test_parser.py"```-Options:+The task comes from `--prompt`, from `--prompt-file`, or from standard input when it is+piped in. The coworker's answer is printed on standard output; progress, prompts and the+closing summary line go to standard error.++### What a run reads from this computer++A run uses this computer's OpenWorker settings: the default model, the stored provider+keys, the sandbox and its allowed sites. It reads them and changes none of them.+Connectors are not available in a run yet.++Each run is its own process. Two runs started from two terminals do not share anything+but those settings, and each is saved as its own session.++### Approvals and questions++These are separate, and each has its own switch.++**Approvals** follow `--mode` (the table above). The default is `ask`.++| | An approval card |+|---|---|+| At a terminal | asked in the terminal: yes once, yes for this session, or no |+| No terminal (a pipe, a CI job) | refused and recorded; nothing hangs |++With no terminal, mode `ask` refuses every approval, and the run says so when it starts.+For a run with nobody present, use `--mode auto-approve` (the reviewer decides) or+`--mode bypass-approvals`.++**Questions** follow `--auto-answer`.++| | A question from the coworker |+|---|---|+| At a terminal | asked in the terminal |+| At a terminal with `--auto-answer` | answered by the fixed rule above, and recorded |+| No terminal | answered by the fixed rule, and recorded |++`--auto-answer` does not touch approvals: at a terminal they are still asked.++Two other requests go with the questions. A pinned tool install is asked at a terminal and+installed by rule otherwise. A request for another folder is declined: a run's folders are+set when it starts, with `--workspace` and `--add-dir`.++### Options| Flag | Meaning ||---|---|-| `--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 |+| `--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) |-| `--mode` | see above; default `bypass-approvals` |-| `--attendance` | `auto` (the only value here) || `--coworker ID` | the coworker that does the task, by its id: `cowork` (default) or `code`. An unknown id stops the run with exit code 2 |+| `--model ID` | `provider:model` or `provider/model` (first slash splits). Default: this computer's setting |+| `--mode` | `ask` (default), `auto-approve`, `bypass-approvals`, `dangerously-bypass-approvals` |+| `--auto-answer` | nobody will answer questions; see above |+| `--allow-site HOST[:PORT]` | a site this run's commands and web tools may reach, beside this computer's allowed sites (repeatable). For this run only; the computer's list is not changed. Exact host names, no wildcards |+| `--allow-sites-file FILE` | the same, from a file: one `HOST[:PORT]` per line, `#` starts a comment |+| `--out DIR` | where the record goes. Default: `sessions/<workspace path>/<session id>/` in OpenWorker's state folder, the workspace path written with dashes |+| `--isolated` | read nothing from this computer; see below || `--reasoning-effort` | `low` … `max`, sent to the provider; unset = provider default, recorded || `--max-output-tokens`, `--max-iterations`, `--timeout-seconds` | ceilings; `--timeout-seconds 0` when an outer runner enforces its own || `--tool-result-max-bytes` | bound each tool result (default 10,000; 0 = off); full text spilled under `out/tool-output/` || `--provider-order` | OpenRouter only: pin the upstream host, no fallback |-| `--out DIR`, `--trajectory-atif PATH` | where the record goes |+| `--trajectory-atif PATH` | also write the trajectory here |++### Isolated runs, for benchmarks-The model key comes from the environment (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,-`TOGETHER_API_KEY`, `OPENROUTER_API_KEY`, …). OpenWorker's state and scratch folders are-pointed under `--out` before the engine starts, so a run never touches the machine's own-conversations, keys or settings.+```+openworker run --isolated --prompt-file task.md --workspace /work \+ --model anthropic/claude-sonnet-5 --mode bypass-approvals --out ./run-record+```++`--isolated` reads nothing from the computer: no settings, no stored keys, no sandbox. The+model key comes from the environment (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,+`TOGETHER_API_KEY`, `OPENROUTER_API_KEY`, …), and OpenWorker's state and scratch folders+are placed under `--out`. Two runs of the same task on two computers then start from the+same place. It needs `--out` and `--model`, and a harness should pass `--mode` too, so the+record states it.++### Exit code++| Code | Meaning |+|---|---|+| 0 | the task finished |+| 1 | the run crashed before it could write a record |+| 2 | the command line could not be run as given |+| 3 | the run stopped early (time limit, model error, iteration limit, cut-off reply); the record is written |### The record@@ -100,9 +163,7 @@ conversations, keys or settings.| `provider_errors.log` | full cause chains of failed model calls, credentials redacted || `audit.db` | OpenWorker's audit log for the session |-The trajectory and the exit code are the stable contract. Exit code 0 means a trajectory-was written (completed, iteration cap, timeout, model error); 1 means the run crashed-before producing one.+The trajectory and the exit code are the stable contract.A transient provider failure or an empty reply does not end the run: the runner waits(30 s, 60 s, 120 s, 240 s, 300 s, 300 s) and re-enters the conversation with a nudge.diff --git a/tests/test_cli_surface.py b/tests/test_cli_surface.pyindex 9fed230f..170e98db 100644--- a/tests/test_cli_surface.py+++ b/tests/test_cli_surface.py@@ -12,7 +12,7 @@ def test_no_arguments_prints_help_that_lists_every_public_command(capsys):ow_cli.main([])out = capsys.readouterr().outassert "usage: openworker <command>" in out- for verb in ("join <link>", "up", "run <task>", "machine", "status", "keys", "logs", "service", "leave", "version"):+ for verb in ("join <link>", "up", "run ", "machine", "status", "keys", "logs", "service", "leave", "version"):assert verb in out# Unlisted until tested as a product surface.for hidden in ("tui", "sessions", "inbox", "doctor"):diff --git a/tests/test_headless_run.py b/tests/test_headless_run.pyindex 6638e1eb..a98f8a02 100644--- a/tests/test_headless_run.py+++ b/tests/test_headless_run.py@@ -11,6 +11,7 @@ import jsonimport osimport subprocessimport sys+import tempfilefrom pathlib import Pathimport pytest@@ -31,8 +32,10 @@ def _env(extra: dict | None = None) -> dict:env["PYTHONPATH"] = str(ROOT) + os.pathsep + env.get("PYTHONPATH", "")env.pop("ANTHROPIC_API_KEY", None)env.pop("OPENAI_API_KEY", None)- env.pop("COWORKER_STATE_DIR", None)env.pop("COWORKER_SCRATCH_BASE", None)+ # "This computer's" state folder for a run that is not --isolated: an empty temporary+ # one, never the developer's own settings, keys and sandbox.+ env["COWORKER_STATE_DIR"] = tempfile.mkdtemp(prefix="ow-run-machine-")env.update(extra or {})return env@@ -46,7 +49,10 @@ def _run(prompt: str = TASK,extra: list[str] | None = None,env: dict | None = None,+ isolated: bool = True,) -> tuple[subprocess.CompletedProcess, Path, Path]:+ """One run with a scripted model. `isolated` (the default here) is the sealed run a+ benchmark harness makes: nothing of the computer is read, everything stays under --out."""ws = tmp_path / "ws"ws.mkdir(exist_ok=True)out = tmp_path / "out"@@ -59,6 +65,7 @@ def _run("--mode", mode, "--out", str(out),"--trajectory-atif", str(tmp_path / "logs" / "trajectory.json"),"--scripted", str(path), "--timeout-seconds", "120",+ *(["--isolated"] if isolated else []),*(extra or []),]proc = subprocess.run(cmd, env=_env(env), capture_output=True, text=True, timeout=300)@@ -200,7 +207,7 @@ def test_a_cut_off_reply_is_continued_and_repeated_cut_offs_end_as_truncated(tmpsecond = tmp_path / "again"second.mkdir()proc, _ws, out = _run(second, "bypass-approvals", [cut, cut, cut], prompt="Do something hard.")- assert proc.returncode == 0, proc.stdout + proc.stderr+ assert proc.returncode == 3, proc.stdout + proc.stderr # stopped early; the record is writtensummary = _summary(out)assert summary["outcome"] == "truncated" and summary["continuations"] == 2assert _messages(out)[-1]["kind"] == "truncated"@@ -272,7 +279,7 @@ def test_empty_reply_is_nudged_and_a_permanent_error_is_not_retried(tmp_path: Pasecond, "bypass-approvals", [fail, {"text": "never reached"}],prompt="Do something hard.", env={"OPENWORKER_RUN_RETRY_DELAYS": "0,0"},)- assert proc.returncode == 0, proc.stdout + proc.stderr # a model error is a recorded outcome+ assert proc.returncode == 3, proc.stdout + proc.stderr # a model error is a recorded outcome, not a finished tasksummary = _summary(out)assert summary["outcome"] == "model_error" and summary["provider_retries"] == 0@@ -354,11 +361,12 @@ def test_run_help_and_the_top_level_help_mention_the_command() -> None:env=_env(), capture_output=True, text=True, timeout=120,)assert proc.returncode == 0 and "usage: openworker run" in proc.stdout- assert "--attendance" in proc.stdout and "--scripted" not in proc.stdout # test-only flag stays hidden+ assert "--auto-answer" in proc.stdout and "--isolated" in proc.stdout+ assert "--attendance" not in proc.stdout and "--scripted" not in proc.stdout # unlisted flags stay hiddentop = subprocess.run([sys.executable, "-m", "coworker.cli"], env=_env(), capture_output=True, text=True, timeout=120)- assert "run <task>" in top.stdout+ assert " run " in top.stdout and "--prompt" in top.stdoutdef test_the_old_persona_flag_still_chooses_the_coworker(tmp_path: Path) -> None:diff --git a/tests/test_run_cli.py b/tests/test_run_cli.pynew file mode 100644index 00000000..8f4938aa--- /dev/null+++ b/tests/test_run_cli.py@@ -0,0 +1,418 @@+"""`openworker run` as a person uses it: this computer's settings are read and never+changed, the session is saved under the state folder by workspace path, approvals and+questions are asked in the terminal, and the exit code says whether the task finished.++The sealed benchmark run (`--isolated`) is covered in test_headless_run.py."""++from __future__ import annotations++import asyncio+import json+import os+import select+import subprocess+import sys+import time+from pathlib import Path++import pytest++from coworker.engine import ApprovalOutcome, PermissionRequest+from coworker.headless.runner import allowed_sites, parse_args, workspace_folder_name+from coworker.headless.terminal import Terminal++ROOT = Path(__file__).resolve().parents[1]++WRITE_THEN_DONE = [+ {"text": "I will create the file.", "tool_calls": [{"name": "write_file", "arguments": {"path": "hello.txt", "content": "hello"}}]},+ {"text": "The file is written. Done."},+]+++def _env(machine: Path) -> dict:+ env = dict(os.environ)+ env["PYTHONPATH"] = str(ROOT) + os.pathsep + env.get("PYTHONPATH", "")+ for name in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "COWORKER_SCRATCH_BASE", "OPENWORKER_BASE_DIR"):+ env.pop(name, None)+ env["COWORKER_STATE_DIR"] = str(machine) # "this computer's" state folder+ return env+++def _command(tmp_path: Path, script: list[dict], *extra: str) -> tuple[list[str], Path]:+ ws = tmp_path / "ws"+ ws.mkdir(exist_ok=True)+ path = tmp_path / "script.json"+ path.write_text(json.dumps(script), encoding="utf-8")+ return [+ sys.executable, "-m", "coworker.cli", "run", "--prompt", "Create hello.txt.",+ "--workspace", str(ws), "--scripted", str(path), "--timeout-seconds", "120", *extra,+ ], ws+++def _run(tmp_path: Path, script: list[dict], *extra: str, machine: Path | None = None):+ machine = machine or tmp_path / "machine"+ machine.mkdir(exist_ok=True)+ cmd, ws = _command(tmp_path, script, *extra)+ proc = subprocess.run(cmd, env=_env(machine), capture_output=True, text=True, timeout=300)+ return proc, ws, machine+++def _session_folders(machine: Path, ws: Path) -> list[Path]:+ base = machine / "sessions" / workspace_folder_name(ws.resolve())+ return sorted(p for p in base.iterdir()) if base.is_dir() else []+++# -- the saved session ------------------------------------------------------------------+++def test_a_run_is_saved_under_the_state_folder_by_workspace_path(tmp_path: Path) -> None:+ proc, ws, machine = _run(tmp_path, WRITE_THEN_DONE, "--model", "anthropic/claude-sonnet-5", "--mode", "bypass-approvals")+ assert proc.returncode == 0, proc.stderr+ assert (ws / "hello.txt").read_text(encoding="utf-8") == "hello"+ (folder,) = _session_folders(machine, ws)+ summary = json.loads((folder / "summary.json").read_text(encoding="utf-8"))+ assert summary["outcome"] == "completed" and summary["args"]["isolated"] is False+ assert folder.name == summary["run_id"]+ for name in ("events.jsonl", "messages.json", "trajectory.json", "audit.db"):+ assert (folder / name).exists(), name+ # Both exist from the start: a sandbox is handed the run's folders when it is made.+ assert (folder / "scratch").is_dir() and (folder / "tool-output").is_dir()+ # Standard output is the coworker's answer and nothing else.+ assert proc.stdout == "The file is written. Done.\n"+ assert "outcome=completed" in proc.stderr and "write_file: hello.txt" in proc.stderr+++def test_the_workspace_folder_name_is_the_path_with_dashes() -> None:+ assert workspace_folder_name(Path("/Users/me/src/my app")) == "-Users-me-src-my-app"+ long = workspace_folder_name(Path("/" + "/".join(["folder"] * 60)))+ assert len(long) < 200 and long != workspace_folder_name(Path("/" + "/".join(["folder"] * 61)))+++def test_this_computers_settings_are_read_and_not_changed(tmp_path: Path) -> None:+ machine = tmp_path / "machine"+ machine.mkdir()+ (machine / "config.toml").write_text('model = "anthropic:claude-sonnet-5"\n', encoding="utf-8")+ before = {p.name: p.read_bytes() for p in machine.iterdir() if p.is_file()}++ proc, ws, _ = _run(tmp_path, WRITE_THEN_DONE, "--mode", "bypass-approvals", machine=machine) # no --model+ assert proc.returncode == 0, proc.stderr+ (folder,) = _session_folders(machine, ws)+ assert json.loads((folder / "summary.json").read_text(encoding="utf-8"))["args"]["model"] == "anthropic:claude-sonnet-5"+ assert {p.name: p.read_bytes() for p in machine.iterdir() if p.is_file()} == before+ # Beside the settings, the run left only its own session.+ assert sorted(p.name for p in machine.iterdir() if p.is_dir()) == ["sessions"]+++def test_two_runs_in_one_workspace_are_two_sessions(tmp_path: Path) -> None:+ for _ in range(2):+ proc, ws, machine = _run(tmp_path, WRITE_THEN_DONE, "--model", "anthropic/claude-sonnet-5", "--mode", "bypass-approvals")+ assert proc.returncode == 0, proc.stderr+ assert len(_session_folders(machine, ws)) == 2+++# -- nobody at a terminal ---------------------------------------------------------------+++def test_the_default_mode_asks_and_with_no_terminal_the_card_is_refused(tmp_path: Path) -> None:+ proc, ws, machine = _run(tmp_path, WRITE_THEN_DONE, "--model", "anthropic/claude-sonnet-5")+ assert proc.returncode == 0, proc.stderr # the model's turn finished; the write was refused+ assert not (ws / "hello.txt").exists()+ assert "no terminal is attached" in proc.stderr and "--mode auto-approve" in proc.stderr+ (folder,) = _session_folders(machine, ws)+ summary = json.loads((folder / "summary.json").read_text(encoding="utf-8"))+ assert summary["args"]["mode"] == "interactive" and summary["args"]["attendance"] == "auto"+ assert summary["answers"]["cards_refused"] == 1+++def test_with_no_terminal_a_question_is_answered_by_rule(tmp_path: Path) -> None:+ script = [+ {"text": "", "tool_calls": [{"name": "ask_user", "arguments": {"question": "Which colour?", "options": ["red", "blue"]}}]},+ {"text": "Going with the safe one."},+ ]+ proc, ws, machine = _run(tmp_path, script, "--model", "anthropic/claude-sonnet-5", "--mode", "bypass-approvals")+ assert proc.returncode == 0, proc.stderr+ (folder,) = _session_folders(machine, ws)+ assert json.loads((folder / "summary.json").read_text(encoding="utf-8"))["answers"]["questions_answered"] == 1+++def test_a_run_that_stops_early_exits_3_and_says_why(tmp_path: Path) -> None:+ fail = {"error": "Invalid API key provided", "error_type": "AuthenticationError"}+ proc, ws, machine = _run(tmp_path, [fail], "--model", "anthropic/claude-sonnet-5", "--mode", "bypass-approvals")+ assert proc.returncode == 3+ assert "outcome=model_error" in proc.stderr and "Invalid API key provided" in proc.stderr+ assert proc.stdout == "" # no answer was given+ (folder,) = _session_folders(machine, ws)+ assert (folder / "trajectory.json").exists() # the record is written all the same+++# -- usage errors -----------------------------------------------------------------------+++ "extra, said",+ [+ (["--isolated", "--model", "anthropic/claude-sonnet-5"], "--isolated needs --out"),+ (["--isolated", "--out", "OUT"], "--isolated needs --model"),+ (["--model", "anthropic/claude-sonnet-5", "--allow-site", "*.example.com"], "not a site name"),+ (["--model", "anthropic/claude-sonnet-5", "--allow-site", "10.0.0.1"], "not a site name"),+ (["--model", "anthropic/claude-sonnet-5", "--allow-sites-file", "missing.txt"], "cannot read --allow-sites-file"),+ ],+)+def test_a_command_line_that_cannot_run_stops_with_exit_code_2(tmp_path: Path, extra: list[str], said: str) -> None:+ extra = [str(tmp_path / "out") if x == "OUT" else x for x in extra]+ proc, ws, machine = _run(tmp_path, WRITE_THEN_DONE, *extra)+ assert proc.returncode == 2+ assert said in proc.stderr and proc.stdout == ""+ assert not (machine / "sessions").exists() # nothing was started, nothing is left behind+++def test_allowed_sites_come_from_the_flag_and_the_file(tmp_path: Path) -> None:+ listed = tmp_path / "sites.txt"+ listed.write_text("# package registries\nregistry.npmjs.org\n\nfiles.pythonhosted.org:443 # wheels\ninternal.example.com:8443\n", encoding="utf-8")+ args = parse_args(["--prompt", "x", "--allow-site", "example.com", "--allow-site", "registry.npmjs.org", "--allow-sites-file", str(listed)])+ assert allowed_sites(args) == [+ "example.com:443", "registry.npmjs.org:443", "files.pythonhosted.org:443", "internal.example.com:8443",+ ]+ assert allowed_sites(parse_args(["--prompt", "x"])) == []+++def test_allow_site_says_so_when_no_list_holds_the_run(tmp_path: Path) -> None:+ proc, _ws, _machine = _run(+ tmp_path, WRITE_THEN_DONE, "--model", "anthropic/claude-sonnet-5", "--mode", "bypass-approvals", "--allow-site", "example.com",+ )+ assert proc.returncode == 0, proc.stderr+ assert "--allow-site has no effect here" in proc.stderr+++# -- the prompts ------------------------------------------------------------------------+++class _Keys:+ """A terminal for the prompts: the lines the person types, and what was printed."""++ def __init__(self, *typed: str) -> None:+ self.typed = list(typed)+ self.printed = ""++ def terminal(self, cwd: Path | None = None) -> Terminal:+ return Terminal(lambda: self.typed.pop(0) if self.typed else None, self._write, cwd=cwd)++ def _write(self, text: str) -> None:+ self.printed += text+++def _request(tool: str, arguments: dict, reason: str = "requires approval") -> PermissionRequest:+ return PermissionRequest(tool_name=tool, arguments=arguments, metadata=None, reason=reason)+++def test_a_command_card_offers_once_this_session_and_no() -> None:+ home = Path.home()+ for typed, outcome in (("y", ApprovalOutcome.ONCE), ("s", ApprovalOutcome.ALWAYS_COMMAND), ("n", ApprovalOutcome.DENY)):+ keys = _Keys(typed)+ got = asyncio.run(keys.terminal(cwd=home / "src" / "project").approve(_request("run_shell", {"command": "npm install"})))+ assert got is outcome+ assert "Approval needed: run a command\n npm install\n in ~/src/project\n" in keys.printed+ assert "[y] yes, once [s] yes, for this session [n] no" in keys.printed+ assert "requires approval" not in keys.printed # the engine's filler reason is not shown+++def test_an_unknown_key_asks_again_and_a_closed_terminal_is_a_no() -> None:+ keys = _Keys("maybe", "", "Y")+ assert asyncio.run(keys.terminal().approve(_request("run_shell", {"command": "ls"}))) is ApprovalOutcome.ONCE+ assert keys.printed.count("Type y, s or n.") == 2++ assert asyncio.run(_Keys().terminal().approve(_request("run_shell", {"command": "ls"}))) is ApprovalOutcome.DENY+++def test_a_file_write_card_shows_its_arguments_and_the_reason() -> None:+ keys = _Keys("s")+ request = _request("write_file", {"path": "notes.md", "content": "x" * 900}, reason="writes outside the workspace")+ assert asyncio.run(keys.terminal().approve(request)) is ApprovalOutcome.ALWAYS_TOOL+ assert "Approval needed: use write_file" in keys.printed and "path: notes.md" in keys.printed+ assert "Why it asks: writes outside the workspace" in keys.printed+ assert "x" * 300 not in keys.printed # a long value is cut+++def test_the_network_card_offers_this_run_only() -> None:+ keys = _Keys("y")+ term = keys.terminal()+ term.card = {+ "network_request": {+ "reason": "npm install needs the package registry.",+ "evidence": True,+ "hosts": [{"host": "registry.npmjs.org:443", "blocked_seconds_ago": 4}],+ }+ }+ request = _request("request_network_access", {"hosts": ["registry.npmjs.org"], "reason": "…"})+ assert asyncio.run(term.approve(request)) is ApprovalOutcome.ALWAYS_DOMAIN # this run; never "always"+ assert "Approval needed: let commands reach registry.npmjs.org\n" in keys.printed+ assert "Reason: npm install needs the package registry." in keys.printed+ assert "The sandbox blocked this site 4 seconds ago." in keys.printed+ assert "[s] yes, for this run [n] no" in keys.printed and "once" not in keys.printed++ keys = _Keys("n")+ term = keys.terminal()+ term.card = {"network_request": {"reason": "", "evidence": True, "hosts": [{"host": "example.org:8443", "blocked_seconds_ago": None}]}}+ assert asyncio.run(term.approve(request)) is ApprovalOutcome.DENY+ assert "let commands reach example.org:8443" in keys.printed and "No command has tried this site yet." in keys.printed+++def test_a_question_takes_a_number_or_typed_text() -> None:+ question = {"question": "Which database should the migration target?", "options": ["staging", "production"]}+ keys = _Keys("2")+ assert asyncio.run(keys.terminal().ask(dict(question))) == {"answer": "production"}+ assert "The coworker asks:\n Which database should the migration target?\n 1. staging\n 2. production\n" in keys.printed+ assert "Type a number, or your own answer:" in keys.printed++ assert asyncio.run(_Keys("", "neither, use a copy").terminal().ask(dict(question))) == {"answer": "neither, use a copy"}+ assert asyncio.run(_Keys("the blue one").terminal().ask({"question": "Which colour?"})) == {"answer": "the blue one"}++ keys = _Keys("other", "1")+ assert asyncio.run(keys.terminal().ask({**question, "allow_text": False})) == {"answer": "staging"}+ assert "Type a number from 1 to 2." in keys.printed+++def test_grouped_questions_are_asked_in_turn_and_keyed_by_header() -> None:+ keys = _Keys("1, 2", "weekly")+ got = asyncio.run(+ keys.terminal().ask(+ {+ "questions": [+ {"header": "Regions", "question": "Which regions?", "options": [{"label": "EU"}, {"label": "US"}], "multi": True},+ {"question": "How often?"},+ ]+ }+ )+ )+ assert got == {"answers": {"Regions": "EU, US", "How often?": "weekly"}}+++def test_a_folder_request_tells_the_person_and_is_declined() -> None:+ keys = _Keys()+ got = asyncio.run(keys.terminal().directory({"path": "/data/exports", "reason": "the report reads last month's exports"}))+ assert got["granted"] is False and "cannot be added to now" in got["error"]+ assert "The coworker asked for a folder: /data/exports." in keys.printed and "--add-dir" in keys.printed+++def test_a_tool_install_is_asked_and_yes_installs_the_pinned_build(monkeypatch: pytest.MonkeyPatch) -> None:+ from coworker import toolchain++ monkeypatch.setattr(toolchain, "describe", lambda name: {"version": "1.2.3", "summary": "a scanner"})+ installed: list[str] = []+ monkeypatch.setattr(toolchain, "install", lambda name: installed.append(name) or f"/tools/{name}")++ keys = _Keys("what", "y")+ got = asyncio.run(keys.terminal().tool({"name": "scanner", "reason": "to check the lockfile"}))+ assert got == {"installed": True, "path": "/tools/scanner", "version": "1.2.3"} and installed == ["scanner"]+ assert "The coworker asks to install a tool: scanner 1.2.3" in keys.printed and "[y] install it [n] no" in keys.printed++ got = asyncio.run(_Keys("n").terminal().tool({"name": "scanner"}))+ assert got["installed"] is False and installed == ["scanner"]+++# -- approvals are separate from questions --------------------------------------------+++def test_with_auto_answer_the_cards_still_reach_the_person() -> None:+ from coworker.engine import TurnEngine++ engine = TurnEngine.__new__(TurnEngine)+ engine.attendance = lambda: "auto"+ engine.cards_reach_person = None+ assert engine._auto_answering() and engine._nobody_answers_cards() # the app's "auto": both+ engine.cards_reach_person = lambda: True+ assert engine._auto_answering() and not engine._nobody_answers_cards()+ engine.attendance = lambda: "attended"+ engine.cards_reach_person = None+ assert not engine._nobody_answers_cards()+++# -- at a real terminal -----------------------------------------------------------------+++def _at_a_terminal(tmp_path: Path, script: list[dict], typed: list[tuple[str, str]], *extra: str):+ """Run with a terminal on standard input and standard error (standard output stays a+ pipe). `typed`: (text to wait for, line to type) in order. Returns (exit code,+ what the terminal showed, standard output, workspace)."""+ import pty++ machine = tmp_path / "machine"+ machine.mkdir(exist_ok=True)+ cmd, ws = _command(tmp_path, script, "--model", "anthropic/claude-sonnet-5", *extra)+ master, slave = pty.openpty()+ proc = subprocess.Popen(cmd, env=_env(machine), stdin=slave, stderr=slave, stdout=subprocess.PIPE)+ os.close(slave)+ shown = ""+ waiting = list(typed)+ deadline = time.time() + 120+ try:+ while time.time() < deadline:+ ready, _, _ = select.select([master], [], [], 0.2)+ if ready:+ try:+ chunk = os.read(master, 4096)+ except OSError: # the run closed its end+ break+ if not chunk:+ break+ shown += chunk.decode("utf-8", errors="replace")+ if waiting and waiting[0][0] in shown and shown.rstrip().endswith(">"):+ os.write(master, (waiting.pop(0)[1] + "\n").encode("utf-8"))+ if proc.poll() is not None and not ready:+ break+ out = proc.stdout.read().decode("utf-8") if proc.stdout else ""+ return proc.wait(timeout=30), shown, out, ws+ finally:+ if proc.poll() is None:+ proc.kill()+ os.close(master)++[email protected](sys.platform == "win32", reason="needs a pseudo-terminal")+def test_at_a_terminal_the_approval_is_asked_and_yes_runs_the_call(tmp_path: Path) -> None:+ code, shown, out, ws = _at_a_terminal(tmp_path, WRITE_THEN_DONE, [("Approval needed: use write_file", "y")])+ assert code == 0, shown+ assert (ws / "hello.txt").read_text(encoding="utf-8") == "hello"+ assert "path: hello.txt" in shown and "no terminal is attached" not in shown+ assert out == "The file is written. Done.\n"++[email protected](sys.platform == "win32", reason="needs a pseudo-terminal")+def test_at_a_terminal_no_refuses_the_call(tmp_path: Path) -> None:+ code, shown, _out, ws = _at_a_terminal(tmp_path, WRITE_THEN_DONE, [("Approval needed: use write_file", "n")])+ assert code == 0, shown+ assert not (ws / "hello.txt").exists()+++QUESTION_THEN_WRITE = [+ {"text": "", "tool_calls": [{"name": "ask_user", "arguments": {"question": "Which colour?", "options": ["red", "blue"]}}]},+ {"text": "", "tool_calls": [{"name": "write_file", "arguments": {"path": "hello.txt", "content": "hello"}}]},+ {"text": "Done."},+]++[email protected](sys.platform == "win32", reason="needs a pseudo-terminal")+def test_at_a_terminal_a_question_is_asked_there(tmp_path: Path) -> None:+ code, shown, _out, ws = _at_a_terminal(+ tmp_path, QUESTION_THEN_WRITE, [("Which colour?", "2")], "--mode", "bypass-approvals",+ )+ assert code == 0, shown+ assert "The coworker asks:" in shown and "2. blue" in shown+ machine = tmp_path / "machine"+ (folder,) = _session_folders(machine, ws)+ messages = json.loads((folder / "messages.json").read_text(encoding="utf-8"))+ assert any(m.get("role") == "tool" and "blue" in str(m.get("content")) for m in messages)+ assert json.loads((folder / "summary.json").read_text(encoding="utf-8"))["args"]["attendance"] == "attended"++[email protected](sys.platform == "win32", reason="needs a pseudo-terminal")+def test_auto_answer_at_a_terminal_answers_the_question_and_still_asks_the_approval(tmp_path: Path) -> None:+ code, shown, _out, ws = _at_a_terminal(+ tmp_path, QUESTION_THEN_WRITE, [("Approval needed: use write_file", "y")], "--auto-answer",+ )+ assert code == 0, shown+ assert "The coworker asks:" not in shown # answered by rule+ assert (ws / "hello.txt").exists() # the approval was the person's, and they said yes+ (folder,) = _session_folders(tmp_path / "machine", ws)+ summary = json.loads((folder / "summary.json").read_text(encoding="utf-8"))+ assert summary["answers"]["questions_answered"] == 1 and summary["answers"]["cards_refused"] == 0