Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Let Task V3 choose its own user-defined error code instead of having one matched on (#8443)
pedrohsdb543464883497
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex a545871ab..9445616cc 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -1498,6 +1498,42 @@ class ForgeAgent:goal = (f"{goal}\n\nIf this becomes true, stop and finish with status=terminated: {task.terminate_criterion}").strip()+ 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,+ )+ if offer_error_codes and task.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(task.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()page_free_validation = bool(task_block is not Noneand task.task_type == TaskType.validation@@ -1998,6 +2034,7 @@ 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,page_free=page_free_validation,page_fingerprint=_page_fingerprint,@@ -2111,6 +2148,14 @@ class ForgeAgent:# it was, and a finish the loop rejected mid-run never persists at all. A verdict-less death# (budget_exhausted/loop_error) records as a FAILED terminate carrying the outcome reason —# those are the runs users most need step details for. Cancellation persists nothing.+ # One lookup for every model-authored string this method persists. Kept out of the branches+ # below because they must agree: a path that skipped it would publish a secret the sibling+ # path redacts.+ run_secrets = (+ app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run(task.workflow_run_id)+ if app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled(task.workflow_run_id)+ else app.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts()+ )if outcome.status in ("completed", "terminated", "failed", "budget_exhausted", "loop_error"):with contained_effect("task_v3 terminal decision persist", task_id=task.task_id):decision_reason = outcome.reason or ""@@ -2125,13 +2170,8 @@ class ForgeAgent:else "completed with no extracted output for a data-extraction goal")decision_reason = f"{decision_reason} — {rejection}" if decision_reason else rejection- decision_secrets = (- app.WORKFLOW_CONTEXT_MANAGER.get_secret_values_for_run(task.workflow_run_id)- if app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled(task.workflow_run_id)- else app.WORKFLOW_CONTEXT_MANAGER.runtime_secret_values_for_artifacts()- )- if decision_secrets:- decision_reason = redact_secrets_from_text(decision_reason, decision_secrets)+ if run_secrets:+ decision_reason = redact_secrets_from_text(decision_reason, run_secrets)decision_reason = decision_reason[:_TASKV3_REASONING_MAX_CHARS]decision_screenshot_id: str | None = Noneif not page_free_validation:@@ -2282,9 +2322,53 @@ class ForgeAgent:failure_category = [{"category": "BUDGET_EXHAUSTED", "confidence_float": 1.0, "reasoning": outcome.cap_trip}]- if task.error_code_mapping and task_status in (TaskStatus.failed, TaskStatus.terminated):- # Same user-defined error detection the step engine runs on failure, so workflows that- # consume configured error codes keep that contract on v3.+ # 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)+ 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.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 12a9ba3b3..5f93709ca 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -898,6 +898,13 @@ class AgentFunction:async def resolve_task_v3_extra_guidance(self, *, task: Task, organization: Organization) -> 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). Cloud+ # overrides behind a flag; False keeps codes out of the loop entirely, which makes the whole+ # feature byte-identical to before it existed.+ async def resolve_task_v3_error_code_choice(self, *, task: Task, organization: Organization) -> bool:+ return False+async def record_run_duration(self,run_type: str,diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex 4c11d92ff..24b7df457 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -212,6 +212,9 @@ 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,@@ -317,6 +320,7 @@ async def run_task_v3_agent_loop(verification_blocker = Nonefinish_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/loop.py b/skyvern/forge/taskv3/loop.pyindex 55f8cccf3..d025a515a 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -96,6 +96,14 @@ class LoopOutcome:status: Literal["completed", "failed", "terminated", "budget_exhausted", "loop_error", "canceled"]reason: strextracted_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.@@ -1115,6 +1123,7 @@ def _append_skipped_tool_results(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,@@ -1339,12 +1348,29 @@ def make_finish_tool("positive confirmation at all, finish with status=failed again 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),},)@@ -1360,6 +1386,29 @@ 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"],},@@ -2521,6 +2570,8 @@ 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")),# 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.cap_trip=cap_trip_pending if final_turn_granted else None,diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 9b144ecd0..ed2de4391 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -2482,6 +2482,375 @@ async def test_execute_task_v3_detects_user_defined_errors_on_failure(detect_mock.assert_not_awaited()+async def test_execute_task_v3_actually_delivers_the_codes_to_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.+ 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(+ 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"] == 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 "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"})])+ 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"})])+ 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"+++async 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.+ detected = [SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"})]+ 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,+ )+ 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,+ )+ detect_mock.assert_awaited_once()+ 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_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"]+++async 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 -- ~15.9k USER_DEFINED_ERROR failures a week across 18 orgs (08-27 to+ # 09-03) -- must keep exactly today's behavior.+ detected = [SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"})]+ 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+ )+ 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_awaited_once()+ assert errors_update.await_args.kwargs["errors"] == [{"error_code": "COVERAGE_NOT_ACTIVE"}]++@pytest.mark.asyncioasync def test_execute_task_v3_router_selected_data_only_validation_goes_page_free(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex f1d31c47a..3b5236aae 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -1295,3 +1295,35 @@ async def test_terminal_log_carries_duration_and_block_type() -> None:)terminal = [e for e in logs if e.get("event") == "taskv3 engine loop finished"]assert terminal[0]["block_type"] is None # bare task: no block context+++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"] == mappingdiff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex 6d56bb963..31c4ac953 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -8153,3 +8153,80 @@ async def test_canonical_loop_cleared_by_positive_probe_mismatch_on_a_failed_calassert outcome.status == "failed"assert len(touches) == 4assert [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+++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.+ 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"})]]+ 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"