Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Record one step per Task V3 turn, with its model call and tool calls, without changing bills (SKY-18790) (#9041)
Shuchang Zheng1b81905c28b7
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex 5e82953a8..91e482d47 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -134,6 +134,7 @@ export type StepApiResponse = {retry_index: number;status: Status;step_cost: number;+ created_by?: string | null;};export type Task = {diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 2a4da4fc2..6345cc17d 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -9,6 +9,7 @@ import randomimport reimport secretsimport string+import sysimport timeimport uuidfrom asyncio.exceptions import CancelledError@@ -180,7 +181,7 @@ from skyvern.forge.sdk.experimentation.workflow_block_engine import task_v3_disafrom skyvern.forge.sdk.fail_fast.shadow import record_fail_fast_shadowfrom skyvern.forge.sdk.forge_log import exception_log_fieldsfrom skyvern.forge.sdk.log_artifacts import save_step_logs, save_task_logs-from skyvern.forge.sdk.models import SpeculativeLLMMetadata, Step, StepStatus+from skyvern.forge.sdk.models import TASK_V3_TURN_STEP_CREATED_BY, SpeculativeLLMMetadata, Step, StepStatusfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import (@@ -219,6 +220,7 @@ from skyvern.forge.taskv3.loop import (DownloadWait,LoopOutcome,RoundAction,+ TurnRecord,submissions_across_contexts,)from skyvern.forge.taskv3.pre_submit_capture import PreSubmitCaptureRing, is_run_sampled, pre_submit_screenshot@@ -620,6 +622,9 @@ _TASKV3_REASONING_MAX_CHARS = 1000# Same reason, for the outcome line: it can carry two page-supplied URLs (or, when the call reached no# page, the tool's own error text), and neither a URL nor a tool error has a length bound._TASKV3_RESPONSE_MAX_CHARS = 500+# A turn step write sits on the turn's critical path (the create precedes its model call), so a slow database+# costs the run at most this per write instead of stalling it.+_TASKV3_TURN_STEP_WRITE_TIMEOUT_SECONDS = 3def _taskv3_row_response(outcome: dict[str, Any]) -> str | None:@@ -3356,6 +3361,60 @@ class ForgeAgent:v3_round_index += 1v3_round_billed = False+ # One step row per loop turn beside this block's own `step`: the turn's model call, its tool calls and the+ # action rows it wrote land on it. `step` keeps the run's status, billing and step-budget unit.+ v3_turn_step: Step | None = None+ v3_turn_step_open = False++ async def _on_turn_start(turn: int) -> Step | None:+ nonlocal v3_turn_step, v3_turn_step_open+ v3_turn_step, v3_turn_step_open = None, False+ try:+ async with asyncio.timeout(_TASKV3_TURN_STEP_WRITE_TIMEOUT_SECONDS):+ v3_turn_step = await app.DATABASE.tasks.create_step(+ task_id=task.task_id,+ order=turn,+ # The LLM layer reads the attributed step's retry_index to decide whether to send screenshots.+ retry_index=step.retry_index,+ organization_id=task.organization_id,+ status=StepStatus.running,+ created_by=TASK_V3_TURN_STEP_CREATED_BY,+ )+ except Exception:+ # The turn's model call and rows then land on the block's step, as before turn steps existed.+ LOG.warning("task_v3 failed to create turn step", task_id=task.task_id, turn=turn, exc_info=True)+ v3_turn_step = None+ return None+ v3_turn_step_open = True+ return v3_turn_step++ async def _finish_v3_turn_step(status: StepStatus, record: TurnRecord | None) -> None:+ nonlocal v3_turn_step_open+ if v3_turn_step is None or not v3_turn_step_open:+ return+ v3_turn_step_open = False+ with contained_effect("task_v3 turn step finish", task_id=task.task_id, step_id=v3_turn_step.step_id):+ async with asyncio.timeout(_TASKV3_TURN_STEP_WRITE_TIMEOUT_SECONDS):+ await app.DATABASE.tasks.finish_step(+ task_id=task.task_id,+ step_id=v3_turn_step.step_id,+ organization_id=task.organization_id,+ status=status,+ output=AgentStepOutput(+ llm_seconds=record.llm_seconds if record else None,+ tool_calls=record.tool_calls if record else None,+ ),+ )++ async def _on_turn_end(record: TurnRecord) -> None:+ if record.outcome_status == "canceled":+ status = StepStatus.canceled+ elif record.outcome_status == "loop_error":+ status = StepStatus.failed+ else:+ status = StepStatus.completed+ await _finish_v3_turn_step(status, record)+async def _on_action_round(round_actions: list[RoundAction], turn_reasoning: str | None, /, *, round_done: bool) -> None:@@ -3378,7 +3437,7 @@ class ForgeAgent:await _settle_before_post_action_screenshot(browser_state)screenshot = await browser_state.take_post_action_screenshot(scrolling_number=0)screenshot_artifact_id = await app.ARTIFACT_MANAGER.create_artifact(- step=step, artifact_type=ArtifactType.SCREENSHOT_ACTION, data=screenshot+ step=v3_turn_step or step, artifact_type=ArtifactType.SCREENSHOT_ACTION, data=screenshot)except Exception:LOG.warning("task_v3 failed to capture post-action screenshot", task_id=task.task_id, exc_info=True)@@ -3394,7 +3453,7 @@ class ForgeAgent:turn_reasoning = turn_reasoning[:_TASKV3_REASONING_MAX_CHARS]for round_action in round_actions:v3_round_billed = v3_round_billed or round_action.billable- # A row that bills nothing rides the LAST consumed index (or the single Step's own+ # A row that bills nothing rides the LAST consumed index (or the block step's own# order 0) the way the decision row below does: the workflow-run step budget counts# distinct (task_id, step_order) pairs, and a fresh index nothing later claims would# open one of its own. Read per row because a row publishes before the rest of its@@ -3436,8 +3495,8 @@ class ForgeAgent:organization_id=task.organization_id,workflow_run_id=task.workflow_run_id,task_id=task.task_id,- step_id=step.step_id,- # Round index, not the single Step's order: makes each BILLABLE v3 action+ step_id=(v3_turn_step or step).step_id,+ # Round index, not the turn step's order: makes each BILLABLE v3 action# ROUND count as one unit of the workflow-run step budget (distinct (task,# order) pairs).step_order=row_step_order,@@ -3810,6 +3869,8 @@ class ForgeAgent:step=step,should_cancel=_should_cancel,on_action_round=_on_action_round,+ on_turn_start=_on_turn_start,+ on_turn_end=_on_turn_end,on_pre_action=pre_submit_ring.capture if pre_submit_ring is not None else None,# A code status the model has moved past is no longer what the run ends on.on_page_action=verification_state.page_engaged,@@ -3849,6 +3910,11 @@ class ForgeAgent:input_dispatch.end_login_pace()if context and credential_parameter_key is not None:context.active_credential_parameter_key = prev_active_credential_parameter_key+ # A loop that raised never ended its last turn.+ await _finish_v3_turn_step(+ StepStatus.canceled if isinstance(sys.exception(), asyncio.CancelledError) else StepStatus.failed,+ None,+ )# Frames are already in memory, so a loop that raised or ran out of budget still# persists what it captured; bounded so the unwind of a cancelled run is not held up.with contained_effect("task_v3 pre-submit frame persist", task_id=task.task_id):@@ -3995,7 +4061,9 @@ class ForgeAgent:async with asyncio.timeout(30):decision_shot = await browser_state.take_post_action_screenshot(scrolling_number=0)decision_screenshot_id = await app.ARTIFACT_MANAGER.create_artifact(- step=step, artifact_type=ArtifactType.SCREENSHOT_ACTION, data=decision_shot+ step=v3_turn_step or step,+ artifact_type=ArtifactType.SCREENSHOT_ACTION,+ data=decision_shot,)except Exception:LOG.warning(@@ -4008,8 +4076,9 @@ class ForgeAgent:organization_id=task.organization_id,workflow_run_id=task.workflow_run_id,task_id=task.task_id,- step_id=step.step_id,- # The decision rides on the LAST consumed billable index (or the single Step's own+ # The last turn's step: a verdict is that turn's finish call.+ step_id=(v3_turn_step or step).step_id,+ # The decision rides on the LAST consumed billable index (or the block step's own# order 0): a fresh index would read as a new distinct (task, step_order) pair to# the workflow-run step budget, the way v1's complete shares its final step.step_order=max(v3_round_index - 1, 0),@@ -4587,7 +4656,8 @@ class ForgeAgent:recovery_code_progress=recovery_code_progress,)finally:- await app.ARTIFACT_MANAGER.flush_step_archive(step.step_id)+ # The block's turn steps share its ZIP: one storage PUT per block rather than one per turn.+ await app.ARTIFACT_MANAGER.flush_task_step_archives_as_one(step)return step, detailed_output, Noneif workflow_owned_recovery:diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.pyindex 1d5742d1f..d4844f1f8 100644--- a/skyvern/forge/sdk/artifact/manager.py+++ b/skyvern/forge/sdk/artifact/manager.py@@ -1885,10 +1885,35 @@ class ArtifactManager:)if _bundling_enabled():- await self._flush_step_archive_bundled(accumulator)+ await self._flush_step_archives_bundled(accumulator.step, [accumulator])else:await self._flush_step_archive_unbundled(accumulator)+ await self._apply_pending_action_screenshot_updates(accumulator)+ async def flush_task_step_archives_as_one(self, owner: Step) -> None:+ """Persist every buffered archive of ``owner``'s task as one ZIP owned by ``owner``.++ One storage PUT for the task instead of one per step; each member row keeps the step that produced it.+ Unbundled mode has no ZIP, so each step flushes on its own there.+ """+ step_ids = [sid for sid, acc in list(self._step_archives.items()) if acc.step.task_id == owner.task_id]+ if not _bundling_enabled():+ for step_id in step_ids:+ await self.flush_step_archive(step_id)+ return+ accumulators = [+ acc+ for step_id in step_ids+ if (acc := self._step_archives.pop(step_id, None)) is not None and acc.entries and acc.member_types+ ]+ if not accumulators:+ return+ accumulators.sort(key=lambda acc: (acc.step.order, acc.step.retry_index))+ await self._flush_step_archives_bundled(owner, accumulators)+ for accumulator in accumulators:+ await self._apply_pending_action_screenshot_updates(accumulator)++ async def _apply_pending_action_screenshot_updates(self, accumulator: StepArchiveAccumulator) -> None:for organization_id, action_id, artifact_id in accumulator.pending_action_screenshot_updates:try:await app.DATABASE.artifacts.update_action_screenshot_artifact_id(@@ -1904,14 +1929,14 @@ class ArtifactManager:exc_info=True,)- async def _flush_step_archive_bundled(self, accumulator: StepArchiveAccumulator) -> None:- """Bundle all accumulated entries into a single ZIP, one storage PUT, parent + member rows."""- step = accumulator.step+ async def _flush_step_archives_bundled(self, owner: Step, accumulators: list[StepArchiveAccumulator]) -> None:+ """Bundle the accumulators' entries into one ZIP owned by ``owner``: one storage PUT, parent + member rows."""+ run_scope = accumulators[0]archive_artifact_id = generate_artifact_id()archive_uri = app.STORAGE.build_uri(- organization_id=step.organization_id,+ organization_id=owner.organization_id,artifact_id=archive_artifact_id,- step=step,+ step=owner,artifact_type=ArtifactType.STEP_ARCHIVE,)@@ -1920,17 +1945,26 @@ class ArtifactManager:artifact_id=archive_artifact_id,artifact_type=ArtifactType.STEP_ARCHIVE,uri=archive_uri,- organization_id=step.organization_id,- step_id=step.step_id,- task_id=step.task_id,- workflow_run_id=accumulator.workflow_run_id,- workflow_run_block_id=accumulator.workflow_run_block_id,- run_id=accumulator.run_id,+ organization_id=owner.organization_id,+ step_id=owner.step_id,+ task_id=owner.task_id,+ workflow_run_id=run_scope.workflow_run_id,+ workflow_run_block_id=run_scope.workflow_run_block_id,+ run_id=run_scope.run_id,created_at=now,modified_at=now,)- zip_bytes = self._build_zip(accumulator.entries)+ entries: dict[str, bytes] = {}+ members: list[tuple[StepArchiveAccumulator, ArtifactType, str, str]] = []+ for accumulator in accumulators:+ # Every step numbers its files from 0, so another step's files get its step id as a prefix in the ZIP.+ prefix = "" if accumulator.step.step_id == owner.step_id else f"{accumulator.step.step_id}_"+ for artifact_type, filename, artifact_id in accumulator.member_types:+ entries[prefix + filename] = accumulator.entries[filename]+ members.append((accumulator, artifact_type, prefix + filename, artifact_id))++ zip_bytes = self._build_zip(entries)await app.STORAGE.store_artifact(archive_artifact, zip_bytes)# Parent archive row (no bundle_key — represents the ZIP object itself)@@ -1938,12 +1972,12 @@ class ArtifactManager:artifact_id=archive_artifact_id,artifact_type=ArtifactType.STEP_ARCHIVE,uri=archive_uri,- organization_id=step.organization_id,- step_id=step.step_id,- task_id=step.task_id,- workflow_run_id=accumulator.workflow_run_id,- workflow_run_block_id=accumulator.workflow_run_block_id,- run_id=accumulator.run_id,+ organization_id=owner.organization_id,+ step_id=owner.step_id,+ task_id=owner.task_id,+ workflow_run_id=run_scope.workflow_run_id,+ workflow_run_block_id=run_scope.workflow_run_block_id,+ run_id=run_scope.run_id,)# Member rows (bundle_key points to the filename inside the ZIP)member_models = [@@ -1952,14 +1986,14 @@ class ArtifactManager:artifact_type=artifact_type,uri=archive_uri,bundle_key=filename,- organization_id=step.organization_id,- step_id=step.step_id,- task_id=step.task_id,+ organization_id=accumulator.step.organization_id,+ step_id=accumulator.step.step_id,+ task_id=accumulator.step.task_id,workflow_run_id=accumulator.workflow_run_id,workflow_run_block_id=accumulator.workflow_run_block_id,run_id=accumulator.run_id,)- for artifact_type, filename, artifact_id in accumulator.member_types+ for accumulator, artifact_type, filename, artifact_id in members]await app.DATABASE.artifacts.bulk_create_artifacts([parent_model, *member_models])diff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.pyindex 4367cb975..ac3f91906 100644--- a/skyvern/forge/sdk/db/repositories/tasks.py+++ b/skyvern/forge/sdk/db/repositories/tasks.py@@ -32,7 +32,7 @@ from skyvern.forge.sdk.db.utils import (hydrate_action,serialize_proxy_location,)-from skyvern.forge.sdk.models import Step, StepStatus+from skyvern.forge.sdk.models import TASK_V3_TURN_STEP_CREATED_BY, Step, StepStatusfrom skyvern.forge.sdk.schemas.runs import Runfrom skyvern.forge.sdk.schemas.tasks import OrderBy, SortDirection, Task, TaskStatusfrom skyvern.forge.sdk.trace import traced@@ -45,6 +45,13 @@ from skyvern.webeye.actions.actions import ActionLOG = structlog.get_logger()+def _step_status_values(status: StepStatus) -> dict[str, Any]:+ values: dict[str, Any] = {"status": status}+ if status.is_terminal():+ values["finished_at"] = func.coalesce(StepModel.finished_at, naive_utc_now())+ return values++class TasksRepository(BaseRepository):_background_tasks: set[asyncio.Task] = set() # noqa: RUF012@@ -173,9 +180,11 @@ class TasksRepository(BaseRepository):created_by=created_by,)session.add(new_step)+ # The flush fills every column default, so the row needs no re-read; convert it before commit expires it.+ await session.flush()+ step = convert_to_step(new_step, debug_enabled=self.debug_enabled)await session.commit()- await session.refresh(new_step)- return convert_to_step(new_step, debug_enabled=self.debug_enabled)+ return step@read_retry()@db_operation("get_task", log_errors=False)@@ -306,13 +315,14 @@ class TasksRepository(BaseRepository):"""Get the total count of unique (step.task_id, step.order) pairs of StepModel for the given task idsBasically translate this sql query into a SQLAlchemy query: select count(distinct(s.task_id, s.order)) from steps s- where s.task_id in task_ids+ where s.task_id in task_ids. Task V3 turn steps are not budget units."""async with self.Session() as session:unique_step_orders = (select(StepModel.task_id, StepModel.order).where(StepModel.task_id.in_(task_ids)).where(StepModel.organization_id == organization_id)+ .where(StepModel.created_by.is_distinct_from(TASK_V3_TURN_STEP_CREATED_BY)).distinct().subquery())@@ -329,14 +339,16 @@ class TasksRepository(BaseRepository):"""Distinct (task_id, order) pairs across steps UNION actions' round-stamped step_order.A step-engine action's step_order mirrors an existing step order, so the union equals the- step count; a task_v3 task has one Step row but round-stamped actions, so each of its- action rounds counts individually. This is the workflow-run step-budget unit.+ step count; a task_v3 task counts its order-0 step plus its round-stamped actions, so each of+ its action rounds counts individually. Its per-turn steps are not budget units.+ This is the workflow-run step-budget unit."""async with self.Session() as session:step_pairs = (select(StepModel.task_id, StepModel.order).where(StepModel.task_id.in_(task_ids)).where(StepModel.organization_id == organization_id)+ .where(StepModel.created_by.is_distinct_from(TASK_V3_TURN_STEP_CREATED_BY)))action_pairs = (select(ActionModel.task_id, ActionModel.step_order)@@ -497,6 +509,8 @@ class TasksRepository(BaseRepository):.filter_by(task_id=task_id).filter_by(organization_id=organization_id).filter(StepModel.status != StepStatus.canceled)+ # A Task V3 block's turn steps sit above its own step, which holds its final screenshot.+ .filter(StepModel.created_by.is_distinct_from(TASK_V3_TURN_STEP_CREATED_BY)).order_by(StepModel.order.desc()).order_by(StepModel.retry_index.desc()))@@ -531,9 +545,7 @@ class TasksRepository(BaseRepository):) -> Step:values: dict[str, Any] = {}if status is not None:- values["status"] = status- if status.is_terminal():- values["finished_at"] = func.coalesce(StepModel.finished_at, naive_utc_now())+ values.update(_step_status_values(status))if output is not None:values["output"] = output.model_dump(exclude_none=True)if is_last is not None:@@ -557,17 +569,7 @@ class TasksRepository(BaseRepository):values["last_llm_model"] = last_llm_modelif values:- async with self.Session() as session:- result = await session.execute(- update(StepModel)- .where(StepModel.task_id == task_id)- .where(StepModel.step_id == step_id)- .where(StepModel.organization_id == organization_id)- .values(values)- )- if result.rowcount == 0:- raise NotFoundError("Step not found")- await session.commit()+ await self._write_step(task_id, step_id, organization_id, values)updated_step = await self.get_step(step_id, organization_id)# get_step does not scope by task_id, so re-check it here: a call carrying no field to@@ -576,6 +578,35 @@ class TasksRepository(BaseRepository):raise NotFoundError("Step not found")return updated_step+ @traced(name="skyvern.db.finish_step")+ @db_operation("finish_step")+ async def finish_step(+ self,+ task_id: str,+ step_id: str,+ organization_id: str | None,+ status: StepStatus,+ output: AgentStepOutput,+ ) -> None:+ """`update_step`'s status and output write without reading the row back, for a caller that has no use for it."""+ values = {**_step_status_values(status), "output": output.model_dump(exclude_none=True)}+ await self._write_step(task_id, step_id, organization_id, values)++ async def _write_step(+ self, task_id: str, step_id: str, organization_id: str | None, values: dict[str, Any]+ ) -> None:+ async with self.Session() as session:+ result = await session.execute(+ update(StepModel)+ .where(StepModel.task_id == task_id)+ .where(StepModel.step_id == step_id)+ .where(StepModel.organization_id == organization_id)+ .values(values)+ )+ if result.rowcount == 0:+ raise NotFoundError("Step not found")+ await session.commit()+@db_operation("clear_task_failure_reason")async def clear_task_failure_reason(self, organization_id: str, task_id: str) -> Task:async with self.Session() as session:diff --git a/skyvern/forge/sdk/models.py b/skyvern/forge/sdk/models.pyindex ad3e79ef8..1073bc2b6 100644--- a/skyvern/forge/sdk/models.py+++ b/skyvern/forge/sdk/models.py@@ -8,6 +8,11 @@ from pydantic import BaseModelfrom skyvern.schemas.steps import AgentStepOutputfrom skyvern.webeye.actions.action_types import ActionType+# `steps.created_by` of a Task V3 turn step: one row per loop turn, beside the block's own order-0 step. Turn+# steps are observability only -- the order-0 step stays the block's billing unit and workflow step-budget unit,+# so the warehouse invoice model and the budget count both skip rows carrying this marker.+TASK_V3_TURN_STEP_CREATED_BY = "task_v3"+class StepStatus(StrEnum):created = "created"diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex 01fa4e5fd..195838d9e 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -74,6 +74,8 @@ from skyvern.forge.taskv3.loop import (SemanticCommitStats,SubmitWatch,ToolSpec,+ TurnEnd,+ TurnStart,UnseenPageText,VerificationBlocker,make_finish_tool,@@ -269,6 +271,8 @@ async def run_task_v3_agent_loop(step: Any = None,should_cancel: Callable[[], Awaitable[bool]] | None = None,on_action_round: ActionRoundSink | None = None,+ on_turn_start: TurnStart | None = None,+ on_turn_end: TurnEnd | None = None,on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,on_page_action: Callable[[], None] | None = None,extra_tools: list[ToolSpec] | None = None,@@ -334,7 +338,8 @@ async def run_task_v3_agent_loop("""Run one Task V3 task to completion against `page`, returning the loop outcome.`step` is threaded into every LLMCaller.call so the run's cost/tokens/model and LLM- artifacts attribute to it. `should_cancel` is polled between turns and mid-batch; token+ artifacts attribute to it, except a turn's own model call when `on_turn_start` returns a `step`+ for that turn. `should_cancel` is polled between turns and mid-batch; tokenand wall-clock budgets bound cost beyond the turn/tool-call caps. When a`page_fingerprint` sampler is provided, a finish(completed) on an unsettled page IS forced backfor a bounded re-verification turn; without one, pre-finish re-verification is prompt guidance@@ -717,6 +722,8 @@ async def run_task_v3_agent_loop(call_kwargs=build_call_kwargs(step, llm_caller),should_cancel=should_cancel,on_action_round=on_action_round,+ on_turn_start=on_turn_start,+ on_turn_end=on_turn_end,on_pre_action=on_pre_action,on_page_action=on_page_action,max_tokens=max_tokens,diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex f76f17aba..46944fdc4 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -54,6 +54,7 @@ from skyvern.forge.taskv3.handoff_redaction import MAX_HANDOFF_URL_CHARS, normalfrom skyvern.forge.taskv3.intercepted_submission import InterceptedSubmission, SubmissionOutcomefrom skyvern.forge.taskv3.run_arms import DEAD_END_RETURN_FLAG, run_arm_enabledfrom skyvern.forge.taskv3.target_label import describe_target+from skyvern.schemas.steps import StepToolCallfrom skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_ENTRIES, ERROR_CODE_MAPPING_MAX_UTF8_BYTESfrom skyvern.webeye.navigation import clear_task_nav_error_code, redact_url_secrets@@ -628,6 +629,33 @@ class ActionRoundSink(Protocol):) -> None: ...+@dataclass+class TurnRecord:+ """One loop turn as `on_turn_end` receives it: one model call and every tool call it asked for, in order."""++ turn: int+ llm_seconds: float | None = None+ tool_calls: list[StepToolCall] = field(default_factory=list)+ # The loop's terminal status when the run ended during this turn, else None.+ outcome_status: str | None = None+++# Awaited right before a turn's model call with the turn number (from 1). A step it returns is that call's `step`,+# so the call's cost, tokens and artifacts land on the turn; None keeps the run-wide one.+TurnStart = Callable[[int], Awaitable[Any]]+# Awaited once the turn is over: when the next turn starts, or when the loop ends during it.+TurnEnd = Callable[[TurnRecord], Awaitable[None]]+++@dataclass+class _OpenTurn:+ record: TurnRecord+ # (recorded name, billable) per call the model asked for, and what each dispatched call returned, both by batch+ # position: a provider's tool-call ids are not guaranteed unique within a response.+ requested: list[tuple[str, bool]] = field(default_factory=list)+ dispatched: dict[int, StepToolCall] = field(default_factory=dict)++# Awaited after a billable/download-signaling result; it never ends the run. A settle hook awaited from# finish(completed) lets a download land, skips files tools staged this run, and never refuses.DownloadWait = Callable[[], Awaitable[None]]@@ -3943,6 +3971,7 @@ class LoopState:# This cap trip's reserve verdict, so the completion offer on the same page does not ask the judge again.block_reserve_verdict: GoalVerdict | None = Nonetarget_action_rounds_granted: int = 0+ open_turn: _OpenTurn | None = Noneasync def run_agent_tool_loop(@@ -3960,6 +3989,8 @@ async def run_agent_tool_loop(call_kwargs: dict[str, Any] | None = None,should_cancel: Callable[[], Awaitable[bool]] | None = None,on_action_round: ActionRoundSink | None = None,+ on_turn_start: TurnStart | None = None,+ on_turn_end: TurnEnd | None = None,on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,# Called before each page-touching tool call is dispatched.on_page_action: Callable[[], None] | None = None,@@ -4060,6 +4091,21 @@ async def run_agent_tool_loop(st.action_counts.clear()st.action_warned.clear()+ async def _close_turn() -> None:+ open_turn, st.open_turn = st.open_turn, None+ if open_turn is None or on_turn_end is None:+ return+ record = open_turn.record+ record.tool_calls = [+ open_turn.dispatched.get(position) or StepToolCall(tool=name, status="skipped", billable=billable)+ for position, (name, billable) in enumerate(open_turn.requested)+ ]+ record.outcome_status = st.outcome.status if st.outcome is not None else None+ try:+ await on_turn_end(record)+ except Exception:+ LOG.warning("taskv3 on_turn_end callback failed", turn=record.turn, exc_info=True)+def _tokens_remaining() -> int | None:"""Charged headroom, clamped to the raw ceiling's turns left in charged units, so a hold or evidence gatepricing N turns at `last_turn_tokens` does not defer into the raw trip. The raw trip itself is never extended."""@@ -4530,6 +4576,8 @@ async def run_agent_tool_loop()while st.outcome is None:+ # The previous turn ends here rather than at each of its exits: a turn leaves by `continue` as well.+ await _close_turn()if should_cancel is not None and await should_cancel():st.outcome = LoopOutcome("canceled", "run canceled")break@@ -4594,6 +4642,16 @@ async def run_agent_tool_loop(activity.tool_calls_remaining = st.max_tool_calls - st.total_tool_callsif st.max_action_steps is not None:activity.action_steps_remaining = st.max_action_steps - st.action_steps+ open_turn = st.open_turn = _OpenTurn(TurnRecord(turn=st.turns))+ turn_call_kwargs: dict[str, Any] = {}+ if on_turn_start is not None:+ try:+ turn_step = await on_turn_start(st.turns)+ except Exception:+ LOG.warning("taskv3 on_turn_start callback failed", turn=st.turns, exc_info=True)+ else:+ if turn_step is not None:+ turn_call_kwargs["step"] = turn_step# Elide superseded perception results before re-sending the transcript, so a perception-heavy# run can't balloon the context to the token backstop (the pre-compaction runaway mode).@@ -4627,6 +4685,7 @@ async def run_agent_tool_loop(# resilience, which v3 otherwise loses by running as one non-retried unit.response = Nonecall_attempt = 0+ llm_started_at = time.monotonic()while True:try:response = await llm_caller.call(@@ -4637,7 +4696,7 @@ async def run_agent_tool_loop(use_message_history=True,raw_response=True,screenshots=screenshots_for_call,- **active_call_kwargs,+ **{**active_call_kwargs, **turn_call_kwargs},)breakexcept retryable_call_exceptions as exc:@@ -4669,6 +4728,7 @@ async def run_agent_tool_loop(on_llm_call_exhausted(exc)st.outcome = LoopOutcome("loop_error", f"llm_call_failed: {type(exc).__name__}: {exc}")break+ open_turn.record.llm_seconds = time.monotonic() - llm_started_atif st.outcome is not None:break@@ -4696,6 +4756,10 @@ async def run_agent_tool_loop(text = _extract_text(response)reasoning_summary = _extract_reasoning_summary(response)tool_calls = _extract_tool_calls(response)+ open_turn.requested = [+ (name, tool_by_name[name].billable) if name in tool_by_name else ("unknown_tool", False)+ for _, name, _ in tool_calls+ ]assistant_message: dict[str, Any] = {"role": "assistant", "content": text or None}if tool_calls:@@ -5549,6 +5613,12 @@ async def run_agent_tool_loop(**solve_fields,**attribution,)+ open_turn.dispatched[idx] = StepToolCall(+ tool=tool_name if spec is not None else "unknown_tool",+ status="refused" if result.status == "error" and result.refused else result.status,+ duration_seconds=tool_duration_seconds,+ billable=bool(spec is not None and spec.billable),+ )if spec is not None and spec.billable:target_key = _call_selector(args) or f"tool:{tool_name}"same_count, same_errors = st.canonical.record_touch(target_key, result.status == "error")@@ -6153,6 +6223,7 @@ async def run_agent_tool_loop(if st.outcome is None:st.outcome = LoopOutcome("loop_error", "loop exited without an outcome")+ await _close_turn()# Every model- or loop-produced terminal once the cap tripped — a finish verdict, a guard# termination (even in the granting batch itself), a stall exit, the spent-grant exit —diff --git a/skyvern/schemas/steps.py b/skyvern/schemas/steps.pyindex a9bdc8b62..d4759463c 100644--- a/skyvern/schemas/steps.py+++ b/skyvern/schemas/steps.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import Any, cast+from typing import Any, Literal, castfrom pydantic import BaseModel, SerializerFunctionWrapHandler, model_serializer@@ -14,6 +14,18 @@ class BrowserMetadata(BaseModel):website_url: str | None = None+class StepToolCall(BaseModel):+ """One tool call the model made in a Task V3 turn. Names, outcomes and timings only: arguments and+ results carry end-user data."""++ tool: str+ # `refused`: the tool itself refused. `skipped`: the loop never dispatched it -- a budget, a cancellation, an+ # earlier failure in the same batch, or a refusal the loop answered before dispatch.+ status: Literal["ok", "error", "refused", "skipped"]+ duration_seconds: float | None = None+ billable: bool = False++class AgentStepOutput(BaseModel):"""Output of the agent step, this is recorded in the database.@@ -28,6 +40,9 @@ class AgentStepOutput(BaseModel):terminal_user_errors: bool = Falsebrowser_metadata: BrowserMetadata | None = Nonestep_exception: str | None = None+ # Task V3 turn steps only: how long the turn's model call took (retries included) and what it called.+ llm_seconds: float | None = None+ tool_calls: list[StepToolCall] | None = None@model_serializer(mode="wrap")def serialize_model(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:diff --git a/tests/unit/forge/sdk/artifact/test_manager.py b/tests/unit/forge/sdk/artifact/test_manager.pynew file mode 100644index 000000000..6b7a3897a--- /dev/null+++ b/tests/unit/forge/sdk/artifact/test_manager.py@@ -0,0 +1,78 @@+import io+import zipfile+from datetime import datetime+from types import SimpleNamespace+from typing import Any++import pytest++from skyvern.forge.sdk.artifact.manager import ArtifactManager+from skyvern.forge.sdk.artifact.models import ArtifactType+from skyvern.forge.sdk.models import Step, StepStatus+++def _step(step_id: str, order: int, task_id: str = "tsk_block") -> Step:+ now = datetime.utcnow()+ return Step(+ task_id=task_id,+ step_id=step_id,+ order=order,+ retry_index=0,+ status=StepStatus.running,+ is_last=False,+ organization_id="o_archive",+ created_at=now,+ modified_at=now,+ )+++async def test_a_tasks_step_archives_flush_as_one_zip_with_each_file_on_its_own_step(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # A Task V3 block's turn steps share its ZIP (one storage PUT per block); each file's row stays on its turn.+ manager = ArtifactManager()+ block, turn_1, turn_2 = _step("stp_block", 0), _step("stp_turn_1", 1), _step("stp_turn_2", 2)+ other = _step("stp_other", 1, task_id="tsk_other")+ for step in (turn_1, turn_2, block, other):+ manager.accumulate_llm_call_to_archive(+ step=step,+ workflow_run_id="wr_archive",+ request=f"{step.step_id} request".encode(),+ response=f"{step.step_id} response".encode(),+ )++ stored: list[tuple[Any, bytes]] = []+ rows: list[Any] = []++ async def _store(artifact: Any, data: bytes) -> None:+ stored.append((artifact, data))++ async def _bulk_create(models: list[Any]) -> list[Any]:+ rows.extend(models)+ return models++ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager._bundling_enabled", lambda: True)+ monkeypatch.setattr(+ "skyvern.forge.sdk.artifact.manager.app.STORAGE",+ SimpleNamespace(build_uri=lambda **kwargs: f"s3://artifacts/{kwargs['artifact_id']}", store_artifact=_store),+ )+ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.bulk_create_artifacts", _bulk_create)++ await manager.flush_task_step_archives_as_one(block)++ [(archive, zip_bytes)] = stored+ parent, *members = rows+ assert (parent.artifact_type, parent.step_id, parent.uri) == (ArtifactType.STEP_ARCHIVE, "stp_block", archive.uri)+ with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:+ assert all(member.uri == archive.uri for member in members)+ assert sorted((member.step_id, zf.read(member.bundle_key).decode()) for member in members) == sorted(+ (step_id, f"{step_id} {kind}")+ for step_id in ("stp_block", "stp_turn_1", "stp_turn_2")+ for kind in ("request", "response")+ )+ # Another task's archive waits for its own flush, and a step flushed alone keeps its own file names.+ assert list(manager._step_archives) == ["stp_other"]+ rows.clear()+ await manager.flush_step_archive("stp_other")+ assert sorted(row.bundle_key for row in rows[1:]) == ["llm_request_0.json", "llm_response_0.json"]diff --git a/tests/unit/forge/sdk/db/test_repositories.py b/tests/unit/forge/sdk/db/test_repositories.pyindex a8b43ac41..16633c214 100644--- a/tests/unit/forge/sdk/db/test_repositories.py+++ b/tests/unit/forge/sdk/db/test_repositories.py@@ -27,6 +27,7 @@ from skyvern.forge.sdk.db.models import (from skyvern.forge.sdk.db.repositories.organizations import OrganizationsRepositoryfrom skyvern.forge.sdk.db.repositories.scripts import ScriptsRepositoryfrom skyvern.forge.sdk.db.repositories.tasks import TasksRepository+from skyvern.forge.sdk.models import Stepfrom skyvern.forge.sdk.schemas.tasks import TaskStatusfrom skyvern.forge.sdk.schemas.totp_codes import OTPType, RawTOTPCode, TOTPCodefrom skyvern.schemas.runs import ProxyLocation@@ -800,6 +801,18 @@ async def _read_raw_otp_code(db: AgentDB, organization_id: str, created: RawTOTPreturn next(code for code in codes if code.totp_code_id == created.totp_code_id)+async def _create_step(db: AgentDB, organization_id: str) -> Step:+ task = await db.tasks.create_task(+ url="https://example.test/",+ title="Insert",+ navigation_goal=None,+ data_extraction_goal=None,+ navigation_payload=None,+ organization_id=organization_id,+ )+ return await db.tasks.create_step(task.task_id, order=1, retry_index=0, organization_id=organization_id)++# Each entry: (create the row, read the same row back by its id)._INSERTS: dict[str, tuple[Callable[..., Awaitable[BaseModel]], Callable[..., Awaitable[BaseModel | None]]]] = {"artifact": (@@ -850,6 +863,10 @@ _INSERTS: dict[str, tuple[Callable[..., Awaitable[BaseModel]], Callable[..., Awa),lambda db, org, row: db.tasks.get_task(row.task_id, organization_id=org),),+ "step": (+ _create_step,+ lambda db, org, row: db.tasks.get_step(row.step_id, organization_id=org),+ ),# The ISP pin is written by a second flush, whose UPDATE also stamps modified_at."browser_session": (lambda db, org: db.browser_sessions.create_persistent_browser_session(diff --git a/tests/unit/forge/sdk/db/test_tasks_repository.py b/tests/unit/forge/sdk/db/test_tasks_repository.pyindex 6a74f1d09..553bde1ed 100644--- a/tests/unit/forge/sdk/db/test_tasks_repository.py+++ b/tests/unit/forge/sdk/db/test_tasks_repository.py@@ -7,6 +7,9 @@ from skyvern.forge import appfrom skyvern.forge.agent import ForgeAgentfrom skyvern.forge.sdk.db.enums import TaskTypefrom skyvern.forge.sdk.db.models import TaskRunModel, WorkflowRunAttemptModel+from skyvern.forge.sdk.models import TASK_V3_TURN_STEP_CREATED_BY, StepStatus+from skyvern.schemas.steps import AgentStepOutput, StepToolCall+from skyvern.webeye.actions.actions import ClickAction@pytest.mark.asyncio@@ -51,6 +54,71 @@ async def test_total_unique_step_order_count_deduplicates_retries_in_sqlite(agen)+async def test_task_v3_turn_steps_count_as_steps_but_not_budget_or_latest_steps(agent_db) -> None:+ # A Task V3 block's turn steps sit above its own order-0 step (SKY-18790). The step budgets still count that step+ # (the workflow one plus the action rounds), and the latest step stays the one holding the block's final screenshot.+ organization = await agent_db.organizations.create_organization(+ organization_name="Test organization", organization_id="o_test_v3_turn_steps"+ )+ org_id = organization.organization_id+ task = await agent_db.tasks.create_task(+ url="https://example.com",+ title="v3 block",+ navigation_goal=None,+ data_extraction_goal=None,+ navigation_payload=None,+ organization_id=org_id,+ )+ block_step = await agent_db.tasks.create_step(task.task_id, order=0, retry_index=0, organization_id=org_id)+ turn_steps = [+ await agent_db.tasks.create_step(+ task.task_id, order=turn, retry_index=0, organization_id=org_id, created_by=TASK_V3_TURN_STEP_CREATED_BY+ )+ for turn in (1, 2, 3)+ ]+ # Turn 1 reads, turns 2 and 3 each run a round: round indexes 0 and 1.+ for round_index, turn_step in enumerate(turn_steps[1:]):+ await agent_db.workflow_params.create_action(+ action=ClickAction(+ element_id="go",+ organization_id=org_id,+ task_id=task.task_id,+ step_id=turn_step.step_id,+ step_order=round_index,+ action_order=round_index,+ )+ )++ assert (+ await agent_db.tasks.get_total_unique_progress_round_count_by_task_ids(+ task_ids=[task.task_id], organization_id=org_id+ )+ == 2+ )+ await agent_db.tasks.finish_step(+ task.task_id,+ turn_steps[0].step_id,+ org_id,+ StepStatus.completed,+ AgentStepOutput(llm_seconds=1.5, tool_calls=[StepToolCall(tool="observe", status="ok")]),+ )++ assert (+ await agent_db.tasks.get_total_unique_step_order_count_by_task_ids(+ task_ids=[task.task_id], organization_id=org_id+ )+ == 1+ )+ assert await agent_db.tasks.get_task_step_count(task.task_id, organization_id=org_id) == 4+ assert await agent_db.tasks.get_step_counts_by_task_ids([task.task_id], organization_id=org_id) == (4, 1)+ finished = await agent_db.tasks.get_step(turn_steps[0].step_id, organization_id=org_id)+ assert finished is not None and finished.output is not None+ assert finished.output.tool_calls == [StepToolCall(tool="observe", status="ok")]+ latest = await agent_db.tasks.get_latest_step(task.task_id, organization_id=org_id)+ assert latest is not None and latest.step_id == block_step.step_id++@pytest.mark.asyncioasync def test_internal_synthetic_sdk_task_round_trips_through_repository(agent_db) -> None:organization = await agent_db.organizations.create_organization(diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 6ef788db0..f6488668d 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -47,7 +47,7 @@ from skyvern.forge.sdk.db.utils import hydrate_actionfrom skyvern.forge.sdk.experimentation.billing_tier import BillingTierfrom skyvern.forge.sdk.experimentation.providers import BaseExperimentationProviderfrom skyvern.forge.sdk.experimentation.workflow_block_engine import DISABLE_TASK_V3_FLAG-from skyvern.forge.sdk.models import Step, StepStatus+from skyvern.forge.sdk.models import TASK_V3_TURN_STEP_CREATED_BY, Step, StepStatusfrom skyvern.forge.sdk.schemas.tasks import Task, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlockfrom skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager, WorkflowRunContext@@ -94,6 +94,7 @@ from skyvern.forge.taskv3.loop import (RoundAction,ToolResult,ToolSpec,+ TurnRecord,_dead_end_reason,make_finish_tool,run_agent_tool_loop,@@ -107,6 +108,7 @@ from skyvern.forge.taskv3.run_arms import (from skyvern.forge.taskv3.tools import NO_ONE_TIME_CODE_SOURCE, PageProvider, _record_frame_workfrom skyvern.schemas.llm import LLMConfigfrom skyvern.schemas.runs import RunEngine+from skyvern.schemas.steps import StepToolCallfrom skyvern.schemas.workflows import BlockTypefrom skyvern.utils.secret_redaction import REDACTED_SECRET_PLACEHOLDERfrom skyvern.webeye.actions.actions import (@@ -2225,6 +2227,7 @@ async def _run_execute_step_gate(workflow_owned_recovery: bool = False,recovery_code_progress: CodeProgressRecord | None = None,observer: Any = None,+ artifact_manager: ArtifactManager | None = None,**task_overrides: Any,) -> tuple[AsyncMock, AsyncMock]:"""Drive ForgeAgent.execute_step through the v3 dispatch gate and return (mocked _execute_task_v3,@@ -2275,7 +2278,10 @@ async def _run_execute_step_gate(mock_app.EXPERIMENTATION_PROVIDER.resolve_feature_flag_strict = AsyncMock(return_value=False)mock_wbe_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)mock_wbe_app.EXPERIMENTATION_PROVIDER.resolve_feature_flag_strict = AsyncMock(return_value=False)- mock_app.ARTIFACT_MANAGER.flush_step_archive = AsyncMock()+ if artifact_manager is not None:+ mock_app.ARTIFACT_MANAGER = artifact_manager+ else:+ mock_app.ARTIFACT_MANAGER.flush_task_step_archives_as_one = AsyncMock()try:await agent.execute_step(organization=organization,@@ -2326,6 +2332,40 @@ async def test_execute_step_dispatches_download_semantics_blocks_to_v3(overridesstep_engine_mock.assert_not_awaited()+async def test_execute_step_writes_a_v3_blocks_turn_files_as_one_zip(monkeypatch: pytest.MonkeyPatch) -> None:+ # A v3 block's turn steps share its ZIP (SKY-18790): the block's end writes their LLM files in one storage PUT,+ # instead of one ZIP per turn left in memory until the run or workflow ends.+ manager = ArtifactManager()+ now = datetime.now(UTC)+ turn_task = make_task(now, make_organization(now), task_id="tsk_zip")+ for order in (1, 2):+ turn = make_step(now, turn_task, step_id=f"turn-{order}", status=StepStatus.completed, order=order, output=None)+ manager.accumulate_llm_call_to_archive(step=turn, request=b"request", response=b"response")+ stored: list[Any] = []++ async def _store(artifact: Any, data: bytes) -> None:+ stored.append(artifact)++ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager._bundling_enabled", lambda: True)+ monkeypatch.setattr(+ "skyvern.forge.sdk.artifact.manager.app.STORAGE",+ SimpleNamespace(build_uri=lambda **kwargs: f"s3://artifacts/{kwargs['artifact_id']}", store_artifact=_store),+ )+ monkeypatch.setattr("skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.bulk_create_artifacts", AsyncMock())++ v3_mock, _ = await _run_execute_step_gate(+ engine=agent_module.RunEngine.skyvern_v3,+ task_block=_make_block(ActionBlock),+ artifact_manager=manager,+ task_id="tsk_zip",+ )++ v3_mock.assert_awaited_once()+ assert [artifact.step_id for artifact in stored] == ["step-gate"]+ assert manager._step_archives == {}++@pytest.mark.asyncioasync def test_execute_step_falls_through_to_step_engine_on_unsupported_block_type() -> None:block = _make_block(HumanInteractionBlock)@@ -4421,6 +4461,10 @@ async def test_execute_task_v3_native_browser_loss_after_the_last_action_fails_treturn actionmonkeypatch.setattr("skyvern.forge.agent.app.DATABASE.workflow_params.create_action", _create_action)+ monkeypatch.setattr(+ "skyvern.forge.agent.app.DATABASE.tasks.create_step",+ AsyncMock(side_effect=lambda **kwargs: SimpleNamespace(step_id=f"turn-{kwargs['order']}", retry_index=0)),+ )monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.observer.get_workflow_run_block_by_task_id", AsyncMock(return_value=None))@@ -4666,6 +4710,61 @@ async def test_execute_task_v3_actions_are_round_stamped(monkeypatch: pytest.Monassert (decision.step_order, decision.action_order) == (1, 3)+async def test_execute_task_v3_writes_a_step_per_turn_beside_the_billed_block_step(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Each loop turn gets its own step (SKY-18790): the turn's model call runs under it and the rows it writes+ # point at it, while the block's own step stays the one billing meters and the run's status lands on.+ created: list[dict[str, Any]] = []++ async def fake_create_step(**kwargs: Any) -> Any:+ created.append(kwargs)+ return SimpleNamespace(step_id=f"turn-{kwargs['order']}")++ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.create_step", fake_create_step)+ finish_turn = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.finish_step", finish_turn)+ steps_by_turn: list[Any] = []++ async def drive_turns(kwargs: dict[str, Any]) -> None:+ steps_by_turn.append(await kwargs["on_turn_start"](1))+ click = RoundAction("click", {"selector": "#go"}, True, billable=True)+ await kwargs["on_action_round"]([click], "clicking", round_done=True)+ await kwargs["on_turn_end"](+ TurnRecord(turn=1, llm_seconds=1.5, tool_calls=[StepToolCall(tool="click", status="ok", billable=True)])+ )+ steps_by_turn.append(await kwargs["on_turn_start"](2))+ await kwargs["on_turn_end"](+ TurnRecord(turn=2, tool_calls=[StepToolCall(tool="finish", status="ok")], outcome_status="completed")+ )++ outcome = LoopOutcome(status="completed", reason="done", billable_actions=["click"])+ step, _task, _loop_mock, post_step = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ on_loop_async=drive_turns,+ data_extraction_goal=None,+ extracted_information_schema=None,+ )++ assert [(c["order"], c["retry_index"], c["status"], c["created_by"]) for c in created] == [+ (1, step.retry_index, StepStatus.running, TASK_V3_TURN_STEP_CREATED_BY),+ (2, step.retry_index, StepStatus.running, TASK_V3_TURN_STEP_CREATED_BY),+ ]+ assert [turn_step.step_id for turn_step in steps_by_turn] == ["turn-1", "turn-2"]+ finished = [+ (c.kwargs["step_id"], c.kwargs["status"], [t.tool for t in c.kwargs["output"].tool_calls])+ for c in finish_turn.await_args_list+ ]+ assert finished == [("turn-1", StepStatus.completed, ["click"]), ("turn-2", StepStatus.completed, ["finish"])]+ # The click row and the finish decision sit on their turns' steps, still stamped with the round index.+ rows = [c.kwargs["action"] for c in agent_module.app.DATABASE.workflow_params.create_action.await_args_list]+ assert [(row.step_id, row.step_order) for row in rows] == [("turn-1", 0), ("turn-2", 0)]+ assert step.step_id == "step-v3" and step.status == StepStatus.completed+ assert post_step.await_args.args[1] is step++@pytest.mark.asyncioasync def test_execute_task_v3_workflow_run_step_budget_caps_and_blocks(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex 3baef98a7..da2835ed6 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -104,6 +104,7 @@ from skyvern.forge.taskv3.loop import (ToolRefusal,ToolResult,ToolSpec,+ TurnRecord,UnseenPageText,_arms_failure_evidence,_budget_extension_gate,@@ -5036,6 +5037,74 @@ async def test_on_action_round_falls_back_to_reasoning_summary_when_text_empty()assert round_texts == ["clicked the primary submit button"]+async def test_each_turn_runs_its_model_call_under_its_own_kwargs_and_reports_every_tool_call() -> None:+ # One record per turn whatever the turn did (SKY-18790): a read, a batch with a failed call, its skipped+ # dependent and an independent call, a turn with no tool call, and the finish. The step on_turn_start returns+ # is that turn's model call `step`, over the run-wide one.+ events: list[Any] = []++ class _StepRecordingCaller(_ScriptedCaller):+ async def call(self, *, step: Any = None, **kwargs: Any) -> dict[str, Any]:+ events.append(("call", step))+ return await super().call(**kwargs)++ async def on_turn_start(turn: int) -> str:+ events.append(("start", turn))+ return f"turn-step-{turn}"++ async def on_turn_end(record: TurnRecord) -> None:+ assert record.llm_seconds is not None+ calls = [(call.tool, call.status, call.billable) for call in record.tool_calls]+ events.append(("end", record.turn, calls, record.outcome_status))++ async def probe() -> str | None:+ return "doc-1"++ sink: list[tuple[str, dict[str, Any]]] = []+ tools = [+ _recording_tool("observe", sink),+ _recording_tool("type", sink, raises=True, billable=True),+ _recording_tool("press_key", sink, billable=True),+ _recording_tool("select_option", sink, billable=True),+ make_finish_tool(),+ ]+ script = [+ [("observe", {})],+ [("type", {"selector": "#q"}), ("press_key", {"selector": "#q"}), ("select_option", {"selector": "#z"})],+ [],+ [("finish", {"status": "completed", "reason": "done"})],+ ]+ outcome = await run_agent_tool_loop(+ llm_caller=_StepRecordingCaller(script),+ system_prompt="sys",+ user_prompt="goal",+ tools=tools,+ max_turns=20,+ max_tool_calls=100,+ call_kwargs={"step": "block-step"},+ page_probe=probe,+ on_turn_start=on_turn_start,+ on_turn_end=on_turn_end,+ )++ assert outcome.status == "completed"+ assert events == [+ ("start", 1),+ ("call", "turn-step-1"),+ ("end", 1, [("observe", "ok", False)], None),+ ("start", 2),+ ("call", "turn-step-2"),+ ("end", 2, [("type", "error", True), ("press_key", "skipped", True), ("select_option", "ok", True)], None),+ ("start", 3),+ ("call", "turn-step-3"),+ ("end", 3, [], None),+ ("start", 4),+ ("call", "turn-step-4"),+ ("end", 4, [("finish", "ok", False)], "completed"),+ ]++@pytest.mark.asyncioasync def test_on_action_round_prefers_content_over_reasoning_summary() -> None:round_texts: list[str | None] = []