Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Remember which reCAPTCHA task type YesCaptcha rejects for each sitekey, so our API key stops getting blocked (SKY-17092) (#8657)
Shuchang Zheng1c1a8b787417
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 731491bb9..93e11e6b8 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -2305,18 +2305,6 @@ class ForgeAgent:)# The judge's finish-time screenshot, reused as the decision screenshot of an accepted completion.goal_judge_shot: list[bytes] = []- offer_error_codes = False- if task.error_code_mapping:- try:- offer_error_codes = await app.AGENT_FUNCTION.resolve_task_v3_error_code_choice(- task=task, organization=organization- )- except Exception:- LOG.warning(- "resolve_task_v3_error_code_choice failed; leaving codes out of the loop",- task_id=task.task_id,- exc_info=True,- )page_free_validation = bool(task_block is not Noneand task.task_type == TaskType.validation@@ -2385,7 +2373,6 @@ class ForgeAgent:# Validation only: that is the task type whose criteria a decision-maker weighs against# each other in both engines, and the only one this was measured on (SKY-16193).criteria_precedence=task.task_type == TaskType.validation,- error_code_mapping=task.error_code_mapping if offer_error_codes else None,framing=framing,block_context_section=block_context_section,),@@ -2978,7 +2965,6 @@ class ForgeAgent:)outcome = await run_task_v3_agent_loop(page_provider=_page_provider,- error_code_mapping=task.error_code_mapping if offer_error_codes else None,resolve_typed_text=resolve_typed_text,credential_release_guard=release_guard,resolve_totp_placeholder=verification_state.resolve_totp_placeholder,@@ -3331,56 +3317,7 @@ class ForgeAgent:completion_rejection=completion_rejection,missing_extraction=missing_extraction,)- # Three cases, and the first is status-INDEPENDENT on purpose. A model that named a code has- # answered the question; discarding that answer because the run also finished `completed`- # would throw away exactly the business-outcome verdict this change exists to capture, and- # the prompt actively tells the model to pick its status on the run's merits.- model_chose_code = bool(task.error_code_mapping and outcome.error_codes_offered and outcome.error_code)- model_declined_code = bool(- task.error_code_mapping- and outcome.error_codes_offered- and not outcome.error_code- # The MODEL's verdict, not the derived one: a completion the gate vetoes is demoted to- # failed above, but the model said "completed" and was never asked which business outcome- # explains a failure, so its silence is not a deliberate decline.- and outcome.status in ("failed", "terminated")- )- if model_chose_code:- with contained_effect("task_v3 model-chosen error code persist", task_id=task.task_id, exc_info=True):- # The model's own finish reason first: it is the account of why THIS code was named.- # failure_reason can be the system's veto text (a completion the gate rejected),- # which explains something else.- code_reasoning = outcome.reason or failure_reason or ""- if run_secrets:- # task.errors reaches the customer's webhook, so this string leaves the system.- code_reasoning = redact_secrets_from_text(code_reasoning, run_secrets)- # Truncate after redacting, like the sibling persists: cutting first can split a- # secret into a fragment the redactor no longer matches.- code_reasoning = code_reasoning[:_TASKV3_REASONING_MAX_CHARS]- await app.DATABASE.tasks.update_task(- task_id=task.task_id,- organization_id=task.organization_id,- errors=[- UserDefinedError(- error_code=outcome.error_code or "",- reasoning=code_reasoning,- confidence_float=1.0,- ).model_dump()- ],- )- elif model_declined_code:- # A deliberate "none of these applied" is the answer. Running the detector here would put- # a guess back on top of a choice -- and on a failed finish it would read `failure_reason`,- # the model's own text, written with these descriptions in front of it, through a- # substring match with no negation handling (SKY-15591).- LOG.info(- "taskv3 user-defined error code declined by the model",- task_id=task.task_id,- task_status=task_status,- )- elif task.error_code_mapping and task_status in (TaskStatus.failed, TaskStatus.terminated):- # Unchanged for every run whose finish never offered codes -- which is all of them while- # the flag is off, plus v1, whose fail_task runs this same detector.+ if task.error_code_mapping and task_status in (TaskStatus.failed, TaskStatus.terminated):try:detected_errors = await detect_user_defined_errors_for_task(task=task,diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex e01b34896..921d46dee 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -979,12 +979,6 @@ class AgentFunction:def task_v3_required_field_answers_text(self) -> tuple[str, str] | None:return None- # Whether v3 offers the task's configured error codes to the model, so a terminal verdict names- # its own business outcome instead of having one matched on afterwards (SKY-15586). No deployment- # overrides it; False keeps codes out of the loop entirely.- async def resolve_task_v3_error_code_choice(self, *, task: Task, organization: Organization) -> bool:- return False-# The v3 code tool, or None when this deployment cannot run model-authored code under a sandbox.# Returning None is the ONLY safe answer without one: there is deliberately no in-process# execution path here to degrade to, so a deployment with no runner offers no code tool ratherdiff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex e9d62ac0e..85af8d0cd 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -268,9 +268,6 @@ async def run_task_v3_agent_loop(llm_caller: Any,goal: str,parameters: dict[str, Any] | None = None,- # The customer's configured business outcomes. Offered to the model on the finish tool so a- # terminal verdict names its own code deliberately, instead of one being matched on afterwards.- error_code_mapping: dict[str, str] | None = None,starting_url: str | None = None,downloads_dir: str | None = None,organization_id: str | None = None,@@ -504,7 +501,6 @@ async def run_task_v3_agent_loop(finish_tool = make_finish_tool(page_fingerprint=None if page_free else page_fingerprint,- error_code_mapping=error_code_mapping,max_settle_deferrals=max_settle_deferrals,pending_marker=None if page_free else pending_marker,submit_watch=None if page_free else submit_watch,diff --git a/skyvern/forge/taskv3/goal_composition.py b/skyvern/forge/taskv3/goal_composition.pyindex 8f1a1f892..56a1a9eb4 100644--- a/skyvern/forge/taskv3/goal_composition.py+++ b/skyvern/forge/taskv3/goal_composition.py@@ -31,15 +31,14 @@ class GoalDirectives:"""Everything that shapes a Task V3 block's goal beyond the navigation goal itself.A field here is already the DECISION, not the raw task attribute: the caller resolves whether a- criterion is trusted and whether error codes are on offer, and passes ``None`` when the sentence- is not to be rendered. That keeps the policy at the caller and the wording here.+ criterion is trusted, and passes ``None`` when the sentence is not to be rendered. That keeps the+ policy at the caller and the wording here."""data_extraction_goal: str | None = Noneextracted_information_schema: Any = Nonecomplete_criterion: str | None = Noneterminate_criterion: str | None = None- error_code_mapping: dict[str, str] | None = None# Whether to state which criterion wins when both hold. Scoped by the caller to the task type the# measurement covers: on v1's general path the terminate criterion reaches no decision-maker at# all, so "which wins" is not the difference there and a rule written for one population would be@@ -102,30 +101,6 @@ def compose_goal(navigation_goal: str, directives: GoalDirectives) -> str:f"{goal}\n\nIf the completion criterion and the termination criterion both hold at once, ""the completion criterion wins: finish with status=completed.").strip()- if directives.error_code_mapping:- # v1 shows the model these codes in-loop (see the error_code_mapping_str prompt sites), so- # a v1 terminal verdict names its own code. v3 did not, and the codes were instead matched- # on afterwards by the detector — which let a block with no adjudication criteria acquire a- # business code it never reasoned about (SKY-15586).- #- # The exclusion is drawn on OUR side of the line, not around the customer's taxonomy: a- # code must not stand in for a failure of this agent or the browser, because those are- # ours and have to surface uncoded. A site or portal problem MAY carry a code when the- # customer defined one for it -- several such codes exist precisely to trigger a retry,- # and a rule of ours that made them unreachable would break the workflow it was meant to- # protect. The description match is what does the real work.- goal = (- f"{goal}\n\nThe user defined these business outcomes and their descriptions:\n"- f"```\n{json.dumps(directives.error_code_mapping, indent=2)}\n```\n"- "If one of these descriptions is what actually happened, set error_code to exactly "- "that code, on whatever finish status is honest -- choose the status on its own "- "merits, never to make a code fit. Do not return a code the user did not define, and "- "do not stretch a description to cover something it does not say. Never use a code to "- "describe a failure of YOU or the browser -- being stuck, losing track of which page "- "you are on, running out of steps, or simply not managing the task are ours to "- "report, so finish those WITHOUT an error_code. A problem with the SITE may take a "- "code when the user defined one whose description names that problem."- ).strip()if directives.framing:goal = f"{goal}\n\n{directives.framing}".strip()if directives.block_context_section:diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex d08ea2d7a..323a1486a 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -496,14 +496,6 @@ class LoopOutcome:# prefix on `reason`; `reason` itself is customer-facing text (see `_guard_verdict`).guard: str | None = Noneextracted_output: Any = None- # A user-defined error code the MODEL chose when finishing, drawn from the task's- # error_code_mapping. Only ever set on a deliberate finish; None means the model was offered codes- # and picked none, or was never offered any (the two are distinguished by error_codes_offered).- error_code: str | None = None- # Whether the finish tool exposed the customer's codes at all. Lets the caller tell "the model- # declined to name a code" from "the model was never asked", so a post-hoc detector can stay out- # of the way of a deliberate choice without also going silent on tasks that never had one.- error_codes_offered: bool = False# The raw budget-cap string (e.g. "max_turns (40) reached") that granted this run its one final# observed turn, carried on whatever outcome the final turn produces — a finish verdict or, if# the model didn't finish, the honest budget_exhausted exit. None for a run that never tripped a cap.@@ -2135,7 +2127,6 @@ FINISH_STATUS_TAXONOMY = (def make_finish_tool(page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,- error_code_mapping: dict[str, str] | None = None,max_settle_deferrals: int = DEFAULT_MAX_SETTLE_DEFERRALS,should_cancel: Callable[[], Awaitable[bool]] | None = None,deadline_at: float | None = None,@@ -2440,9 +2431,6 @@ def make_finish_tool("status": "failed" if action == "fail" else "terminated","reason": f"goal check: {verdict.bounded_missing}","extracted_output": None,- "error_code": None,- # The model was offered codes for its own verdict, not for this one, so it declined nothing.- "error_codes_offered": False,"goal_check_ended": True,},)@@ -2542,29 +2530,12 @@ def make_finish_tool("is right. If it is -- if there is nothing here that advances the goal you were ""given -- finish again with the same status and the verdict will stand.")- raw_code = args.get("error_code")- # isinstance first: a model can answer with a non-string (a list, a number), and `in` against- # a dict would raise TypeError on an unhashable one and take the whole finish down.- chosen_code = raw_code if isinstance(raw_code, str) and raw_code in (error_code_mapping or {}) else None- if error_code_mapping:- # The A/B and the ramp read need to split "was a code offered" from "did the model take- # one", and a dropped invented code must not vanish silently -- filter_to_user_defined_codes- # returns its dropped set for exactly this reason and every other caller logs it.- LOG.info(- "taskv3 finish user-defined error code",- status=status,- chosen_error_code=chosen_code,- declined=chosen_code is None and raw_code is None,- dropped_error_code=raw_code if chosen_code is None and raw_code is not None else None,- )return ToolResult.ok(content="Task attempt ended. No further actions are permitted.",data={"status": status,"reason": args.get("reason") or "","extracted_output": args.get("extracted_output"),- "error_code": chosen_code,- "error_codes_offered": bool(error_code_mapping),},)@@ -2577,29 +2548,6 @@ def make_finish_tool("status": {"type": "string", "enum": ["completed", "failed", "terminated"]},"reason": {"type": "string", "maxLength": 2000},"extracted_output": {"description": "Structured output requested by the goal, if any."},- # Offered ONLY when the task configured codes, and enum-bound to those keys: a task- # without a mapping keeps today's exact finish schema, and a model with a mapping- # cannot invent a code the customer never defined.- **(- {- "error_code": {- "type": "string",- "enum": sorted(error_code_mapping),- "description": (- "Set when one of these descriptions is what actually happened, on "- "whatever finish status is honest — choose the status on its own "- "merits, never to make a code fit. Never use a code to describe a "- "failure of you or the browser: being stuck, losing track of which "- "page you are on, running out of steps, or simply not managing the "- "task are reported without a code. A problem with the SITE may take "- "a code when the user defined one whose description names that "- "problem."- ),- }- }- if error_code_mapping- else {}- ),},"required": ["status", "reason"],},@@ -4358,8 +4306,6 @@ async def run_agent_tool_loop(status=data.get("status", "completed"),reason=data.get("reason", ""),extracted_output=data.get("extracted_output"),- error_code=data.get("error_code"),- error_codes_offered=bool(data.get("error_codes_offered")),goal_check_ended=bool(data.get("goal_check_ended")),# The model's own verdict wins whether or not it landed on the granted final turn;# cap_trip just records the fact that a cap forced this to be the last turn.diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 84282b3ab..373cffb9c 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -4257,18 +4257,12 @@ async def test_execute_task_v3_a_vetoed_completion_is_not_attributed_to_a_missin@pytest.mark.asyncio-async def test_execute_task_v3_actually_delivers_the_codes_to_the_loop_and_the_goal(+async def test_execute_task_v3_keeps_the_codes_out_of_the_loop_and_the_goal(monkeypatch: pytest.MonkeyPatch,) -> None:- # Wiring test. Without it the whole feature can be deleted -- the mapping pass-through, the engine- # kwarg, or the goal block -- and every other test here still passes, because they call- # make_finish_tool directly or inject a hand-built LoopOutcome. This is the only one that fails if- # the codes never reach the model.+ # v3 never shows the model the customer's codes: they reach neither the loop nor the goal, and+ # the detector after the loop is what assigns one.mapping = {"COVERAGE_NOT_ACTIVE": "The member has no active plan today."}- monkeypatch.setattr(- "skyvern.forge.agent.app.AGENT_FUNCTION.resolve_task_v3_error_code_choice",- AsyncMock(return_value=True),- )outcome = LoopOutcome(status="completed", reason="ok", billable_actions=[])block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping=mapping)_step, _task, loop_mock, _post = await _run_execute_task_v3(@@ -4279,236 +4273,23 @@ async def test_execute_task_v3_actually_delivers_the_codes_to_the_loop_and_the_gdata_extraction_goal=None,extracted_information_schema=None,)- assert loop_mock.await_args.kwargs["error_code_mapping"] == mapping-- goal = loop_mock.await_args.kwargs["goal"]- assert "COVERAGE_NOT_ACTIVE" in goal- assert "The member has no active plan today." in goal- # The rule is pinned as content, not left to survive a prompt edit by luck. It is drawn on OUR- # side of the line: our own failures may not wear a code, while a site problem the customer- # defined a code for still can.- assert "failure of YOU or the browser" in goal- assert "problem with the SITE may take a code" in goal- # The example has to name OUR disorientation, not the page's state: "losing the page" sat- # directly opposite a customer code for a tab that could not render because of a portal-side- # failure -- the exact code the rule above must leave reachable.- assert "losing track of which page you are on" in goal- assert "losing the page" not in goal---async def test_execute_task_v3_flag_off_keeps_the_codes_out_of_the_loop(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # Off-state must be byte-identical to before this feature existed: no mapping reaches the loop,- # nothing is added to the goal, and error_codes_offered stays False so every downstream branch- # falls through to the detector exactly as today.- mapping = {"COVERAGE_NOT_ACTIVE": "The member has no active plan today."}- monkeypatch.setattr(- "skyvern.forge.agent.app.AGENT_FUNCTION.resolve_task_v3_error_code_choice",- AsyncMock(return_value=False),- )- outcome = LoopOutcome(status="completed", reason="ok", billable_actions=[])- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping=mapping)- _step, _task, loop_mock, _post = await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping=mapping,- data_extraction_goal=None,- extracted_information_schema=None,- )- assert loop_mock.await_args.kwargs["error_code_mapping"] is None+ assert "error_code_mapping" not in loop_mock.await_args.kwargsassert "COVERAGE_NOT_ACTIVE" not in loop_mock.await_args.kwargs["goal"]---async def test_execute_task_v3_persists_a_chosen_code_on_a_completed_finish(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # A named code is an answer about WHAT HAPPENED, so it survives whatever status the run reached.- # Discarding it on `completed` would throw away the business-outcome verdict this change exists- # to capture -- and the prompt actively tells the model to choose its status on the run's merits,- # so it steers exactly that class of run here.- detect_mock = AsyncMock(return_value=[])- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="completed",- reason="the member has no active plan today",- billable_actions=[],- error_code="COVERAGE_NOT_ACTIVE",- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- )- detect_mock.assert_not_awaited()- (persisted,) = errors_update.await_args.kwargs["errors"]- assert persisted["error_code"] == "COVERAGE_NOT_ACTIVE"- # failure_reason is None on a clean completion, so the model's own finish reason is the account.- assert persisted["reasoning"] == "the member has no active plan today"---async def test_execute_task_v3_prefers_the_models_own_code_over_the_detector(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # SKY-15586. Once the model is shown the codes it finishes deliberately, so ITS verdict is the- # answer -- re-running the detector would put a guess back on top of a choice.- detect_mock = AsyncMock(return_value=[])- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="terminated",- reason="no active plan",- billable_actions=[],- error_code="COVERAGE_NOT_ACTIVE",- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "no plan"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "no plan"},- data_extraction_goal=None,- extracted_information_schema=None,- )- detect_mock.assert_not_awaited()- (persisted,) = errors_update.await_args.kwargs["errors"]- assert persisted["error_code"] == "COVERAGE_NOT_ACTIVE"- assert persisted["confidence_float"] == 1.0---async def test_execute_task_v3_terminal_block_that_names_no_code_gets_none(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # A model that was offered the codes and named none must end with NO business code at all. This- # is the case the detector cannot get right on its own: it sees a page, not the question, so on a- # block whose terminal reason none of the codes describes it can still match one from the page.- detect_mock = AsyncMock(- return_value=[SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, reasoning="")]- )- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="terminated",- reason="the control this block needs was never reachable",- billable_actions=[],- error_code=None,- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Log out", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- )- detect_mock.assert_not_awaited()- errors_update.assert_not_awaited()---async def test_execute_task_v3_declining_a_code_holds_on_the_failed_path_too(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # The gate is error_codes_offered, NOT status. Honoring the choice only on terminated would leave- # the failed path running the detector over `failure_reason` -- which on a deliberate finish is- # the model's own free text, now written with the code descriptions in front of it. The- # detector's last resort substring-matches a description with no negation handling, so a model- # explaining "this was NOT <description>" would persist that code at confidence 1.0: the very- # defect this PR exists to fix.- detect_mock = AsyncMock(- return_value=[SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, reasoning="")]- )- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="failed",- reason="the coverage tab was present, so this was not a portal-side failure",- billable_actions=[],- error_code=None,- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- )- detect_mock.assert_not_awaited()- errors_update.assert_not_awaited()---async def test_execute_task_v3_persists_a_model_chosen_code_on_a_failed_outcome(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # A code is about what happened, not about which status was reached. If only terminated could- # carry one, a mapped task ending in a model-declared failure would end with no code at all --- # the detector is skipped whenever codes were offered.- detect_mock = AsyncMock(return_value=[])- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="failed",- reason="no active plan on file",- billable_actions=[],- error_code="COVERAGE_NOT_ACTIVE",- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- )- detect_mock.assert_not_awaited()- (persisted,) = errors_update.await_args.kwargs["errors"]- assert persisted["error_code"] == "COVERAGE_NOT_ACTIVE"+ assert "The member has no active plan today." not in loop_mock.await_args.kwargs["goal"]@pytest.mark.asyncioasync def test_execute_task_v3_vetoed_completion_still_reaches_the_detector(monkeypatch: pytest.MonkeyPatch,) -> None:- # A completion the gate vetoes is demoted to failed, but the MODEL said "completed" -- it was- # never asked which business outcome explains a failure, so its silence is not a deliberate- # decline and must not suppress the detector. Gating on task_status alone would swallow it.+ # A completion the gate vetoes is demoted to failed, and the detector runs on the demoted status,+ # not on the model's own "completed".detected = [SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, reasoning="")]detect_mock = AsyncMock(return_value=detected)monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)errors_update = AsyncMock()monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="completed",- reason="done",- billable_actions=[],- error_code=None,- error_codes_offered=True,- )+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})await _run_execute_task_v3(monkeypatch,@@ -4523,89 +4304,6 @@ async def test_execute_task_v3_vetoed_completion_still_reaches_the_detector(assert errors_update.await_args.kwargs["errors"] == [{"error_code": "COVERAGE_NOT_ACTIVE"}]-async def test_execute_task_v3_scrubs_a_registered_secret_from_the_chosen_codes_reasoning(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # task.errors is aggregated into the workflow run's top-level errors[] and goes out over the- # customer's webhook, so this string LEAVES the system. The sibling decision row built from the- # same outcome.reason is already scrubbed; a code's reasoning that skipped the pass would publish- # a secret the row next to it redacts.- monkeypatch.setattr(- "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled", lambda *_a, **_k: True- )- monkeypatch.setattr(- "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run",- lambda *_a, **_k: {"sk4829137765"},- )- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", AsyncMock(return_value=[]))- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="terminated",- reason="the portal rejected the keysk4829137765I was given",- billable_actions=[],- error_code="COVERAGE_NOT_ACTIVE",- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- )- (persisted,) = errors_update.await_args.kwargs["errors"]- assert "sk4829137765" not in persisted["reasoning"]- assert REDACTED_SECRET_PLACEHOLDER in persisted["reasoning"]---async def test_execute_task_v3_caps_the_chosen_codes_reasoning_after_redacting_it(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # The two sibling reasoning persists (action row, decision row) both cap at- # _TASKV3_REASONING_MAX_CHARS; the code's reasoning is the only one that reaches the customer's- # webhook and was the only one uncapped.- # The secret straddles the cap boundary, so this also pins the ORDER: redact, then truncate.- # Truncating first would cut the secret in half, leaving a fragment the redactor can no longer- # match, and publish it.- from skyvern.forge import agent as agent_mod-- monkeypatch.setattr(- "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled", lambda *_a, **_k: True- )- monkeypatch.setattr(- "skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run",- lambda *_a, **_k: {"sk4829137765"},- )- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", AsyncMock(return_value=[]))- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- straddling = "a" * (agent_mod._TASKV3_REASONING_MAX_CHARS - 5) + "sk4829137765" + "b" * 4000- outcome = LoopOutcome(- status="terminated",- reason=straddling,- billable_actions=[],- error_code="COVERAGE_NOT_ACTIVE",- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- )- (persisted,) = errors_update.await_args.kwargs["errors"]- assert len(persisted["reasoning"]) == agent_mod._TASKV3_REASONING_MAX_CHARS- assert "sk48" not in persisted["reasoning"]--@pytest.mark.asyncioasync def test_execute_task_v3_scrubs_a_registered_secret_from_the_webhook_bound_failure_reason(monkeypatch: pytest.MonkeyPatch,@@ -4671,9 +4369,8 @@ async def test_execute_task_v3_redacts_failure_reason_before_any_consumer_reads_async def test_execute_task_v3_scrubs_a_registered_secret_from_detector_written_errors(monkeypatch: pytest.MonkeyPatch,) -> None:- # The fourth reasoning persist in this method. The detector also reads the page, so redacting- # its input is not enough -- a secret typed into the form can come back in its reasoning, and- # task.errors leaves over the customer's webhook exactly like the chosen-code branch does.+ # The detector also reads the page, so redacting its input is not enough -- a secret typed into+ # the form can come back in its reasoning, and task.errors leaves over the customer's webhook.monkeypatch.setattr("skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled", lambda *_a, **_k: True)@@ -4802,59 +4499,18 @@ async def test_execute_task_v3_leaves_failure_reason_byte_identical_when_redactiassert loop_mock.update_task_kwargs["failure_reason"] == raw-async def test_execute_task_v3_records_the_models_own_account_not_the_gate_veto(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # The one path where failure_reason and the model's finish reason disagree: the gate demotes a- # completion to failed and writes its own text, which explains the DEMOTION, not why the model- # named this code. Reading failure_reason first would file the business code under "the gate- # rejected it" and lose the only account of the code.- detect_mock = AsyncMock(return_value=[])- monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)- errors_update = AsyncMock()- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="completed",- reason="the member has no active plan today",- billable_actions=[],- error_code="COVERAGE_NOT_ACTIVE",- error_codes_offered=True,- )- block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})- await _run_execute_task_v3(- monkeypatch,- outcome,- task_block=block,- error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},- data_extraction_goal=None,- extracted_information_schema=None,- completion_gate_vetoes=True,- )- (persisted,) = errors_update.await_args.kwargs["errors"]- assert persisted["error_code"] == "COVERAGE_NOT_ACTIVE"- assert persisted["reasoning"] == "the member has no active plan today"- assert "completion gate" not in persisted["reasoning"]--@pytest.mark.asyncioasync def test_execute_task_v3_leaves_unasked_failures_to_the_detector(monkeypatch: pytest.MonkeyPatch,) -> None:- # The scope guard: every v1 caller and every v3 task without a mapping has error_codes_offered- # False, and those runs must keep exactly today's behavior -- the detector still runs.+ # The scope guard: a failed v3 run on a task with a mapping hands the code to the detector,+ # exactly as v1's fail_task does.detected = [SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, reasoning="")]detect_mock = AsyncMock(return_value=detected)monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)errors_update = AsyncMock()monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)- outcome = LoopOutcome(- status="failed",- reason="the page never loaded",- billable_actions=[],- error_code=None,- error_codes_offered=False, # never asked- )+ outcome = LoopOutcome(status="failed", reason="the page never loaded", billable_actions=[])block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})await _run_execute_task_v3(monkeypatch,diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex dd7a4e4a6..6c4bbd712 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -1602,38 +1602,6 @@ async def test_terminal_log_merges_a_fully_populated_telemetry_without_collidingassert record["form_ever_armed"] is True-async def test_engine_forwards_the_error_code_mapping_to_the_finish_tool(monkeypatch: pytest.MonkeyPatch) -> None:- # The engine hop is the one link no other test covers: the agent-side wiring test mocks the loop,- # the loop tests call make_finish_tool directly, and the agent tests hand-build a LoopOutcome. Drop- # this pass-through and the codes silently stop reaching the model in production.- from skyvern.forge.taskv3 import engine as engine_mod- from skyvern.forge.taskv3.loop import LoopOutcome-- finish_kwargs: dict[str, Any] = {}-- async def fake_loop(**kwargs: Any) -> LoopOutcome:- return LoopOutcome(status="completed", reason="ok")-- real_make_finish_tool = engine_mod.make_finish_tool-- def capturing_make_finish_tool(*args: Any, **kwargs: Any) -> Any:- finish_kwargs.update(kwargs)- return real_make_finish_tool(*args, **kwargs)-- monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)- monkeypatch.setattr(engine_mod, "make_finish_tool", capturing_make_finish_tool)-- mapping = {"COVERAGE_NOT_ACTIVE": "The member has no active plan today."}- await run_task_v3_agent_loop(- page_provider=_fixed_page_provider(_FakePage()),- llm_caller=_ScriptedCaller([]),- goal="check coverage",- error_code_mapping=mapping,- )- assert finish_kwargs["error_code_mapping"] == mapping--def _advertised(caller: _ScriptedCaller) -> set[str]:"""The tool names the MODEL was actually offered, read off the request the caller built."""return {t["function"]["name"] for t in (caller.sent_tools or [])}diff --git a/tests/unit/test_taskv3_goal_composition.py b/tests/unit/test_taskv3_goal_composition.pyindex 4c56c42ce..3392ed460 100644--- a/tests/unit/test_taskv3_goal_composition.py+++ b/tests/unit/test_taskv3_goal_composition.py@@ -72,7 +72,6 @@ _DIRECTIVE_VALUES: dict[str, tuple[Any, Any]] = {"extracted_information_schema": (None, {"type": "object", "properties": {"ref": {"type": "string"}}}),"complete_criterion": (None, "the confirmation page is showing"),"terminate_criterion": (None, "the form says the role is closed"),- "error_code_mapping": (None, {"ROLE_CLOSED": "the posting is no longer accepting submissions"}),"criteria_precedence": (False, True),"framing": ("", "This is one block of a larger workflow."),"block_context_section": ("", "<workflow_context>\nblocks: one, two\n</workflow_context>"),@@ -84,7 +83,7 @@ _DIRECTIVE_VALUES: dict[str, tuple[Any, Any]] = {def test_compose_goal_is_byte_identical_to_the_inline_patching_it_replaced(navigation_goal: str, mask: tuple[int, ...]) -> None:- # Every on/off combination of the eight directives, against both an empty and a non-empty+ # Every on/off combination of the seven directives, against both an empty and a non-empty# navigation goal. The empty one matters: the first directive's .strip() is what decides# whether the goal opens with a blank line, and that only shows up when the base is "".chosen = {name: options[bit] for (name, options), bit in zip(_DIRECTIVE_VALUES.items(), mask)}@@ -101,7 +100,6 @@ def _goal_as_agent_py_built_it(complete_criterion: str | None,terminate_criterion: str | None,criteria_precedence: bool,- error_code_mapping: dict[str, str] | None,framing: str,block_context_section: str,) -> str:@@ -142,19 +140,6 @@ def _goal_as_agent_py_built_it(f"{goal}\n\nIf the completion criterion and the termination criterion both hold at once, ""the completion criterion wins: finish with status=completed.").strip()- if error_code_mapping:- goal = (- f"{goal}\n\nThe user defined these business outcomes and their descriptions:\n"- f"```\n{json.dumps(error_code_mapping, indent=2)}\n```\n"- "If one of these descriptions is what actually happened, set error_code to exactly "- "that code, on whatever finish status is honest -- choose the status on its own "- "merits, never to make a code fit. Do not return a code the user did not define, and "- "do not stretch a description to cover something it does not say. Never use a code to "- "describe a failure of YOU or the browser -- being stuck, losing track of which page "- "you are on, running out of steps, or simply not managing the task are ours to "- "report, so finish those WITHOUT an error_code. A problem with the SITE may take a "- "code when the user defined one whose description names that problem."- ).strip()if framing:goal = f"{goal}\n\n{framing}".strip()if block_context_section:diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex c2f279335..75625e034 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -9164,81 +9164,16 @@ async def test_canonical_loop_cleared_by_positive_probe_mismatch_on_a_failed_calassert [e for e in logs if e.get("event") == CANONICAL_LOOP_EVENT] == []-_COVERAGE_CODES = {- "COVERAGE_NOT_ACTIVE": "The coverage tab loaded but the member has no active plan today.",- "COVERAGE_TAB_UNAVAILABLE": "The coverage tab could not be rendered because of a portal-side failure.",-}---async def test_finish_offers_configured_codes_and_carries_a_deliberate_choice() -> None:- # v1 shows the model the user's codes in-loop, so a v1 terminal verdict names its own code. v3- # did not, and codes were matched on afterwards instead -- so a block that never reasoned about- # coverage could still be handed a coverage outcome (SKY-15586). The model must be able to say it.- finish = make_finish_tool(error_code_mapping=_COVERAGE_CODES)- assert finish.parameters["properties"]["error_code"]["enum"] == sorted(_COVERAGE_CODES)-- script = [[("finish", {"status": "terminated", "reason": "no active plan", "error_code": "COVERAGE_NOT_ACTIVE"})]]- outcome, _ = await _run(script, [finish])- assert outcome.status == "terminated"- assert outcome.error_code == "COVERAGE_NOT_ACTIVE"- assert outcome.error_codes_offered is True--@pytest.mark.asyncio-async def test_a_block_with_no_business_outcome_acquires_no_code() -> None:- # The load-bearing case: a block that reaches a terminal state for a reason none of the codes- # describes must end with NO code. Today nothing asks the model, so a detector matches one on- # from the page afterwards; once asked, a verdict that names none must REPORT none -- and stay- # distinguishable from a task that was never offered any.- finish = make_finish_tool(error_code_mapping=_COVERAGE_CODES)- script = [[("finish", {"status": "terminated", "reason": "could not reach the logout control"})]]- outcome, _ = await _run(script, [finish])- assert outcome.error_code is None- assert outcome.error_codes_offered is True # asked and declined -- not merely unasked---async def test_a_code_the_user_never_defined_is_refused() -> None:- # Same guarantee filter_to_user_defined_codes gives the step engine: only configured codes may- # reach the customer's webhooks, whatever the model returns.- finish = make_finish_tool(error_code_mapping=_COVERAGE_CODES)- script = [[("finish", {"status": "terminated", "reason": "made one up", "error_code": "INVENTED_CODE"})]]- outcome, _ = await _run(script, [finish])- assert outcome.error_code is None---async def test_a_task_without_configured_codes_keeps_todays_finish_schema() -> None:- # Out-of-scope guard: tasks with no mapping must see byte-identical finish parameters, so this- # change cannot alter behavior for the overwhelming majority of runs.+async def test_the_finish_schema_offers_no_error_code() -> None:+ # The customer's codes are assigned by the detector after the loop, never by the model, so the+ # finish tool exposes no code field and ignores one a model sends anyway.assert "error_code" not in make_finish_tool().parameters["properties"]- assert make_finish_tool().parameters == make_finish_tool(error_code_mapping=None).parameters- script = [[("finish", {"status": "terminated", "reason": "done"})]]+ script = [[("finish", {"status": "terminated", "reason": "done", "error_code": "COVERAGE_NOT_ACTIVE"})]]outcome, _ = await _run(script, [make_finish_tool()])- assert outcome.error_code is None- assert outcome.error_codes_offered is False # never asked -- the detector must stay in charge---async def test_a_code_is_accepted_on_a_failed_finish_too() -> None:- # The schema and the goal must agree that a code is about WHAT HAPPENED, not about which status- # was reached. A schema saying "terminated only" would both re-create the pressure to terminate- # in order to fit a code, and -- since the detector is now skipped whenever codes were offered --- # leave a model-declared failure with no user-defined code at all.- finish = make_finish_tool(error_code_mapping=_COVERAGE_CODES)- # Assert the absence of ONLY-ness, not of the word: accurate future wording may well mention a- # status, and pinning the word would block it.- assert "ONLY with status" not in finish.parameters["properties"]["error_code"]["description"]- # The twin of the goal text, and it drifts the same way: an example of OUR failure that reads- # as a broken page would tell the model to withhold the very code the site problem earns.- assert "losing the page" not in finish.parameters["properties"]["error_code"]["description"]-- script = [[("finish", {"status": "failed", "reason": "no active plan", "error_code": "COVERAGE_NOT_ACTIVE"})]]- outcome, _ = await _run(script, [finish])- assert outcome.status == "failed"- assert outcome.error_code == "COVERAGE_NOT_ACTIVE"+ assert outcome.status == "terminated"+ assert outcome.reason == "done"@pytest.mark.asyncio@@ -12017,26 +11952,6 @@ async def test_goal_check_honors_a_cancellation_that_lands_during_the_judge_callassert outcome.status == "canceled"-async def test_a_judge_ended_run_leaves_error_code_detection_to_the_detector() -> None:- # The model never saw codes for a status the judge chose, so it cannot have declined one.- goal_check, _calls = _scripted_goal_check("not_achieved", "not_achieved")- tools = [- make_finish_tool(- activity=ActivityRecency(),- goal_check=goal_check,- goal_check_enforce=True,- error_code_mapping={"OUT_OF_STOCK": "the item is unavailable"},- )- ]-- outcome, _ = await _run([[_COMPLETED], [_COMPLETED]], tools)-- assert outcome.status == "failed"- assert outcome.error_code is None- assert outcome.error_codes_offered is False--@pytest.mark.asyncioasync def test_goal_check_that_raises_accepts_the_completion() -> None:async def goal_check() -> GoalVerdict: