diff --git a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py index e3a8653f1..9cc911e23 100644 --- a/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py +++ b/src/agent_env/task_step/task_steps/agent/deploy_user_sim_agent.py @@ -192,7 +192,8 @@ def persona_problems(persona: Any) -> list[str]: return out -def person(key: str, persona: dict, opening: list[dict], seed: dict, multi_day: Optional[bool]) -> dict: +def person(key: str, persona: dict, opening: list[dict], seed: dict, multi_day: Optional[bool], + preset: Optional[str] = None) -> dict: """The user as the built-in user sim's ``setup`` takes them: ``persona``'s fields, the ``opening`` parts with the run's ```` placeholders filled in (as always_on fills them), and the done line ``multi_day`` picks. The step writes its prompt from this, and user_sim_judge rebuilds that prompt from the step's record (``recorded_person``).""" @@ -205,7 +206,7 @@ def person(key: str, persona: dict, opening: list[dict], seed: dict, multi_day: "description": persona.get("description"), "permissions": persona.get("permissions"), "keep_private": persona.get("keep_private"), "opening": {"text": text, **({"files": files} if files else {})} if text else None, - "done_ends_run": not multi_day} + "done_ends_run": not multi_day, **({"preset": preset} if preset else {})} def recorded_person(us: dict, seed: dict, multi_day: Optional[bool] = None) -> dict: @@ -214,7 +215,7 @@ def recorded_person(us: dict, seed: dict, multi_day: Optional[bool] = None) -> d persona = {**{k: us.get(k) for k in PERSONA_KEYS}, "display_name": us.get("display_name") or us.get("name") or "the user"} return person(us.get("name"), persona, recorded_opening(us), seed, - us["multi_day"] if us.get("multi_day") is not None else multi_day) + us["multi_day"] if us.get("multi_day") is not None else multi_day, us.get("preset")) def recorded_instructions(us: dict, seed: dict, multi_day: Optional[bool] = None) -> Optional[str]: @@ -250,7 +251,8 @@ class DeployUserSimAgentTaskStep(DeployAgentTaskStep): "a2a_agent_version": FieldScope.TASK} def __init__(self, id: str, version: Optional[int], *, persona: Optional[dict] = None, model: Optional[str] = None, - multi_day: Optional[bool] = None, opening_prompt: Optional[str | list[dict]] = None, **deploy: Any): + multi_day: Optional[bool] = None, opening_prompt: Optional[str | list[dict]] = None, + preset: Optional[str] = None, **deploy: Any): if deploy.get("system_prompt") is not None: raise ValueError(f"{self.type} '{id}': system_prompt is written from the persona and opening_prompt; don't set it") deploy.pop("system_prompt", None) @@ -268,16 +270,21 @@ def __init__(self, id: str, version: Optional[int], *, persona: Optional[dict] = # Required: always_on starts the run from it, and refuses a user sim without one only after the deploy. found += opening_problems(opening_prompt) found += persona_problems(persona) + if preset is not None and preset not in user_sim_versions.PRESETS: + found.append(f"preset {preset!r} is not one of {list(user_sim_versions.PRESETS)}") + elif preset in ("chat", "milestone") and multi_day: + found.append(f"preset {preset!r} is one conversation: multi_day must be false") if found: raise ValueError(f"{self.type} '{self.agent_name}': " + "; ".join(found)) self.persona = persona self.model = model self.multi_day = multi_day self.opening_prompt = opening_prompt + self.preset = preset # Who the user is as the task writes it, the seed not filled in: what the judge's rubric_persona_sha256 is. self.persona_sha256 = persona_fingerprint(persona, opening_prompt) - _OWN = ("persona", "model", "multi_day", "opening_prompt") + _OWN = ("persona", "model", "multi_day", "opening_prompt", "preset") def seeded_from(self, written: "DeployUserSimAgentTaskStep") -> None: """This step is ``written`` with the run's seed filled in (``substitute_seed_in_steps``): keep the fingerprint @@ -308,7 +315,24 @@ def _resolve_agent_ref(self, context: TaskStepContext) -> tuple[str, Optional[in def person(self, context: TaskStepContext) -> dict: """The user as the built-in user sim's ``setup`` takes them, as always_on hands them over.""" return person(self.agent_name, self.persona, opening_parts(self.opening_prompt), - context.metadata.get("seed") or {}, self.multi_day) + context.metadata.get("seed") or {}, self.multi_day, self.preset) + + def task_problems(self, steps: list) -> list[str]: + """A preset names the steps this user goes with: a milestone user talks to a prompt_agent with a post-turn + hook (the hook's notes are what it moves on), and a chat or milestone user is never always_on's.""" + if self.preset is None: + return [] + out = [] + talks = [s for s in steps if s.type == "prompt_agent" and getattr(s, "user_agent_name", None) == self.agent_name] + if self.preset == "milestone": + if not talks: + out.append(f"user '{self.agent_name}' has preset milestone, but no prompt_agent step talks to it") + out += [f"user '{self.agent_name}' has preset milestone, but prompt_agent '{s.id}' has no post_turn_hooks " + "to check its milestones" for s in talks if not getattr(s, "post_turn_hooks", None)] + if self.preset in ("chat", "milestone"): + out += [f"user '{self.agent_name}' has preset {self.preset}, one conversation, but always_on '{s.id}' " + "plays it" for s in steps if s.type == "always_on" and getattr(s, "user_sim", None) == self.agent_name] + return out def _setup(self, context: TaskStepContext) -> dict: return user_sim_versions.setup(user_sim_versions.VERSION, self.person(context)) @@ -365,6 +389,9 @@ async def _set_user(self, context: TaskStepContext, agent, setup: dict) -> TaskS # Each tag the prompt shows with its line, so an answer's ``used`` ("D9") names what this run saw. "tagged_lines": user_sim_versions.tagged_lines(self.person(context)), "multi_day": self.multi_day, + # The preset as written (None: chat or always_on by multi_day), and what a judge's rules may depend on. + "preset": self.preset, + "features": sorted(user_sim_versions.features(self.person(context))), # The run record's user sim settings, as always_on wrote them when it set the agent up itself. "setup": {"model": model, "model_from": source, "user_sim_step_model": self.model, "model_set": True, "system_prompt_chars": len(prompt), "output_format": setup.get("output_format"), diff --git a/src/agent_env/task_step/task_steps/agent/user_sim.md b/src/agent_env/task_step/task_steps/agent/user_sim.md index aff2aaf66..67c3dce9a 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim.md +++ b/src/agent_env/task_step/task_steps/agent/user_sim.md @@ -32,11 +32,26 @@ Its own fields: | `persona` | required | Who the user is: `display_name` (their full name), `first_name` (else the display name's first word), `time_zone` (their IANA zone; else the task clock's, else UTC; a clock that sets a different zone is refused), `description`, `permissions`, `keep_private`, `schedule`, `response_times`, `max_replies` (after that many replies the user stops reading) | | `model` | required | The user sim's model. This step's `step_params` `model` wins, then the run's `user_model` (`--user-model`), then this | | `opening_prompt` | required | The user's first message: text, or text and file parts (below). The always-on step sends it and has no prompt of its own | +| `preset` | optional | `chat`, `always_on` or `milestone`: the kind of run (below) | | `multi_day` | required, for now | Whether the run goes past the day it starts on (always-on's `end_time` falls on a later day). It picks the prompt's done line; always-on refuses a run of the other kind | `multi_day` is a stopgap: the prompt is written before the run, so the step has to be told which done line to use. It goes away once the step can learn it from the task. +`preset` (optional) names the kind of run the user is in: + +| Preset | The run | What it changes | +|---|---|---| +| `chat` | One conversation with a `prompt_agent`; done ends it. `multi_day: false` | Nothing: the prompt is today's single-session one | +| `always_on` | An `always_on` run; the user reads emails, texts and notifications between messages | Nothing: the prompt is today's multi-day one | +| `milestone` | One conversation in steps that a `prompt_agent` post-turn hook checks (such as milestone-gates). `multi_day: false` | The prompt tells the user to trust the hook's note over the reply, always reply while it says something isn't done, press on what it raises in their own words and never more specifically (not even with names from the assistant's own reply), move on only when it says so, send the line it gives word for word, and answer done only after it says everything is done | + +Without a preset the user is `chat` or `always_on` by `multi_day`, as before. The task is refused when it loads if a +`milestone` user's `prompt_agent` has no `post_turn_hooks`, if no `prompt_agent` talks to it, or if an `always_on` +step plays a `chat` or `milestone` user. The step records the preset as written and `features`: the parts of the +prompt and run a judge's rules may depend on (`told_lines`, `should_know_lines`, `permission_rules`, `when_done`, +`phone`, `milestones`, `hook_notes`), so a judge can read only the rules that fit this user. + **A first message with files.** `opening_prompt` can be a list of parts in `prompt_agent`'s `parts` format, text and file parts, for a first message that attaches a photo, a PDF, a spreadsheet or any other file: diff --git a/src/agent_env/task_step/task_steps/agent/user_sim_versions.py b/src/agent_env/task_step/task_steps/agent/user_sim_versions.py index 785905870..46d5978e4 100644 --- a/src/agent_env/task_step/task_steps/agent/user_sim_versions.py +++ b/src/agent_env/task_step/task_steps/agent/user_sim_versions.py @@ -1,6 +1,7 @@ """The built-in user sim: deploy_user_sim_agent writes its system prompt with ``setup``, and the always_on step reads with ``answer``. The interface is in deploy_user_sim_agent.py; how to write a user for it is in user_sim.md. It has -one version, ``ours``. +one version, ``ours``, and three presets (``PRESETS``): chat, always_on and milestone. A preset sets the done line +and, for milestone, how the user takes a post-turn hook's note; ``features`` names what a judge's rules may depend on. ``setup`` writes the system prompt once per run: fixed lines on how a real person reads and answers, the description as tagged sections (with the opening request), the user's rules from ``permissions`` and ``keep_private``, and the @@ -53,6 +54,33 @@ "never_supply": "put facts the assistant should find in what_to_look_up, and secrets in keep_private", } +# What kind of run the user sim is in. Each sets its done line and any rules for what it's sent, and names the parts +# of the prompt and the run a judge's rules may depend on (``features``). None: chat or always_on, by ``done_ends_run``. +PRESETS: dict[str, str] = { + "chat": "one conversation; done ends it", + "always_on": "a run over hours or days; the user reads emails, texts and notifications between messages", + "milestone": "one conversation in steps a post-turn hook checks; the user moves on when its note says so", +} +# The milestone preset: a post-turn hook checks the work and tells the user what it found in a note only they see. +MILESTONE_LINES = ( + "After the assistant's reply you may get a note that only you see: what you found when you checked its work " + "yourself. Trust the note over what the reply says about itself. If it says something isn't done, always reply " + "(never no reply) and bring it up in your own words, never more specifically than the note: no answer, figure, " + "name or record it doesn't give you, not even one from the assistant's own reply. Move on only when the note says " + "so, and when it gives you a line to send next, send that line word for word.") +DONE_MILESTONE = ('Answer "done" only after the note says everything is done and you\'ve sent your last line; until ' + 'then, keep the chat going.') +# The parts of the prompt or the run a judge's rule may depend on (see ``features``). +FEATURES: dict[str, str] = { + "told_lines": "a THINGS YOU ALREADY TOLD THE ASSISTANT section (T lines)", + "should_know_lines": "a THINGS THE ASSISTANT SHOULD ALREADY KNOW section (C lines)", + "permission_rules": "rules for the assistant: just do, ask first, never, tell you after", + "when_done": "a WHEN YOU'RE DONE section", + "phone": "reads that show the emails, texts and notifications that reached the user", + "milestones": "a run in steps that a hook opens one at a time", + "hook_notes": "notes from a post-turn hook on what the user found checking the work", +} + PERMISSION_KINDS: dict[str, str] = { "just_do": "Just do", "ask_first": "Ask you first", @@ -124,7 +152,9 @@ def _first(person: dict) -> str: def _preamble(person: dict) -> list[str]: full, first = person["name"], _first(person) - if person.get("done_ends_run"): + if preset_of(person) == "milestone": + done = DONE_MILESTONE + elif person.get("done_ends_run"): done = DONE_ENDS_RUN elif person["description"].get("when_done"): done = DONE_MULTI_DAY @@ -141,11 +171,35 @@ def _preamble(person: dict) -> list[str]: "make calls about it unless the assistant asks, or your description says to.", "If the assistant asks something no line below covers: for a choice, choose the way you would; for a fact " "about you or anyone else that isn't written below, say you don't know. Never guess facts.", + *([MILESTONE_LINES] if preset_of(person) == "milestone" else []), done, 'In "used", write the tag of the line you relied on, or "none". Answer in JSON:\n' + ANSWER_LINE, ] +def preset_of(person: dict) -> str: + """The run kind the user sim is in: its ``preset``, else chat when done ends the run, else always_on.""" + return person.get("preset") or ("chat" if person.get("done_ends_run") else "always_on") + + +def features(person: dict) -> frozenset[str]: + """The parts of this user sim's prompt and run that a judge's rules may depend on (``FEATURES``): a section the + description fills in, rules the permissions give, and what the preset adds. A judge given these reads only the + rules that fit this sim, so one product's rules never reach a sim whose prompt never asked for them.""" + description = person.get("description") or {} + have = {feature for key, feature in (("already_told", "told_lines"), ("should_already_know", "should_know_lines"), + ("when_done", "when_done")) + if _lines(description.get(key))} + if any(_items((person.get("permissions") or {}).get(kind))[0] for kind in PERMISSION_KINDS): + have.add("permission_rules") + preset = preset_of(person) + if preset == "always_on": + have.add("phone") + if preset == "milestone": + have |= {"milestones", "hook_notes"} + return frozenset(have) + + def tag_line(tag: str, text: str) -> str: """One description line under its tag; the line's later lines hang under its text.""" head, *rest = text.split("\n") @@ -270,6 +324,11 @@ def problems(person: Any) -> list[str]: out.append("keep_private must be a list of non-empty lines") if person.get("time_zone") is not None: out += zone_problems(person["time_zone"]) + preset = person.get("preset") + if preset is not None and preset not in PRESETS: + out.append(f"preset {preset!r} is not one of {list(PRESETS)}") + elif preset in ("chat", "milestone") and not person.get("done_ends_run"): + out.append(f"preset {preset!r} is one conversation: it can't run over more than one day") return out diff --git a/tst/unit/task_step/test_user_sim_presets.py b/tst/unit/task_step/test_user_sim_presets.py new file mode 100644 index 000000000..2a5804586 --- /dev/null +++ b/tst/unit/task_step/test_user_sim_presets.py @@ -0,0 +1,117 @@ +"""The built-in user sim's presets: chat and always_on keep today's prompt byte for byte, milestone adds how the user +takes a post-turn hook's note, each names the features a judge's rules may depend on, and a preset that doesn't fit +the task's other steps is refused when the task loads.""" + +from __future__ import annotations + +import hashlib + +import pytest + +from agent_env.task import Task +from agent_env.task_step.task_steps.agent import user_sim_versions as usv +from agent_env.task_step.task_steps.agent.deploy_user_sim_agent import recorded_instructions +from tst.unit.task_step.test_deploy_user_sim_agent import HANNAH, PERSON, PROMPT, _Deploy, _published, _step + +PROMPT_AGENT = {"id": "talk", "type": "prompt_agent", "prompt": "sort the weekend", "agent_name": "solver", + "user_agent_name": "hannah", "max_conversation_turns": 6} +HOOK = [{"file_artifact_id": "milestone-gates", "params": {}}] + + +def _person(**over) -> dict: + return {**PERSON, **over} + + +# ---- the prompt ---------------------------------------------------------------------------------------------------- +@pytest.mark.asyncio +async def test_an_always_on_preset_keeps_todays_prompt_byte_for_byte(monkeypatch): + deploy = _Deploy(monkeypatch) + context = await deploy.run(_step(preset="always_on")) + + assert deploy.fields("system_prompt") == [PROMPT] + record = context.metadata["user_sims"]["hannah"] + assert record["prompt_sha256"] == hashlib.sha256(PROMPT.encode()).hexdigest() + assert record["preset"] == "always_on" + + +def test_a_chat_preset_writes_the_prompt_a_single_session_writes_today(): + single = _person(done_ends_run=True) + assert usv.system_prompt({**single, "preset": "chat"}) == usv.system_prompt(single) + + +def test_a_milestone_preset_tells_the_user_how_to_take_a_hooks_note_and_when_it_is_done(): + chat = usv.system_prompt(_person(done_ends_run=True)) + milestone = usv.system_prompt(_person(done_ends_run=True, preset="milestone")) + + assert usv.MILESTONE_LINES in milestone and usv.MILESTONE_LINES not in chat + assert usv.DONE_MILESTONE in milestone and usv.DONE_ENDS_RUN not in milestone + + +@pytest.mark.asyncio +async def test_the_prompt_rebuilt_from_the_record_is_the_one_the_milestone_user_got(monkeypatch): + deploy = _Deploy(monkeypatch) + context = await deploy.run(_step(preset="milestone", multi_day=False)) + record = context.metadata["user_sims"]["hannah"] + + assert recorded_instructions(record, {}) == deploy.fields("system_prompt")[0] + + +# ---- features ------------------------------------------------------------------------------------------------------ +def test_features_follow_the_sections_the_persona_fills_in_and_the_preset(): + plain = {"name": "Ada Park", "description": {"who_you_are": ["You run finance."]}, "done_ends_run": True} + assert usv.features(plain) == frozenset() + assert usv.features({**plain, "description": {**plain["description"], "already_told": ["The budget is 5k."]}, + "permissions": {"ask_first": ["sending money"]}}) == {"told_lines", "permission_rules"} + assert usv.features({**plain, "done_ends_run": False}) == {"phone"} + assert usv.features({**plain, "preset": "milestone"}) == {"milestones", "hook_notes"} + assert set(usv.features(_person(done_ends_run=False))) <= set(usv.FEATURES) + + +@pytest.mark.asyncio +async def test_the_record_carries_the_features_for_the_judge(monkeypatch): + record = await _published(monkeypatch, _step(preset="milestone", multi_day=False)) + + assert record["preset"] == "milestone" + assert {"milestones", "hook_notes"} <= set(record["features"]) + assert "phone" not in record["features"] + + +@pytest.mark.asyncio +async def test_a_step_without_a_preset_records_none_and_its_features(monkeypatch): + record = await _published(monkeypatch, _step()) + + assert record["preset"] is None and "phone" in record["features"] + + +# ---- checks -------------------------------------------------------------------------------------------------------- +@pytest.mark.parametrize("fields, problem", [ + ({"preset": "weekly"}, "is not one of"), + ({"preset": "milestone", "multi_day": True}, "multi_day must be false"), + ({"preset": "chat", "multi_day": True}, "multi_day must be false"), +]) +def test_a_bad_preset_is_refused(fields, problem): + with pytest.raises(ValueError, match=problem): + _step(**fields) + + +def _task(*steps: dict) -> Task: + sim = {"id": "user", "type": "deploy_user_sim_agent", "a2a_agent_id": "sim-image", "agent_name": "hannah", + "model": "sim-model", "opening_prompt": PERSON["opening"]["text"], "persona": HANNAH} + return Task.from_dict({"id": "t", "version": 1, "steps": [{**sim, **steps[0]}, *steps[1:]]}) + + +def test_a_milestone_user_with_a_hooked_conversation_loads(): + task = _task({"preset": "milestone", "multi_day": False}, {**PROMPT_AGENT, "post_turn_hooks": HOOK}) + assert [s.type for s in task.steps] == ["deploy_user_sim_agent", "prompt_agent"] + + +@pytest.mark.parametrize("steps, problem", [ + (({"preset": "milestone", "multi_day": False}, PROMPT_AGENT), "has no post_turn_hooks"), + (({"preset": "milestone", "multi_day": False},), "no prompt_agent step talks to it"), + (({"preset": "chat", "multi_day": False}, + {"id": "week", "type": "always_on", "user_sim": "hannah", "prompt_id": "ask", "agent_name": "solver"}), + "one conversation, but always_on"), +]) +def test_a_preset_that_doesnt_fit_the_task_is_refused_when_it_loads(steps, problem): + with pytest.raises(ValueError, match=problem): + _task(*steps)