Skip to content

Automate browser based workflows with AI

Route non-mutating requests to answer-only Copilot turns (#7939)

Andrew Neilson95c5d7c99782
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index 1ca864cd0..36a3fd1e6 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -964,6 +964,13 @@ describe("hydrateNarrativeFromPayload — terminal adjudication fields", () => {
expect(turn?.verifiedSuccess).toBe(true);
});
+ it("hydrates the answer response kind from persisted payloads", () => {
+ const turn = hydrateNarrativeFromPayload(
+ reproClarifyPayload({ responseKind: "answer" }),
+ );
+ expect(turn?.responseKind).toBe("answer");
+ });
+
it("treats absent fields as null", () => {
const turn = hydrateNarrativeFromPayload(reproClarifyPayload());
expect(turn?.responseKind).toBeNull();
@@ -1192,6 +1199,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
["recover", "Question"],
["refuse", "Declined"],
["diagnose", "Answered"],
+ ["answer", "Answered"],
] as const)(
"maps non-build kind %s to %s with qa accent",
(kind, headline) => {
@@ -1444,6 +1452,7 @@ describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", ()
it.each([
["refuse", "Declined"],
["diagnose", "Answered"],
+ ["answer", "Answered"],
] as const)(
"leaves %s as %s under uxV1 — only the clarify/Question case renames",
(kind, headline) => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index d6a6dd924..e5df4c912 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -162,6 +162,7 @@ export interface ActivityEntry {
// Closed vocabulary of the backend TurnOutcome.response_kind enum. Unknown
// wire values parse to null so a newer backend cannot crash the renderer.
export type TurnResponseKind =
+ | "answer"
| "build"
| "clarify"
| "diagnose"
@@ -293,7 +294,8 @@ export function parseUtcIsoMs(iso: string | null | undefined): number | null {
}
export function parseResponseKind(value: unknown): TurnResponseKind | null {
- return value === "build" ||
+ return value === "answer" ||
+ value === "build" ||
value === "clarify" ||
value === "diagnose" ||
value === "refuse" ||
@@ -1421,7 +1423,7 @@ function adjudicatedSummaryParts(
if (turn.responseKind === "refuse") {
return { headline: "Declined", accent: "qa", glyph: "✦" };
}
- if (turn.responseKind === "diagnose") {
+ if (turn.responseKind === "answer" || turn.responseKind === "diagnose") {
return { headline: "Answered", accent: "qa", glyph: "✦" };
}
if (
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
index 0da17358b..ca9435d3f 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
@@ -1,3 +1,31 @@
+{% if answer_only %}
+You are the Skyvern Workflow assistant. Respond to the user's current request inline in the user's language.
+
+Use the Workflow Knowledge Base below as the source of truth for Skyvern product and workflow facts. This answer-only turn has no workflow or browser authority: do not create, edit, inspect, test, or run a workflow. Explain the answer in prose. Do not return serialized workflow YAML/JSON or literal credential values. No tools are available in this answer-only turn.
+
+{% if security_rules %}
+{{ security_rules }}
+
+{% endif %}
+WORKFLOW KNOWLEDGE BASE:
+
+{{ workflow_knowledge_base }}
+
+Return only this JSON shape:
+{
+ "type": "REPLY",
+ "user_response": "A useful, concise inline response.",
+ "goal_reached": true,
+ "global_llm_context": {
+ "user_goal": "The user's request answered this turn"
+ }
+}
+
+Current datetime, ISO format:
+```
+{{ current_datetime }}
+```
+{% else %}
You are an expert Skyvern Workflow assistant with access to tools that let you build, validate, test, and debug browser automation workflows.
CRITICAL ROLE BOUNDARY:
@@ -295,3 +323,4 @@ Current datetime, ISO format:
```
{{ current_datetime }}
```
+{% endif %}
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
index 2f756f5fe..a9fb41af4 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
@@ -21,6 +21,10 @@ PRIMARY COMPLETION CRITERIA:
```{{ reconciliation_criteria }}```
{% else %}
Classify the latest Workflow Copilot request. Return only JSON with keys:
+{% if trust_floor_only %}
+testing_intent=require_test|skip_test|unspecified; credential_input_kind=none|raw_secret|credential_id|credential_name|website_stored_credential|placeholder; credential_refs; login_page_urls; login_intent; email_signin_intent; signin_email_candidates; requires_user_clarification; clarification_reason; raw_secret_evidence; raw_secret_handling=none|block|redacted_draft.
+Do not produce workflow outcomes, completion criteria, request slots, or an authoring decision in this trust-floor pass.
+{% else %}
testing_intent=require_test|skip_test|unspecified; authoring_intent=author_now|defer_authoring; credential_input_kind=none|raw_secret|credential_id|credential_name|website_stored_credential|placeholder; credential_refs; login_page_urls; login_intent; email_signin_intent; signin_email_candidates; requires_user_clarification; clarification_reason; completion_contract; completion_criteria; raw_secret_evidence; raw_secret_handling=none|block|redacted_draft.
terminal_action priority:
@@ -31,17 +35,22 @@ terminal_action priority:
order terminal_action criterion, not a sign-in criterion.
- Emit no terminal_action for a pure-login or MFA request whose only requested end state is authentication. Do not
invent a post-login action that the user did not request.
+{% endif %}
testing_intent:
- skip_test: the user asks for an untested draft, says they will test it themselves, says draft only, just sketch it, no validation run, or skip testing.
- require_test: the user asks to build/create and test/run/verify/end-to-end it, or asks for a complete workflow that should be validated.
- unspecified: the user does not say whether Skyvern should test the workflow.
+{% if trust_floor_only %}
+- A done/complete/success condition does not by itself mean skip_test.
+{% else %}
- Do not use skip_test for a "done when", "complete when", or success-condition sentence; that is a completion_contract.
authoring_intent:
- defer_authoring: only when the latest message BOTH asks to act on the live page/form now (fill, enter, click, submit it on the open page) AND explicitly says not to author, build, save, or create a workflow yet. Both halves must be present.
- author_now: the default for every other request, including an ordinary "build a workflow that fills the form" — building a workflow IS the author-now case.
- Do not infer defer_authoring from a live-action verb alone, from skip_test, or from a draft-only request; author-deferral requires the explicit "do not author the workflow yet" half.
+{% endif %}
credential_input_kind:
- raw_secret: the user pasted a literal credential value — a password string, an API key/bearer token value, a session/auth cookie value, a TOTP/OTP/MFA digit code, a private-key body, a card number, or a CVV. The value must look like the secret itself (e.g. `password: hunter2`, `[email protected]:<password>`, bulk `[email protected]:<password>` account rows, `eyJ…` JWT, `sk-…` API key, a numeric OTP). Identifier-shaped vault-pointer strings such as `customer-<uuid>-pass`, `prod-app-secret-id`, `<service>-key-vault-id`, or `https://<vault>.vault.azure.net/secrets/<name>` are POINTERS to where a secret is stored, not secret values; do NOT classify them as raw_secret on the basis of a `-pass`, `-secret`, `-key`, or `-token` suffix alone.
@@ -74,6 +83,7 @@ requires_user_clarification:
- true only when the user refers to credentials but does not provide enough information to identify a saved credential or login page.
- false for normal build/test/verify requests with no credential reference, for explicit credential IDs/names/URLs, for placeholders, and for skip_test requests.
+{% if not trust_floor_only %}
completion_contract:
- Set to the user's explicit done/complete/success condition when they provide one.
- The value must be an exact span copied from the latest user message. Do not paraphrase, summarize, or infer a completion condition.
@@ -111,6 +121,7 @@ completion_criteria:
- Do not emit a criterion that restates or negates another criterion in the list (for example a "values are not hardcoded" duplicate of a reusable-inputs criterion); one outcome, one criterion. State a definition-level outcome as the positive checkable property of the named inputs, never as a negation.
- When ACTIVE COMPLETION CRITERIA are provided below, they are the canonical phrasing of the chat's current goal. If the latest request keeps that goal — including repeat, retest, fix, and follow-up turns — emit each still-required outcome COPIED VERBATIM from that list, character for character, punctuation included; never rephrase or reword a covered outcome. Write new phrasing only for an outcome the list does not cover, and drop an item only when the latest request abandons or replaces it.
- Set to [] when the user gives no goal with a checkable outcome (for example a pure draft-only or sketch request).
+{% endif %}
raw_secret_evidence:
- When credential_input_kind=raw_secret, set this to the verbatim substring of the LATEST user message that is the pasted secret value (e.g. the password string, JWT, API key, OTP digits, or PEM body). Do not paraphrase. Do not cite a token that appears only in prior turns or in the workflow_yaml — the substring must occur in the latest user message.
@@ -158,11 +169,13 @@ Latest assistant turn (slot-purpose anchor):
```{{ latest_assistant_turn }}```
Retained recent history:
```{{ retained_history }}```
+{% if not trust_floor_only %}
REQUEST SLOT SOURCES (authoritative user text anchors; server-owned slot identity and pinability are resolved separately):
```{{ request_slot_sources }}```
+{% endif %}
Current workflow YAML:
```{{ workflow_yaml }}```
-{% if active_completion_criteria %}ACTIVE COMPLETION CRITERIA (canonical phrasing for the current goal):
+{% if not trust_floor_only and active_completion_criteria %}ACTIVE COMPLETION CRITERIA (canonical phrasing for the current goal):
```{{ active_completion_criteria }}```
{% endif %}Global context: ```{{ global_llm_context }}```
{% endif %}
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2
index a06c7da4d..b88d18840 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-turn-intent.j2
@@ -8,7 +8,7 @@ Allowed reason_codes values: {{ reason_code_values }}.
Classify task shape only. RequestPolicy owns credential/raw-secret/testing policy and deterministic code owns authority.
-Modes: build=new or blank workflow task; edit=change existing workflow/proposal; diagnose=inspect/debug/continue from run evidence; docs_answer=product/docs/concept answer without mutation; draft_only=workflow change but no validation run; clarify=ambiguous target/change; refuse=unsupported request; unknown=insufficient signal.
+Modes: build=new or blank workflow task; edit=change existing workflow/proposal; diagnose=inspect/debug/continue from run evidence; docs_answer=respond inline when no workflow, browser, or run action is requested; draft_only=workflow change but no validation run; clarify=ambiguous target/change; refuse=unsupported request; unknown=insufficient signal.
Context keys: current_workflow for existing YAML; latest_assistant_proposal/workflow_change for prior draft/proposal edits; latest_run_result for diagnose/continuation; credential_metadata when safe credential metadata is relevant; docs_context for docs_answer; browser_state when current page/session is required.
@@ -20,7 +20,7 @@ Rules:
- Do not override request_policy_summary.
- A draft/skip-test/no-run request is draft_only unless it only asks to read/debug run results.
- Bare confirmations and short follow-ups classify from transcript anchors, not keyword matching.
-- Docs questions mentioning block/step names or run modes stay docs_answer unless the user asks to change the workflow.
+- Classify by the requested effect, not by vocabulary or subject matter: use docs_answer when an inline response fully satisfies the request, and use build/edit/diagnose when workflow, browser, or run work is requested.
- Failure/run-result language is diagnose unless the user explicitly asks to implement a repair.
Structural feasibility:
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index c9bcef64d..f53215797 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -174,9 +174,10 @@ from skyvern.forge.sdk.copilot.request_policy import (
RAW_SECRET_REFUSAL_SENTINEL,
CompletionCriterion,
RequestPolicy,
- build_request_policy,
+ build_request_policy_trust_floor,
credential_prompt_reason,
is_defer_authoring_durable_fill_criterion,
+ materialize_request_policy_authoring,
redact_raw_secrets_for_prompt,
)
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, run_outcome_display_reason
@@ -540,6 +541,7 @@ def _store_request_policy_on_context(
policy: RequestPolicy,
policy_inputs: RequestPolicyGuardrailInputs,
turn_intent_classifier_result: TurnIntentClassifierResult | None = None,
+ reconcile_completion_criteria: bool = True,
) -> None:
agent_user_message, policy_chat_history_text = _request_policy_agent_inputs(
policy,
@@ -549,7 +551,8 @@ def _store_request_policy_on_context(
)
ctx.turn_intent_classifier_result = turn_intent_classifier_result
_derive_turn_intent_on_context(ctx, policy, policy_inputs)
- _reconcile_completion_criteria_on_context(ctx, policy, policy_inputs)
+ if reconcile_completion_criteria:
+ _reconcile_completion_criteria_on_context(ctx, policy, policy_inputs)
ctx.request_policy = policy
ctx.allow_untested_workflow_draft = policy.testing_intent == "skip_test"
ctx.user_message = agent_user_message
@@ -586,6 +589,50 @@ def _derive_turn_intent_on_context(
)
+async def _materialize_authoring_for_resolved_intent(
+ ctx: CopilotContext,
+ policy: RequestPolicy,
+ policy_inputs: RequestPolicyGuardrailInputs,
+) -> None:
+ """Fill authoring policy only after the resolved effect earns it."""
+ turn_intent = ctx.turn_intent
+ if not isinstance(turn_intent, TurnIntent) or not (
+ turn_intent.authority.may_update_workflow or turn_intent.authority.may_run_blocks
+ ):
+ return
+ await materialize_request_policy_authoring(
+ policy,
+ user_message=policy_inputs.user_message,
+ workflow_yaml=policy_inputs.workflow_yaml,
+ chat_history=policy_inputs.chat_history_messages,
+ global_llm_context=policy_inputs.global_llm_context,
+ handler=policy_inputs.request_policy_handler,
+ active_criteria=_stored_active_completion_criteria(policy_inputs),
+ config=ctx.copilot_config,
+ )
+ _reconcile_completion_criteria_on_context(ctx, policy, policy_inputs)
+ _derive_turn_intent_on_context(ctx, policy, policy_inputs)
+
+
+async def _resume_turn_intent_after_preflight_credential(
+ ctx: CopilotContext,
+ policy: RequestPolicy,
+ policy_inputs: RequestPolicyGuardrailInputs,
+) -> None:
+ """Resume the staged intent pipeline after a credential pause lifts its policy block."""
+ if ctx.turn_intent_classifier_result is None:
+ ctx.turn_intent_classifier_result = await classify_turn_intent(
+ user_message=policy_inputs.user_message,
+ workflow_yaml=policy_inputs.workflow_yaml,
+ chat_history=policy_inputs.chat_history_messages,
+ global_llm_context=policy_inputs.global_llm_context,
+ request_policy=policy,
+ handler=policy_inputs.turn_intent_handler,
+ )
+ _derive_turn_intent_on_context(ctx, policy, policy_inputs)
+ await _materialize_authoring_for_resolved_intent(ctx, policy, policy_inputs)
+
+
def _turn_intent_log_fields(intent: TurnIntent | None) -> dict[str, Any]:
if not isinstance(intent, TurnIntent):
return {}
@@ -656,6 +703,7 @@ def _build_system_prompt(
tool_usage_guide: str,
config: CopilotConfig | None = None,
security_rules: str | None = None,
+ answer_only: bool = False,
) -> str:
copilot_config = config or CopilotConfig(security_rules=security_rules or "")
template = copilot_config.prompt_template.removesuffix(".j2")
@@ -668,6 +716,7 @@ def _build_system_prompt(
current_datetime=datetime_boundary,
tool_usage_guide=tool_usage_guide,
security_rules=copilot_config.security_rules,
+ answer_only=answer_only,
)
stable_prefix, boundary, dynamic_suffix = prompt_with_boundary.partition(datetime_boundary)
if boundary:
@@ -677,7 +726,7 @@ def _build_system_prompt(
# suffix, so its complete rendered prompt is safe to mark stable.
stable_prefix = prompt_with_boundary
dynamic_suffix = ""
- if copilot_config.block_authoring_policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ if not answer_only and copilot_config.block_authoring_policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
dynamic_suffix = f"{dynamic_suffix}\n\n{_render_code_only_browser_authoring_prompt()}"
return CacheableSystemInstructions(stable_prefix, dynamic_suffix)
@@ -1230,6 +1279,7 @@ def _synthesized_block_offer_prompt(ctx: CopilotContext | None) -> str:
def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -> Callable[[object, object], str]:
base_system_prompt = _build_system_prompt(tool_usage_guide=tool_usage_guide, config=config)
+ answer_only_system_prompt = _build_system_prompt(tool_usage_guide="", config=config, answer_only=True)
def instructions(context: object, _agent: object) -> str:
if not isinstance(context, _AgentInstructionsContext):
@@ -1240,55 +1290,48 @@ def _build_dynamic_system_prompt(tool_usage_guide: str, config: CopilotConfig) -
policy = ctx.request_policy
if not isinstance(policy, RequestPolicy):
return base_system_prompt
- policy_summary = escape_code_fences(redact_raw_secrets_for_prompt(policy.prompt_summary()))
- dynamic_context = (
- "\n\nREQUEST POLICY:\n```yaml\n"
- + policy_summary
- + "\n```\nFollow this policy. If `allow_run_blocks` is false, do not call block-running tools. "
- + "Exception: when `clarification_reason` is `workflow_credential_inputs_unbound` or "
- + "`credential_name_unresolved` and "
- + "`allow_missing_credentials_in_draft` is true, call `update_and_run_blocks`; it will save the draft "
- + "workflow and skip the browser run with a credential setup message. "
- + "If `raw_secret_handling` is `redacted_draft`, build only from the redacted request, do not run blocks, "
- + "and tell the user to store the redacted secret as a saved credential before testing. "
- + "If `resolved_credentials` are present, use those `credential_id` values. "
- + "If `resolved_signin_email` is present, that address signs in: bind it to the workflow as a "
- + "workflow input parameter with that value as the default, so the saved workflow can be re-run "
- + "under a different address, and do not ask for a saved password credential for that login."
- )
- dynamic_context = (
- dynamic_context
- + _runtime_verification_evidence_prompt(ctx)
- + _recorded_build_test_outcome_prompt(ctx)
- + _code_authoring_repair_context_prompt(ctx)
- + _synthesized_block_offer_prompt(ctx)
- + todo_list_prompt(ctx)
- + _docs_answer_turn_directive(ctx.turn_intent)
- )
- if isinstance(base_system_prompt, CacheableSystemInstructions):
+ answer_only = isinstance(ctx.turn_intent, TurnIntent) and ctx.turn_intent.is_inline_only
+ selected_system_prompt = answer_only_system_prompt if answer_only else base_system_prompt
+ summary = policy.trust_floor_summary() if answer_only else policy.prompt_summary()
+ policy_summary = escape_code_fences(redact_raw_secrets_for_prompt(summary))
+ if answer_only:
+ dynamic_context = (
+ "\n\nREQUEST POLICY TRUST FLOOR:\n```yaml\n"
+ + policy_summary
+ + "\n```\nFollow the trust floor while answering inline."
+ )
+ else:
+ dynamic_context = (
+ "\n\nREQUEST POLICY:\n```yaml\n"
+ + policy_summary
+ + "\n```\nFollow this policy. If `allow_run_blocks` is false, do not call block-running tools. "
+ + "Exception: when `clarification_reason` is `workflow_credential_inputs_unbound` or "
+ + "`credential_name_unresolved` and "
+ + "`allow_missing_credentials_in_draft` is true, call `update_and_run_blocks`; it will save the "
+ + "draft workflow and skip the browser run with a credential setup message. "
+ + "If `raw_secret_handling` is `redacted_draft`, build only from the redacted request, do not run "
+ + "blocks, and tell the user to store the redacted secret as a saved credential before testing. "
+ + "If `resolved_credentials` are present, use those `credential_id` values. "
+ + "If `resolved_signin_email` is present, that address signs in: bind it to the workflow as a "
+ + "workflow input parameter with that value as the default, so the saved workflow can be re-run "
+ + "under a different address, and do not ask for a saved password credential for that login."
+ + _runtime_verification_evidence_prompt(ctx)
+ + _recorded_build_test_outcome_prompt(ctx)
+ + _code_authoring_repair_context_prompt(ctx)
+ + _synthesized_block_offer_prompt(ctx)
+ + todo_list_prompt(ctx)
+ )
+ if isinstance(selected_system_prompt, CacheableSystemInstructions):
return CacheableSystemInstructions(
- base_system_prompt.stable_prefix,
- base_system_prompt.dynamic_suffix + dynamic_context,
+ selected_system_prompt.stable_prefix,
+ selected_system_prompt.dynamic_suffix + dynamic_context,
cache_namespace=ctx.workflow_copilot_chat_id,
)
- return base_system_prompt + dynamic_context
+ return selected_system_prompt + dynamic_context
return instructions
-def _docs_answer_turn_directive(turn_intent: TurnIntent | None) -> str:
- """Prompt-side complement to the no-mutation tool gate — keeps a docs-answer
- turn from substituting a routing question or build offer for the inline answer."""
- if not isinstance(turn_intent, TurnIntent) or turn_intent.mode != TurnIntentMode.DOCS_ANSWER:
- return ""
- return (
- "\n\nTURN INTENT: docs_answer\n"
- "This turn is a documentation or explanation question. Answer it inline in the user's language. "
- "Do not ask whether the user wants a workflow change instead, do not re-ask a confirmation the "
- "prior turn already covered, and do not offer to build an example workflow in place of answering."
- )
-
-
def _build_user_context(
workflow_yaml: str,
chat_history_text: str,
@@ -1576,10 +1619,10 @@ def _native_tools_for_turn(
turn_intent: TurnIntent | None,
request_policy: RequestPolicy | None = None,
) -> list[Any]:
- # Keep native tools registered even when the current turn is not allowed to
- # use them. The tool implementations enforce TurnIntent/RequestPolicy
- # authority and return structured blockers; removing a tool lets the model
- # hit an SDK-level ModelBehaviorError if static prompt text still names it.
+ if isinstance(turn_intent, TurnIntent) and turn_intent.is_inline_only:
+ return []
+ # Draft-only turns keep permitted authoring tools registered; tool
+ # implementations remain the defense-in-depth authority boundary.
if _request_policy_disables_browser_scout_tools(request_policy):
return [tool for tool in native_tools if getattr(tool, "name", None) not in _DRAFT_ONLY_NATIVE_TOOL_DENYLIST]
return list(native_tools)
@@ -4301,14 +4344,13 @@ def _build_copilot_input_guardrails(
ctx = getattr(context, "context", None)
policy = getattr(ctx, "request_policy", None)
if not isinstance(policy, RequestPolicy) and policy_inputs is not None:
- policy = await build_request_policy(
+ policy = await build_request_policy_trust_floor(
user_message=policy_inputs.user_message,
workflow_yaml=policy_inputs.workflow_yaml,
chat_history=policy_inputs.chat_history_messages,
global_llm_context=policy_inputs.global_llm_context,
organization_id=policy_inputs.organization_id,
handler=policy_inputs.request_policy_handler,
- active_criteria=_stored_active_completion_criteria(policy_inputs),
config=getattr(ctx, "copilot_config", None) if isinstance(ctx, CopilotContext) else None,
)
if isinstance(ctx, CopilotContext):
@@ -4327,7 +4369,9 @@ def _build_copilot_input_guardrails(
policy,
policy_inputs,
turn_intent_classifier_result=turn_intent_classifier_result,
+ reconcile_completion_criteria=False,
)
+ await _materialize_authoring_for_resolved_intent(ctx, policy, policy_inputs)
blocked = isinstance(policy, RequestPolicy) and policy.user_response_policy == "ask_clarification"
if isinstance(policy, RequestPolicy):
turn_intent = ctx.turn_intent if isinstance(ctx, CopilotContext) else None
@@ -4948,7 +4992,7 @@ async def _run_copilot_turn_impl(
if request_policy.clarification_reason == "login_credentials_unresolved":
preflight_resolution = await preflight_credential_pause(ctx, stream, copilot_config)
if preflight_resolution is not None:
- _derive_turn_intent_on_context(ctx, request_policy, policy_inputs)
+ await _resume_turn_intent_after_preflight_credential(ctx, request_policy, policy_inputs)
if preflight_resolution is None:
return _build_request_policy_clarification_result(
request_policy,
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 6bab78de7..eb0767ef7 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -95,7 +95,7 @@ class TurnNarrativePayload(TypedDict):
responseType: NotRequired[ResponseType]
cancelled: NotRequired[bool]
proposalDisposition: NotRequired[ProposalDisposition]
- # TurnOutcome.response_kind value: "build" | "clarify" | "diagnose" | "refuse" | "recover".
+ # TurnOutcome.response_kind value: "answer" | "build" | "clarify" | "diagnose" | "refuse" | "recover".
responseKind: NotRequired[str]
terminalEnvelope: NotRequired[dict[str, Any]]
# The ADR-0005 terminal adjudication (enforcement.verified_goal_claim_authorized):
diff --git a/skyvern/forge/sdk/copilot/credential_pause.py b/skyvern/forge/sdk/copilot/credential_pause.py
index beb7d15d3..8394e2e62 100644
--- a/skyvern/forge/sdk/copilot/credential_pause.py
+++ b/skyvern/forge/sdk/copilot/credential_pause.py
@@ -592,15 +592,11 @@ async def preflight_credential_pause(
if resolution is None or policy is None:
return resolution
policy.user_response_policy = "proceed"
- if policy.authoring_intent == "defer_authoring":
- # Lifting the credential clarification must not also lift the user's
- # explicit defer_authoring hold. Re-apply it, overriding the run grant
- # a connect resolution stamped via _apply_connected_credential_to_policy.
- policy.allow_update_workflow = False
- policy.allow_run_blocks = False
- else:
- policy.allow_update_workflow = True
- policy.allow_run_blocks = True
+ # Trust-floor policy has not classified authoring intent yet. Grant the
+ # provisional policy baseline; the resumed TurnIntent pipeline decides
+ # whether the requested effect earns authoring authority.
+ policy.allow_update_workflow = True
+ policy.allow_run_blocks = True
if resolution.action == "skip":
policy.allow_missing_credentials_in_draft = True
policy.requires_user_clarification = False
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 2c7032119..aff07a88d 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -599,6 +599,7 @@ class RequestPolicy:
classifier_non_runtime_requested_output_evidence_sources: list[str] = field(default_factory=list)
completion_contract_status: str = "absent"
request_slot_failure_kind: str | None = None
+ _authoring_pending: bool = field(default=False, repr=False, compare=False)
def graded_completion_criteria(self) -> list[CompletionCriterion]:
return [criterion for criterion in self.completion_criteria if not criterion.method_mandated]
@@ -762,6 +763,20 @@ class RequestPolicy:
lines.append("invalid_credential_ids: " + ", ".join(f"`{cid}`" for cid in self.invalid_credential_ids))
return "\n".join(lines)
+ def trust_floor_summary(self) -> str:
+ return "\n".join(
+ [
+ f"testing_intent: {self.testing_intent}",
+ f"credential_input_kind: {self.credential_input_kind}",
+ f"clarification_reason: {self.clarification_reason}",
+ f"allow_update_workflow: {self.allow_update_workflow}",
+ f"allow_run_blocks: {self.allow_run_blocks}",
+ f"allow_missing_credentials_in_draft: {self.allow_missing_credentials_in_draft}",
+ f"raw_secret_handling: {self.raw_secret_handling}",
+ f"classifier_status: {self.classifier_status}",
+ ]
+ )
+
def request_policy_has_present_completion_contract(request_policy: RequestPolicy | None) -> bool:
if request_policy is None:
@@ -3981,6 +3996,7 @@ async def _classify_request(
prompt = prompt_engine.load_prompt(
template=PROMPT_NAME,
terminal_action_reconciliation=False,
+ trust_floor_only=False,
user_message=escape_code_fences(safe_user_message),
raw_secret_present=str(raw_secret_present).lower(),
workflow_yaml=escape_code_fences(redact_raw_secrets_for_prompt(workflow_yaml)[:2048]),
@@ -5186,6 +5202,134 @@ def _workflow_credential_inputs_unbound(workflow_yaml: str) -> list[dict[str, st
return findings
+async def _classify_request_trust_floor(
+ user_message: str,
+ workflow_yaml: str,
+ chat_history: list[WorkflowCopilotChatHistoryMessage],
+ global_llm_context: str,
+ handler: LLMAPIHandler | None,
+ *,
+ config: CopilotConfig | None = None,
+) -> RequestPolicy:
+ requested_output_path_aliases = config.requested_output_path_aliases if config is not None else {}
+ ids = _credential_ids(user_message)
+ raw_secret_present = _raw_secret_detected(user_message)
+ structural_reason = _structural_clarification_reason(user_message)
+ if raw_secret_present and handler is None:
+ policy = _classifier_fallback_policy(
+ ids,
+ raw_secret_present=True,
+ failure_kind="raw_secret_no_handler",
+ user_message=user_message,
+ requested_output_path_aliases=requested_output_path_aliases,
+ )
+ policy.authoring_intent = "pending"
+ policy.completion_contract = None
+ policy.completion_criteria = []
+ policy.completion_contract_status = "absent"
+ policy._authoring_pending = True
+ return policy
+ if structural_reason != "none" and not raw_secret_present:
+ return RequestPolicy(
+ authoring_intent="pending",
+ credential_input_kind="credential_id" if ids else "none",
+ credential_refs=ids,
+ requires_user_clarification=True,
+ clarification_reason=structural_reason,
+ _authoring_pending=True,
+ )
+ if handler is None:
+ policy = _classifier_fallback_policy(
+ ids,
+ raw_secret_present=False,
+ failure_kind="missing_handler",
+ user_message=user_message,
+ requested_output_path_aliases=requested_output_path_aliases,
+ )
+ policy.authoring_intent = "pending"
+ policy.completion_contract = None
+ policy.completion_criteria = []
+ policy.completion_contract_status = "absent"
+ policy._authoring_pending = True
+ return policy
+
+ safe_user_message = redact_raw_secrets_for_prompt(user_message) if raw_secret_present else user_message
+ safe_global_llm_context = sanitize_global_llm_context_for_prompt(global_llm_context)
+ transcript = build_transcript_context(chat_history, safe_user_message)
+ prompt = prompt_engine.load_prompt(
+ template=PROMPT_NAME,
+ terminal_action_reconciliation=False,
+ trust_floor_only=True,
+ user_message=escape_code_fences(safe_user_message),
+ raw_secret_present=str(raw_secret_present).lower(),
+ workflow_yaml=escape_code_fences(redact_raw_secrets_for_prompt(workflow_yaml)[:2048]),
+ earliest_user_turn=transcript.earliest_user_turn,
+ latest_prior_user_turn=transcript.latest_prior_user_turn,
+ latest_assistant_turn=transcript.latest_assistant_turn,
+ retained_history=transcript.retained_history,
+ global_llm_context=escape_code_fences(redact_raw_secrets_for_prompt(safe_global_llm_context)[:2048]),
+ )
+ classifier_deadline = time.monotonic() + settings.COPILOT_REQUEST_POLICY_CLASSIFIER_TIMEOUT_SECONDS
+ raw, failure_kind, retry_count = await _run_request_policy_classifier(
+ handler,
+ prompt,
+ deadline=classifier_deadline,
+ )
+ raw_payload = _coerce_classifier_payload(raw)
+ if raw_payload is None:
+ policy = _classifier_fallback_policy(
+ ids,
+ raw_secret_present=raw_secret_present,
+ failure_kind=failure_kind if failure_kind != "none" else "provider_error",
+ retry_count=retry_count,
+ user_message=user_message,
+ requested_output_path_aliases=requested_output_path_aliases,
+ )
+ policy.authoring_intent = "pending"
+ policy.completion_contract = None
+ policy.completion_criteria = []
+ policy.completion_contract_status = "absent"
+ policy._authoring_pending = True
+ return policy
+
+ policy = _classification_from_raw(raw_payload)
+ policy.classifier_retry_count = retry_count
+ policy.authoring_intent = "pending"
+ policy.completion_contract = None
+ policy.completion_criteria = []
+ policy._authoring_pending = True
+ policy.raw_secret_detected = raw_secret_present or policy.credential_input_kind == "raw_secret"
+ classifier_credential_refs = [_canonicalize_credential_ref(ref) for ref in policy.credential_refs]
+ policy.credential_refs = _clean_list(classifier_credential_refs + ids)
+ if raw_secret_present:
+ if policy.raw_secret_handling == "redacted_draft":
+ if policy.credential_input_kind == "raw_secret":
+ policy.credential_input_kind = "placeholder"
+ policy.raw_secret_evidence = None
+ else:
+ policy.credential_input_kind = "raw_secret"
+ policy.raw_secret_handling = "block"
+ policy.clarification_reason = structural_reason if structural_reason != "none" else "raw_secret"
+ if ids and policy.credential_input_kind != "raw_secret":
+ classifier_named_a_credential = any(not _credential_ids(ref) for ref in classifier_credential_refs)
+ classifier_target_wins = (
+ policy.credential_input_kind == "credential_name" and classifier_named_a_credential
+ ) or (policy.credential_input_kind == "website_stored_credential" and bool(policy.login_page_urls))
+ if not classifier_target_wins:
+ policy.credential_input_kind = "credential_id"
+ if (
+ policy.credential_input_kind == "raw_secret"
+ and not raw_secret_present
+ and not _verify_raw_secret_evidence(policy.raw_secret_evidence, user_message)
+ ):
+ policy.credential_input_kind = "credential_id" if ids else "none"
+ policy.clarification_reason = "none"
+ policy.requires_user_clarification = False
+ policy.raw_secret_evidence = None
+ policy.completion_contract_status = "absent"
+ return policy
+
+
async def build_request_policy(
*,
user_message: str,
@@ -5196,16 +5340,19 @@ async def build_request_policy(
handler: LLMAPIHandler | None,
active_criteria: list[CompletionCriterion] | None = None,
config: CopilotConfig | None = None,
+ _preclassified_policy: RequestPolicy | None = None,
) -> RequestPolicy:
- policy = await _classify_request(
- user_message,
- workflow_yaml,
- chat_history,
- global_llm_context,
- handler,
- active_criteria=active_criteria,
- config=config,
- )
+ policy = _preclassified_policy
+ if policy is None:
+ policy = await _classify_request(
+ user_message,
+ workflow_yaml,
+ chat_history,
+ global_llm_context,
+ handler,
+ active_criteria=active_criteria,
+ config=config,
+ )
policy.raw_secret_detected = policy.raw_secret_detected or policy.credential_input_kind == "raw_secret"
policy.existing_workflow_credential_ids = sorted(workflow_credential_ids(workflow_yaml))
policy.existing_workflow_credential_origins = {
@@ -5369,7 +5516,7 @@ async def build_request_policy(
else:
policy.clarification_reason = "login_credentials_unresolved"
- if policy.authoring_intent == "defer_authoring":
+ if policy.authoring_intent == "defer_authoring" and not policy._authoring_pending:
policy.allow_update_workflow = False
policy.allow_run_blocks = False
if not any(is_defer_authoring_durable_fill_criterion(criterion) for criterion in policy.completion_criteria):
@@ -5381,3 +5528,77 @@ async def build_request_policy(
with copilot_span("request_policy", data=trace_data):
LOG.info("request-policy decision", **trace_data)
return policy
+
+
+async def build_request_policy_trust_floor(
+ *,
+ user_message: str,
+ workflow_yaml: str,
+ chat_history: list[WorkflowCopilotChatHistoryMessage],
+ global_llm_context: str,
+ organization_id: str,
+ handler: LLMAPIHandler | None,
+ config: CopilotConfig | None = None,
+) -> RequestPolicy:
+ policy = await _classify_request_trust_floor(
+ user_message,
+ workflow_yaml,
+ chat_history,
+ global_llm_context,
+ handler,
+ config=config,
+ )
+ return await build_request_policy(
+ user_message=user_message,
+ workflow_yaml=workflow_yaml,
+ chat_history=chat_history,
+ global_llm_context=global_llm_context,
+ organization_id=organization_id,
+ handler=handler,
+ config=config,
+ _preclassified_policy=policy,
+ )
+
+
+async def materialize_request_policy_authoring(
+ policy: RequestPolicy,
+ *,
+ user_message: str,
+ workflow_yaml: str,
+ chat_history: list[WorkflowCopilotChatHistoryMessage],
+ global_llm_context: str,
+ handler: LLMAPIHandler | None,
+ active_criteria: list[CompletionCriterion] | None = None,
+ config: CopilotConfig | None = None,
+) -> RequestPolicy:
+ if not policy._authoring_pending:
+ return policy
+ enriched = await _classify_request(
+ user_message,
+ workflow_yaml,
+ chat_history,
+ global_llm_context,
+ handler,
+ active_criteria=active_criteria,
+ config=config,
+ )
+ policy.authoring_intent = enriched.authoring_intent
+ policy.completion_contract = enriched.completion_contract
+ policy.completion_criteria = list(enriched.completion_criteria)
+ policy.classifier_non_runtime_requested_output_evidence_sources = list(
+ enriched.classifier_non_runtime_requested_output_evidence_sources
+ )
+ policy.completion_contract_status = enriched.completion_contract_status
+ policy.request_slot_failure_kind = enriched.request_slot_failure_kind
+ policy._authoring_pending = False
+ if policy.authoring_intent == "defer_authoring":
+ policy.allow_update_workflow = False
+ policy.allow_run_blocks = False
+ if not any(is_defer_authoring_durable_fill_criterion(criterion) for criterion in policy.completion_criteria):
+ policy.completion_criteria = list(policy.completion_criteria) + [_defer_authoring_durable_fill_criterion()]
+ LOG.info(
+ "request-policy authoring enrichment materialized",
+ completion_criteria_count=len(policy.completion_criteria),
+ completion_contract_status=policy.completion_contract_status,
+ )
+ return policy
diff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.py
index 18fdc59b1..b1de056cf 100644
--- a/skyvern/forge/sdk/copilot/terminal_envelope.py
+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py
@@ -221,7 +221,7 @@ def _derive_response_kind(
return "answer"
# Refusals and repeat-reply recover escalations are complete answer-only
# replies, not halted work — their text must survive envelope rendering.
- if workflow_mutated is False and turn_outcome_response_kind in ("diagnose", "refuse", "recover"):
+ if workflow_mutated is False and turn_outcome_response_kind in ("answer", "diagnose", "refuse", "recover"):
return "answer"
return "stopped"
diff --git a/skyvern/forge/sdk/copilot/turn_context.py b/skyvern/forge/sdk/copilot/turn_context.py
index 3a5f2575a..7b2642bc4 100644
--- a/skyvern/forge/sdk/copilot/turn_context.py
+++ b/skyvern/forge/sdk/copilot/turn_context.py
@@ -373,7 +373,7 @@ class TurnContextAssembler:
return packet
def _should_include_workflow(self, intent: TurnIntent, required: set[RequiredContextKey]) -> bool:
- if intent.mode == TurnIntentMode.DOCS_ANSWER:
+ if intent.mode == TurnIntentMode.ANSWER:
return False
# Edit-capable turns still need workflow context even when the shadow classifier
# did not include a specific workflow key yet.
@@ -399,7 +399,7 @@ class TurnContextAssembler:
return RunnableDraftContext(rendered_summary=summary, block_labels=labels)
def _should_include_run_context(self, intent: TurnIntent, required: set[RequiredContextKey]) -> bool:
- if intent.mode == TurnIntentMode.DOCS_ANSWER:
+ if intent.mode == TurnIntentMode.ANSWER:
return False
return RequiredContextKey.LATEST_RUN_RESULT in required or intent.mode in _RUN_MODES
diff --git a/skyvern/forge/sdk/copilot/turn_intent.py b/skyvern/forge/sdk/copilot/turn_intent.py
index 886ead287..a6b796ea2 100644
--- a/skyvern/forge/sdk/copilot/turn_intent.py
+++ b/skyvern/forge/sdk/copilot/turn_intent.py
@@ -42,7 +42,9 @@ class TurnIntentMode(StrEnum):
BUILD = "build"
EDIT = "edit"
DIAGNOSE = "diagnose"
- DOCS_ANSWER = "docs_answer"
+ # Keep the established wire value for persisted turns and API consumers;
+ # the mode is defined by its answer-only effect, not by one content family.
+ ANSWER = "docs_answer"
DRAFT_ONLY = "draft_only"
CLARIFY = "clarify"
REFUSE = "refuse"
@@ -58,10 +60,11 @@ _EDIT_SPECIFIC_TARGET_ENTITY_TYPES = frozenset(
NO_MUTATION_TURN_INTENT_MODES = frozenset(
{
- TurnIntentMode.DOCS_ANSWER,
+ TurnIntentMode.ANSWER,
TurnIntentMode.DIAGNOSE,
TurnIntentMode.CLARIFY,
TurnIntentMode.REFUSE,
+ TurnIntentMode.UNKNOWN,
}
)
@@ -69,9 +72,10 @@ NO_MUTATION_TURN_INTENT_MODES = frozenset(
# the intra-turn read-context override away from explicitly answer-only turns.
READ_CONTEXT_DENIED_MODES = frozenset(
{
- TurnIntentMode.DOCS_ANSWER,
+ TurnIntentMode.ANSWER,
TurnIntentMode.REFUSE,
TurnIntentMode.CLARIFY,
+ TurnIntentMode.UNKNOWN,
}
)
@@ -144,7 +148,7 @@ _DEFAULT_EXPECTED_OUTPUT_BY_MODE: dict[TurnIntentMode, TurnIntentExpectedOutput]
TurnIntentMode.BUILD: TurnIntentExpectedOutput.WORKFLOW_DRAFT,
TurnIntentMode.EDIT: TurnIntentExpectedOutput.WORKFLOW_UPDATE,
TurnIntentMode.DIAGNOSE: TurnIntentExpectedOutput.RUN_RESULT,
- TurnIntentMode.DOCS_ANSWER: TurnIntentExpectedOutput.EXPLANATION,
+ TurnIntentMode.ANSWER: TurnIntentExpectedOutput.EXPLANATION,
TurnIntentMode.DRAFT_ONLY: TurnIntentExpectedOutput.WORKFLOW_DRAFT,
TurnIntentMode.CLARIFY: TurnIntentExpectedOutput.CLARIFICATION,
TurnIntentMode.REFUSE: TurnIntentExpectedOutput.REFUSAL,
@@ -203,6 +207,19 @@ class TurnIntent(BaseModel):
self.expected_output = mapped_expected_output
return self
+ @property
+ def is_inline_only(self) -> bool:
+ """Whether the resolved effect is a prose answer with no external authority."""
+ authority = self.authority
+ return (
+ self.expected_output == TurnIntentExpectedOutput.EXPLANATION
+ and authority.may_answer_without_mutation
+ and not authority.may_update_workflow
+ and not authority.may_run_blocks
+ and not authority.may_read_run_context
+ and not authority.requires_user_input
+ )
+
def to_trace_data(self) -> dict[str, object]:
data: dict[str, object] = {
"mode": self.mode.value,
@@ -597,7 +614,7 @@ async def classify_turn_intent(
required_context_values=", ".join(key.value for key in RequiredContextKey),
reason_code_values=", ".join(reason.value for reason in _CLASSIFIER_REASON_CODES),
user_message=escape_code_fences(safe_user_message),
- request_policy_summary=escape_code_fences(request_policy.prompt_summary()),
+ request_policy_summary=escape_code_fences(request_policy.trust_floor_summary()),
workflow_yaml=escape_code_fences(
redact_raw_secrets_for_prompt(workflow_yaml)[:_WORKFLOW_YAML_PROMPT_MAX_CHARS]
),
@@ -812,8 +829,8 @@ def build_turn_intent(
if classification is not None and TurnIntentReasonCode.STRUCTURALLY_INFEASIBLE in classification.reason_codes:
infeasibility_question = (classification.missing_context_question or "").strip()
if not infeasibility_question:
- # Questionless infeasibility fails open: drop the verdict and proceed at request-policy
- # authority rather than stranding the turn in an answerless CLARIFY.
+ # Drop the unusable verdict rather than stranding the turn in an answerless
+ # CLARIFY. The resulting UNKNOWN still cannot earn side-effect authority.
LOG.warning("turn-intent dropped questionless structural-infeasibility verdict, proceeding")
classification = classification.model_copy(
update={
@@ -926,10 +943,15 @@ def build_turn_intent(
expected_output = TurnIntentExpectedOutput.RUN_RESULT
reason_codes.append(TurnIntentReasonCode.RECOVERY_FROM_RUN_CONTEXT)
- if mode == TurnIntentMode.DOCS_ANSWER:
+ if mode == TurnIntentMode.ANSWER:
authority.may_update_workflow = False
authority.may_run_blocks = False
required_context.append(RequiredContextKey.DOCS_CONTEXT)
+ elif mode == TurnIntentMode.UNKNOWN:
+ # Insufficient signal cannot inherit RequestPolicy's permissive defaults.
+ # A later, classified turn can earn side-effect authority; this turn has not.
+ authority.may_update_workflow = False
+ authority.may_run_blocks = False
elif mode == TurnIntentMode.DRAFT_ONLY:
authority.may_run_blocks = False
elif mode == TurnIntentMode.CLARIFY:
diff --git a/skyvern/forge/sdk/copilot/turn_outcome.py b/skyvern/forge/sdk/copilot/turn_outcome.py
index 2c378eb5a..27ed93807 100644
--- a/skyvern/forge/sdk/copilot/turn_outcome.py
+++ b/skyvern/forge/sdk/copilot/turn_outcome.py
@@ -1,4 +1,4 @@
-"""Builders + closed `TurnIntentMode -> ResponseKind` mapping for `TurnOutcome`.
+"""Builders + deterministic `TurnIntent -> ResponseKind` mapping for `TurnOutcome`.
Schema types live in ``schemas/copilot_turn_outcome.py`` so chat-history
schemas can embed ``TurnOutcome`` without importing copilot business logic.
@@ -74,7 +74,7 @@ _RESPONSE_KIND_BY_MODE: dict[TurnIntentMode, ResponseKind] = {
TurnIntentMode.CLARIFY: ResponseKind.CLARIFY,
TurnIntentMode.UNKNOWN: ResponseKind.CLARIFY,
TurnIntentMode.DIAGNOSE: ResponseKind.DIAGNOSE,
- TurnIntentMode.DOCS_ANSWER: ResponseKind.DIAGNOSE,
+ TurnIntentMode.ANSWER: ResponseKind.ANSWER,
TurnIntentMode.REFUSE: ResponseKind.REFUSE,
}
@@ -87,8 +87,13 @@ if _missing_modes:
def derive_response_kind(turn_intent: TurnIntent | None) -> ResponseKind:
- """Closed mapping. ``RECOVER`` is set only by the enforcement guard."""
+ """Closed mapping with an effect-based fallback for safe unknown explanations.
+
+ ``RECOVER`` is set only by the enforcement guard.
+ """
mode = getattr(turn_intent, "mode", None)
+ if isinstance(turn_intent, TurnIntent) and mode is TurnIntentMode.UNKNOWN and turn_intent.is_inline_only:
+ return ResponseKind.ANSWER
if isinstance(mode, TurnIntentMode):
return _RESPONSE_KIND_BY_MODE[mode]
return ResponseKind.CLARIFY
diff --git a/skyvern/forge/sdk/schemas/copilot_turn_outcome.py b/skyvern/forge/sdk/schemas/copilot_turn_outcome.py
index be0f667f2..453965177 100644
--- a/skyvern/forge/sdk/schemas/copilot_turn_outcome.py
+++ b/skyvern/forge/sdk/schemas/copilot_turn_outcome.py
@@ -15,6 +15,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator
class ResponseKind(StrEnum):
+ ANSWER = "answer"
BUILD = "build"
CLARIFY = "clarify"
DIAGNOSE = "diagnose"
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index ebb50515a..49bbed637 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -99,7 +99,8 @@ class WorkflowCopilotTurnMode(StrEnum):
BUILD = "build"
EDIT = "edit"
DIAGNOSE = "diagnose"
- DOCS_ANSWER = "docs_answer"
+ # Wire-compatible mirror of the generic answer-only TurnIntent mode.
+ ANSWER = "docs_answer"
DRAFT_ONLY = "draft_only"
CLARIFY = "clarify"
REFUSE = "refuse"
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index b382c6f4b..b655b8da7 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -84,9 +84,12 @@ from skyvern.forge.sdk.copilot.request_policy import (
RequestPolicy,
_classifier_fallback_policy,
_classify_request,
+ _classify_request_trust_floor,
build_classifier_fallback_floor,
build_transcript_context,
+ is_defer_authoring_durable_fill_criterion,
is_fallback_floor_criterion,
+ materialize_request_policy_authoring,
redact_raw_secrets_for_prompt,
)
from skyvern.forge.sdk.copilot.request_slots import PROMPT_NAME as REQUEST_SLOTS_PROMPT_NAME
@@ -110,6 +113,8 @@ from skyvern.forge.sdk.copilot.turn_intent import (
RequiredContextKey,
TurnIntent,
TurnIntentAuthority,
+ TurnIntentClassification,
+ TurnIntentClassifierResult,
TurnIntentMode,
TurnIntentReasonCode,
)
@@ -1657,6 +1662,394 @@ class TestSupersededAgentIntentGates:
class TestRequestPolicyInputGuardrail:
+ @pytest.mark.asyncio
+ async def test_answer_only_turn_skips_authoring_enrichment_and_stored_criteria(self, monkeypatch) -> None:
+ policy = RequestPolicy(_authoring_pending=True)
+ stored = StoredCriteriaSet(
+ set_id="wccs_1",
+ goal_epoch=1,
+ criteria=(CompletionCriterion(id="c0", outcome="A prior authoring criterion"),),
+ )
+ monkeypatch.setattr(
+ agent_module,
+ "build_request_policy_trust_floor",
+ AsyncMock(return_value=policy),
+ )
+ monkeypatch.setattr(
+ agent_module,
+ "classify_turn_intent",
+ AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.ANSWER, confidence=0.95)
+ )
+ ),
+ )
+ materialize = AsyncMock()
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize)
+ ctx = _ctx()
+ policy_inputs = agent_module.RequestPolicyGuardrailInputs(
+ user_message="How do I make a workflow with a google sheet step?",
+ workflow_yaml="",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ request_policy_handler=object(),
+ turn_intent_handler=object(),
+ stored_completion_criteria=StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ )
+
+ guardrail = agent_module._build_copilot_input_guardrails(
+ InputGuardrail,
+ GuardrailFunctionOutput,
+ policy_inputs=policy_inputs,
+ )[0]
+ await guardrail.run(SimpleNamespace(), "input", RunContextWrapper(context=ctx))
+
+ materialize.assert_not_awaited()
+ assert ctx.turn_intent is not None
+ assert ctx.turn_intent.mode is TurnIntentMode.ANSWER
+ assert policy.completion_criteria == []
+ assert ctx.completion_criteria_turn_state is None
+
+ @pytest.mark.asyncio
+ async def test_read_only_diagnose_skips_authoring_enrichment(self, monkeypatch) -> None:
+ policy = RequestPolicy(testing_intent="unspecified", _authoring_pending=True)
+ monkeypatch.setattr(
+ agent_module,
+ "build_request_policy_trust_floor",
+ AsyncMock(return_value=policy),
+ )
+ monkeypatch.setattr(
+ agent_module,
+ "classify_turn_intent",
+ AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.DIAGNOSE, confidence=0.95)
+ )
+ ),
+ )
+ materialize = AsyncMock()
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize)
+ ctx = _ctx()
+ policy_inputs = agent_module.RequestPolicyGuardrailInputs(
+ user_message="Why did the last run fail?",
+ workflow_yaml="workflow: yaml",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ request_policy_handler=object(),
+ turn_intent_handler=object(),
+ workflow_run_id="wr_1",
+ )
+
+ guardrail = agent_module._build_copilot_input_guardrails(
+ InputGuardrail,
+ GuardrailFunctionOutput,
+ policy_inputs=policy_inputs,
+ )[0]
+ await guardrail.run(SimpleNamespace(), "input", RunContextWrapper(context=ctx))
+
+ materialize.assert_not_awaited()
+ assert ctx.turn_intent is not None
+ assert ctx.turn_intent.mode is TurnIntentMode.DIAGNOSE
+ assert ctx.turn_intent.authority.may_run_blocks is False
+
+ @pytest.mark.asyncio
+ async def test_diagnose_retest_authority_materializes_completion_criteria(
+ self,
+ monkeypatch,
+ ) -> None:
+ stored = StoredCriteriaSet(
+ set_id="wccs_1",
+ goal_epoch=1,
+ criteria=(CompletionCriterion(id="c0", outcome="The requested value is returned"),),
+ )
+ policy = RequestPolicy(
+ testing_intent="require_test",
+ allow_run_blocks=True,
+ _authoring_pending=True,
+ )
+ monkeypatch.setattr(
+ agent_module,
+ "build_request_policy_trust_floor",
+ AsyncMock(return_value=policy),
+ )
+ monkeypatch.setattr(
+ agent_module,
+ "classify_turn_intent",
+ AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.DIAGNOSE, confidence=0.95)
+ )
+ ),
+ )
+
+ async def materialize(target: RequestPolicy, **_kwargs) -> RequestPolicy:
+ target.completion_criteria = list(stored.criteria)
+ target._authoring_pending = False
+ return target
+
+ materialize_mock = AsyncMock(side_effect=materialize)
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize_mock)
+ ctx = _ctx()
+ policy_inputs = agent_module.RequestPolicyGuardrailInputs(
+ user_message="Run it again and verify the requested value",
+ workflow_yaml="workflow: yaml",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ request_policy_handler=object(),
+ turn_intent_handler=object(),
+ stored_completion_criteria=StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ workflow_run_id="wr_1",
+ )
+
+ guardrail = agent_module._build_copilot_input_guardrails(
+ InputGuardrail,
+ GuardrailFunctionOutput,
+ policy_inputs=policy_inputs,
+ )[0]
+ await guardrail.run(SimpleNamespace(), "input", RunContextWrapper(context=ctx))
+
+ materialize_mock.assert_awaited_once()
+ assert materialize_mock.await_args.kwargs["active_criteria"] == list(stored.criteria)
+ assert ctx.turn_intent is not None
+ assert ctx.turn_intent.mode is TurnIntentMode.DIAGNOSE
+ assert ctx.turn_intent.authority.may_update_workflow is False
+ assert ctx.turn_intent.authority.may_run_blocks is True
+ assert policy.completion_criteria == list(stored.criteria)
+ assert ctx.completion_criteria_turn_state is not None
+
+ @pytest.mark.asyncio
+ async def test_unknown_turn_skips_authoring_enrichment(self, monkeypatch) -> None:
+ policy = RequestPolicy(allow_update_workflow=True, allow_run_blocks=True, _authoring_pending=True)
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", AsyncMock(return_value=policy))
+ monkeypatch.setattr(
+ agent_module,
+ "classify_turn_intent",
+ AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.UNKNOWN, confidence=0.95)
+ )
+ ),
+ )
+ materialize = AsyncMock()
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize)
+ ctx = _ctx()
+ policy_inputs = agent_module.RequestPolicyGuardrailInputs(
+ user_message="Insufficient signal for a requested effect",
+ workflow_yaml="",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ request_policy_handler=object(),
+ turn_intent_handler=object(),
+ )
+
+ guardrail = agent_module._build_copilot_input_guardrails(
+ InputGuardrail,
+ GuardrailFunctionOutput,
+ policy_inputs=policy_inputs,
+ )[0]
+ await guardrail.run(SimpleNamespace(), "input", RunContextWrapper(context=ctx))
+
+ materialize.assert_not_awaited()
+ assert ctx.turn_intent is not None
+ assert ctx.turn_intent.mode is TurnIntentMode.UNKNOWN
+ assert ctx.turn_intent.authority.may_update_workflow is False
+ assert ctx.turn_intent.authority.may_run_blocks is False
+
+ @pytest.mark.asyncio
+ async def test_authoring_enriches_once_and_rebuilds_authority_from_same_classifier_result(
+ self, monkeypatch
+ ) -> None:
+ policy = RequestPolicy(_authoring_pending=True)
+ classifier_result = TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.BUILD, confidence=0.95)
+ )
+ monkeypatch.setattr(
+ agent_module,
+ "build_request_policy_trust_floor",
+ AsyncMock(return_value=policy),
+ )
+ classify = AsyncMock(return_value=classifier_result)
+ monkeypatch.setattr(agent_module, "classify_turn_intent", classify)
+
+ async def materialize(target: RequestPolicy, **_kwargs) -> RequestPolicy:
+ target.allow_update_workflow = False
+ target.allow_run_blocks = False
+ target.completion_criteria = [CompletionCriterion(id="c0", outcome="Draft exists")]
+ target._authoring_pending = False
+ return target
+
+ materialize_mock = AsyncMock(side_effect=materialize)
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize_mock)
+ ctx = _ctx()
+ policy_inputs = agent_module.RequestPolicyGuardrailInputs(
+ user_message="Add a Google Sheets write step to this workflow",
+ workflow_yaml="",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ request_policy_handler=object(),
+ turn_intent_handler=object(),
+ )
+
+ guardrail = agent_module._build_copilot_input_guardrails(
+ InputGuardrail,
+ GuardrailFunctionOutput,
+ policy_inputs=policy_inputs,
+ )[0]
+ await guardrail.run(SimpleNamespace(), "input", RunContextWrapper(context=ctx))
+
+ classify.assert_awaited_once()
+ materialize_mock.assert_awaited_once()
+ assert ctx.turn_intent is not None
+ assert ctx.turn_intent.mode is TurnIntentMode.BUILD
+ assert ctx.turn_intent.authority.may_update_workflow is False
+ assert ctx.turn_intent.authority.may_run_blocks is False
+
+ @pytest.mark.asyncio
+ async def test_request_policy_trust_floor_defers_completion_producers(self, monkeypatch) -> None:
+ prompts: list[str] = []
+
+ async def handler(*, prompt: str, **_kwargs: object) -> dict[str, object]:
+ prompts.append(prompt)
+ return {
+ "testing_intent": "require_test",
+ "credential_input_kind": "none",
+ "credential_refs": [],
+ "login_page_urls": [],
+ "login_intent": False,
+ "email_signin_intent": False,
+ "signin_email_candidates": [],
+ "requires_user_clarification": False,
+ "raw_secret_handling": "none",
+ "clarification_reason": "none",
+ }
+
+ produce_request_slots = AsyncMock()
+ monkeypatch.setattr(request_policy_module, "produce_request_slots", produce_request_slots)
+
+ policy = await _classify_request_trust_floor(
+ "Build and test a workflow",
+ "",
+ [],
+ "",
+ handler,
+ )
+
+ produce_request_slots.assert_not_awaited()
+ assert policy.authoring_intent == "pending"
+ assert policy.completion_contract is None
+ assert policy.completion_criteria == []
+ assert policy._authoring_pending is True
+ assert len(prompts) == 1
+ assert "completion_contract" not in prompts[0]
+ assert "completion_criteria" not in prompts[0]
+ assert "REQUEST SLOT SOURCES" not in prompts[0]
+
+ @pytest.mark.asyncio
+ async def test_request_policy_trust_floor_defers_fallback_criteria_until_authoring(self) -> None:
+ policy = await _classify_request_trust_floor(
+ "Build a workflow that extracts the page title",
+ "",
+ [],
+ "",
+ None,
+ )
+
+ assert policy.completion_criteria == []
+ assert policy._authoring_pending is True
+
+ await materialize_request_policy_authoring(
+ policy,
+ user_message="Build a workflow that extracts the page title",
+ workflow_yaml="",
+ chat_history=[],
+ global_llm_context="",
+ handler=None,
+ )
+
+ assert policy.completion_criteria
+ assert policy.authoring_intent == "author_now"
+ assert policy._authoring_pending is False
+
+ @pytest.mark.asyncio
+ async def test_authoring_materialization_preserves_trust_floor_fields(self, monkeypatch) -> None:
+ policy = RequestPolicy(
+ testing_intent="require_test",
+ credential_input_kind="credential_name",
+ credential_refs=["saved-login"],
+ allow_update_workflow=False,
+ allow_run_blocks=False,
+ _authoring_pending=True,
+ )
+ enriched = RequestPolicy(
+ testing_intent="skip_test",
+ authoring_intent="author_now",
+ credential_input_kind="none",
+ allow_update_workflow=True,
+ allow_run_blocks=True,
+ completion_contract="The draft exists",
+ completion_criteria=[CompletionCriterion(id="c0", outcome="The draft exists")],
+ completion_contract_status="present",
+ )
+ classify = AsyncMock(return_value=enriched)
+ monkeypatch.setattr(request_policy_module, "_classify_request", classify)
+
+ await materialize_request_policy_authoring(
+ policy,
+ user_message="Build and test the workflow with saved-login",
+ workflow_yaml="",
+ chat_history=[],
+ global_llm_context="",
+ handler=object(),
+ )
+
+ classify.assert_awaited_once()
+ assert policy.testing_intent == "require_test"
+ assert policy.credential_input_kind == "credential_name"
+ assert policy.credential_refs == ["saved-login"]
+ assert policy.allow_update_workflow is False
+ assert policy.allow_run_blocks is False
+ assert policy.completion_criteria == enriched.completion_criteria
+ assert policy._authoring_pending is False
+
+ @pytest.mark.asyncio
+ async def test_authoring_materialization_preserves_explicit_defer_authoring_authority(self, monkeypatch) -> None:
+ policy = RequestPolicy(
+ allow_update_workflow=True,
+ allow_run_blocks=True,
+ _authoring_pending=True,
+ )
+ enriched = RequestPolicy(
+ authoring_intent="defer_authoring",
+ allow_update_workflow=True,
+ allow_run_blocks=True,
+ )
+ monkeypatch.setattr(request_policy_module, "_classify_request", AsyncMock(return_value=enriched))
+
+ await materialize_request_policy_authoring(
+ policy,
+ user_message="Fill the live form, but do not create a workflow yet",
+ workflow_yaml="",
+ chat_history=[],
+ global_llm_context="",
+ handler=object(),
+ )
+
+ assert policy.authoring_intent == "defer_authoring"
+ assert policy.allow_update_workflow is False
+ assert policy.allow_run_blocks is False
+ assert any(is_defer_authoring_durable_fill_criterion(item) for item in policy.completion_criteria)
+ assert policy._authoring_pending is False
+
@pytest.mark.asyncio
async def test_sdk_input_guardrail_computes_and_stores_request_policy(self, monkeypatch) -> None:
policy = RequestPolicy(
@@ -1666,7 +2059,7 @@ class TestRequestPolicyInputGuardrail:
allow_run_blocks=False,
)
build_request_policy = AsyncMock(return_value=policy)
- monkeypatch.setattr(agent_module, "build_request_policy", build_request_policy)
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", build_request_policy)
ctx = _ctx()
policy_inputs = agent_module.RequestPolicyGuardrailInputs(
user_message="just draft without testing",
@@ -1702,7 +2095,6 @@ class TestRequestPolicyInputGuardrail:
global_llm_context="",
organization_id="org-1",
handler=policy_inputs.request_policy_handler,
- active_criteria=None,
config=None,
)
@@ -1715,7 +2107,7 @@ class TestRequestPolicyInputGuardrail:
policy = RequestPolicy()
build_request_policy = AsyncMock(return_value=policy)
classify_turn_intent = AsyncMock(return_value=None)
- monkeypatch.setattr(agent_module, "build_request_policy", build_request_policy)
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", build_request_policy)
monkeypatch.setattr(agent_module, "classify_turn_intent", classify_turn_intent)
policy_inputs = agent_module.RequestPolicyGuardrailInputs(
user_message="build and test it",
@@ -1741,14 +2133,25 @@ class TestRequestPolicyInputGuardrail:
assert classify_turn_intent.await_args.kwargs["handler"] is turn_intent_handler
@pytest.mark.asyncio
- async def test_sdk_input_guardrail_forwards_stored_active_criteria(self, monkeypatch) -> None:
+ async def test_sdk_input_guardrail_defers_stored_active_criteria_until_authoring(self, monkeypatch) -> None:
stored = StoredCriteriaSet(
set_id="wccs_1",
goal_epoch=1,
criteria=(CompletionCriterion(id="c0", outcome="The main heading is extracted into the run output"),),
)
- build_request_policy = AsyncMock(return_value=RequestPolicy())
- monkeypatch.setattr(agent_module, "build_request_policy", build_request_policy)
+ build_request_policy = AsyncMock(return_value=RequestPolicy(_authoring_pending=True))
+ materialize = AsyncMock()
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", build_request_policy)
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize)
+ monkeypatch.setattr(
+ agent_module,
+ "classify_turn_intent",
+ AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.BUILD, confidence=0.95)
+ )
+ ),
+ )
policy_inputs = agent_module.RequestPolicyGuardrailInputs(
user_message="run it again",
workflow_yaml="",
@@ -1768,7 +2171,9 @@ class TestRequestPolicyInputGuardrail:
await guardrails[0].run(SimpleNamespace(), "input", RunContextWrapper(context=_ctx()))
assert build_request_policy.await_args is not None
- assert build_request_policy.await_args.kwargs["active_criteria"] == list(stored.criteria)
+ assert "active_criteria" not in build_request_policy.await_args.kwargs
+ assert materialize.await_args is not None
+ assert materialize.await_args.kwargs["active_criteria"] == list(stored.criteria)
@pytest.mark.asyncio
async def test_sdk_input_guardrail_trips_after_computing_blocked_policy(self, monkeypatch) -> None:
@@ -1781,7 +2186,7 @@ class TestRequestPolicyInputGuardrail:
clarification_reason="raw_secret",
clarification_question="Do not paste raw credentials.",
)
- monkeypatch.setattr(agent_module, "build_request_policy", AsyncMock(return_value=policy))
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", AsyncMock(return_value=policy))
ctx = _ctx()
guardrails = agent_module._build_copilot_input_guardrails(
InputGuardrail,
@@ -1813,7 +2218,7 @@ class TestRequestPolicyInputGuardrail:
testing_intent="unspecified",
user_response_policy="proceed",
)
- monkeypatch.setattr(agent_module, "build_request_policy", AsyncMock(return_value=policy))
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", AsyncMock(return_value=policy))
ctx = _ctx()
guardrails = agent_module._build_copilot_input_guardrails(
InputGuardrail,
@@ -1852,7 +2257,7 @@ class TestRequestPolicyInputGuardrail:
testing_intent="unspecified",
user_response_policy="proceed",
)
- monkeypatch.setattr(agent_module, "build_request_policy", AsyncMock(return_value=policy))
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", AsyncMock(return_value=policy))
ctx = _ctx()
guardrails = agent_module._build_copilot_input_guardrails(
InputGuardrail,
@@ -1893,7 +2298,7 @@ class TestRequestPolicyInputGuardrail:
allow_run_blocks=False,
allow_missing_credentials_in_draft=True,
)
- monkeypatch.setattr(agent_module, "build_request_policy", AsyncMock(return_value=policy))
+ monkeypatch.setattr(agent_module, "build_request_policy_trust_floor", AsyncMock(return_value=policy))
ctx = _ctx()
guardrails = agent_module._build_copilot_input_guardrails(
InputGuardrail,
@@ -3360,6 +3765,77 @@ class TestCredentialRefusalReachesAgent:
assert "Do not call `validate_block`" not in prompt
assert "native_allowed" not in prompt
+ def test_answer_only_prompt_is_content_neutral_and_has_no_tool_guidance(self) -> None:
+ prompt = agent_module._build_system_prompt(
+ tool_usage_guide="",
+ security_rules="",
+ answer_only=True,
+ )
+
+ assert "Respond to the user's current request inline" in prompt
+ assert "No tools are available in this answer-only turn" in prompt
+ assert "Explain the answer in prose" in prompt
+ assert "Do not return serialized workflow YAML/JSON or literal credential values" in prompt
+ assert "product or workflow-concept question" not in prompt
+ assert "documentation question" not in prompt
+ assert "greeting" not in prompt
+ for unavailable_name in (
+ "update_workflow",
+ "update_and_run_blocks",
+ "navigate_browser",
+ "list_credentials",
+ ):
+ assert unavailable_name not in prompt
+
+ def test_code_only_docs_answer_prompt_has_no_authoring_appendix(self) -> None:
+ prompt = agent_module._build_system_prompt(
+ tool_usage_guide="",
+ config=CopilotConfig(block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER),
+ answer_only=True,
+ )
+
+ assert "ACTIVE BLOCK AUTHORING POLICY: CODE-ONLY BROWSER MODE" not in prompt
+ assert "SYNTHESIZED CODE BLOCK" not in prompt
+ assert "update_workflow" not in prompt
+
+ def test_docs_answer_prompt_keeps_custom_security_rules(self) -> None:
+ prompt = agent_module._build_system_prompt(
+ tool_usage_guide="",
+ config=CopilotConfig(security_rules="CUSTOM SECURITY RULE"),
+ answer_only=True,
+ )
+
+ assert "CUSTOM SECURITY RULE" in prompt
+
+ @pytest.mark.parametrize("mode", [TurnIntentMode.ANSWER, TurnIntentMode.UNKNOWN])
+ def test_inline_only_dynamic_prompt_keeps_projected_guide_empty(self, mode: TurnIntentMode) -> None:
+ config = CopilotConfig()
+ ctx = _ctx(
+ copilot_config=config,
+ request_policy=RequestPolicy(),
+ turn_intent=TurnIntent(mode=mode),
+ )
+ instructions = agent_module._build_dynamic_system_prompt(
+ tool_usage_guide="- **update_workflow** — Mutate a workflow.",
+ config=config,
+ )
+
+ prompt = instructions(SimpleNamespace(context=ctx), object())
+
+ assert "Respond to the user's current request inline" in prompt
+ assert "TURN INTENT: docs_answer" not in prompt
+ assert "Mutate a workflow" not in prompt
+ assert "authoring_intent" not in prompt
+ assert "completion_contract" not in prompt
+ for unavailable_name in (
+ "update_workflow",
+ "update_and_run_blocks",
+ "navigate_browser",
+ "list_credentials",
+ ):
+ assert f"`{unavailable_name}`" not in prompt
+ assert f"**{unavailable_name}**" not in prompt
+
@pytest.mark.asyncio
async def test_run_copilot_agent_logs_resolved_block_authoring_policy(
self, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/test_copilot_build_phase.py b/tests/unit/test_copilot_build_phase.py
index 79d913015..a30063ac6 100644
--- a/tests/unit/test_copilot_build_phase.py
+++ b/tests/unit/test_copilot_build_phase.py
@@ -49,7 +49,7 @@ def _ti(mode: TurnIntentMode) -> TurnIntent:
[
# Explicitly-non-build modes return the COMPOSING sentinel.
(TurnIntentMode.EDIT, "no url", "no url", "", BuildPhase.COMPOSING),
- (TurnIntentMode.DOCS_ANSWER, "what is a workflow?", "what is a workflow?", "", BuildPhase.COMPOSING),
+ (TurnIntentMode.ANSWER, "what is a workflow?", "what is a workflow?", "", BuildPhase.COMPOSING),
(TurnIntentMode.DIAGNOSE, "the run failed", "the run failed", "", BuildPhase.COMPOSING),
(TurnIntentMode.CLARIFY, "anything", "anything", "", BuildPhase.COMPOSING),
(TurnIntentMode.REFUSE, "anything", "anything", "", BuildPhase.COMPOSING),
diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.py
index 5c5d71914..8a8e632be 100644
--- a/tests/unit/test_copilot_credential_pause.py
+++ b/tests/unit/test_copilot_credential_pause.py
@@ -34,6 +34,7 @@ from fastapi import HTTPException, status
from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.cache.base import NoopLock
+from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot import credential_pause as credential_pause_module
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.agent import RequestPolicyGuardrailInputs, _derive_turn_intent_on_context
@@ -72,7 +73,13 @@ from skyvern.forge.sdk.copilot.request_policy import (
credential_prompt_reason,
)
from skyvern.forge.sdk.copilot.tools._shared import TOTAL_TIMEOUT_SECONDS, _copilot_seconds_remaining
-from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode
+from skyvern.forge.sdk.copilot.turn_intent import (
+ TurnIntent,
+ TurnIntentAuthority,
+ TurnIntentClassification,
+ TurnIntentClassifierResult,
+ TurnIntentMode,
+)
from skyvern.forge.sdk.routes.workflow_copilot import (
WorkflowCopilotCredentialResponseRequest,
workflow_copilot_credential_response,
@@ -1882,36 +1889,6 @@ async def test_preflight_connect_binds_the_credential_and_clears_the_clarificati
assert sent_types == [WorkflowCopilotStreamMessageType.CREDENTIAL_REQUIRED]
-async def test_preflight_connect_preserves_an_explicit_defer_authoring_hold(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- ctx = _preflight_ctx()
- ctx.request_policy.authoring_intent = "defer_authoring"
- cache = _FakeCache()
- cache.store[credential_response_cache_key("org-1", "chat-1", "turn-1")] = encode_credential_response(
- "connected", "cred_1"
- )
- monkeypatch.setattr(credential_pause_module.app._inst, "CACHE", cache, raising=False)
- credential = _make_credential()
- monkeypatch.setattr(
- credential_pause_module.app,
- "DATABASE",
- SimpleNamespace(credentials=SimpleNamespace(get_credentials_by_ids=AsyncMock(return_value=[credential]))),
- )
- monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
- config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)
-
- resolution = await preflight_credential_pause(ctx, _make_stream(), config)
-
- assert resolution is not None and resolution.action == "connected"
- policy = ctx.request_policy
- assert policy.user_response_policy == "proceed"
- assert policy.resolved_credentials == [credential]
- assert policy.allow_update_workflow is False
- assert policy.allow_run_blocks is False
-
-
def _preflight_policy_inputs() -> RequestPolicyGuardrailInputs:
return RequestPolicyGuardrailInputs(
user_message="Log in to https://portal.example.com/login and download the invoices.",
@@ -1948,16 +1925,56 @@ async def test_preflight_connect_re_derives_run_authority_onto_the_turn_intent(
),
)
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
+ classify = AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.BUILD, confidence=0.95)
+ )
+ )
+ materialize = AsyncMock()
+ monkeypatch.setattr(agent_module, "classify_turn_intent", classify)
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize)
config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)
resolution = await preflight_credential_pause(ctx, _make_stream(), config)
assert resolution is not None and resolution.action == "connected"
- _derive_turn_intent_on_context(ctx, ctx.request_policy, policy_inputs)
+ await agent_module._resume_turn_intent_after_preflight_credential(ctx, ctx.request_policy, policy_inputs)
assert ctx.request_policy.clarification_reason == "none"
- assert ctx.turn_intent.mode is not TurnIntentMode.CLARIFY
+ assert ctx.turn_intent.mode is TurnIntentMode.BUILD
assert ctx.turn_intent.authority.may_update_workflow is True
assert ctx.turn_intent.authority.may_run_blocks is True
+ classify.assert_awaited_once()
+ materialize.assert_awaited_once()
+
+
+async def test_preflight_resume_unknown_does_not_inherit_connected_policy_authority(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _preflight_ctx()
+ policy = ctx.request_policy
+ policy.user_response_policy = "proceed"
+ policy.clarification_reason = "none"
+ policy.allow_update_workflow = True
+ policy.allow_run_blocks = True
+ monkeypatch.setattr(
+ agent_module,
+ "classify_turn_intent",
+ AsyncMock(
+ return_value=TurnIntentClassifierResult.success(
+ TurnIntentClassification(mode=TurnIntentMode.UNKNOWN, confidence=0.95)
+ )
+ ),
+ )
+ materialize = AsyncMock()
+ monkeypatch.setattr(agent_module, "materialize_request_policy_authoring", materialize)
+
+ await agent_module._resume_turn_intent_after_preflight_credential(ctx, policy, _preflight_policy_inputs())
+
+ assert ctx.turn_intent.mode is TurnIntentMode.UNKNOWN
+ assert ctx.turn_intent.authority.may_update_workflow is False
+ assert ctx.turn_intent.authority.may_run_blocks is False
+ materialize.assert_not_awaited()
@pytest.mark.asyncio
diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.py
index 928660502..76eef61af 100644
--- a/tests/unit/test_copilot_output_policy.py
+++ b/tests/unit/test_copilot_output_policy.py
@@ -1521,7 +1521,7 @@ def test_actuation_obligation_unrelated_prior_steer_stays_recoverable() -> None:
assert evaluation.reason_code == ACTUATION_OBLIGATION_STEER_REASON_CODE
[email protected]("mode", [TurnIntentMode.DOCS_ANSWER, TurnIntentMode.DIAGNOSE])
[email protected]("mode", [TurnIntentMode.ANSWER, TurnIntentMode.DIAGNOSE])
def test_actuation_obligation_allows_non_actuation_intents(mode: TurnIntentMode) -> None:
evaluation = evaluate_actuation_obligation(
turn_intent=TurnIntent(mode=mode, authority=TurnIntentAuthority(may_update_workflow=False)),
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index 473b9d43f..52e306680 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -137,6 +137,7 @@ def test_next_state_derivation(
({"response_type": "ASK_QUESTION"}, "question"),
({"verified": True, "workflow_applied": True}, "update"),
({"proposal_disposition": "review_untested"}, "update"),
+ ({"turn_outcome_response_kind": "answer", "workflow_mutated": False}, "answer"),
({"turn_outcome_response_kind": "diagnose", "workflow_mutated": False}, "answer"),
({"turn_outcome_response_kind": "diagnose", "workflow_mutated": True}, "stopped"),
({"turn_outcome_response_kind": "refuse", "workflow_mutated": False}, "answer"),
@@ -219,7 +220,7 @@ def test_finalize_applied_state_keeps_question_for_user_action_required() -> Non
def test_finalize_applied_state_preserves_answer_when_not_promoted_to_update() -> None:
- envelope = _assemble(turn_outcome_response_kind="diagnose", workflow_mutated=False)
+ envelope = _assemble(turn_outcome_response_kind="answer", workflow_mutated=False)
assert envelope.response_kind == "answer"
finalized = finalize_applied_state(envelope, applied=False)
diff --git a/tests/unit/test_copilot_turn_context.py b/tests/unit/test_copilot_turn_context.py
index f443a28d4..e258d01ca 100644
--- a/tests/unit/test_copilot_turn_context.py
+++ b/tests/unit/test_copilot_turn_context.py
@@ -188,7 +188,7 @@ def test_docs_answer_turn_does_not_pull_workflow_or_run_context() -> None:
packet = TurnContextAssembler().assemble(
TurnContextInputs(
turn_intent=TurnIntent(
- mode=TurnIntentMode.DOCS_ANSWER,
+ mode=TurnIntentMode.ANSWER,
required_context=[RequiredContextKey.DOCS_CONTEXT],
),
request_policy=RequestPolicy(),
diff --git a/tests/unit/test_copilot_turn_intent.py b/tests/unit/test_copilot_turn_intent.py
index 90372c048..4fc85a52b 100644
--- a/tests/unit/test_copilot_turn_intent.py
+++ b/tests/unit/test_copilot_turn_intent.py
@@ -9,9 +9,9 @@ import pytest
from pydantic import ValidationError
from skyvern.config import settings
+from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.copilot.agent import (
RequestPolicyGuardrailInputs,
- _docs_answer_turn_directive,
_store_request_policy_on_context,
)
from skyvern.forge.sdk.copilot.context import CopilotContext, StructuredContext
@@ -78,6 +78,33 @@ def _classification(
return TurnIntentClassifierResult.success(classification)
+def test_answer_mode_keeps_the_legacy_wire_value() -> None:
+ assert TurnIntentMode.ANSWER.value == "docs_answer"
+
+
+def test_turn_intent_prompt_defines_answer_mode_by_effect_not_examples() -> None:
+ prompt = prompt_engine.load_prompt(
+ template=PROMPT_NAME,
+ mode_values=", ".join(mode.value for mode in TurnIntentMode),
+ expected_output_values=", ".join(output.value for output in TurnIntentExpectedOutput),
+ required_context_values=", ".join(key.value for key in RequiredContextKey),
+ reason_code_values=", ".join(reason.value for reason in TurnIntentReasonCode),
+ user_message="hello",
+ request_policy_summary="",
+ workflow_yaml="",
+ earliest_user_turn="",
+ latest_prior_user_turn="",
+ latest_assistant_turn="",
+ retained_history="",
+ global_llm_context="",
+ )
+
+ assert "docs_answer=respond inline when no workflow, browser, or run action is requested" in prompt
+ assert "Classify by the requested effect, not by vocabulary or subject matter" in prompt
+ assert "product/docs/concept answer or conversational greeting" not in prompt
+ assert "A greeting with no workflow-change request" not in prompt
+
+
def _classifier_failure(failure_kind: TurnIntentClassifierFailureKind) -> TurnIntentClassifierResult:
return TurnIntentClassifierResult.failure(failure_kind)
@@ -139,9 +166,41 @@ def test_build_turn_intent_does_not_keyword_classify_without_llm_result() -> Non
)
assert intent.mode == TurnIntentMode.UNKNOWN
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_run_blocks is False
assert TurnIntentReasonCode.LLM_CLASSIFIER not in intent.reason_codes
+def test_genuine_unknown_classification_cannot_inherit_side_effect_authority() -> None:
+ intent = build_turn_intent(
+ user_message="Insufficient signal for a requested effect",
+ workflow_yaml="",
+ chat_history=[],
+ global_llm_context="",
+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),
+ classifier_result=_classification(TurnIntentMode.UNKNOWN, confidence=0.95),
+ )
+
+ assert intent.mode is TurnIntentMode.UNKNOWN
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_run_blocks is False
+ assert intent.is_inline_only is True
+
+
+ "authority",
+ [
+ TurnIntentAuthority(may_update_workflow=True),
+ TurnIntentAuthority(may_run_blocks=True),
+ TurnIntentAuthority(may_read_run_context=True),
+ TurnIntentAuthority(requires_user_input=True),
+ TurnIntentAuthority(may_answer_without_mutation=False),
+ ],
+)
+def test_inline_only_effect_requires_no_external_authority(authority: TurnIntentAuthority) -> None:
+ assert TurnIntent(mode=TurnIntentMode.UNKNOWN, authority=authority).is_inline_only is False
+
+
def test_build_turn_intent_applies_llm_build_classification() -> None:
intent = build_turn_intent(
user_message="Create a workflow from the page I have open.",
@@ -173,10 +232,10 @@ def test_build_turn_intent_applies_docs_classification_without_mutation() -> Non
chat_history=[],
global_llm_context="",
request_policy=RequestPolicy(),
- classifier_result=_classification(TurnIntentMode.DOCS_ANSWER),
+ classifier_result=_classification(TurnIntentMode.ANSWER),
)
- assert intent.mode == TurnIntentMode.DOCS_ANSWER
+ assert intent.mode == TurnIntentMode.ANSWER
assert intent.authority.may_update_workflow is False
assert intent.authority.may_run_blocks is False
assert RequiredContextKey.CURRENT_WORKFLOW in intent.required_context
@@ -907,17 +966,6 @@ def test_user_non_progress_does_not_fire_on_first_turn_even_when_marker_matches(
assert TurnIntentReasonCode.USER_NON_PROGRESS not in intent.reason_codes
-def test_docs_answer_turn_directive_renders_only_for_docs_answer_mode() -> None:
- docs_directive = _docs_answer_turn_directive(TurnIntent(mode=TurnIntentMode.DOCS_ANSWER))
- assert "TURN INTENT: docs_answer" in docs_directive
- assert "Answer it inline in the user's language" in docs_directive
- assert "do not offer to build an example workflow" in docs_directive
-
- assert _docs_answer_turn_directive(TurnIntent(mode=TurnIntentMode.BUILD)) == ""
- assert _docs_answer_turn_directive(TurnIntent(mode=TurnIntentMode.EDIT)) == ""
- assert _docs_answer_turn_directive(None) == ""
-
-
def test_store_request_policy_attaches_classified_turn_intent_to_context() -> None:
ctx = CopilotContext(
organization_id="org-1",
@@ -1281,7 +1329,7 @@ def test_structurally_infeasible_with_question_but_non_clarify_mode_forces_clari
assert intent.target_entities == {"workflow": ["current_workflow"]}
-def test_structurally_infeasible_without_question_fails_open_to_request_policy_baseline() -> None:
+def test_structurally_infeasible_without_question_falls_back_to_safe_unknown_baseline() -> None:
baseline = build_turn_intent(
user_message="build a workflow",
workflow_yaml="",
@@ -1306,8 +1354,8 @@ def test_structurally_infeasible_without_question_fails_open_to_request_policy_b
assert TurnIntentReasonCode.STRUCTURALLY_INFEASIBLE not in intent.reason_codes
assert intent.missing_context_question is None
assert intent.authority.model_dump() == baseline.authority.model_dump()
- assert intent.authority.may_update_workflow is True
- assert intent.authority.may_run_blocks is True
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_run_blocks is False
def test_request_policy_clarification_precedes_structural_infeasibility() -> None:
@@ -1345,8 +1393,8 @@ def test_classifier_failure_does_not_emit_infeasibility_clarify() -> None:
assert intent.mode != TurnIntentMode.CLARIFY
assert TurnIntentReasonCode.STRUCTURALLY_INFEASIBLE not in intent.reason_codes
- assert intent.authority.may_update_workflow is True
- assert intent.authority.may_run_blocks is True
+ assert intent.authority.may_update_workflow is False
+ assert intent.authority.may_run_blocks is False
def test_skip_test_bare_value_continuation_classifies_identically_after_fold() -> None:
diff --git a/tests/unit/test_copilot_turn_intent_tool_gate.py b/tests/unit/test_copilot_turn_intent_tool_gate.py
index 64be05583..31e61cc5b 100644
--- a/tests/unit/test_copilot_turn_intent_tool_gate.py
+++ b/tests/unit/test_copilot_turn_intent_tool_gate.py
@@ -82,9 +82,9 @@ def _assert_signal(
@pytest.mark.parametrize(
("mode", "tool_name", "expected_reason"),
[
- (TurnIntentMode.DOCS_ANSWER, "update_workflow", "turn_intent_no_mutation_update_blocked"),
- (TurnIntentMode.DOCS_ANSWER, "inspect_page_for_composition", "turn_intent_page_inspection_blocked"),
- (TurnIntentMode.DOCS_ANSWER, "list_credentials", "turn_intent_credential_metadata_blocked"),
+ (TurnIntentMode.ANSWER, "update_workflow", "turn_intent_no_mutation_update_blocked"),
+ (TurnIntentMode.ANSWER, "inspect_page_for_composition", "turn_intent_page_inspection_blocked"),
+ (TurnIntentMode.ANSWER, "list_credentials", "turn_intent_credential_metadata_blocked"),
(TurnIntentMode.CLARIFY, "inspect_page_for_composition", "turn_intent_page_inspection_blocked"),
(TurnIntentMode.CLARIFY, "update_and_run_blocks", "turn_intent_no_mutation_run_blocked"),
(TurnIntentMode.REFUSE, "update_and_run_blocks", "turn_intent_no_mutation_run_blocked"),
@@ -405,7 +405,7 @@ def test_turn_intent_gate_preserves_request_policy_update_skip_path() -> None:
@pytest.mark.asyncio
async def test_update_workflow_stops_before_persisting_for_answer_only_intent() -> None:
intent = TurnIntent(
- mode=TurnIntentMode.DOCS_ANSWER,
+ mode=TurnIntentMode.ANSWER,
authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),
)
ctx = _ctx(intent)
@@ -597,6 +597,26 @@ def test_recovery_diagnose_keeps_all_native_tools_registered() -> None:
assert names == {tool.name for tool in NATIVE_TOOLS}
[email protected]("mode", [TurnIntentMode.ANSWER, TurnIntentMode.UNKNOWN])
+def test_inline_only_turn_registers_no_model_visible_tools(mode: TurnIntentMode) -> None:
+ intent = TurnIntent(
+ mode=mode,
+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),
+ )
+
+ alias_map, overlays = _mcp_tool_surface_for_turn(
+ get_skyvern_mcp_alias_map(),
+ _build_skyvern_mcp_overlays(),
+ intent,
+ RequestPolicy(),
+ )
+ native_tools = _native_tools_for_turn(list(NATIVE_TOOLS), intent, RequestPolicy())
+
+ assert alias_map == {}
+ assert overlays == {}
+ assert native_tools == []
+
+
@pytest.mark.asyncio
async def test_get_run_results_rejects_explicit_run_from_other_workflow() -> None:
ctx = _ctx(
diff --git a/tests/unit/test_copilot_turn_outcome.py b/tests/unit/test_copilot_turn_outcome.py
index 132f53809..775e1d03d 100644
--- a/tests/unit/test_copilot_turn_outcome.py
+++ b/tests/unit/test_copilot_turn_outcome.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import pytest
from skyvern.forge.sdk.copilot.signature import compute_signature
-from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentMode
+from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode
from skyvern.forge.sdk.copilot.turn_outcome import (
build_minimal_turn_outcome,
build_turn_outcome,
@@ -19,9 +19,9 @@ from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOut
(TurnIntentMode.EDIT, ResponseKind.BUILD),
(TurnIntentMode.DRAFT_ONLY, ResponseKind.BUILD),
(TurnIntentMode.CLARIFY, ResponseKind.CLARIFY),
- (TurnIntentMode.UNKNOWN, ResponseKind.CLARIFY),
+ (TurnIntentMode.UNKNOWN, ResponseKind.ANSWER),
(TurnIntentMode.DIAGNOSE, ResponseKind.DIAGNOSE),
- (TurnIntentMode.DOCS_ANSWER, ResponseKind.DIAGNOSE),
+ (TurnIntentMode.ANSWER, ResponseKind.ANSWER),
(TurnIntentMode.REFUSE, ResponseKind.REFUSE),
],
)
@@ -34,6 +34,15 @@ def test_derive_response_kind_handles_none_intent() -> None:
assert derive_response_kind(None) is ResponseKind.CLARIFY
+def test_unknown_that_requires_user_input_remains_clarification() -> None:
+ intent = TurnIntent(
+ mode=TurnIntentMode.UNKNOWN,
+ authority=TurnIntentAuthority(requires_user_input=True),
+ )
+
+ assert derive_response_kind(intent) is ResponseKind.CLARIFY
+
+
def test_build_minimal_turn_outcome_sets_signature_and_inherited() -> None:
outcome = build_minimal_turn_outcome(
"The file is in the Artifacts section.",
diff --git a/tests/unit/test_copilot_turn_span.py b/tests/unit/test_copilot_turn_span.py
index 38b11f8b9..fcbea44c7 100644
--- a/tests/unit/test_copilot_turn_span.py
+++ b/tests/unit/test_copilot_turn_span.py
@@ -53,19 +53,15 @@ async def _stub_build_request_policy_with_child_span(*_args: Any, **_kwargs: Any
)
-async def _stub_build_request_policy_proceed(*_args: Any, **_kwargs: Any) -> RequestPolicy:
- return RequestPolicy(user_response_policy="ask_clarification", clarification_question="?")
-
-
async def _raise_unhandled_turn_error(*_args: Any, **_kwargs: Any) -> None:
raise RuntimeError("boom")
@pytest.fixture
-def patched_build_request_policy(monkeypatch: pytest.MonkeyPatch) -> None:
+def patched_request_policy_trust_floor(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
copilot_agent,
- "build_request_policy",
+ "build_request_policy_trust_floor",
_stub_build_request_policy_with_child_span,
)
@@ -80,7 +76,7 @@ def _find_span(spans: list[Any], name: str) -> Any:
@pytest.mark.asyncio
async def test_copilot_turn_span_parents_inner_spans(
span_exporter: Any,
- patched_build_request_policy: None,
+ patched_request_policy_trust_floor: None,
) -> None:
chat_request = _make_chat_request(message="Hello, build me a workflow")
chat_history = [_user_message("prior question")]
@@ -116,7 +112,7 @@ async def test_copilot_turn_span_parents_inner_spans(
@pytest.mark.asyncio
async def test_copilot_turn_span_uses_explicit_turn_index(
span_exporter: Any,
- patched_build_request_policy: None,
+ patched_request_policy_trust_floor: None,
) -> None:
chat_request = _make_chat_request()
chat_history = [_user_message("a"), _user_message("b"), _user_message("c")]
@@ -139,7 +135,7 @@ async def test_copilot_turn_span_uses_explicit_turn_index(
@pytest.mark.asyncio
async def test_copilot_turn_span_omits_session_id_when_missing(
span_exporter: Any,
- patched_build_request_policy: None,
+ patched_request_policy_trust_floor: None,
) -> None:
chat_request = _make_chat_request(workflow_copilot_chat_id=None)
@@ -161,7 +157,7 @@ async def test_copilot_turn_span_omits_session_id_when_missing(
@pytest.mark.asyncio
async def test_copilot_turn_span_preview_is_single_line_and_truncated(
span_exporter: Any,
- patched_build_request_policy: None,
+ patched_request_policy_trust_floor: None,
) -> None:
long_msg = "Line one\nLine two with extra content " + ("x" * 200)
chat_request = _make_chat_request(message=long_msg)
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index ac14dcd13..5f59125d2 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -39,6 +39,7 @@ from skyvern.forge.sdk.copilot.terminal_envelope import (
INTERRUPTED_TERMINAL_REASON,
assemble_terminal_envelope,
)
+from skyvern.forge.sdk.copilot.turn_outcome import build_minimal_turn_outcome
from skyvern.forge.sdk.routes import workflow_copilot as workflow_copilot_route
from skyvern.forge.sdk.routes.workflow_copilot import (
COPILOT_V2_FLAG_KEY,
@@ -89,7 +90,13 @@ def _make_chat_request(
)
-def _terminal_payload(*, verified: bool, workflow_applied: bool) -> dict[str, Any]:
+def _terminal_payload(
+ *,
+ verified: bool,
+ workflow_applied: bool,
+ workflow_mutated: bool = True,
+ turn_outcome_response_kind: str = "build",
+) -> dict[str, Any]:
envelope = assemble_terminal_envelope(
response_type="REPLY",
verified=verified,
@@ -99,8 +106,8 @@ def _terminal_payload(*, verified: bool, workflow_applied: bool) -> dict[str, An
blocker_reason=None,
halt_kind=None,
attempted="Attempted full run.",
- workflow_mutated=True,
- turn_outcome_response_kind="build",
+ workflow_mutated=workflow_mutated,
+ turn_outcome_response_kind=turn_outcome_response_kind,
)
assert envelope is not None
return envelope.model_dump(mode="json")
@@ -523,6 +530,60 @@ async def test_finalise_normal_turn_flag_on_stopped_envelope_renders_terminal_te
assert persisted_payload["terminalEnvelope"]["rendered_from_envelope"] is True
+async def test_finalise_normal_turn_preserves_and_persists_answer_outcome(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "should_render_copilot_terminal_from_envelope",
+ AsyncMock(return_value=True),
+ )
+ chat = SimpleNamespace(
+ organization_id="org-1",
+ workflow_copilot_chat_id="chat-1",
+ proposed_workflow=None,
+ auto_accept=False,
+ )
+ answer = "Google Sheets steps can read rows through a connected integration."
+ outcome = build_minimal_turn_outcome(answer, response_kind=ResponseKind.ANSWER)
+ agent_result = AgentResult(
+ user_response=answer,
+ updated_workflow=None,
+ global_llm_context=None,
+ response_type="REPLY",
+ narrative_payload=_narrative_payload(),
+ turn_outcome=outcome,
+ terminal_envelope=_terminal_payload(
+ verified=False,
+ workflow_applied=False,
+ workflow_mutated=False,
+ turn_outcome_response_kind="answer",
+ ),
+ )
+ setup_workflow = SimpleNamespace(workflow_id="wf-canonical")
+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, setup_workflow, agent_result)
+ stream = MagicMock(send=AsyncMock(return_value=True))
+
+ await workflow_copilot_route._finalise_normal_turn(
+ stream=stream,
+ chat=chat,
+ organization_id="org-1",
+ original_workflow=None,
+ chat_request=_make_chat_request(),
+ agent_result=agent_result,
+ )
+
+ response_frame = stream.send.await_args.args[0]
+ assert response_frame.message == answer
+ assert response_frame.terminal_envelope is not None
+ assert response_frame.terminal_envelope["response_kind"] == "answer"
+ assert response_frame.terminal_envelope["user_action_required"] is False
+ persisted = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs
+ assert persisted["content"] == answer
+ assert persisted["turn_outcome"].response_kind is ResponseKind.ANSWER
+
+
@pytest.mark.asyncio
async def test_finalise_normal_turn_flag_on_completed_envelope_keeps_message_but_sets_marker(
monkeypatch: pytest.MonkeyPatch,