Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-12811 Let the copilot keep exploring until it finds every value the request asked for (#7628)
Andrew Neilson169407c25754
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex c31386d2b..0c733dd7d 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -37,6 +37,7 @@ from skyvern.forge.sdk.copilot.output_extraction_plan import (output_path_segments,)from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget+from skyvern.forge.sdk.copilot.request_slots import is_canonical_request_slot_pathfrom skyvern.forge.sdk.copilot.runtime import ScoutedInputCorrespondencefrom skyvern.utils.strings import escape_code_fences@@ -2507,16 +2508,41 @@ def _table_group_read_lines(return lines+def _returned_output_segments_by_binding(+ bindings: list[LiveReadBinding],+) -> dict[str, tuple[tuple[str, bool], ...]]:+ """Segments each extracted value is returned under, keyed by output path. A slot identity is a+ digest, so the matched label names the field and an already-taken name is suffixed."""+ segments_by_path: dict[str, tuple[tuple[str, bool], ...]] = {}+ used_names: set[str] = set()+ for binding in bindings:+ if not (is_canonical_request_slot_path(binding.output_path) and binding.relation_label.strip()):+ segments = output_path_segments(binding.output_path)+ used_names.update(name for name, _is_array in segments[1:])+ segments_by_path[binding.output_path] = segments+ continue+ base = _slug(binding.relation_label)+ name = base+ suffix = 2+ while name in used_names:+ name = f"{base}_{suffix}"+ suffix += 1+ used_names.add(name)+ segments_by_path[binding.output_path] = (("output", False), (name, False))+ return segments_by_path++def synthesize_extraction_suffix(plan: RequestedOutputExtractionPlan) -> SynthesizedExtractionSuffix | None:if not plan.live_reads:return Nonelines: list[str] = []return_root = _ExtractionReturnNode()scalar_bindings = [binding for binding in plan.live_reads if binding.kind == LiveReadKind.KEY_VALUE]+ segments_by_path = _returned_output_segments_by_binding(scalar_bindings)for index, binding in enumerate(scalar_bindings):variable = f"_extraction_value_{index}"lines.extend(_key_value_scalar_read_statements(binding, variable, guard_empty=False))- _set_return_expression(return_root, output_path_segments(binding.output_path), variable)+ _set_return_expression(return_root, segments_by_path[binding.output_path], variable)table_groups: dict[tuple[str, int, tuple[tuple[str, bool], ...]], list[LiveReadBinding]] = {}for binding in plan.live_reads:diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 45917b73a..481f7f8b2 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -2353,9 +2353,49 @@ def _pre_run_gated_completion_criteria(ctx: AgentContext) -> tuple[CompletionCri)+def _floor_rekeyed_requested_output_paths(ctx: AgentContext) -> set[str]:+ """Identity of runtime-output criteria whose slot rekey cleared ``output_path``; the rekey+ preserves it in ``floor_rekeyed_from_path``, and without it they vanish from the requested set."""+ return {+ criterion.floor_rekeyed_from_path+ for criterion in _pre_run_gated_completion_criteria(ctx)+ if criterion.requested_output_floor_rekeyed+ and criterion.floor_rekeyed_from_path+ and criterion.kind == "outcome"+ and criterion.level != "definition"+ and not criterion.method_mandated+ and criterion.requested_output_evidence_source == "runtime_output"+ }+++def pre_run_gated_outputs_without_path(ctx: AgentContext) -> tuple[CompletionCriterion, ...]:+ """Pre-run-gated runtime-output criteria carrying neither an ``output_path`` nor rekey+ provenance, so nothing identifies them and they would drop from the gate unseen."""+ return tuple(+ criterion+ for criterion in _pre_run_gated_completion_criteria(ctx)+ if criterion.kind == "outcome"+ and criterion.level != "definition"+ and not criterion.method_mandated+ and criterion.requested_output_evidence_source == "runtime_output"+ and not criterion.output_path+ and not (criterion.requested_output_floor_rekeyed and criterion.floor_rekeyed_from_path)+ )++def _requested_output_paths_for_ctx(ctx: AgentContext) -> set[str]:pre_run_gated_paths = set(requested_output_paths(_pre_run_gated_completion_criteria(ctx)))- paths = set(pre_run_gated_paths)+ unregisterable = pre_run_gated_outputs_without_path(ctx)+ if unregisterable:+ LOG.warning(+ "copilot_pre_run_gated_output_criterion_without_path",+ count=len(unregisterable),+ criterion_ids=[criterion.id for criterion in unregisterable],+ outcomes=[criterion.outcome[:80] for criterion in unregisterable],+ floor_rekeyed=[criterion.requested_output_floor_rekeyed for criterion in unregisterable],+ floor_rekeyed_from_path=[criterion.floor_rekeyed_from_path for criterion in unregisterable],+ )+ paths = set(pre_run_gated_paths) | _floor_rekeyed_requested_output_paths(ctx)repair_context = ctx.last_code_authoring_repair_contextif repair_context is not None:paths.update(@@ -2389,6 +2429,18 @@ def _requested_output_coverage_tokens(ctx: AgentContext) -> dict[str, frozenset[tokens_by_path.setdefault(path, set()).update(token for token in leaf_tokens if token not in _COVERAGE_GENERIC_TOKENS)+ # A rekeyed path is an opaque digest whose leaf would never match the page and would false-match+ # on "request"/"slot", so coverage keys on the outcome text instead.+ for criterion in _pre_run_gated_completion_criteria(ctx):+ if not (criterion.requested_output_floor_rekeyed and criterion.floor_rekeyed_from_path):+ continue+ outcome_tokens = {+ token+ for token in COVERAGE_TOKEN_RE.findall((criterion.outcome or "").lower())+ if token not in _COVERAGE_GENERIC_TOKENS+ }+ if outcome_tokens:+ tokens_by_path[criterion.floor_rekeyed_from_path] = outcome_tokensreturn {path: frozenset(token for token in tokens if not token.isdigit()) for path, tokens in tokens_by_path.items()}@@ -2430,14 +2482,24 @@ def uncovered_requested_output_paths(ctx: AgentContext) -> set[str]:return {path for path in requested if path not in covered and tokens_by_path.get(path)}+def _effective_requested_output_path(criterion: CompletionCriterion) -> str | None:+ """The path a requested output is known by, falling back to the identity a slot rekey preserved."""+ if criterion.output_path:+ return criterion.output_path+ if criterion.requested_output_floor_rekeyed and criterion.floor_rekeyed_from_path:+ return criterion.floor_rekeyed_from_path+ return None++def _requested_output_labels_by_path(ctx: AgentContext) -> dict[str, tuple[str, ...]]:requested_paths = _requested_output_paths_for_ctx(ctx)labels_by_path: dict[str, tuple[str, ...]] = {}for criterion in _pre_run_gated_completion_criteria(ctx):outcome = criterion.outcome.strip()- if criterion.output_path in requested_paths and outcome:- labels_by_path.setdefault(criterion.output_path, ())- labels_by_path[criterion.output_path] += (outcome,)+ path = _effective_requested_output_path(criterion)+ if path in requested_paths and outcome:+ labels_by_path.setdefault(path, ())+ labels_by_path[path] += (outcome,)return labels_by_path@@ -2464,9 +2526,11 @@ def requested_scalar_output_extraction_plan(ctx: AgentContext) -> RequestedOutpulabels_by_path: dict[str, tuple[str, ...]] = {}for criterion in _pre_run_gated_completion_criteria(ctx):outcome = criterion.outcome.strip()- if criterion.output_path in requested_paths and outcome:- labels_by_path.setdefault(criterion.output_path, ())- labels_by_path[criterion.output_path] += (outcome,)+ path = _effective_requested_output_path(criterion)+ if path in requested_paths and outcome:+ labels_by_path.setdefault(path, ())+ labels_by_path[path] += (outcome,)+ # A path with no label is an underivable field; withholding the plan keeps a clarification legitimate.if set(labels_by_path) != requested_paths:return Nonereturn derive_requested_output_extraction_plan(diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex eb67c7e64..ac56525c0 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -276,6 +276,15 @@ _OUTPUT_FIELD_WORDS = frozenset("amount amounts domain domains name names number numbers owner owners phone phones rate rates specialties specialty ""status statuses taxonomy total totals url urls website websites".split())+# When one of these is followed by "of <noun phrase>" the field is the noun phrase, not the+# quantifier; the head-at-end window below cannot reach a subject that trails the field word.+_OUTPUT_QUANTIFIER_HEAD_WORDS = frozenset(+ "number numbers count counts total totals amount amounts sum sums quantity quantities "+ "average averages percentage percentages proportion proportions share shares".split()+)+# Words that end a quantifier's noun phrase: a scope/time qualifier ("... in the past 7 days") or another+# preposition begins here, so the field name stops before it.+_OUTPUT_PHRASE_BOUNDARY_WORDS = frozenset("in on over during within for per by from since between as at with".split())# Intentionally distinct from enforcement._COVERAGE_GENERIC_TOKENS: this list filters intent prose when# parsing requested-output field names, so it drops phrase-level noise ("each", "profile", "structured");# the coverage list filters path leaf tokens only. Not unified — the consumers differ.@@ -1647,6 +1656,21 @@ def _bind_criterion_to_request_slot(or isinstance(expected_classification, bool)or judgment_truth_condition is not None)+ if rekeyed:+ LOG.info(+ "copilot_request_slot_criterion_rekeyed",+ slot_id=slot.slot_id,+ canonical_path=slot.canonical_path,+ pinability=pinability,+ antecedent_family=antecedent_family,+ has_exact_requirement=has_exact_requirement,+ degraded=degraded,+ rekeyed_reason="degraded" if degraded else "shapeless_valid",+ kind=kind,+ original_output_path=original_output_path,+ requested_output_evidence_source=criterion.requested_output_evidence_source,+ outcome=(criterion.outcome or source_quote or "")[:80],+ )return replace(criterion,id=slot.slot_id,@@ -2190,6 +2214,26 @@ def _clean_requested_output_candidate(segment: str, aliases: dict[str, str] | Noreturn Noneif all(word in _OUTPUT_GENERIC_WORDS for word in normalized_words):return None+ quantifier_index = next(+ (+ index+ for index, word in enumerate(normalized_words)+ if word in _OUTPUT_QUANTIFIER_HEAD_WORDS+ and index + 1 < len(normalized_words)+ and normalized_words[index + 1] == "of"+ ),+ None,+ )+ if quantifier_index is not None:+ subject_words: list[str] = []+ for word, normalized_word in zip(words[quantifier_index + 2 :], normalized_words[quantifier_index + 2 :]):+ if normalized_word in _OUTPUT_PHRASE_BOUNDARY_WORDS:+ break+ if normalized_word in _OUTPUT_GENERIC_WORDS:+ continue+ subject_words.append(word)+ if subject_words:+ return " ".join(subject_words)field_indexes = [i for i, word in enumerate(normalized_words) if word in _OUTPUT_FIELD_WORDS]if not field_indexes:return Nonediff --git a/skyvern/forge/sdk/copilot/request_slots.py b/skyvern/forge/sdk/copilot/request_slots.pyindex 86fb9f027..e26a76e42 100644--- a/skyvern/forge/sdk/copilot/request_slots.py+++ b/skyvern/forge/sdk/copilot/request_slots.py@@ -193,11 +193,23 @@ def request_slot_request_digest(request: RequestSlotProducerInputV1) -> str:return _request_digest(request.version, request_slot_sources(request), request.datum_targets)+_CANONICAL_SLOT_LEAF_PREFIX = "request_slot_"++def _canonical_path(request_digest: str, ordinal: int) -> tuple[str, tuple[str, str]]:- leaf = f"request_slot_{request_digest[:48]}_{ordinal:02d}"+ leaf = f"{_CANONICAL_SLOT_LEAF_PREFIX}{request_digest[:48]}_{ordinal:02d}"return f"output.{leaf}", ("output", leaf)+def is_canonical_request_slot_path(path: str | None) -> bool:+ """Whether a path is a server-minted slot identity, which carries a request digest and so+ identifies an output without naming it."""+ if not path:+ return False+ leaf = path.removeprefix("output.")+ return leaf.startswith(_CANONICAL_SLOT_LEAF_PREFIX)++def _slot_id(version: str, request_digest: str, ordinal: int, plane: RequestSlotPlane) -> str:encoded = json.dumps([version, request_digest, ordinal, plane.value],diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 96c192680..641c284e7 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -417,6 +417,46 @@ def test_fill_snapshot_never_emits_select_option_value_binding() -> None:assert snapshot.terminal.tool_name not in _SELECTION_MATCH_BASES+def test_rekeyed_outputs_with_alike_labels_return_under_distinct_keys() -> None:+ # Labels are not guaranteed distinct, so alike-slugging labels must not collapse onto one key.+ plan = RequestedOutputExtractionPlan(+ requested_output_paths=("output.request_slot_aaa_00", "output.request_slot_aaa_01"),+ observation_step=3,+ observation_identity="observation-identity",+ reveal=RevealAnchor(selector="#show"),+ live_reads=(+ LiveReadBinding(+ output_path="output.request_slot_aaa_00",+ kind=LiveReadKind.KEY_VALUE,+ selector=".kv",+ selector_count=2,+ selector_index=0,+ child_index=1,+ child_count=2,+ relation_label="Visitors",+ ),+ LiveReadBinding(+ output_path="output.request_slot_aaa_01",+ kind=LiveReadKind.KEY_VALUE,+ selector=".kv",+ selector_count=2,+ selector_index=1,+ child_index=1,+ child_count=2,+ relation_label="visitors",+ ),+ ),+ identity="plan-identity",+ )++ suffix = synthesize_extraction_suffix(plan)++ assert suffix is not None+ assert '"visitors": _extraction_value_0' in suffix.code+ assert '"visitors_2": _extraction_value_1' in suffix.code+ assert "request_slot_aaa" not in suffix.code++def _extraction_plan() -> RequestedOutputExtractionPlan:return RequestedOutputExtractionPlan(requested_output_paths=(diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.pyindex 75dcc040a..1983e13a2 100644--- a/tests/unit/test_copilot_enforcement_pruning.py+++ b/tests/unit/test_copilot_enforcement_pruning.py@@ -55,7 +55,9 @@ from skyvern.forge.sdk.copilot.enforcement import (arm_credential_scout_reopen,consume_uncovered_output_reopen_event,mint_scout_observation_contract_for_ctx,+ pre_run_gated_outputs_without_path,record_scouted_output_coverage,+ requested_scalar_output_extraction_plan,run_with_enforcement,synthesized_block_persistence_signal,synthesized_goal_completion_landing_pending,@@ -3184,6 +3186,129 @@ class TestScoutOutputCoverageGate:_restore_post_hook_context(ctx, snapshot)assert ctx.scout_observation_contract is None+ def test_both_surfaces_grounded_still_blocks_mutating_tool(self) -> None:+ ctx = self._authoring_ctx(+ _criterion("output.visitors", "Visitors"),+ _criterion("output.signups", "Signups"),+ )+ surface_one = self._kv_page(+ key_text="Visitors",+ url="https://analytics.example.com/dashboard",+ value_prose="Visitors 1,234 recorded this week",+ )+ first_contract = mint_scout_observation_contract_for_ctx(+ ctx, surface_one, url="https://analytics.example.com/dashboard"+ )+ record_scouted_output_coverage(ctx, surface_one, contract=first_contract)++ surface_two = self._kv_page(+ key_text="Signups",+ url="https://analytics.example.com/query",+ value_prose="Signups 987 total this week",+ )+ second_contract = mint_scout_observation_contract_for_ctx(+ ctx, surface_two, url="https://analytics.example.com/query"+ )+ record_scouted_output_coverage(ctx, surface_two, contract=second_contract)++ assert ctx.scouted_output_covered_paths == {"output.visitors", "output.signups"}+ assert uncovered_requested_output_paths(ctx) == set()++ assert _should_block_mutating_tool_after_synthesized_offer(ctx, "click") is True+ signal = synthesized_block_persistence_signal(ctx, "click")+ assert signal is not None+ assert signal.internal_reason_code == SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE++ def test_rekeyed_requested_output_compiles_the_offer_recipe_named_from_its_label(self) -> None:+ # Without the rekey fallback no label reaches the plan, so the offer is skipped and the+ # schema is left to the agent to invent.+ rekeyed = CompletionCriterion(+ id="slot0",+ outcome="Document Name",+ output_path=None,+ requested_output_evidence_source="runtime_output",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path="output.request_slot_abc_00",+ )+ ctx = self._authoring_ctx(rekeyed)+ self._attach_document_plan(ctx, step=6)+ ctx.synthesized_block_offered = False++ message = _maybe_synthesized_block_offer_msg(ctx)++ assert message is not None+ content = str(message["content"])+ assert 'return {"output": {"document_name": _extraction_value_0}}' in content+ assert "request_slot_abc_00" not in content++ def test_requested_output_without_a_label_leaves_the_ask_legitimate(self) -> None:+ # An underivable field yields no plan, so a clarification about it stays legitimate.+ unlabelled = CompletionCriterion(+ id="slot0",+ outcome="",+ output_path=None,+ requested_output_evidence_source="runtime_output",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path="output.request_slot_abc_00",+ )+ ctx = self._authoring_ctx(unlabelled)+ self._attach_document_plan(ctx, step=6)++ assert requested_scalar_output_extraction_plan(ctx) is None++ def test_floor_rekeyed_runtime_output_stays_owed_until_grounded(self) -> None:+ # The rekey clears output_path but keeps floor_rekeyed_from_path; keyed only on the former,+ # both outputs vanish from the requested set and the blocker forecloses scouting.+ rekeyed = [+ CompletionCriterion(+ id=f"slot{index}",+ outcome=outcome,+ output_path=None,+ requested_output_evidence_source="runtime_output",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path=f"output.request_slot_b97f_{index:02d}",+ )+ for index, outcome in enumerate(["number of website visitors", "number of new signups"])+ ]+ ctx = self._authoring_ctx(*rekeyed)++ # Provenance stands in for the cleared path, so both stay owed and neither is flagged.+ assert uncovered_requested_output_paths(ctx) == {+ "output.request_slot_b97f_00",+ "output.request_slot_b97f_01",+ }+ assert pre_run_gated_outputs_without_path(ctx) == ()++ surface_one = self._kv_page(+ key_text="Website visitors",+ url="https://analytics.example.com/web-analytics",+ value_prose="Website visitors 9,420 recorded for the past 7 days",+ )+ contract = mint_scout_observation_contract_for_ctx(+ ctx, surface_one, url="https://analytics.example.com/web-analytics"+ )+ record_scouted_output_coverage(ctx, surface_one, contract=contract)++ # Coverage keys on the outcome text, since the digest leaf carries no groundable tokens.+ assert uncovered_requested_output_paths(ctx) == {"output.request_slot_b97f_01"}+ ctx.synthesized_block_offered_goal_complete = synthesized_trajectory_is_goal_complete(ctx)+ assert _should_block_mutating_tool_after_synthesized_offer(ctx, "click") is False+ assert synthesized_block_persistence_signal(ctx, "click") is None++ def test_pathless_runtime_output_criterion_reaching_enforcement_is_flagged(self) -> None:+ # A runtime-output criterion reaching enforcement with no identity is surfaced, not dropped.+ pathless = CompletionCriterion(+ id="c0",+ outcome="number of new signups is extracted for the past 7 days",+ output_path=None,+ requested_output_evidence_source="runtime_output",+ )+ flagged = pre_run_gated_outputs_without_path(self._authoring_ctx(pathless))+ assert [criterion.id for criterion in flagged] == ["c0"]++ with_path = _criterion("output.new_signups", "number of new signups is extracted")+ assert pre_run_gated_outputs_without_path(self._authoring_ctx(with_path)) == ()+class TestAdvisoryRunDispatchForceLane:"""A granted output-contract advisory run is forced onto update_and_run_blocks through the samediff --git a/tests/unit/test_copilot_request_policy_completion_criteria.py b/tests/unit/test_copilot_request_policy_completion_criteria.pyindex 7c8781576..ee7ea3ae9 100644--- a/tests/unit/test_copilot_request_policy_completion_criteria.py+++ b/tests/unit/test_copilot_request_policy_completion_criteria.py@@ -35,6 +35,7 @@ from skyvern.forge.sdk.copilot.request_policy import (_degrade_pathless_contingent_criteria,_parse_completion_criteria,_render_active_criteria_for_prompt,+ _requested_output_fields,build_classifier_fallback_floor,is_fallback_floor_base_criterion,request_policy_has_present_completion_contract,@@ -514,6 +515,58 @@ def test_completion_criteria_preserve_requested_output_evidence_source() -> Noneassert trace["requested_output_criterion_3_evidence_source"] == "registered_artifact_content"+def test_quantifier_of_shape_extracts_noun_phrase_not_quantifier() -> None:+ # A quantifier followed by "of <noun phrase>" inverts the head-at-end shape the window assumes.+ assert _requested_output_fields(+ 'extract "number of website visitors" and "number of new signups" in the past 7 days.', {}+ ) == ["website visitors", "new signups"]+ # The rule covers the quantifier class, not two hard-coded prefixes.+ assert _requested_output_fields("extract the count of active users", {}) == ["active users"]+ assert _requested_output_fields("return the total number of orders", {}) == ["orders"]+++def test_head_at_end_field_shape_unchanged_by_quantifier_rule() -> None:+ # A head-at-end phrase has no "<quantifier> of" trigger, so the backward window is untouched.+ assert _requested_output_fields("Return a final record with account number and invoice date.", {}) == [+ "account number",+ "invoice date",+ ]+ assert _requested_output_fields("Return a final record with record id and status.", {}) == [+ "record id",+ "status",+ ]+ assert _requested_output_fields("Extract the invoice total.", {}) == ["invoice total"]+++def test_quantifier_extract_goal_binds_output_paths_to_pathless_criteria() -> None:+ # Pathless "number of X" criteria bind to canonical output paths once the field is extracted.+ policy = RequestPolicy(+ testing_intent="require_test",+ classifier_status="success",+ classifier_failure_kind="none",+ completion_criteria=_parse_completion_criteria(+ [+ {"outcome": "number of website visitors is extracted for the past 7 days"},+ {"outcome": "number of new signups is extracted for the past 7 days"},+ ]+ ),+ )+ _apply_requested_output_completion_criteria(+ policy,+ 'extract "number of website visitors" and "number of new signups" in the past 7 days.',+ )+ assert _criteria_for_path(policy, "output.website_visitors")+ assert _criteria_for_path(policy, "output.new_signups")+ assert not any(criterion.output_path is None for criterion in policy.completion_criteria)+++def test_quantifier_rule_leaves_negated_forbidden_fields_as_noun_phrase() -> None:+ # The forbidden-output path shares the cleaner, so the negated field is the noun phrase too.+ assert _requested_output_fields("Do not return the number of website visitors.", {}, negated=True) == [+ "website visitors"+ ]++def test_requested_output_canonicalization_preserves_independent_evidence_source() -> None:policy = RequestPolicy(completion_criteria=[