Skip to content
Python

Two switches for unattended work: a dangerous mode and an auto attendance (OPE-196)

Devika Vermabcdaaa8e4823
diff --git a/coworker/cli.py b/coworker/cli.py
index 87cb69e5..a0d06bb0 100644
--- a/coworker/cli.py
+++ b/coworker/cli.py
@@ -105,7 +105,14 @@ def main(argv: Optional[list[str]] = None) -> None:
parser.add_argument(
"--mode",
default=cfg.mode,
- choices=["plan", "interactive", "auto", "bypass-approvals", "auto-approve"],
+ choices=[
+ "plan",
+ "interactive",
+ "auto",
+ "bypass-approvals",
+ "dangerously-bypass-approvals",
+ "auto-approve",
+ ],
help="permission mode",
)
parser.add_argument("--resume", default=None, help="resume a session id")
diff --git a/coworker/engine.py b/coworker/engine.py
index 081b60a0..b330c399 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -28,6 +28,7 @@ from . import provenance
from . import session_facts
from . import toolchain as _toolchain
from . import toolresult
+from . import unattended as _attendance
from .events import Event, EventType
# §8.4 retry guard: the reviewer pauses for the rest of the turn after this many denials
@@ -58,7 +59,7 @@ _REVIEWER_PAUSED_TEXT = (
"Auto-approve is paused for the rest of this turn — the reviewer blocked "
f"{_REVIEWER_TRIP} actions in a row, so approvals now come to you."
)
-from .permissions import Mode, PermissionEngine
+from .permissions import CLEARED_BY_MODE, Mode, PermissionEngine
from .providers import AssistantTurn, ProviderClient, ToolCall
from .providers.errors import friendly_model_error
from .providers.openai_provider import looks_like_unparsed_tool_call
@@ -213,6 +214,12 @@ class TurnEngine:
self.compaction_state: Optional[_compaction.CompactionState] = None
self.compaction_settings: Optional[Callable[[], dict[str, Any]]] = None
self.is_attended: Optional[Callable[[], bool]] = None
+ # Attendance (coworker/unattended.py): who answers when the agent asks. A live
+ # getter returning "attended" / "inbox" / "auto"; None reads as attended. In "auto"
+ # 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
+ self._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
# compaction above, so the constructor footprint stays put. None ⇒ nothing recorded
@@ -399,6 +406,11 @@ class TurnEngine:
message["_activity"] = activity
self.messages.append(message)
self._cancel.clear()
+ if not self._dangerous_warned:
+ if self.permissions.mode is Mode.DANGEROUSLY_BYPASS_APPROVALS:
+ # Once per engine: the name is the warning, and the transcript keeps it.
+ self._append_notice("dangerous_mode", _attendance.DANGEROUS_MODE_WARNING)
+ self._dangerous_warned = True
if self.session_facts is not None:
self.session_facts.begin_turn()
# §8.4 retry guard resets per user turn: two reviewer denials in one turn route
@@ -1203,19 +1215,29 @@ class TurnEngine:
# -- Auto-Approve reviewer (spec Part 8) ----------------------------------------
+ def _auto_answering(self) -> bool:
+ """Attendance is "auto": nobody will answer, so the engine answers by fixed rule."""
+ try:
+ return self.attendance is not None and self.attendance() == _attendance.AUTO
+ except Exception: # noqa: BLE001 - a broken getter must read as attended
+ return False
+
def _reviewer_active(self) -> bool:
"""The reviewer is consulted only when ALL of these hold. Any miss ⇒ today's
- behaviour (the card). Attended is required explicitly: `is_attended` unset counts
- as NOT attended, so automations — which never set it — can never be reviewed
- (§1.5: the mode is attended-only)."""
+ behaviour (the card). Someone must be accountable for the asks it cannot clear:
+ a person attending (`is_attended` unset counts as NOT attended, so automations —
+ which never set it — can never be reviewed; §1.5), or attendance "auto", where
+ every escalation is refused by rule instead of parked."""
from .permissions import Mode
return (
self.reviewer is not None
and self.reviewer_enabled
and self.permissions.mode is Mode.AUTO_APPROVE
- and self.is_attended is not None
- and self.is_attended()
+ and (
+ (self.is_attended is not None and self.is_attended())
+ or self._auto_answering()
+ )
and self._reviewer_denials < _REVIEWER_TRIP
)
@@ -1517,15 +1539,24 @@ class TurnEngine:
if self._downloaded_target(tool_call) is not None and (
decision.needs_user or allowed
):
- allowed = False
- reason = f"this file was downloaded by the agent this session — {provenance_note}"
- decision = replace(
- decision,
- allowed=False,
- reason=reason,
- needs_user=True,
- human_only=True,
- )
+ if self.permissions.mode is Mode.DANGEROUSLY_BYPASS_APPROVALS:
+ # The dangerous mode grants this floor too — recorded like every other
+ # clearance, with the provenance fact the card would have carried.
+ allowed = True
+ reason = f"{CLEARED_BY_MODE}: file the agent downloaded — {provenance_note}"
+ decision = replace(
+ decision, allowed=True, reason=reason, needs_user=False, human_only=False
+ )
+ else:
+ allowed = False
+ reason = f"this file was downloaded by the agent this session — {provenance_note}"
+ decision = replace(
+ decision,
+ allowed=False,
+ reason=reason,
+ needs_user=True,
+ human_only=True,
+ )
if allowed and decision.rule:
# A task-scoped standing rule auto-allowed this call: audit the exact rule
@@ -1540,6 +1571,16 @@ class TurnEngine:
# "full access" is the exact reason string of permissions.py's bypass branch.
if allowed and decision.reason == "full access":
self._approval_origins[tool_call.id] = {"origin": "bypass"}
+ # (d) The dangerous mode crossed a floor a person would otherwise have seen:
+ # annotated AND audited per call, so the record can count exactly what was cleared.
+ if allowed and decision.reason.startswith("cleared by mode"):
+ self._approval_origins[tool_call.id] = {
+ "origin": "bypass",
+ "note": decision.reason,
+ }
+ self._audit(
+ tool_call, stage="auto_allowed", status="allowed", reason=decision.reason
+ )
# OPE-136: a trusted-MCP allow ran cardless on standing config (a user trust
# rule, or the legacy server flag) — audited and chip-annotated like every
@@ -1672,6 +1713,26 @@ class TurnEngine:
self._reviewer_denials = 0 # streak semantics: any non-deny resets
unsure_note = verdict.reason
+ if not allowed and decision.needs_user and self._auto_answering():
+ # 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.)
+ reason = "refused: no one is available to approve this (attendance: auto)"
+ self._approval_origins[tool_call.id] = {
+ "origin": "unattended_auto",
+ "grant": "deny",
+ **({"note": unsure_note} if unsure_note else {}),
+ }
+ self._audit(
+ tool_call,
+ stage="approval_resolved",
+ call_id=tool_call.id,
+ status="denied",
+ approval="auto_refused",
+ reason=reason,
+ )
+ decision = replace(decision, needs_user=False)
+
if not allowed and decision.needs_user:
escalation = (
{"kind": "human_required", "reason": decision.reason} if decision.human_only else
@@ -2266,16 +2327,37 @@ class TurnEngine:
args = tool_call.arguments or {}
name = str(args.get("name", "")).strip()
reason = str(args.get("reason", ""))
+ fallback_guidance = (
+ "Continue without it: use a fallback check if you have one, and say in "
+ "your report which checks were degraded."
+ )
- if self.tool_requester is None or not name:
+ if not name or (self.tool_requester is None and not self._auto_answering()):
result: dict[str, Any] = {
"installed": False,
"error": "tool requests aren't available here",
- "guidance": (
- "Continue without it: use a fallback check if you have one, and say in "
- "your report which checks were degraded."
- ),
+ "guidance": fallback_guidance,
}
+ elif _toolchain.describe(name) is not None and self._auto_answering():
+ # Attendance "auto": nobody will approve the card, and the install is the
+ # verified pinned build (version + digest fixed in the catalog) — run it and
+ # record the outcome. The rule follows the catalog, not a list of names.
+ info = _toolchain.describe(name) or {}
+ self._audit(tool_call, stage="tool_auto_install", reason=reason)
+ try:
+ path = await asyncio.to_thread(_toolchain.install, name)
+ result = {
+ "installed": True,
+ "path": path,
+ "version": info.get("version", ""),
+ "note": "installed by the unattended-auto rule (pinned, checksum-verified)",
+ }
+ except Exception as exc: # noqa: BLE001 - the agent must hear why
+ result = {
+ "installed": False,
+ "error": f"install failed: {exc}",
+ "guidance": fallback_guidance,
+ }
elif _toolchain.describe(name) is None:
# Not in the pinned catalog: no card at all (owner-hit 2026-08-20 — agents
# routed ordinary brew/pip installs through the install card, which could
@@ -2359,8 +2441,26 @@ class TurnEngine:
"""Emit the grant prompt, await the user's out-of-band decision (which the requester also
applies to this session's roots), and return the outcome as the tool result."""
args = tool_call.arguments or {}
- if self.directory_requester is None:
+ if self._auto_answering():
+ # Attendance "auto": there is no picker and no person to choose. The reply
+ # says what the agent can still do, and to stop rather than guess when the
+ # task truly needs the user. No grant, no card.
+ unscoped = self.permissions.mode is Mode.DANGEROUSLY_BYPASS_APPROVALS
result: dict[str, Any] = {
+ "granted": False,
+ "error": (
+ _attendance.AUTO_DIRECTORY_REPLY_UNSCOPED
+ if unscoped
+ else _attendance.AUTO_DIRECTORY_REPLY
+ ),
+ }
+ self._audit(
+ tool_call,
+ stage="directory_auto_refused",
+ reason=str(args.get("reason", "")),
+ )
+ elif self.directory_requester is None:
+ result = {
"granted": False,
"error": "directory requests aren't available here",
}
@@ -2420,7 +2520,7 @@ class TurnEngine:
if isinstance(entry, dict) and str(entry.get("question", "")).strip():
question = str(entry["question"]).strip()
break
- if self.question_asker is None or not question:
+ if not question or (self.question_asker is None and not self._auto_answering()):
result: dict[str, Any] = {
"answer": "",
"error": (
@@ -2429,6 +2529,24 @@ class TurnEngine:
else "asking isn't available here"
),
}
+ elif self._auto_answering():
+ # Attendance "auto": the fixed least-destructive answer stands in for the
+ # person, one copy per grouped question, keyed the way the surfaces key them.
+ grouped = [
+ entry
+ for entry in (args.get("questions") or [])
+ if isinstance(entry, dict) and str(entry.get("question", "")).strip()
+ ]
+ if grouped:
+ result = {
+ "answers": {
+ str(entry.get("header") or entry.get("question")): _attendance.AUTO_QUESTION_ANSWER
+ for entry in grouped
+ }
+ }
+ else:
+ result = {"answer": _attendance.AUTO_QUESTION_ANSWER}
+ self._audit(tool_call, stage="question_auto_answered", reason=question)
else:
# The asker is mode-aware (attended → live inline prompt; unattended → Inbox), so it
# owns surfacing the question. The engine just awaits the answer.
diff --git a/coworker/permissions.py b/coworker/permissions.py
index 14020f5e..3ff9045f 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -209,6 +209,7 @@ MODE_LABELS = {
"interactive": "Ask for approval",
"auto": "Bypass approvals",
"bypass-approvals": "Bypass approvals",
+ "dangerously-bypass-approvals": "Dangerously bypass approvals",
"auto-approve": "Auto-approve",
}
@@ -224,6 +225,16 @@ class Mode(str, Enum):
# NOT "bypass-ALL-approvals": Phase 1's floors (settings files, out-of-root writes,
# `.git/hooks`) still hold in this mode, so "all" would be a false promise.
BYPASS_APPROVALS = "bypass-approvals" # full access (minus the hard floors)
+ # Everything BYPASS_APPROVALS keeps is granted too: the three floors that otherwise
+ # reach a person (running a file the agent downloaded, writing outside the session's
+ # folders, files that run later such as git hooks / CI configs, and authority that
+ # outlives the session) are cleared by the mode and each clearance is recorded. The
+ # name follows the convention other harnesses use for the same switch, because the
+ # name is the warning: only for a disposable machine or container. Never offered in
+ # the desktop picker; the server accepts it only when started with the flag. The
+ # self-protection floor (OpenWorker's own settings files) is a refusal, not an
+ # approval, and stays.
+ DANGEROUSLY_BYPASS_APPROVALS = "dangerously-bypass-approvals"
# Interactive, but an LLM reviewer judges each would-be approval card first: clear
# allows run without a prompt, everything else still reaches the human. The reviewer
# can only turn "ask" into "allow", never "blocked" into "allow" (spec §1.2). With no
@@ -242,6 +253,17 @@ class Mode(str, Enum):
# Modes whose enforcement is read-only. DISCUSS and PLAN share the same gate; they differ
# only in intent — PLAN additionally drives the agent toward a propose_plan approval.
READ_ONLY_MODES = frozenset({Mode.DISCUSS, Mode.PLAN})
+# Modes that grant every ordinary approval without a card. Only the second also clears
+# the floors below.
+BYPASS_MODES = frozenset({Mode.BYPASS_APPROVALS, Mode.DANGEROUSLY_BYPASS_APPROVALS})
+
+# Reason prefix on every decision the dangerous mode granted in place of a person. The
+# engine audits these individually ("recorded, never invisible") and the tool card says so.
+CLEARED_BY_MODE = "cleared by mode"
+
+
+def _cleared(floor: str) -> "Decision":
+ return Decision(True, f"{CLEARED_BY_MODE}: {floor}")
@dataclass
@@ -254,6 +276,8 @@ class Decision:
# sees them — protected in-project files that execute later (git hooks, CI configs:
# "never WITHOUT a human — no auto-approve path may clear them") and writes whose path
# could not be located for scoping (an allow would bypass root scoping unverified).
+ # The one exception is DANGEROUSLY_BYPASS_APPROVALS, which never produces these asks:
+ # it grants them up front (see `_cleared`) and the engine records each grant.
human_only: bool = False
# Set when a task-scoped standing rule allowed the call ("tool → target") so the
# engine can audit the exact rule and the tool card can say so (§25).
@@ -380,6 +404,12 @@ class PermissionEngine:
False, f"{self.mode.value} mode is read-only", needs_user=False
)
+ # The dangerous mode clears every floor below that would otherwise reach a person.
+ # Each clearance keeps its own reason so the record says which floor was crossed.
+ # (The self-protection refusal above and the read-only modes are not approvals and
+ # are untouched.)
+ dangerous = self.mode is Mode.DANGEROUSLY_BYPASS_APPROVALS
+
# Path scoping for writes (all modes): every path the write touches must land in a
# writable root. A write whose path can't be located is not scoped-able, so it fails
# closed to approval rather than slipping through auto/custom unscoped.
@@ -387,6 +417,8 @@ class PermissionEngine:
if is_write:
paths, located = write_paths(tool_name, arguments)
if not located:
+ if dangerous:
+ return _cleared("write path could not be scoped")
return Decision(
False,
"cannot determine the write path to scope",
@@ -395,6 +427,11 @@ class PermissionEngine:
)
for path in paths:
if not self._under_writable_root(path):
+ if dangerous:
+ # The permission floor is cleared; the file tools still resolve
+ # paths against the session's roots by construction, so this
+ # mostly matters for tools that write wherever they are pointed.
+ return _cleared(f"write outside the session's directories: {path}")
return Decision(
False, f"path is not in a writable directory: {path}"
)
@@ -408,6 +445,8 @@ class PermissionEngine:
# purpose: these tools are consequential today, but a metadata slip must not be
# able to switch the floor off. Read-only modes still hard-deny above this.
if tool_name in PERSISTENT_AUTHORITY_TOOLS:
+ if dangerous:
+ return _cleared("authority that outlives the session")
return Decision(
False,
"this outlives the session — approval required",
@@ -422,6 +461,8 @@ class PermissionEngine:
# A protected in-project target (git hooks, CI config) skips every auto-approve path
# below — including auto mode and the session/config allowlists — and asks.
if needs_human_for_protected:
+ if dangerous:
+ return _cleared("file that runs automatically later")
return Decision(
False,
"this file runs automatically later — approval required",
@@ -430,7 +471,7 @@ class PermissionEngine:
)
# Full access.
- if self.mode is Mode.BYPASS_APPROVALS:
+ if self.mode in BYPASS_MODES:
return Decision(True, "full access")
# interactive / custom / auto-approve: allowlists.
diff --git a/coworker/personas/manifest.py b/coworker/personas/manifest.py
index 61dc02be..69c93879 100644
--- a/coworker/personas/manifest.py
+++ b/coworker/personas/manifest.py
@@ -24,7 +24,16 @@ _ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
VALID_FAMILIES = {"code", "knowledge"} # legacy key, shimmed in parse()
VALID_TEAM = {"lead", "worker"}
# "auto" kept as the legacy spelling of "bypass-approvals" (Mode._missing_).
-VALID_MODES = {"discuss", "plan", "interactive", "custom", "auto", "bypass-approvals", "auto-approve"}
+VALID_MODES = {
+ "discuss",
+ "plan",
+ "interactive",
+ "custom",
+ "auto",
+ "bypass-approvals",
+ "dangerously-bypass-approvals",
+ "auto-approve",
+}
VALID_REC_KINDS = {"connector", "mcp"}
VALID_REC_TIERS = {"core", "optional"}
VALID_GROUPS = {"general", "engineering", "security"}
diff --git a/coworker/server/app.py b/coworker/server/app.py
index 872073ad..7afe6662 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -429,7 +429,10 @@ def create_app(manager: SessionManager) -> FastAPI:
@app.get("/v1/sessions/{session_id}/unattended")
def get_unattended(session_id: str) -> dict[str, Any]:
- return {"unattended": manager.unattended.is_unattended(session_id)}
+ return {
+ "unattended": manager.unattended.is_unattended(session_id),
+ "attendance": manager.unattended.attendance(session_id),
+ }
@app.get("/v1/sessions/{session_id}/reviewer-stats")
def get_reviewer_stats(session_id: str) -> dict[str, Any]:
@@ -440,8 +443,10 @@ def create_app(manager: SessionManager) -> FastAPI:
@app.post("/v1/sessions/{session_id}/unattended")
def set_unattended(session_id: str, body: dict) -> dict[str, Any]:
# The GUI gates the on-transition behind a one-tap confirm; the manager records the
- # transition either way, so the change is answerable from the audit store.
- return manager.set_unattended(session_id, bool(body.get("unattended")))
+ # transition either way, so the change is answerable from the audit store. Newer
+ # clients send `attendance` ("attended" / "inbox" / "auto"); older ones the boolean.
+ value = body["attendance"] if "attendance" in body else bool(body.get("unattended"))
+ return manager.set_unattended(session_id, value)
@app.get("/v1/sessions/{session_id}/skills")
def session_skills(session_id: str, workspace: str = "") -> dict[str, Any]:
@@ -2922,6 +2927,9 @@ def create_app(manager: SessionManager) -> FastAPI:
# configuration, or a worker under an auto-approve lead) is reviewed even when
# nobody attends it.
engine.is_attended = lambda: _visibility() == VIS_INLINE or manager.reviewer_opted(session_id)
+ # Attendance "auto" (coworker/unattended.py): the engine answers by rule instead of
+ # routing to the Inbox. Read live, so the toggle applies mid-session.
+ engine.attendance = lambda: manager.unattended.attendance(session_id)
await ws.send_json(
{
"type": "ready",
@@ -3135,6 +3143,16 @@ def create_app(manager: SessionManager) -> FastAPI:
except (TypeError, ValueError):
pass
else:
+ if (
+ new_mode is Mode.DANGEROUSLY_BYPASS_APPROVALS
+ and not manager.allow_dangerous_mode
+ ):
+ await reject_input(
+ "dangerously-bypass-approvals is not available here: "
+ "start the server with --allow-dangerous-mode, and only "
+ "on a disposable machine or container."
+ )
+ continue
previous = engine.permissions.mode
engine.permissions.mode = new_mode
if previous is not new_mode:
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index 2026c0c4..a331e158 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -307,6 +307,13 @@ class SessionManager:
self.model = model
self.mode = mode
self.provider = provider
+ # The dangerous mode is never offered by the desktop app: a session may run in it
+ # only when this server was started with it enabled (`openworker-server
+ # --allow-dangerous-mode`, or the environment switch the CLI's one-shot `run`
+ # sets). Stored sessions in that mode fall back to plain bypass otherwise.
+ self.allow_dangerous_mode = (
+ os.environ.get("COWORKER_ALLOW_DANGEROUS_MODE", "").strip() == "1"
+ )
if data_dir is not None:
base = Path(data_dir).expanduser()
@@ -809,6 +816,7 @@ class SessionManager:
if record:
ws = record.workspace or None
model, mode, messages = record.model, Mode(record.mode), record.messages
+ mode = self.permitted_mode(mode)
else:
ws = self.resolve_workspace(workspace)
# A coworker with a `models:` list starts on the first entry this machine
@@ -1135,6 +1143,14 @@ class SessionManager:
)
return granted
+ def permitted_mode(self, mode: Mode) -> Mode:
+ """The mode a session may actually run in on this server: the dangerous mode
+ needs the start-up switch; without it the session runs as plain bypass (the same
+ checks minus the cleared floors) rather than failing to open."""
+ if mode is Mode.DANGEROUSLY_BYPASS_APPROVALS and not self.allow_dangerous_mode:
+ return Mode.BYPASS_APPROVALS
+ return mode
+
@staticmethod
def _mode_value(raw: str) -> Optional[Mode]:
"""A stored mode string → Mode, accepting the legacy "auto" for bypass."""
@@ -5970,11 +5986,21 @@ class SessionManager:
"auto-approve": 3,
"auto": 4,
"bypass-approvals": 4,
+ "dangerously-bypass-approvals": 5,
}
+ # Attendance: attended < inbox (prompts leave the screen) < auto (the engine
+ # answers). The legacy boolean maps onto the first two.
+ attendance_order = {"attended": 0, "inbox": 1, "auto": 2}
+
+ def _attendance_rank(value: Any) -> int:
+ from ..unattended import normalize_attendance
+
+ return attendance_order.get(normalize_attendance(value), 0)
+
raised = (
order.get(str(after), 0) > order.get(str(before), 0)
if kind == "mode"
- else bool(after) and not bool(before)
+ else _attendance_rank(after) > _attendance_rank(before)
)
try:
self.audit_store.append(
@@ -5990,16 +6016,22 @@ class SessionManager:
except Exception:
pass
- def set_unattended(self, session_id: str, on: bool) -> dict[str, Any]:
- """Flip the attended/unattended toggle, with an audit row. Note this changes only
- WHERE the human is reached, never the autonomy ceiling (that's the mode) — but it is
- still worth recording, since an unattended session routes prompts away from the
- screen the user is looking at."""
- before = self.unattended.is_unattended(session_id)
- self.unattended.set(session_id, on)
- if before != on:
- self.audit_autonomy_change(session_id, "unattended", before, on)
- return {"ok": True, "session_id": session_id, "unattended": on}
+ def set_unattended(self, session_id: str, value: Any) -> dict[str, Any]:
+ """Set the session's attendance (attended / inbox / auto, or the legacy boolean),
+ with an audit row. Note this changes only WHO ANSWERS when the agent asks, never
+ the autonomy ceiling (that's the mode) — but it is still worth recording, since an
+ unattended session routes prompts away from the screen the user is looking at, and
+ `auto` answers them by rule."""
+ before = self.unattended.attendance(session_id)
+ after = self.unattended.set(session_id, value)
+ if before != after:
+ self.audit_autonomy_change(session_id, "unattended", before, after)
+ return {
+ "ok": True,
+ "session_id": session_id,
+ "unattended": after != "attended",
+ "attendance": after,
+ }
def _audit_grant_refused(self, session_id: str, request, resolution: str) -> None:
try:
diff --git a/coworker/server/run.py b/coworker/server/run.py
index e10bcc04..5738a886 100644
--- a/coworker/server/run.py
+++ b/coworker/server/run.py
@@ -169,11 +169,31 @@ def main(argv=None) -> None:
parser.add_argument(
"--mode",
default=cfg.mode,
- choices=["discuss", "plan", "interactive", "auto", "bypass-approvals", "auto-approve"],
+ choices=[
+ "discuss",
+ "plan",
+ "interactive",
+ "auto",
+ "bypass-approvals",
+ "dangerously-bypass-approvals",
+ "auto-approve",
+ ],
+ )
+ parser.add_argument(
+ "--allow-dangerous-mode",
+ action="store_true",
+ help=(
+ "let sessions run in dangerously-bypass-approvals (all approvals granted, "
+ "safety checks off); only on a disposable machine or container"
+ ),
)
parser.add_argument("--host", default=cfg.host)
parser.add_argument("--port", type=int, default=cfg.port)
args = parser.parse_args(argv)
+ if args.allow_dangerous_mode:
+ os.environ["COWORKER_ALLOW_DANGEROUS_MODE"] = "1"
+ elif args.mode == "dangerously-bypass-approvals":
+ parser.error("--mode dangerously-bypass-approvals requires --allow-dangerous-mode")
# Publish the ACTUAL bound port so loopback URLs (the managed-OAuth callback)
# target this process, not config.port. The desktop shell runs the sidecar on
diff --git a/coworker/tui/app.py b/coworker/tui/app.py
index 8b1478ff..4f7d069c 100644
--- a/coworker/tui/app.py
+++ b/coworker/tui/app.py
@@ -216,7 +216,14 @@ class CoworkerApp(App):
self._write(
"commands: /mode plan|interactive|auto · /model <id> · /clear · /quit"
)
- elif name == "/mode" and arg in {"plan", "interactive", "auto", "bypass-approvals", "auto-approve"}:
+ elif name == "/mode" and arg in {
+ "plan",
+ "interactive",
+ "auto",
+ "bypass-approvals",
+ "dangerously-bypass-approvals",
+ "auto-approve",
+ }:
self.mode = Mode(arg)
if self.engine:
self.engine.permissions.mode = self.mode
diff --git a/coworker/unattended.py b/coworker/unattended.py
index 6b60873f..b5259aad 100644
--- a/coworker/unattended.py
+++ b/coworker/unattended.py
@@ -1,9 +1,19 @@
-"""Unattended mode — a per-session toggle for *where the human is reached*.
+"""Attendance — a per-session setting for *who answers when the agent asks*.
-It does **not** change the autonomy ceiling (the permission mode does). When a session is
-unattended, anything that would prompt inline (approval / question) is routed to the Inbox and
-the agent suspends until answered; the composer is disabled. Turning it on is a one-tap confirm
-(enforced at the API/GUI layer). This registry just persists the per-session flag.
+It does **not** change the autonomy ceiling (the permission mode does). Three values:
+
+* ``attended`` — a person is at the screen: questions and approval cards appear inline.
+* ``inbox`` — nobody is watching right now: anything that would prompt inline is parked in
+ the Inbox and the agent suspends until answered; the composer is disabled.
+* ``auto`` — nobody will come: the engine answers by fixed rule and records each answer.
+ Questions get a least-destructive default, folder requests are declined with guidance,
+ pinned tool installs run the verified installer, and an approval card that only a person
+ could clear is refused (unless the permission mode clears it). Never a hang.
+
+The toggle was a boolean (attended / unattended-to-Inbox) before the third value existed;
+stored ``true`` still reads as ``inbox`` and ``false`` as ``attended``. Turning it on is a
+one-tap confirm (enforced at the API/GUI layer). This registry just persists the per-session
+value; the fixed replies live here too so every surface says the same thing.
"""
from __future__ import annotations
@@ -13,31 +23,81 @@ import threading
from pathlib import Path
from typing import Optional
+ATTENDED = "attended"
+INBOX = "inbox"
+AUTO = "auto"
+ATTENDANCE_VALUES = (ATTENDED, INBOX, AUTO)
+
+# What the engine says on the person's behalf in `auto`. Fixed text, never model-authored.
+AUTO_QUESTION_ANSWER = (
+ "No one is available. Choose the least destructive option that still satisfies the "
+ "task as written."
+)
+AUTO_DIRECTORY_REPLY = (
+ "No user is available to choose a folder. Work inside the current workspace. If the "
+ "task cannot continue without information only the user has, stop and say what is "
+ "missing so it can be restarted."
+)
+# In dangerously-bypass-approvals the out-of-root floor is cleared, so the shell reaches
+# any path; the file tools stay scoped to the session's folders by construction.
+AUTO_DIRECTORY_REPLY_UNSCOPED = (
+ "No user is available to choose a folder. Outside the workspace, use your shell tools "
+ "(they can reach any path); the file tools stay inside the workspace. If the task "
+ "cannot continue without information only the user has, stop and say what is missing "
+ "so it can be restarted."
+)
+# Printed once when a session starts in dangerously-bypass-approvals.
+DANGEROUS_MODE_WARNING = "Dangerously bypass approvals is on. Nothing will stop for you."
+
+
+def normalize_attendance(value: object) -> str:
+ """Accept the three names or the legacy boolean; anything else reads as attended."""
+ if isinstance(value, bool):
+ return INBOX if value else ATTENDED
+ text = str(value or "").strip().lower()
+ if text in ("true", "on", "unattended"):
+ return INBOX
+ return text if text in ATTENDANCE_VALUES else ATTENDED
+
class UnattendedRegistry:
def __init__(self, path: Optional[str | Path] = None) -> None:
self.path = Path(path) if path else None
self._lock = threading.Lock()
- self._flags: dict[str, bool] = {}
+ self._values: dict[str, str] = {}
if self.path and self.path.is_file():
- self._flags = dict(json.loads(self.path.read_text(encoding="utf-8")))
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
+ for sid, value in dict(raw).items():
+ normalized = normalize_attendance(value)
+ if normalized != ATTENDED:
+ self._values[str(sid)] = normalized
def _save(self) -> None:
if not self.path:
return
self.path.parent.mkdir(parents=True, exist_ok=True)
- self.path.write_text(json.dumps(self._flags, indent=2), encoding="utf-8")
+ self.path.write_text(json.dumps(self._values, indent=2), encoding="utf-8")
+
+ def attendance(self, session_id: str) -> str:
+ return self._values.get(session_id, ATTENDED)
def is_unattended(self, session_id: str) -> bool:
- return bool(self._flags.get(session_id, False))
+ """True for both unattended values — the Inbox route and the auto route."""
+ return self.attendance(session_id) != ATTENDED
+
+ def is_auto(self, session_id: str) -> bool:
+ return self.attendance(session_id) == AUTO
- def set(self, session_id: str, unattended: bool) -> None:
+ def set(self, session_id: str, value: object) -> str:
+ """Set the session's attendance (a name, or the legacy boolean) and return it."""
+ normalized = normalize_attendance(value)
with self._lock:
- if unattended:
- self._flags[session_id] = True
+ if normalized == ATTENDED:
+ self._values.pop(session_id, None)
else:
- self._flags.pop(session_id, None)
+ self._values[session_id] = normalized
self._save()
+ return normalized
def sessions(self) -> list[str]:
- return [sid for sid, on in self._flags.items() if on]
+ return list(self._values)
diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsx
index 997dd5ce..615b7f7d 100644
--- a/surfaces/gui/src/App.tsx
+++ b/surfaces/gui/src/App.tsx
@@ -19,7 +19,7 @@ import {
getSettings,
getPersonas,
getInbox,
- getUnattended,
+ getAttendance,
PERSONAS_CHANGED,
resolveInboxItem,
routeInboxItemLike,
@@ -37,6 +37,7 @@ import {
renameSession,
runAutomation,
setSessionFlags,
+ setAttendance,
setUnattended,
Session,
type InboxItem,
@@ -48,6 +49,7 @@ import {
type SurfaceVisibility,
type WorkspaceCommandTrust,
type TeamMemberDecision,
+ type Attendance,
API_UNAUTHORIZED,
} from "./api";
import type {
@@ -537,11 +539,19 @@ export function App() {
// so we suppress the inline live cards (the Inbox / answer-in-context path shows them instead).
// A ref too, because the WS event handler closes over stale state.
const [unattended, setUnattendedState] = useState(false);
+ // The three-way attendance value behind the boolean: "inbox" and "auto" are both
+ // unattended; only "auto" makes the engine answer on the user's behalf.
+ const [attendance, setAttendanceState] = useState<Attendance>("attended");
const unattendedRef = useRef(false);
- const markUnattended = useCallback((on: boolean) => {
- unattendedRef.current = on;
- setUnattendedState(on);
+ const markAttendance = useCallback((value: Attendance) => {
+ unattendedRef.current = value !== "attended";
+ setUnattendedState(value !== "attended");
+ setAttendanceState(value);
}, []);
+ const markUnattended = useCallback(
+ (on: boolean) => markAttendance(on ? "inbox" : "attended"),
+ [markAttendance],
+ );
// The Mode menu's "Send approvals to Inbox" toggle (§22 — the old InboxControl, folded in).
const toggleUnattended = async (on: boolean) => {
await setUnattended(sessionId, on);
@@ -549,6 +559,12 @@ export function App() {
// First Unattended enable = Inbox machinery engaged → the account row's chip unlocks (§26).
if (on) announceInboxUnlock();
};
+ // The Mode menu's "Answer for me while I'm away" toggle: attendance "auto".
+ const toggleAutoAnswer = async (on: boolean) => {
+ const value: Attendance = on ? "auto" : "attended";
+ await setAttendance(sessionId, value);
+ markAttendance(value);
+ };
const resolveSessionInbox = async (id: string, resolution: string) => {
await resolveInboxItem(id, resolution);
getInbox(sessionId, "pending").then(inbox => setSessionInbox(pendingInbox(inbox))).catch(() => {});
@@ -1327,14 +1343,14 @@ export function App() {
setSessionInbox(pendingInbox(inbox));
setItems(items => reconcileResolvedGates(items, inbox));
}).catch(() => {});
- getUnattended(sessionId).then(value => {
- if (!canceled && current === request) markUnattended(value);
+ getAttendance(sessionId).then(value => {
+ if (!canceled && current === request) markAttendance(value);
}).catch(() => {});
};
load();
const t = setInterval(load, 4000);
return () => { canceled = true; clearInterval(t); };
- }, [surface, sessionId, browserRefreshKey, markUnattended, pendingInbox, gateScope]);
+ }, [surface, sessionId, browserRefreshKey, markAttendance, pendingInbox, gateScope]);
const send = (text: string, attachments?: Attachment[], skill?: string) => {
// UX-029: folder enforcement AT SEND. A code-family session with no folder has no
@@ -2435,6 +2451,8 @@ export function App() {
workspace={workspace || ""}
unattended={unattended}
onUnattendedChange={agent !== "chat" ? toggleUnattended : undefined}
+ attendance={attendance}
+ onAutoAnswerChange={agent !== "chat" ? toggleAutoAnswer : undefined}
prefill={composerPrefill}
resetKey={sessionId}
usage={usage}
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index cc276b7f..9308a1ac 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -2043,6 +2043,11 @@ export async function unsubscribeChannel(
return res.json();
}
+// Who answers when the agent asks (server: coworker/unattended.py). "attended" = inline,
+// "inbox" = parked in the Inbox until someone returns, "auto" = the engine answers by
+// fixed rule and refuses anything only a person could approve.
+export type Attendance = "attended" | "inbox" | "auto";
+
export async function getUnattended(sessionId: string): Promise<boolean> {
const res = await fetch(
`${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/unattended`,
@@ -2050,6 +2055,31 @@ export async function getUnattended(sessionId: string): Promise<boolean> {
return (await res.json()).unattended;
}
+export async function getAttendance(sessionId: string): Promise<Attendance> {
+ const res = await fetch(
+ `${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/unattended`,
+ );
+ const body = await res.json();
+ const value = body.attendance;
+ if (value === "inbox" || value === "auto") return value;
+ return body.unattended ? "inbox" : "attended";
+}
+
+export async function setAttendance(
+ sessionId: string,
+ attendance: Attendance,
+): Promise<{ ok: boolean; unattended: boolean; attendance: Attendance }> {
+ const res = await fetch(
+ `${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/unattended`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ attendance }),
+ },
+ );
+ return res.json();
+}
+
export async function setUnattended(
sessionId: string,
unattended: boolean,
diff --git a/surfaces/gui/src/components/Composer.tsx b/surfaces/gui/src/components/Composer.tsx
index 325e7160..75b1d0e2 100644
--- a/surfaces/gui/src/components/Composer.tsx
+++ b/surfaces/gui/src/components/Composer.tsx
@@ -45,17 +45,24 @@ const PERMISSION_OPTIONS: ModeOption[] = [
gated: true,
},
{
- value: "auto",
+ // The wire value is the server's real name; "auto" (the legacy spelling saved by
+ // older sessions and configs) is folded onto it by `canonicalMode`.
+ value: "bypass-approvals",
label: "composer.mode.auto",
description: "composer.mode.auto_desc",
caution: true,
},
];
+/** The server's name for a mode value: the legacy "auto" reads as "bypass-approvals". */
+export function canonicalMode(value: string): string {
+ return value === "auto" ? "bypass-approvals" : value;
+}
+
/** The picker's label for a mode value ("auto-approve" -> "Auto-approve"). Exported so the
* transcript's mode markers read the same names the user just chose from. */
export function modeLabel(value: string): string {
- const option = PERMISSION_OPTIONS.find((o) => o.value === value);
+ const option = PERMISSION_OPTIONS.find((o) => o.value === canonicalMode(value));
return option ? getI18n().t(option.label) : value;
}
@@ -122,6 +129,10 @@ interface Props {
// when" is one mental model. Absent handler = no toggle (e.g. Chat).
unattended?: boolean;
onUnattendedChange?: (on: boolean) => void;
+ // Attendance "auto" (the third position): the engine answers questions and requests
+ // by fixed rule while nobody is there. Absent handler = no toggle.
+ attendance?: "attended" | "inbox" | "auto";
+ onAutoAnswerChange?: (on: boolean) => void;
// The pending-approval card rendered above the input (plan / work-items / team / tool /
// folder requests). Attended sessions only — Unattended parks the prompt in the Inbox.
approvalSlot?: ReactNode;
@@ -750,6 +761,8 @@ export function Composer(props: Props) {
onModeChange={props.onModeChange}
unattended={props.unattended}
onUnattendedChange={props.onUnattendedChange}
+ attendance={props.attendance}
+ onAutoAnswerChange={props.onAutoAnswerChange}
/>
) : null}
@@ -905,14 +918,23 @@ function ModeMenu({
onModeChange,
unattended,
onUnattendedChange,
+ attendance,
+ onAutoAnswerChange,
reviewerPaused,
}: {
mode: string;
onModeChange: (mode: string) => void;
unattended?: boolean;
onUnattendedChange?: (on: boolean) => void;
+ attendance?: "attended" | "inbox" | "auto";
+ onAutoAnswerChange?: (on: boolean) => void;
reviewerPaused?: boolean;
}) {
+ // A session saved under the legacy "auto" spelling is the same mode as the picker's
+ // "bypass-approvals" entry: compare on the canonical value so its tick shows.
+ const canonical = canonicalMode(mode);
+ const inboxOn = attendance ? attendance === "inbox" : !!unattended;
+ const autoOn = attendance === "auto";
const { t } = useTranslation();
const [open, setOpen] = useState(false);
// The Auto-Approve entry is gated on the server flag. Fetch once on first open; a session
@@ -926,9 +948,9 @@ function ModeMenu({
.catch(() => {});
}, [open]);
const options = PERMISSION_OPTIONS.filter(
- (o) => !o.gated || autoApproveEnabled || o.value === mode,
+ (o) => !o.gated || autoApproveEnabled || o.value === canonical,
);
- const current = PERMISSION_OPTIONS.find((o) => o.value === mode);
+ const current = PERMISSION_OPTIONS.find((o) => o.value === canonical);
return (
<div className="relative">
{/* Borderless, and it names the CHOSEN mode (owner ask 2026-07-11, competitor composer
@@ -972,14 +994,14 @@ function ModeMenu({
<span
className={
"flex items-center text-ui " +
- (o.value === mode ? "font-medium text-accent" : "text-ink")
+ (o.value === canonical ? "font-medium text-accent" : "text-ink")
}
>
{o.caution && (
<Icon name="warning" size={13} className="mr-1.5 shrink-0 text-warnInk" />
)}
{t(o.label)}
- {o.value === mode && <span className="ml-1.5">✓</span>}
+ {o.value === canonical && <span className="ml-1.5">✓</span>}
</span>
<span className="text-label text-faint leading-snug">{t(o.description ?? "")}</span>
</button>
@@ -995,13 +1017,28 @@ function ModeMenu({
</span>
</span>
<Toggle
- checked={!!unattended}
+ checked={inboxOn}
onChange={onUnattendedChange}
title={t("composer.send_approvals_to_inbox")}
/>
</div>
</>
)}
+ {onAutoAnswerChange && (
+ <div className="flex items-center gap-2 px-2.5 py-1.5" data-testid="auto-answer-row">
+ <span className="flex-1 min-w-0">
+ <span className="block text-ui text-ink">{t("composer.answer_for_me")}</span>
+ <span className="block text-label text-faint leading-snug">
+ {t("composer.answer_for_me_help")}
+ </span>
+ </span>
+ <Toggle
+ checked={autoOn}
+ onChange={onAutoAnswerChange}
+ title={t("composer.answer_for_me")}
+ />
+ </div>
+ )}
</div>
</>
)}
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index ed2c5653..d3bf1bb3 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -149,7 +149,7 @@
"interactive": "Ask for approval",
"interactive_desc": "Ask before edits and commands",
"auto": "Bypass approvals",
- "auto_desc": "Run everything without asking — approvals off",
+ "auto_desc": "No reviewer, fewer prompts, basic safety checks kept",
"auto_approve": "Auto-approve",
"auto_approve_desc": "Let your session model classify actions and handle approvals, prompting you for anything it's unsure about"
},
@@ -165,6 +165,8 @@
"err_mic_start": "Could not start the microphone.",
"starting_mic": "Starting microphone…",
"approvals_to_inbox_help": "When a run is unattended, approval asks go to the Inbox.",
+ "answer_for_me": "Answer for me while I'm away",
+ "answer_for_me_help": "Questions get a safe default answer and requests are answered by rule; anything only you could approve is refused.",
"listening_sr": "Listening, {{time}}",
"pdf_could_not_read": "Couldn't read that PDF.",
"pdf_too_big": "{{name}} skipped — {{mb}} MB is over your {{limit}} MB limit (Settings → Token savings)",
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 0a967356..20529c31 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -147,7 +147,7 @@
"interactive": "需审批",
"interactive_desc": "编辑和执行命令前先询问",
"auto": "绕过审批",
- "auto_desc": "无需询问,全部执行 —— 审批已关闭",
+ "auto_desc": "不用审查器,减少询问,保留基本安全检查",
"auto_approve": "自动审批",
"auto_approve_desc": "由会话模型对操作分类并处理审批,拿不准的仍会询问你"
},
@@ -163,6 +163,8 @@
"err_mic_start": "无法启动麦克风。",
"starting_mic": "正在启动麦克风…",
"approvals_to_inbox_help": "无人值守运行时,审批请求会进入收件箱。",
+ "answer_for_me": "无人时替我作答",
+ "answer_for_me_help": "问题使用安全的默认回答,请求按规则处理;只有你能批准的事项会被拒绝。",
"listening_sr": "正在聆听,{{time}}",
"pdf_could_not_read": "无法读取该 PDF。",
"pdf_too_big": "已跳过 {{name}} —— {{mb}} MB 超过 {{limit}} MB 上限(设置 → Token 节省)",
diff --git a/tests/test_attendance_auto.py b/tests/test_attendance_auto.py
new file mode 100644
index 00000000..34d8e9e3
--- /dev/null
+++ b/tests/test_attendance_auto.py
@@ -0,0 +1,297 @@
+"""Attendance "auto" (OPE-196): nobody will answer, so the engine answers by fixed rule
+and records every answer — questions, folder requests, pinned installs, and the approval
+cards only a person could clear. Never a hang.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from dataclasses import dataclass
+
+from coworker import reviewer as reviewer_mod
+from coworker import unattended as att
+from coworker.engine import ApprovalOutcome, TurnEngine
+from coworker.events import EventType
+from coworker.permissions import Mode, PermissionEngine
+from coworker.providers import AssistantTurn, ModelCapabilities, ProviderClient, ToolCall
+from coworker.tools import ToolRegistry
+from coworker.unattended import UnattendedRegistry
+
+
+# -- the registry --------------------------------------------------------------------
+
+
+def test_registry_has_three_values_and_reads_the_old_boolean_file(tmp_path):
+ path = tmp_path / "unattended.json"
+ path.write_text(json.dumps({"old-on": True, "old-off": False}), encoding="utf-8")
+ reg = UnattendedRegistry(path)
+ assert reg.attendance("old-on") == att.INBOX and reg.is_unattended("old-on")
+ assert reg.attendance("old-off") == att.ATTENDED and not reg.is_unattended("old-off")
+ assert reg.attendance("never-set") == att.ATTENDED
+
+ assert reg.set("s1", "auto") == att.AUTO
+ assert reg.is_auto("s1") and reg.is_unattended("s1")
+ assert reg.set("s2", True) == att.INBOX # the legacy boolean still works
+ assert reg.set("s3", "nonsense") == att.ATTENDED
+ assert sorted(reg.sessions()) == ["old-on", "s1", "s2"]
+ # Persisted as names, read back the same.
+ again = UnattendedRegistry(path)
+ assert again.attendance("s1") == att.AUTO and again.attendance("s2") == att.INBOX
+
+
+# -- engine helpers ------------------------------------------------------------------
+
+
+@dataclass
+class _Meta:
+ category: str = ""
+ risk_level: str = "high"
+ requires_approval: bool = False
+
+
+class _Scripted(ProviderClient):
+ def __init__(self, turns):
+ self._turns = list(turns)
+
+ def complete(self, *, model, messages, tools=None, **settings):
+ return self._turns.pop(0)
+
+ def capabilities(self, model):
+ return ModelCapabilities()
+
+
+def _tool_turn(name, args, call_id="c1"):
+ return AssistantTurn(
+ tool_calls=[ToolCall(id=call_id, name=name, arguments=args)],
+ finish_reason="tool_calls",
+ )
+
+
+def _text(text="done"):
+ return AssistantTurn(text=text, finish_reason="stop")
+
+
+def _engine(tmp_path, turns, *, mode=Mode.INTERACTIVE, attendance="auto", **kw):
+ def run_shell(command: str) -> str:
+ """Run a command.
+
+ Args:
+ command: the command line
+ """
+ return f"ran: {command}"
+
+ registry = ToolRegistry()
+ registry.register(run_shell, metadata=_Meta())
+ rows: list[dict] = []
+ cards: list[str] = []
+
+ async def approver(request):
+ cards.append(request.tool_name)
+ return ApprovalOutcome.ONCE
+
+ engine = TurnEngine(
+ provider=_Scripted(turns),
+ registry=registry,
+ permissions=PermissionEngine(workspace_root=tmp_path, mode=mode),
+ model="test-model",
+ approver=approver,
+ audit_sink=rows.append,
+ **kw,
+ )
+ if attendance is not None:
+ engine.attendance = lambda: attendance
+ return engine, rows, cards
+
+
+def _run(engine, text="go"):
+ async def _go():
+ return [ev async for ev in engine.run(text)]
+
+ return asyncio.run(_go())
+
+
+def _tool_result(engine):
+ msg = [m for m in engine.messages if m.get("role") == "tool"][-1]
+ return json.loads(msg["content"])
+
+
+# -- questions -----------------------------------------------------------------------
+
+
+def test_a_question_gets_the_least_destructive_default_and_is_recorded(tmp_path):
+ engine, rows, _ = _engine(
+ tmp_path, [_tool_turn("ask_user", {"question": "Rewrite git history?"}), _text()]
+ )
+ events = _run(engine)
+ assert _tool_result(engine) == {"answer": att.AUTO_QUESTION_ANSWER}
+ assert any(r.get("stage") == "question_auto_answered" for r in rows)
+ finished = [e for e in events if e.type is EventType.TOOL_FINISHED]
+ assert finished[0].data["status"] == "ok"
+
+
+def test_a_grouped_question_gets_one_answer_per_entry(tmp_path):
+ args = {
+ "questions": [
+ {"header": "History", "question": "Rewrite it?"},
+ {"question": "Which branch?"},
+ ]
+ }
+ engine, _, _ = _engine(tmp_path, [_tool_turn("ask_user", args), _text()])
+ _run(engine)
+ assert _tool_result(engine) == {
+ "answers": {
+ "History": att.AUTO_QUESTION_ANSWER,
+ "Which branch?": att.AUTO_QUESTION_ANSWER,
+ }
+ }
+
+
+def test_without_auto_a_question_still_goes_to_the_surface_or_is_unavailable(tmp_path):
+ engine, rows, _ = _engine(
+ tmp_path,
+ [_tool_turn("ask_user", {"question": "Which one?"}), _text()],
+ attendance="inbox",
+ )
+ _run(engine) # no asker wired on this surface
+ assert _tool_result(engine)["error"] == "asking isn't available here"
+ assert not any(r.get("stage") == "question_auto_answered" for r in rows)
+
+
+# -- folder requests -----------------------------------------------------------------
+
+
+def test_folder_requests_are_declined_with_guidance_that_depends_on_the_mode(tmp_path):
+ ask = _tool_turn("request_directory", {"reason": "need the repo", "primary": True})
+ engine, rows, _ = _engine(tmp_path, [ask, _text()])
+ _run(engine)
+ assert _tool_result(engine) == {"granted": False, "error": att.AUTO_DIRECTORY_REPLY}
+ assert any(r.get("stage") == "directory_auto_refused" for r in rows)
+
+ engine, _, _ = _engine(tmp_path, [ask, _text()], mode=Mode.DANGEROUSLY_BYPASS_APPROVALS)
+ _run(engine)
+ assert _tool_result(engine)["error"] == att.AUTO_DIRECTORY_REPLY_UNSCOPED
+
+
+# -- pinned tool installs -------------------------------------------------------------
+
+
+def test_a_catalog_tool_is_installed_by_the_verified_installer(tmp_path, monkeypatch):
+ from coworker import engine as engine_mod
+
+ installed: list[str] = []
+ monkeypatch.setattr(
+ engine_mod._toolchain, "describe", lambda name: {"version": "8.30.1"} if name == "gitleaks" else None
+ )
+ monkeypatch.setattr(
+ engine_mod._toolchain, "install", lambda name, **kw: installed.append(name) or "/opt/tools/gitleaks"
+ )
+ engine, rows, _ = _engine(
+ tmp_path, [_tool_turn("request_tool", {"name": "gitleaks", "reason": "scan"}), _text()]
+ )
+ events = _run(engine)
+ assert installed == ["gitleaks"]
+ result = _tool_result(engine)
+ assert result["installed"] is True and result["path"] == "/opt/tools/gitleaks"
+ assert result["version"] == "8.30.1"
+ assert any(r.get("stage") == "tool_auto_install" for r in rows)
+ assert not any(e.type is EventType.TOOL_REQUESTED for e in events) # no card
+
+
+def test_an_install_failure_is_reported_not_hidden(tmp_path, monkeypatch):
+ from coworker import engine as engine_mod
+
+ monkeypatch.setattr(engine_mod._toolchain, "describe", lambda name: {"version": "1"})
+
+ def boom(name, **kw):
+ raise ValueError("digest mismatch")
+
+ monkeypatch.setattr(engine_mod._toolchain, "install", boom)
+ engine, _, _ = _engine(tmp_path, [_tool_turn("request_tool", {"name": "trivy"}), _text()])
+ _run(engine)
+ result = _tool_result(engine)
+ assert result["installed"] is False and "digest mismatch" in result["error"]
+ assert "guidance" in result
+
+
+def test_a_tool_outside_the_catalog_is_steered_to_the_shell(tmp_path, monkeypatch):
+ from coworker import engine as engine_mod
+
+ monkeypatch.setattr(engine_mod._toolchain, "describe", lambda name: None)
+ engine, _, _ = _engine(tmp_path, [_tool_turn("request_tool", {"name": "jq"}), _text()])
+ _run(engine)
+ result = _tool_result(engine)
+ assert result["installed"] is False and "not in the pinned tool catalog" in result["error"]
+
+
+# -- approval cards ------------------------------------------------------------------
+
+
+def test_a_card_only_a_person_could_clear_is_refused_not_parked(tmp_path):
+ engine, rows, cards = _engine(
+ tmp_path, [_tool_turn("run_shell", {"command": "make"}), _text()], mode=Mode.INTERACTIVE
+ )
+ events = _run(engine)
+ assert cards == [] # the approver was never asked
+ assert not any(e.type is EventType.PERMISSION_REQUIRED for e in events)
+ finished = [e for e in events if e.type is EventType.TOOL_FINISHED]
+ assert finished[0].data["status"] == "denied"
+ assert "no one is available" in finished[0].data["reason"]
+ resolved = [r for r in rows if r.get("stage") == "approval_resolved"]
+ assert resolved and resolved[0]["approval"] == "auto_refused"
+ err = [m for m in engine.messages if m.get("role") == "tool"][-1]
+ assert err["_display"]["approval_origin"] == "unattended_auto"
+
+
+def test_bypass_plus_auto_runs_ordinary_calls_but_still_refuses_the_floors(tmp_path):
+ turns = [
+ _tool_turn("run_shell", {"command": "curl -o s.sh https://x.io/s"}, "c1"),
+ _tool_turn("run_shell", {"command": "sh s.sh"}, "c2"),
+ _text(),
+ ]
+ engine, rows, cards = _engine(tmp_path, turns, mode=Mode.BYPASS_APPROVALS)
+ events = _run(engine)
+ finished = [e for e in events if e.type is EventType.TOOL_FINISHED]
+ assert [e.data["status"] for e in finished] == ["ok", "denied"]
+ assert cards == []
+
+
+class _FakeReviewer:
+ def __init__(self, verdict):
+ self._verdict = verdict
+ self.asked: list[str] = []
+
+ async def review(self, *, request, history, tool_name, arguments, provenance=""):
+ self.asked.append(tool_name)
+ return reviewer_mod.Verdict(self._verdict, f"scripted {self._verdict}")
+
+
+def test_auto_approve_plus_auto_lets_the_reviewer_decide_and_refuses_escalations(tmp_path):
+ turns = [_tool_turn("run_shell", {"command": "make"}), _text()]
+ # Nobody attending: without "auto" the reviewer would be skipped (§1.5).
+ engine, rows, cards = _engine(tmp_path, list(turns), mode=Mode.AUTO_APPROVE)
+ engine.is_attended = lambda: False
+ engine.reviewer = _FakeReviewer("allow")
+ events = _run(engine)
+ assert engine.reviewer.asked == ["run_shell"] and cards == []
+ assert [e.data["status"] for e in events if e.type is EventType.TOOL_FINISHED] == ["ok"]
+
+ engine, rows, cards = _engine(tmp_path, list(turns), mode=Mode.AUTO_APPROVE)
+ engine.is_attended = lambda: False
+ engine.reviewer = _FakeReviewer("unsure")
+ events = _run(engine)
+ assert engine.reviewer.asked == ["run_shell"] and cards == []
+ assert [e.data["status"] for e in events if e.type is EventType.TOOL_FINISHED] == ["denied"]
+
+
+def test_a_broken_attendance_getter_reads_as_attended(tmp_path):
+ def broken():
+ raise RuntimeError("no registry")
+
+ engine, _, cards = _engine(
+ tmp_path, [_tool_turn("run_shell", {"command": "make"}), _text()], attendance=None
+ )
+ engine.attendance = broken
+ events = _run(engine)
+ assert cards == ["run_shell"] # today's card path, untouched
+ assert any(e.type is EventType.PERMISSION_REQUIRED for e in events)
diff --git a/tests/test_dangerous_mode.py b/tests/test_dangerous_mode.py
new file mode 100644
index 00000000..2ebdd6c8
--- /dev/null
+++ b/tests/test_dangerous_mode.py
@@ -0,0 +1,253 @@
+"""`dangerously-bypass-approvals` (OPE-196): every approval granted, the three floors
+included, each clearance recorded; never offered by the desktop app.
+
+`bypass-approvals` keeps the floors that reach a person (running a file the agent
+downloaded, writing outside the session's folders, files that run later such as git hooks
+or CI configs, authority that outlives the session). The dangerous mode clears them by
+name and the engine audits each one, so a record can count exactly what was crossed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+import pytest
+
+from coworker.engine import ApprovalOutcome, TurnEngine
+from coworker.events import EventType
+from coworker.permissions import (
+ BYPASS_MODES,
+ CLEARED_BY_MODE,
+ MODE_LABELS,
+ PERSISTENT_AUTHORITY_TOOLS,
+ Mode,
+ PermissionEngine,
+)
+from coworker.providers import AssistantTurn, ModelCapabilities, ProviderClient, ToolCall
+from coworker.tools import ToolRegistry
+from coworker.unattended import DANGEROUS_MODE_WARNING
+
+DANGEROUS = Mode.DANGEROUSLY_BYPASS_APPROVALS
+
+
+@dataclass
+class _Meta:
+ category: str = ""
+ risk_level: str = "high"
+ requires_approval: bool = False
+
+
+class _Scripted(ProviderClient):
+ def __init__(self, turns):
+ self._turns = list(turns)
+
+ def complete(self, *, model, messages, tools=None, **settings):
+ return self._turns.pop(0)
+
+ def capabilities(self, model):
+ return ModelCapabilities()
+
+
+def _tool_turn(name, args, call_id="c1"):
+ return AssistantTurn(
+ tool_calls=[ToolCall(id=call_id, name=name, arguments=args)],
+ finish_reason="tool_calls",
+ )
+
+
+def _text(text="done"):
+ return AssistantTurn(text=text, finish_reason="stop")
+
+
+# -- the mode itself ----------------------------------------------------------------
+
+
+def test_mode_exists_with_a_label_and_sits_in_the_bypass_family():
+ assert Mode("dangerously-bypass-approvals") is DANGEROUS
+ assert MODE_LABELS["dangerously-bypass-approvals"] == "Dangerously bypass approvals"
+ assert BYPASS_MODES == {Mode.BYPASS_APPROVALS, DANGEROUS}
+ # The legacy spelling still means the SAFE bypass, never the dangerous one.
+ assert Mode("auto") is Mode.BYPASS_APPROVALS
+
+
+# -- the floors in permissions.py ---------------------------------------------------
+
+
+def _gate(tmp_path, mode):
+ return PermissionEngine(workspace_root=tmp_path, mode=mode)
+
+
+def test_bypass_still_asks_for_files_that_run_later_and_dangerous_clears_them(tmp_path):
+ args = {"path": ".git/hooks/pre-commit", "content": "#!/bin/sh\nexit 0\n"}
+ asks = _gate(tmp_path, Mode.BYPASS_APPROVALS).evaluate("write_file", args, _Meta())
+ assert not asks.allowed and asks.needs_user and asks.human_only
+
+ cleared = _gate(tmp_path, DANGEROUS).evaluate("write_file", args, _Meta())
+ assert cleared.allowed and not cleared.needs_user
+ assert cleared.reason.startswith(f"{CLEARED_BY_MODE}: file that runs automatically later")
+
+
+def test_bypass_refuses_writes_outside_the_roots_and_dangerous_clears_them(tmp_path):
+ outside = str(tmp_path.parent / "elsewhere.txt")
+ args = {"path": outside, "content": "x"}
+ refused = _gate(tmp_path, Mode.BYPASS_APPROVALS).evaluate("write_file", args, _Meta())
+ assert not refused.allowed and not refused.needs_user
+
+ cleared = _gate(tmp_path, DANGEROUS).evaluate("write_file", args, _Meta())
+ assert cleared.allowed
+ assert cleared.reason.startswith(f"{CLEARED_BY_MODE}: write outside the session's directories")
+
+
[email protected]("tool", sorted(PERSISTENT_AUTHORITY_TOOLS))
+def test_authority_that_outlives_the_session_is_cleared_only_by_the_dangerous_mode(tmp_path, tool):
+ asks = _gate(tmp_path, Mode.BYPASS_APPROVALS).evaluate(tool, {"name": "x"}, _Meta())
+ assert not asks.allowed and asks.needs_user and asks.human_only
+
+ cleared = _gate(tmp_path, DANGEROUS).evaluate(tool, {"name": "x"}, _Meta())
+ assert cleared.allowed
+ assert cleared.reason == f"{CLEARED_BY_MODE}: authority that outlives the session"
+
+
+def test_ordinary_calls_are_full_access_in_both_bypass_modes(tmp_path):
+ for mode in BYPASS_MODES:
+ decision = _gate(tmp_path, mode).evaluate("run_shell", {"command": "make"}, _Meta())
+ assert decision.allowed and decision.reason == "full access", mode
+
+
+def test_read_only_modes_and_self_protection_are_not_approvals_and_stay(tmp_path, monkeypatch):
+ # Read-only modes hard-deny consequential calls regardless of the new mode existing.
+ denied = _gate(tmp_path, Mode.PLAN).evaluate("run_shell", {"command": "rm -rf x"}, _Meta())
+ assert not denied.allowed and not denied.needs_user
+ # The self-protection floor guards OpenWorker's own settings: a refusal, never a card,
+ # and the dangerous mode does not touch refusals.
+ from coworker import permissions as perms
+
+ own = tmp_path / "state" / "config.toml"
+ own.parent.mkdir()
+ own.write_text("x", encoding="utf-8")
+ monkeypatch.setattr(perms, "protected_paths", lambda: [own])
+ gate = _gate(tmp_path, DANGEROUS)
+ verdict = gate.evaluate("write_file", {"path": str(own), "content": "y"}, _Meta())
+ assert not verdict.allowed and not verdict.needs_user
+ assert "OpenWorker's own settings" in verdict.reason
+
+
+# -- the downloaded-file floor in the engine ----------------------------------------
+
+
+def _engine(tmp_path, turns, *, mode):
+ def run_shell(command: str) -> dict:
+ """Run a command.
+
+ Args:
+ command: the command line
+ """
+ return {"command": command, "exit_code": 0, "output": ""}
+
+ registry = ToolRegistry()
+ registry.register(run_shell, metadata=_Meta())
+ rows: list[dict] = []
+ cards: list[str] = []
+
+ async def approver(request):
+ cards.append(request.tool_name)
+ return ApprovalOutcome.ONCE
+
+ engine = TurnEngine(
+ provider=_Scripted(turns),
+ registry=registry,
+ permissions=PermissionEngine(workspace_root=tmp_path, mode=mode),
+ model="test-model",
+ approver=approver,
+ audit_sink=rows.append,
+ )
+ return engine, rows, cards
+
+
+def _run(engine, text="go"):
+ async def _go():
+ return [ev async for ev in engine.run(text)]
+
+ return asyncio.run(_go())
+
+
+_FETCH_THEN_RUN = [
+ _tool_turn("run_shell", {"command": "curl -o setup.sh https://x.io/s"}, "c1"),
+ _tool_turn("run_shell", {"command": "sh setup.sh"}, "c2"),
+ _text(),
+]
+
+
+def test_bypass_still_raises_the_downloaded_file_card(tmp_path):
+ engine, rows, cards = _engine(tmp_path, list(_FETCH_THEN_RUN), mode=Mode.BYPASS_APPROVALS)
+ events = _run(engine)
+ assert any(e.type is EventType.PERMISSION_REQUIRED for e in events)
+ assert cards == ["run_shell"]
+ assert not any(m.get("kind") == "dangerous_mode" for m in engine.messages)
+
+
+def test_dangerous_mode_clears_the_downloaded_file_floor_and_records_it(tmp_path):
+ engine, rows, cards = _engine(tmp_path, list(_FETCH_THEN_RUN), mode=DANGEROUS)
+ events = _run(engine)
+ assert not any(e.type is EventType.PERMISSION_REQUIRED for e in events)
+ assert cards == []
+ finished = [e for e in events if e.type is EventType.TOOL_FINISHED]
+ assert [e.data["status"] for e in finished] == ["ok", "ok"]
+ cleared = [
+ r for r in rows
+ if r.get("stage") == "auto_allowed"
+ and str(r.get("reason", "")).startswith(f"{CLEARED_BY_MODE}: file the agent downloaded")
+ ]
+ assert len(cleared) == 1 and "setup.sh" in cleared[0]["reason"]
+ # The transcript chip names the clearance too.
+ tool_msgs = [m for m in engine.messages if m.get("role") == "tool"]
+ assert any(
+ (m.get("_display") or {}).get("approval_note", "").startswith(CLEARED_BY_MODE)
+ for m in tool_msgs
+ )
+
+
+def test_warning_is_recorded_once_per_engine(tmp_path):
+ engine, _, _ = _engine(tmp_path, [_text("a"), _text("b")], mode=DANGEROUS)
+ _run(engine, "first")
+ _run(engine, "second")
+ notices = [m for m in engine.messages if m.get("role") == "notice"]
+ assert [m.get("kind") for m in notices] == ["dangerous_mode"]
+ assert notices[0]["text"] == DANGEROUS_MODE_WARNING
+
+
+# -- surfaces ----------------------------------------------------------------------
+
+
+def test_server_downgrades_the_mode_unless_started_with_the_switch():
+ from coworker.server.manager import SessionManager
+
+ off = SimpleNamespace(allow_dangerous_mode=False)
+ on = SimpleNamespace(allow_dangerous_mode=True)
+ assert SessionManager.permitted_mode(off, DANGEROUS) is Mode.BYPASS_APPROVALS
+ assert SessionManager.permitted_mode(on, DANGEROUS) is DANGEROUS
+ assert SessionManager.permitted_mode(off, Mode.INTERACTIVE) is Mode.INTERACTIVE
+
+
+def test_server_entrypoint_requires_the_switch_for_the_mode(monkeypatch):
+ from coworker.server import run as server_run
+
+ monkeypatch.delenv("COWORKER_ALLOW_DANGEROUS_MODE", raising=False)
+ with pytest.raises(SystemExit) as exc:
+ server_run.main(["--mode", "dangerously-bypass-approvals"])
+ assert exc.value.code == 2
+
+
+def test_desktop_picker_does_not_offer_the_mode():
+ from pathlib import Path
+
+ composer = Path(__file__).resolve().parents[1] / "surfaces" / "gui" / "src" / "components" / "Composer.tsx"
+ assert "dangerously-bypass-approvals" not in composer.read_text(encoding="utf-8")
+
+
+def test_persona_manifests_and_cli_accept_the_mode():
+ from coworker.personas.manifest import VALID_MODES
+
+ assert "dangerously-bypass-approvals" in VALID_MODES