From cd1827ebb11af18e3969f007810af63018d49214 Mon Sep 17 00:00:00 2001 From: Bas Alberts Date: Wed, 1 Jul 2026 13:49:26 -0400 Subject: [PATCH 01/28] feat(grammar): multi-model tasks with per-model parallel streams Add a `models:` field to a task so one prompt can fan out across several models concurrently, each streamed as its own labelled output block. This is the first milestone (M1) of the grammar maturity effort. Grammar (models.py): - New `ModelEntry` submodel; `models: list[str | {model, model_settings}]` on TaskDefinition, coerced from bare names or override maps. - `completion: all|any` policy and `model_concurrency` cap. - Validators: `model` xor `models`; reject multi-entry `models` with `repeat_prompt` (deferred to a later milestone); non-negative concurrency. - `effective_model_entries()` normalises single- and multi-model tasks. Engine (runner.py): - Refactor resolution into `_resolve_one_model` + `_resolve_task_models` returning `ResolvedModel` per entry (mixed backends supported). - Extract the fan-out matrix into a testable `_fan_out_deploys` helper that owns the prompt x model cross product, bounded concurrency, exception isolation, and the completion policy. - Isolate multi-model tool-result capture so concurrent models do not corrupt the shared repeat_prompt/session channel. Single-model path is unchanged. Output (render_utils.py): - `flush_async_output` takes an optional `label` so each model's buffered block is tagged with its model name. Docs/examples: - "Multiple Models" section in doc/GRAMMAR.md. - examples/taskflows/example_multi_model.yaml + model_configs/multi_model.yaml. Tests: +30 (grammar, resolution fan-out, `_fan_out_deploys` matrix/ concurrency/completion, output labelling). Full suite 321 passed, 2 skipped; CI-parity lint clean. Backwards compatible: `model:` stays valid and equals `models: [x]`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/GRAMMAR.md | 71 +++++ examples/model_configs/multi_model.yaml | 16 + examples/taskflows/example_multi_model.yaml | 24 ++ src/seclab_taskflow_agent/models.py | 83 ++++++ src/seclab_taskflow_agent/render_utils.py | 11 +- src/seclab_taskflow_agent/runner.py | 306 ++++++++++++++++---- tests/test_models.py | 88 ++++++ tests/test_render_utils.py | 75 +++++ tests/test_runner.py | 212 ++++++++++++++ 9 files changed, 823 insertions(+), 63 deletions(-) create mode 100644 examples/model_configs/multi_model.yaml create mode 100644 examples/taskflows/example_multi_model.yaml create mode 100644 tests/test_render_utils.py diff --git a/doc/GRAMMAR.md b/doc/GRAMMAR.md index 88b0bf9f..805420d8 100644 --- a/doc/GRAMMAR.md +++ b/doc/GRAMMAR.md @@ -103,6 +103,77 @@ Parameters to the model can also be specified in the task using the `model_setti If `model_settings` is absent, then the model parameters will fall back to either the default or the ones supplied in a `model_config`. However, any parameters supplied in the task will override those that are set in the `model_config`. +### Multiple Models (multi-model tasks) + +A task can be run against several models at once using the `models` field. Each +model runs the task in parallel and its output is streamed as its own labelled +block, which makes it easy to compare how different models respond to the same +prompt (for example when evaluating an audit prompt across model families). + +The simplest form is a list of logical model names (resolved through the +`model_config` exactly like the singular `model` field): + +```yaml + - task: + models: [gpt_default, claude_native, gpt_responses] + agents: + - seclab_taskflow_agent.personalities.c_auditer + user_prompt: | + Audit this function for memory safety issues. +``` + +Each entry may also be a map with its own `model_settings`, so different models +can use different parameters in the same task: + +```yaml + - task: + models: + - model: gpt_default + model_settings: + temperature: 0.2 + - model: claude_native + model_settings: + reasoning: + effort: high + agents: + - seclab_taskflow_agent.personalities.c_auditer + user_prompt: | + Audit this function for memory safety issues. +``` + +Notes and semantics: + +- `model` (singular) and `models` (plural) are mutually exclusive. `model: x` + is exactly equivalent to `models: [x]`; existing single-model taskflows are + unaffected. +- Per-entry `model_settings` support the same engine keys as `model_config` + (`api_type`, `endpoint`, `token`, `backend`), so different models may run on + different backends within one task. +- `completion` controls when a multi-model task counts as complete: `all` + (default, every model must succeed) or `any` (one success suffices). This is + what `must_complete` checks against. +- `model_concurrency` caps how many models run at once (default `0` runs them + all in parallel): + +```yaml + - task: + models: [m1, m2, m3, m4] + model_concurrency: 2 + completion: any + agents: + - seclab_taskflow_agent.personalities.assistant + user_prompt: | + ... +``` + +- Multi-model output is buffered per model and flushed as a labelled block when + each model finishes, so streams from different models do not interleave. +- Multi-model tasks are for parallel evaluation: their tool results are not + threaded into the `repeat_prompt` result channel, and combining `models` + (with more than one entry) with `repeat_prompt` on the same task is not yet + supported. Typed named outputs for consuming multi-model results downstream + are planned in a later milestone. + ### Completion Requirement Tasks can be marked as requiring completion, if a required task fails, the taskflow will abort. This defaults to false. diff --git a/examples/model_configs/multi_model.yaml b/examples/model_configs/multi_model.yaml new file mode 100644 index 00000000..f8bd4043 --- /dev/null +++ b/examples/model_configs/multi_model.yaml @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +# Example model_config for multi-model tasks: two logical models that a +# single task can fan out across in parallel. Swap the provider IDs for +# whatever your endpoint exposes. + +seclab-taskflow-agent: + version: "1.0" + filetype: model_config +models: + gpt_fast: gpt-5.4-mini + gpt_alt: gpt-4.1 +model_settings: + gpt_fast: + api_type: responses diff --git a/examples/taskflows/example_multi_model.yaml b/examples/taskflows/example_multi_model.yaml new file mode 100644 index 00000000..0fb30a89 --- /dev/null +++ b/examples/taskflows/example_multi_model.yaml @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +# Example: run the same prompt across multiple models in parallel. +# Each model's answer is streamed as its own labelled output block, which +# makes side-by-side comparison easy. See doc/GRAMMAR.md "Multiple Models". + +seclab-taskflow-agent: + version: "1.0" + filetype: taskflow + +model_config: examples.model_configs.multi_model + +taskflow: + - task: + # fan out this task across both models concurrently + models: [gpt_fast, gpt_alt] + # the task is complete only if every model answers (use `any` for + # first-success semantics) + completion: all + agents: + - seclab_taskflow_agent.personalities.assistant + user_prompt: | + In two sentences, explain what a use-after-free bug is. diff --git a/src/seclab_taskflow_agent/models.py b/src/seclab_taskflow_agent/models.py index 837e4e2c..c9dcd23d 100644 --- a/src/seclab_taskflow_agent/models.py +++ b/src/seclab_taskflow_agent/models.py @@ -13,8 +13,10 @@ __all__ = [ "ApiType", "BackendSdk", + "CompletionPolicy", "DOCUMENT_MODELS", "ModelConfigDocument", + "ModelEntry", "PersonalityDocument", "PromptDocument", "SUPPORTED_VERSION", @@ -36,6 +38,10 @@ # Valid backend names. Must stay in sync with ``sdk._KNOWN``. BackendSdk = Literal["openai_agents", "copilot_sdk", "anthropic_sdk"] +# Completion policy for multi-model tasks: whether all models must succeed +# for the task to be considered complete, or any single success suffices. +CompletionPolicy = Literal["all", "any"] + # --------------------------------------------------------------------------- # Header @@ -76,6 +82,22 @@ def _validate_version(cls, v: str) -> str: # Task definition (a single step inside a taskflow) # --------------------------------------------------------------------------- +class ModelEntry(BaseModel): + """A single model entry for multi-model task execution. + + Accepts either a bare logical model name (coerced to ``model=``) + or a mapping with ``model`` and optional ``model_settings``. Logical + names are resolved through the taskflow's ``model_config`` exactly like + the singular ``model:`` field, so per-entry ``api_type``/``endpoint``/ + ``token``/``backend`` overrides work the same way. + """ + + model_config = ConfigDict(extra="allow", protected_namespaces=()) + + model: str = "" + model_settings: dict[str, Any] = Field(default_factory=dict) + + class TaskDefinition(BaseModel): """A single task within a taskflow. @@ -92,6 +114,14 @@ class TaskDefinition(BaseModel): run: str = "" model: str = "" model_settings: dict[str, Any] = Field(default_factory=dict) + # Multi-model fan-out: run this task against each listed model in + # parallel with per-model output streams. Mutually exclusive with the + # singular ``model`` field. Empty means single-model (see ``model``). + models: list[ModelEntry] = Field(default_factory=list) + # Completion policy when ``models`` lists more than one model. + completion: CompletionPolicy = "all" + # Upper bound on concurrent model runs (0 = run all models at once). + model_concurrency: int = 0 must_complete: bool = False headless: bool = False repeat_prompt: bool = False @@ -107,12 +137,65 @@ class TaskDefinition(BaseModel): async_task: bool = Field(default=False, alias="async") async_limit: int = 5 + @field_validator("models", mode="before") + @classmethod + def _coerce_models(cls, v: Any) -> list[Any]: + """Coerce list items into ``ModelEntry`` maps. + + Accepts a list whose entries are either bare model-name strings + (``[gpt_default, claude_native]``) or ``{model, model_settings}`` + maps. Strings become ``{"model": }``; maps and ``ModelEntry`` + instances pass through for ``ModelEntry`` to validate. + """ + if v is None: + return [] + if not isinstance(v, list): + raise ValueError( + "'models' must be a list of model names or {model, model_settings} maps" + ) + out: list[Any] = [] + for item in v: + if isinstance(item, str): + out.append({"model": item}) + elif isinstance(item, (dict, ModelEntry)): + out.append(item) + else: + raise ValueError(f"invalid 'models' entry: {item!r}") + return out + @model_validator(mode="after") def _run_xor_prompt(self) -> TaskDefinition: if self.run and self.user_prompt: raise ValueError("shell task ('run') and prompt task ('user_prompt') are mutually exclusive") return self + @model_validator(mode="after") + def _validate_models(self) -> TaskDefinition: + if self.models and self.model: + raise ValueError( + "'model' and 'models' are mutually exclusive; use 'model' for a single " + "model or 'models' for multi-model fan-out" + ) + if len(self.models) > 1 and self.repeat_prompt: + raise ValueError( + "multi-model 'models' is not yet supported together with 'repeat_prompt' " + "(planned as a later milestone); use a single model with repeat_prompt" + ) + if self.model_concurrency < 0: + raise ValueError("'model_concurrency' must be >= 0") + return self + + def effective_model_entries(self) -> list[ModelEntry]: + """Return the normalised list of models this task runs against. + + When ``models`` is set it is returned as-is. Otherwise the singular + ``model``/``model_settings`` pair is wrapped in a one-element list so + callers can treat single-model and multi-model tasks uniformly. + """ + if self.models: + return list(self.models) + return [ModelEntry(model=self.model, model_settings=dict(self.model_settings))] + class TaskWrapper(BaseModel): """Wraps the ``- task:`` YAML list entry.""" diff --git a/src/seclab_taskflow_agent/render_utils.py b/src/seclab_taskflow_agent/render_utils.py index 7a018506..6ccce55a 100644 --- a/src/seclab_taskflow_agent/render_utils.py +++ b/src/seclab_taskflow_agent/render_utils.py @@ -20,14 +20,19 @@ render_logger.propagate = False -async def flush_async_output(task_id: str) -> None: - """Flush buffered async output for *task_id* to the console.""" +async def flush_async_output(task_id: str, label: str | None = None) -> None: + """Flush buffered async output for *task_id* to the console. + + When *label* is provided it replaces the default ``async task: `` + heading, letting multi-model runs tag each block with its model name. + """ async with async_output_lock: if task_id not in async_output: # No buffered output (agent may have failed before producing any). return data = async_output.pop(task_id) - await render_model_output(f"** 🤖✏️ Output for async task: {task_id}\n\n") + heading = label if label else f"async task: {task_id}" + await render_model_output(f"** 🤖✏️ Output for {heading}\n\n") await render_model_output(data) diff --git a/src/seclab_taskflow_agent/runner.py b/src/seclab_taskflow_agent/runner.py index b5ed43fd..01f1d74b 100644 --- a/src/seclab_taskflow_agent/runner.py +++ b/src/seclab_taskflow_agent/runner.py @@ -23,6 +23,8 @@ import json import logging import uuid +from collections.abc import Awaitable, Callable +from dataclasses import dataclass from typing import TYPE_CHECKING, Any import jinja2 @@ -120,23 +122,24 @@ def _merge_reusable_task( return TaskDefinition.model_validate(merged) -def _resolve_task_model( - task: TaskDefinition, +def _resolve_one_model( + logical_name: str, + task_model_settings: dict[str, Any], model_keys: list[str], model_dict: dict[str, str], models_params: dict[str, dict[str, Any]], default_api_type: str = "chat_completions", ) -> tuple[str, dict[str, Any], str, str | None, str | None, str | None]: - """Resolve the final model name, settings, and per-model overrides. + """Resolve one logical model name plus overrides into a concrete spec. + + Shared core for both the singular ``model:`` field and each entry of the + multi-model ``models:`` list. *task_model_settings* are the per-task (or + per-entry) overrides that win over the ``model_config`` settings. Returns: A tuple of ``(model_id, model_settings, api_type, endpoint, token, backend)`` where *endpoint*, *token*, and *backend* are ``None`` when not overridden. - - Raises: - ValueError: If task-level model_settings is not a dictionary. """ - logical_name: str = task.model or DEFAULT_MODEL model_settings: dict[str, Any] = {} api_type: str = default_api_type endpoint: str | None = None @@ -154,11 +157,7 @@ def _resolve_task_model( token = model_settings.pop("token", None) backend = model_settings.pop("backend", None) - task_model_settings: dict[str, Any] | Any = task.model_settings or {} - if not isinstance(task_model_settings, dict): - raise ValueError(f"model_settings in task {task.name or ''} needs to be a dictionary") - - # Task-level overrides can also set engine keys + # Task/entry-level overrides can also set engine keys task_settings = dict(task_model_settings) api_type = task_settings.pop("api_type", api_type) endpoint = task_settings.pop("endpoint", endpoint) @@ -169,6 +168,167 @@ def _resolve_task_model( return logical_name, model_settings, api_type, endpoint, token, backend +def _resolve_task_model( + task: TaskDefinition, + model_keys: list[str], + model_dict: dict[str, str], + models_params: dict[str, dict[str, Any]], + default_api_type: str = "chat_completions", +) -> tuple[str, dict[str, Any], str, str | None, str | None, str | None]: + """Resolve the final model name, settings, and per-model overrides. + + Returns: + A tuple of ``(model_id, model_settings, api_type, endpoint, token, backend)`` + where *endpoint*, *token*, and *backend* are ``None`` when not overridden. + + Raises: + ValueError: If task-level model_settings is not a dictionary. + """ + task_model_settings: dict[str, Any] | Any = task.model_settings or {} + if not isinstance(task_model_settings, dict): + raise ValueError(f"model_settings in task {task.name or ''} needs to be a dictionary") + return _resolve_one_model( + task.model or DEFAULT_MODEL, + task_model_settings, + model_keys, + model_dict, + models_params, + default_api_type, + ) + + +@dataclass(frozen=True) +class ResolvedModel: + """A fully resolved model spec for one branch of a (multi-)model task.""" + + model: str + model_settings: dict[str, Any] + api_type: str + endpoint: str | None + token: str | None + backend: str | None + label: str + + +def _resolve_task_models( + task: TaskDefinition, + model_keys: list[str], + model_dict: dict[str, str], + models_params: dict[str, dict[str, Any]], + default_api_type: str = "chat_completions", +) -> list[ResolvedModel]: + """Resolve every model this task runs against. + + Single-model tasks yield a one-element list (equivalent to + :func:`_resolve_task_model`); multi-model tasks yield one + :class:`ResolvedModel` per ``models`` entry. The ``label`` is the + user-facing logical name (falling back to the resolved provider id) and + is used to tag per-model output streams. + """ + resolved: list[ResolvedModel] = [] + for entry in task.effective_model_entries(): + entry_settings: dict[str, Any] | Any = entry.model_settings or {} + if not isinstance(entry_settings, dict): + raise ValueError(f"model_settings in task {task.name or ''} needs to be a dictionary") + model_id, settings, api_type, endpoint, token, backend = _resolve_one_model( + entry.model or DEFAULT_MODEL, + entry_settings, + model_keys, + model_dict, + models_params, + default_api_type, + ) + resolved.append( + ResolvedModel( + model=model_id, + model_settings=settings, + api_type=api_type, + endpoint=endpoint, + token=token, + backend=backend, + label=entry.model or model_id, + ) + ) + return resolved + + +def _completion(oks: list[bool], policy: str) -> bool: + """Reduce per-branch success flags to a single task result. + + An empty branch list is treated as success (nothing ran, nothing + failed), matching the pre-multi-model behaviour. ``"any"`` succeeds if + at least one branch succeeded; ``"all"`` (the default) requires every + branch to succeed. + """ + if not oks: + return True + if policy == "any": + return any(oks) + return all(oks) + + +async def _fan_out_deploys( + work_items: list[tuple[Any, ResolvedModel]], + deploy: Callable[[Any, ResolvedModel], Awaitable[bool]], + *, + concurrent: bool, + concurrency: int, + completion_policy: str, +) -> bool: + """Run ``deploy`` for every ``(payload, model)`` work item. + + This is the single place that owns the task fan-out matrix (prompts x + models), the concurrency bound, exception isolation, and the completion + policy, so the behaviour is unit-testable independently of the agent and + MCP machinery. + + Args: + work_items: ``(payload, resolved_model)`` pairs to execute. The + payload is opaque to this helper and handed back to ``deploy``. + deploy: coroutine factory invoked as ``deploy(payload, model)``, + returning ``True`` on success. + concurrent: when True all deploys run under a bounded ``gather`` and + per-branch exceptions are captured and counted as failures; when + False they run sequentially and exceptions propagate to the + caller's retry loop (preserving the legacy single-model path). + concurrency: maximum simultaneous deploys (clamped to >= 1) when + ``concurrent`` is True. + completion_policy: ``"all"`` or ``"any"`` (see :func:`_completion`). + + Returns: + The reduced task success flag. + """ + if not work_items: + return True + + if not concurrent: + # Sequential path: exceptions propagate exactly as the pre-multi-model + # single-model path did, so the caller's retry loop still sees + # transient backend errors. + oks: list[bool] = [] + for payload, model in work_items: + oks.append(await deploy(payload, model)) + return _completion(oks, completion_policy) + + semaphore = asyncio.Semaphore(max(1, concurrency)) + + async def _guarded(payload: Any, model: ResolvedModel) -> bool: + async with semaphore: + return await deploy(payload, model) + + gathered = await asyncio.gather( + *(_guarded(payload, model) for payload, model in work_items), + return_exceptions=True, + ) + reduced: list[bool] = [] + for result in gathered: + if not isinstance(result, bool): + logging.error("Caught exception in Gather: %s", result, exc_info=result) + result = False + reduced.append(result) + return _completion(reduced, completion_policy) + + async def _build_prompts_to_run( task_prompt: str, repeat_prompt: bool, @@ -267,6 +427,7 @@ async def deploy_task_agents( backend: str | None = None, run_hooks: TaskRunHooks | None = None, agent_hooks: TaskAgentHooks | None = None, + stream_label: str | None = None, ) -> bool: """Deploy and run task agents with MCP servers. @@ -280,6 +441,9 @@ async def deploy_task_agents( backend: Optional explicit SDK adapter name (``"openai_agents"`` or ``"copilot_sdk"``). Defaults to ``SECLAB_TASKFLOW_BACKEND`` or an endpoint-based auto-default. + stream_label: Optional human-readable label for this run's buffered + output block (used to tag per-model streams in multi-model tasks). + Only takes effect when ``async_task`` is True. Returns: True if the task completed successfully. @@ -444,7 +608,7 @@ async def deploy_task_agents( logging.exception("API Timeout") if async_task: - await flush_async_output(task_id) + await flush_async_output(task_id, label=stream_label) return complete @@ -603,10 +767,12 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo if task.uses: task = _merge_reusable_task(available_tools, task) - # Resolve model (name, settings, api_type, optional endpoint/token/backend) - model, model_settings, task_api_type, task_endpoint, task_token, task_backend = _resolve_task_model( + # Resolve models (one per model entry; single-model tasks yield + # a one-element list). Multi-model tasks fan out over this list. + resolved_models = _resolve_task_models( task, model_keys, model_dict, models_params, default_api_type=api_type, ) + multi_model = len(resolved_models) > 1 # Read task fields via typed attributes agents_list = task.agents or [] @@ -625,6 +791,9 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo exclude_from_context = task.exclude_from_context async_task = task.async_task max_concurrent_tasks = task.async_limit + completion_policy = task.completion + # Bound on concurrent model runs (0 == run all models at once). + model_concurrency = task.model_concurrency or len(resolved_models) # Render prompt template (skip if repeat_prompt — result not yet available) if task_prompt and not repeat_prompt: @@ -657,9 +826,16 @@ async def run_prompts(async_task: bool = False, max_concurrent_tasks: int = 5) - logging.exception("Shell task error") return False - tasks: list[Any] = [] - task_results: list[Any] = [] - semaphore = asyncio.Semaphore(max_concurrent_tasks) + # Concurrency: repeat_prompt async fans out over prompts; + # multi-model fans out over models. Either triggers the + # buffered/gathered path so per-branch output stays intact. + concurrent = async_task or multi_model + concurrency = model_concurrency if multi_model else max_concurrent_tasks + + # Resolve agents (and rewrite bare prompts) once per prompt, + # before fanning out across models so the work is not + # repeated per model. + resolved_prompts: list[tuple[dict[str, Any], str]] = [] for p_prompt in prompts_to_run: resolved_agents: dict[str, Any] = {} current_agents = list(agents_list) @@ -679,49 +855,59 @@ async def run_prompts(async_task: bool = False, max_concurrent_tasks: int = 5) - "No agents resolved for this task. " "Specify a personality with -p or provide an agents list." ) - - async def _deploy(ra: dict, pp: str) -> bool: - async with semaphore: - return await deploy_task_agents( - available_tools, - ra, - pp, - async_task=async_task, - toolboxes_override=toolboxes_override, - blocked_tools=blocked_tools, - headless=headless, - exclude_from_context=exclude_from_context, - max_turns=max_turns, - run_hooks=TaskRunHooks( - on_tool_end=on_tool_end_hook, on_tool_start=on_tool_start_hook - ), - model=model, - model_par=model_settings, - api_type=task_api_type, - endpoint=task_endpoint, - token=task_token, - backend=task_backend or backend, - agent_hooks=TaskAgentHooks(on_handoff=on_handoff_hook), - ) - - task_coroutine = _deploy(resolved_agents, p_prompt) - - if not async_task: - result = await task_coroutine - task_results.append(result) + resolved_prompts.append((resolved_agents, p_prompt)) + + async def _deploy(payload: tuple[dict[str, Any], str], rm: ResolvedModel) -> bool: + ra, pp = payload + # Isolate multi-model tool-result capture: concurrent + # models must not interleave into the shared + # last_mcp_tool_results (which feeds downstream + # repeat_prompt / session checkpoints). Single-model + # runs keep the shared sink for backwards compatibility. + if multi_model: + async def _isolated_tool_end(context, agent, tool, result) -> None: # noqa: ANN001 + watchdog_ping() + run_hooks = TaskRunHooks( + on_tool_end=_isolated_tool_end, on_tool_start=on_tool_start_hook + ) else: - tasks.append(task_coroutine) - - if async_task: - task_results = await asyncio.gather(*tasks, return_exceptions=True) - - complete = True - for result in task_results: - if not isinstance(result, bool): - logging.error("Caught exception in Gather: %s", result, exc_info=result) - result = False - complete = result and complete - return complete + run_hooks = TaskRunHooks( + on_tool_end=on_tool_end_hook, on_tool_start=on_tool_start_hook + ) + return await deploy_task_agents( + available_tools, + ra, + pp, + async_task=concurrent, + toolboxes_override=toolboxes_override, + blocked_tools=blocked_tools, + headless=headless, + exclude_from_context=exclude_from_context, + max_turns=max_turns, + run_hooks=run_hooks, + model=rm.model, + model_par=rm.model_settings, + api_type=rm.api_type, + endpoint=rm.endpoint, + token=rm.token, + backend=rm.backend or backend, + agent_hooks=TaskAgentHooks(on_handoff=on_handoff_hook), + stream_label=rm.label if multi_model else None, + ) + + # Fan-out matrix: every (prompt, model) pair. + work_items = [ + (payload, rm) + for payload in resolved_prompts + for rm in resolved_models + ] + return await _fan_out_deploys( + work_items, + _deploy, + concurrent=concurrent, + concurrency=concurrency, + completion_policy=completion_policy, + ) # Execute the task with auto-retry on transient failures. # Only retry on network/API errors — deterministic failures diff --git a/tests/test_models.py b/tests/test_models.py index cdbb9a91..59f93ca3 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -8,6 +8,7 @@ from seclab_taskflow_agent.models import ( ModelConfigDocument, + ModelEntry, PersonalityDocument, PromptDocument, ServerParams, @@ -83,6 +84,93 @@ def test_extra_fields_allowed(self): assert t.model_extra["future_field"] == "value" +class TestMultiModel: + """Test the multi-model ``models:`` grammar on a task.""" + + def test_defaults_single_model(self): + """Absent ``models`` leaves a task single-model with default policy.""" + t = TaskDefinition(user_prompt="hi") + assert t.models == [] + assert t.completion == "all" + assert t.model_concurrency == 0 + entries = t.effective_model_entries() + assert len(entries) == 1 + assert entries[0].model == "" + assert entries[0].model_settings == {} + + def test_singular_model_wrapped_in_entry(self): + """The singular ``model``/``model_settings`` pair maps to one entry.""" + t = TaskDefinition(user_prompt="hi", model="fast", model_settings={"temperature": 0.5}) + entries = t.effective_model_entries() + assert len(entries) == 1 + assert entries[0].model == "fast" + assert entries[0].model_settings == {"temperature": 0.5} + + def test_string_list_coerced_to_entries(self): + """A bare list of names coerces each into a ModelEntry.""" + t = TaskDefinition(user_prompt="hi", models=["gpt_default", "claude_native"]) + assert all(isinstance(e, ModelEntry) for e in t.models) + assert [e.model for e in t.effective_model_entries()] == ["gpt_default", "claude_native"] + assert all(e.model_settings == {} for e in t.effective_model_entries()) + + def test_rich_entries_preserve_settings(self): + """Per-entry ``model_settings`` maps are preserved.""" + t = TaskDefinition( + user_prompt="hi", + models=[ + {"model": "gpt_default", "model_settings": {"temperature": 0.2}}, + {"model": "claude_native", "model_settings": {"reasoning": {"effort": "high"}}}, + ], + ) + entries = t.effective_model_entries() + assert entries[0].model == "gpt_default" + assert entries[0].model_settings == {"temperature": 0.2} + assert entries[1].model_settings == {"reasoning": {"effort": "high"}} + + def test_mixed_string_and_map_entries(self): + """A list may mix bare names and override maps.""" + t = TaskDefinition( + user_prompt="hi", + models=["gpt_default", {"model": "claude_native", "model_settings": {"temperature": 0.1}}], + ) + entries = t.effective_model_entries() + assert entries[0].model == "gpt_default" + assert entries[0].model_settings == {} + assert entries[1].model == "claude_native" + assert entries[1].model_settings == {"temperature": 0.1} + + def test_model_and_models_mutually_exclusive(self): + with pytest.raises(ValidationError, match="mutually exclusive"): + TaskDefinition(user_prompt="hi", model="fast", models=["a"]) + + def test_multi_model_with_repeat_prompt_rejected(self): + with pytest.raises(ValidationError, match="repeat_prompt"): + TaskDefinition(user_prompt="{{ result }}", repeat_prompt=True, models=["a", "b"]) + + def test_single_model_with_repeat_prompt_allowed(self): + """One-element ``models`` is fine with repeat_prompt (no fan-out).""" + t = TaskDefinition(user_prompt="{{ result }}", repeat_prompt=True, models=["only"]) + assert len(t.effective_model_entries()) == 1 + + def test_completion_policy_validated(self): + with pytest.raises(ValidationError): + TaskDefinition(user_prompt="hi", models=["a", "b"], completion="quorum") + t = TaskDefinition(user_prompt="hi", models=["a", "b"], completion="any") + assert t.completion == "any" + + def test_negative_model_concurrency_rejected(self): + with pytest.raises(ValidationError, match="model_concurrency"): + TaskDefinition(user_prompt="hi", models=["a", "b"], model_concurrency=-1) + + def test_invalid_models_type_rejected(self): + with pytest.raises(ValidationError, match="must be a list"): + TaskDefinition(user_prompt="hi", models="gpt_default") + + def test_invalid_models_entry_rejected(self): + with pytest.raises(ValidationError, match="invalid 'models' entry"): + TaskDefinition(user_prompt="hi", models=[123]) + + class TestTaskflowDocument: """Test complete taskflow document parsing.""" diff --git a/tests/test_render_utils.py b/tests/test_render_utils.py new file mode 100644 index 00000000..e6a71954 --- /dev/null +++ b/tests/test_render_utils.py @@ -0,0 +1,75 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Tests for buffered output rendering and per-model stream labelling.""" + +import asyncio + +from seclab_taskflow_agent import render_utils +from seclab_taskflow_agent.render_utils import flush_async_output, render_model_output + + +def _capture(monkeypatch) -> list[str]: + """Redirect print() inside render_model_output into a captured list.""" + captured: list[str] = [] + + def _fake_print(data, *args, **kwargs): + captured.append(data) + + monkeypatch.setattr("builtins.print", _fake_print) + return captured + + +class TestFlushAsyncOutput: + """flush_async_output buffers per task and flushes with an optional label.""" + + def test_buffered_output_flushes_with_default_heading(self, monkeypatch): + captured = _capture(monkeypatch) + + async def scenario(): + await render_model_output("hello ", async_task=True, task_id="abc123") + await render_model_output("world", async_task=True, task_id="abc123") + await flush_async_output("abc123") + + asyncio.run(scenario()) + joined = "".join(captured) + # Default heading names the task id. + assert "Output for async task: abc123" in joined + assert "hello world" in joined + + def test_label_overrides_heading(self, monkeypatch): + captured = _capture(monkeypatch) + + async def scenario(): + await render_model_output("audit result", async_task=True, task_id="tid-1") + await flush_async_output("tid-1", label="model: gpt_default") + + asyncio.run(scenario()) + joined = "".join(captured) + assert "Output for model: gpt_default" in joined + # The task id is not used when a label is supplied. + assert "async task: tid-1" not in joined + assert "audit result" in joined + + def test_flush_unknown_task_is_noop(self, monkeypatch): + captured = _capture(monkeypatch) + asyncio.run(flush_async_output("does-not-exist", label="model: x")) + assert captured == [] + + def test_buffers_are_isolated_per_task(self, monkeypatch): + captured = _capture(monkeypatch) + + async def scenario(): + await render_model_output("A-out", async_task=True, task_id="A") + await render_model_output("B-out", async_task=True, task_id="B") + await flush_async_output("A", label="model: alpha") + await flush_async_output("B", label="model: beta") + + asyncio.run(scenario()) + joined = "".join(captured) + assert "model: alpha" in joined + assert "model: beta" in joined + assert "A-out" in joined + assert "B-out" in joined + # Both buffers fully drained. + assert render_utils.async_output == {} diff --git a/tests/test_runner.py b/tests/test_runner.py index 5cb1c26a..e497f9ae 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -20,10 +20,14 @@ TaskWrapper, ) from seclab_taskflow_agent.runner import ( + ResolvedModel, _build_prompts_to_run, + _completion, + _fan_out_deploys, _merge_reusable_task, _resolve_model_config, _resolve_task_model, + _resolve_task_models, ) @@ -530,3 +534,211 @@ def test_raises_type_error_on_non_iterable_result(self): inputs={}, ) ) + + +# =================================================================== +# _resolve_task_models (multi-model resolution) +# =================================================================== + +class TestResolveTaskModels: + """Tests for _resolve_task_models (pure fan-out over model entries).""" + + def test_single_model_matches_resolve_task_model(self): + """A singular-model task yields one ResolvedModel equal to the legacy path.""" + task = TaskDefinition(model="fast", model_settings={"temperature": 0.2}) + resolved = _resolve_task_models( + task, + model_keys=["fast"], + model_dict={"fast": "gpt-4o-mini"}, + models_params={"fast": {"temperature": 0.7}}, + ) + assert len(resolved) == 1 + rm = resolved[0] + legacy = _resolve_task_model( + task, model_keys=["fast"], model_dict={"fast": "gpt-4o-mini"}, + models_params={"fast": {"temperature": 0.7}}, + ) + assert (rm.model, rm.model_settings, rm.api_type, rm.endpoint, rm.token, rm.backend) == legacy + # Label falls back to the logical name the user wrote. + assert rm.label == "fast" + + def test_default_model_label_when_empty(self): + """An empty model resolves to DEFAULT_MODEL and labels with it.""" + from seclab_taskflow_agent.agent import DEFAULT_MODEL + + resolved = _resolve_task_models( + TaskDefinition(user_prompt="hi"), + model_keys=[], model_dict={}, models_params={}, + ) + assert len(resolved) == 1 + assert resolved[0].model == DEFAULT_MODEL + assert resolved[0].label == DEFAULT_MODEL + + def test_fan_out_over_multiple_models(self): + """Each ``models`` entry resolves to its own ResolvedModel.""" + task = TaskDefinition(user_prompt="hi", models=["fast", "smart"]) + resolved = _resolve_task_models( + task, + model_keys=["fast", "smart"], + model_dict={"fast": "gpt-4o-mini", "smart": "gpt-4o"}, + models_params={}, + ) + assert [rm.model for rm in resolved] == ["gpt-4o-mini", "gpt-4o"] + assert [rm.label for rm in resolved] == ["fast", "smart"] + + def test_per_entry_settings_and_engine_keys(self): + """Per-entry model_settings override config and engine keys are extracted.""" + task = TaskDefinition( + user_prompt="hi", + models=[ + {"model": "fast", "model_settings": {"temperature": 0.1}}, + {"model": "native", "model_settings": {"backend": "anthropic_sdk", "api_type": "messages"}}, + ], + ) + resolved = _resolve_task_models( + task, + model_keys=["fast", "native"], + model_dict={"fast": "gpt-4o-mini", "native": "claude-opus-4.7"}, + models_params={"fast": {"temperature": 0.9, "top_p": 0.5}}, + ) + # entry-level temperature wins over config; config top_p preserved + assert resolved[0].model_settings == {"temperature": 0.1, "top_p": 0.5} + # engine keys are popped out of settings + assert resolved[1].backend == "anthropic_sdk" + assert resolved[1].api_type == "messages" + assert "backend" not in resolved[1].model_settings + assert "api_type" not in resolved[1].model_settings + + def test_unknown_model_passes_through(self): + """A model name absent from model_keys passes through as the id.""" + task = TaskDefinition(user_prompt="hi", models=["claude-3-opus"]) + resolved = _resolve_task_models( + task, model_keys=["fast"], model_dict={"fast": "gpt-4o-mini"}, models_params={}, + ) + assert resolved[0].model == "claude-3-opus" + assert resolved[0].label == "claude-3-opus" + + +# =================================================================== +# _completion (task success reduction) +# =================================================================== + +class TestCompletion: + """Tests for the completion-policy reducer.""" + + def test_empty_is_success(self): + assert _completion([], "all") is True + assert _completion([], "any") is True + + def test_all_policy(self): + assert _completion([True, True], "all") is True + assert _completion([True, False], "all") is False + + def test_any_policy(self): + assert _completion([False, True], "any") is True + assert _completion([False, False], "any") is False + + +# =================================================================== +# _fan_out_deploys (execution matrix + concurrency + completion) +# =================================================================== + +def _rm(label: str) -> ResolvedModel: + return ResolvedModel( + model=label, model_settings={}, api_type="chat_completions", + endpoint=None, token=None, backend=None, label=label, + ) + + +class TestFanOutDeploys: + """Tests for the fan-out execution helper (no agent/MCP machinery).""" + + def test_runs_every_prompt_model_pair(self): + """Deploy is invoked once for each (prompt, model) pair.""" + calls: list[tuple[str, str]] = [] + + async def deploy(payload, rm): + calls.append((payload, rm.label)) + return True + + items = [(p, rm) for p in ("p1", "p2") for rm in (_rm("m1"), _rm("m2"))] + ok = asyncio.run( + _fan_out_deploys(items, deploy, concurrent=True, concurrency=4, completion_policy="all") + ) + assert ok is True + assert set(calls) == {("p1", "m1"), ("p1", "m2"), ("p2", "m1"), ("p2", "m2")} + + def test_empty_work_items_is_success(self): + async def deploy(payload, rm): # pragma: no cover - never called + raise AssertionError("deploy should not be called") + + ok = asyncio.run( + _fan_out_deploys([], deploy, concurrent=True, concurrency=2, completion_policy="all") + ) + assert ok is True + + def test_concurrency_bound_is_respected(self): + """No more than ``concurrency`` deploys run simultaneously.""" + active = 0 + peak = 0 + + async def deploy(payload, rm): + nonlocal active, peak + active += 1 + peak = max(peak, active) + await asyncio.sleep(0.02) + active -= 1 + return True + + items = [("p", _rm(f"m{i}")) for i in range(6)] + asyncio.run( + _fan_out_deploys(items, deploy, concurrent=True, concurrency=2, completion_policy="all") + ) + assert peak <= 2 + + def test_sequential_path_preserves_order_and_propagates(self): + """Non-concurrent path runs in order and lets exceptions propagate.""" + order: list[str] = [] + + async def deploy(payload, rm): + order.append(rm.label) + if rm.label == "boom": + raise RuntimeError("kaboom") + return True + + items = [("p", _rm("a")), ("p", _rm("boom")), ("p", _rm("c"))] + with pytest.raises(RuntimeError, match="kaboom"): + asyncio.run( + _fan_out_deploys(items, deploy, concurrent=False, concurrency=1, completion_policy="all") + ) + # Stopped at the failing branch; "c" never ran. + assert order == ["a", "boom"] + + def test_concurrent_exceptions_counted_as_failure(self): + """In the concurrent path a raised branch becomes a failure, not a crash.""" + async def deploy(payload, rm): + if rm.label == "bad": + raise RuntimeError("branch failed") + return True + + items = [("p", _rm("good")), ("p", _rm("bad"))] + ok_all = asyncio.run( + _fan_out_deploys(items, deploy, concurrent=True, concurrency=2, completion_policy="all") + ) + ok_any = asyncio.run( + _fan_out_deploys(items, deploy, concurrent=True, concurrency=2, completion_policy="any") + ) + assert ok_all is False + assert ok_any is True + + def test_completion_any_with_one_success(self): + async def deploy(payload, rm): + return rm.label == "winner" + + items = [("p", _rm("loser")), ("p", _rm("winner"))] + assert asyncio.run( + _fan_out_deploys(items, deploy, concurrent=True, concurrency=2, completion_policy="any") + ) is True + assert asyncio.run( + _fan_out_deploys(items, deploy, concurrent=True, concurrency=2, completion_policy="all") + ) is False From 6aa66107dae740fc9a0e592dd3a3ba4ee563c188 Mon Sep 17 00:00:00 2001 From: Bas Alberts Date: Wed, 1 Jul 2026 16:15:15 -0400 Subject: [PATCH 02/28] feat(grammar): typed named outputs on a neutral cross-task I/O foundation Replaces the naive cross-task data channel and adds typed, named object passing between tasks (M2), built on a redesigned I/O foundation that also advances M0. Foundation (removes the ugly, multi-SDK-fragile channel): - results.py: neutral ToolResult; normalize_openai_tool_output handles all three openai-agents MCP serialisation shapes; a single decode_tool_result; and a per-run ResultStore (ordered results + named outputs, snapshot/restore) replacing the shared last_mcp_tool_results list. - _stream.py: copilot/anthropic tool results now record a neutral ToolResult instead of reconstructing openai-agents' faked {"text": ...} JSON envelope, so no backend fakes another's wire format. - runner.py: openai on_tool_end normalises into the store; a record_tool_result sink threads through deploy_task_agents/drive_backend_stream for the other backends; shell tasks record a ToolResult; multi-model branches stay isolated. - session.py: persists a ResultStore snapshot (result_snapshot) for resume. Typed named outputs (M2): - Grammar adds id, outputs (inline schema), and over to a task. - output_schema.py compiles an inline outputs schema into a Pydantic model (scalars/optionals/lists/nested objects/lists-of-objects), validated at load. - Producing tasks capture their final result under outputs., validated against the schema when present; downstream tasks consume it by name. - over: is an explicit, typed repeat_prompt iterable selector (evaluated to a real object), replacing the last-tool-result double-JSON heuristic. - template_utils: outputs. namespace + evaluate_expression; a data-first Jinja environment so keys named items/keys/values resolve to data. Backwards compatible for external users: model:, {{ result }}, and implicit repeat_prompt are unchanged (legacy repeat_prompt verified live). Full suite 379 passed, 2 skipped; CI-parity lint clean; live typed-outputs and legacy-repeat_prompt CAPI runs verified. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/GRAMMAR.md | 63 ++++++ examples/taskflows/example_typed_outputs.yaml | 31 +++ src/seclab_taskflow_agent/_stream.py | 49 ++--- src/seclab_taskflow_agent/models.py | 28 +++ src/seclab_taskflow_agent/output_schema.py | 141 ++++++++++++++ src/seclab_taskflow_agent/results.py | 184 ++++++++++++++++++ src/seclab_taskflow_agent/runner.py | 168 ++++++++++++---- src/seclab_taskflow_agent/session.py | 12 +- src/seclab_taskflow_agent/template_utils.py | 93 +++++++-- tests/test_models.py | 37 ++++ tests/test_output_schema.py | 107 ++++++++++ tests/test_results.py | 153 +++++++++++++++ tests/test_runner.py | 159 +++++++++++---- tests/test_session.py | 11 +- tests/test_session_edge.py | 35 ++-- tests/test_stream.py | 43 ++-- tests/test_template_utils.py | 49 +++++ 17 files changed, 1207 insertions(+), 156 deletions(-) create mode 100644 examples/taskflows/example_typed_outputs.yaml create mode 100644 src/seclab_taskflow_agent/output_schema.py create mode 100644 src/seclab_taskflow_agent/results.py create mode 100644 tests/test_output_schema.py create mode 100644 tests/test_results.py diff --git a/doc/GRAMMAR.md b/doc/GRAMMAR.md index 805420d8..9ad49a94 100644 --- a/doc/GRAMMAR.md +++ b/doc/GRAMMAR.md @@ -330,6 +330,69 @@ Example: - seclab_taskflow_agent.toolboxes.codeql ``` +### Typed named outputs + +By default, data flows between tasks implicitly: `repeat_prompt` consumes the +*last tool result* of the previous task. That is positional (whichever tool +fired last) and untyped. A task can instead publish a **named, typed output** +that later tasks consume by name. + +Three fields drive this: + +- `id` names a task. Its produced value (its final tool result) is exposed to + later tasks as `outputs.`. +- `outputs` declares an inline schema. When present, the task's value is + validated and coerced against it before being stored. A malformed schema is + rejected when the taskflow is loaded, before any model calls are made. +- `over` is an explicit iterable selector for `repeat_prompt`: a Jinja + expression evaluated against the template context (so it yields a real list, + not a re-parsed string). + +Example: one task produces a typed list of functions, the next analyses each. + +```yaml + - task: + id: list_functions + agents: [seclab_taskflow_agent.personalities.assistant] + user_prompt: | + List all functions as JSON: {"functions": [{"name": ..., "body": ...}]} + outputs: + functions: + type: list + items: + name: str + body: str + - task: + repeat_prompt: true + over: "outputs.list_functions.functions" + agents: [seclab_taskflow_agent.personalities.c_auditer] + user_prompt: | + Analyze function {{ result.name }}: + {{ result.body }} +``` + +The `outputs` schema is a mapping of field name to type spec: + +- Scalars (as strings): `str`, `int`, `float`, `bool`, `any` (plus synonyms + `string`/`integer`/`number`/`boolean`). A trailing `?` marks a field + optional, e.g. `note: str?`. +- Lists (as strings): `list` (list of any) or `list[T]` for a scalar `T`, e.g. + `tags: list[str]`. +- Nested objects: a mapping whose keys are sub-field specs, or the explicit + `{type: object, fields: {...}}` form. +- Lists of objects: `{type: list, items: }`, where `items` is any spec + (a scalar, a nested object mapping, etc.). + +Notes: + +- `outputs.` is a template namespace alongside `globals`, `inputs`, and + the per-iteration `result`. Keys named after dict methods (`items`, `keys`, + `values`, ...) resolve to your data, not the method. +- Without `id`/`outputs`/`over`, the implicit last-tool-result `repeat_prompt` + behaviour is unchanged. +- Typed outputs are not yet supported on multi-model tasks (planned in a later + milestone). + ### Toolboxes / MCP Servers Toolboxes are MCP server configurations. They can be defined at the Agent level or overridden at the task level. These MCP servers are started and made available to the Agents in the Agents list during a Task. The `toolboxes` field should contain a list of files for the `toolboxes` that are available for the task: diff --git a/examples/taskflows/example_typed_outputs.yaml b/examples/taskflows/example_typed_outputs.yaml new file mode 100644 index 00000000..c611fb9d --- /dev/null +++ b/examples/taskflows/example_typed_outputs.yaml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +# Example: typed, named object passing between tasks. +# The first task produces a structured object validated against an inline +# `outputs` schema and exposed as `outputs.fruit_list`. The second task +# consumes it explicitly with `over:` instead of the implicit last-tool-result. +# See doc/GRAMMAR.md "Typed named outputs". + +seclab-taskflow-agent: + version: "1.0" + filetype: taskflow + +taskflow: + - task: + id: fruit_list + # a shell task produces the structured object deterministically + run: | + echo '{"items": ["apples", "bananas", "oranges"]}' + # validate/coerce the produced value against this schema before it is + # stored as outputs.fruit_list + outputs: + items: list[str] + - task: + repeat_prompt: true + # iterate the typed output by name (no double-JSON heuristic) + over: "outputs.fruit_list.items" + agents: + - seclab_taskflow_agent.personalities.assistant + user_prompt: | + In one short sentence, say something nice about {{ result }}. diff --git a/src/seclab_taskflow_agent/_stream.py b/src/seclab_taskflow_agent/_stream.py index b758a55f..40d9926b 100644 --- a/src/seclab_taskflow_agent/_stream.py +++ b/src/seclab_taskflow_agent/_stream.py @@ -15,16 +15,16 @@ from __future__ import annotations -__all__ = ["STREAM_IDLE_TIMEOUT", "bridge_copilot_tool_event", "drive_backend_stream"] +__all__ = ["STREAM_IDLE_TIMEOUT", "handle_tool_end_event", "drive_backend_stream"] import asyncio -import json import logging from types import SimpleNamespace from typing import Any from ._watchdog import watchdog_ping from .render_utils import render_model_output +from .results import ToolResult from .sdk import TextDelta, ToolEnd from .sdk.errors import BackendRateLimitError, BackendTimeoutError @@ -36,28 +36,28 @@ STREAM_IDLE_TIMEOUT = 1800 -async def bridge_copilot_tool_event(event: ToolEnd, run_hooks: Any) -> None: - """Forward a Copilot ``ToolEnd`` into the openai-agents-style hooks. +async def handle_tool_end_event( + event: ToolEnd, + run_hooks: Any, + record_tool_result: Any = None, +) -> None: + """Handle a backend ``ToolEnd`` stream event (copilot/anthropic). - The runner captures MCP tool output via ``run_hooks.on_tool_end``, - which the openai-agents path drives natively. The Copilot adapter - surfaces tool completions as ``ToolEnd`` events instead, so we - invoke the same hooks here with: + Renders the tool-call progress notice via ``run_hooks.on_tool_start`` + (the openai path renders this natively) and forwards a neutral + :class:`ToolResult` to *record_tool_result* so the runner captures it in + its result store. - * a ``SimpleNamespace(name=...)`` placeholder in lieu of the - openai-agents ``Tool`` object — the hooks only read ``.name``. - * a ``json.dumps({"text": ...})`` envelope around the result text, - matching the wire format openai-agents uses when serialising MCP - ``TextContent`` lists. ``_build_prompts_to_run`` in the runner - depends on that exact envelope shape, so both backends produce - identical entries in ``last_mcp_tool_results``. + Unlike the previous implementation, this does **not** reconstruct an + openai-agents-specific ``{"text": ...}`` JSON envelope: the runner now + consumes a neutral :class:`ToolResult` directly, so no backend has to fake + another backend's wire format. """ - if run_hooks is None: - return fake_tool = SimpleNamespace(name=event.tool_name) - payload = json.dumps({"text": event.text}) - await run_hooks.on_tool_start(None, None, fake_tool) - await run_hooks.on_tool_end(None, None, fake_tool, payload) + if run_hooks is not None: + await run_hooks.on_tool_start(None, None, fake_tool) + if record_tool_result is not None: + await record_tool_result(ToolResult(tool_name=event.tool_name, text=event.text)) async def drive_backend_stream( @@ -72,11 +72,14 @@ async def drive_backend_stream( max_api_retry: int, initial_rate_limit_backoff: int, max_rate_limit_backoff: int, + record_tool_result: Any = None, ) -> None: """Run the backend's event stream to completion with retry/backoff. - Renders ``TextDelta`` events to stdout, forwards ``ToolEnd`` events - to the run-hook bridge, retries up to *max_api_retry* times on + Renders ``TextDelta`` events to stdout, forwards ``ToolEnd`` events to + :func:`handle_tool_end_event` (which records a neutral + :class:`~seclab_taskflow_agent.results.ToolResult` via + *record_tool_result*), retries up to *max_api_retry* times on :class:`BackendTimeoutError`, and applies exponential backoff up to *max_rate_limit_backoff* seconds on :class:`BackendRateLimitError` before giving up with a :class:`BackendTimeoutError`. @@ -109,7 +112,7 @@ async def drive_backend_stream( event.text, async_task=async_task, task_id=task_id ) elif isinstance(event, ToolEnd): - await bridge_copilot_tool_event(event, run_hooks) + await handle_tool_end_event(event, run_hooks, record_tool_result) finally: # Close the async generator so its finally block runs even # if we abort early (timeout / consumer break) — the diff --git a/src/seclab_taskflow_agent/models.py b/src/seclab_taskflow_agent/models.py index c9dcd23d..8744378d 100644 --- a/src/seclab_taskflow_agent/models.py +++ b/src/seclab_taskflow_agent/models.py @@ -109,11 +109,19 @@ class TaskDefinition(BaseModel): name: str = "" description: str = "" + id: str = "" agents: list[str] = Field(default_factory=list) user_prompt: str = "" run: str = "" model: str = "" model_settings: dict[str, Any] = Field(default_factory=dict) + # Typed named outputs (M2): declare a schema for this task's produced + # value; when set, the captured output is validated/coerced and exposed to + # later tasks as ``outputs.``. + outputs: dict[str, Any] = Field(default_factory=dict) + # Explicit iterable selector for repeat_prompt: a Jinja expression + # evaluated against the template context (e.g. ``outputs.list_fns.items``). + over: str = "" # Multi-model fan-out: run this task against each listed model in # parallel with per-model output streams. Mutually exclusive with the # singular ``model`` field. Empty means single-model (see ``model``). @@ -185,6 +193,26 @@ def _validate_models(self) -> TaskDefinition: raise ValueError("'model_concurrency' must be >= 0") return self + @model_validator(mode="after") + def _validate_outputs(self) -> TaskDefinition: + # Fail fast on a malformed outputs schema at load time, before any + # model calls are made. + if self.outputs: + from .output_schema import OutputSchemaError, build_output_model + + try: + build_output_model(f"{self.id or self.name or 'task'}_output", self.outputs) + except OutputSchemaError as exc: + raise ValueError(f"invalid 'outputs' schema: {exc}") from exc + if self.over and not self.repeat_prompt: + raise ValueError("'over' only applies to repeat_prompt tasks") + if len(self.models) > 1 and (self.id or self.outputs or self.over): + raise ValueError( + "typed outputs ('id'/'outputs'/'over') are not yet supported on multi-model " + "tasks (planned as a later milestone)" + ) + return self + def effective_model_entries(self) -> list[ModelEntry]: """Return the normalised list of models this task runs against. diff --git a/src/seclab_taskflow_agent/output_schema.py b/src/seclab_taskflow_agent/output_schema.py new file mode 100644 index 00000000..959894e6 --- /dev/null +++ b/src/seclab_taskflow_agent/output_schema.py @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Compile inline ``outputs`` schemas into Pydantic models. + +A task can declare a typed output contract inline: + +.. code-block:: yaml + + outputs: + functions: + type: list + items: + name: str + body: str + +This module turns such a schema into a generated Pydantic model so a task's +produced value can be validated and coerced before it is passed to downstream +tasks as ``outputs.``. + +Supported field type specs: + +* Scalars (as strings): ``str``, ``int``, ``float``, ``bool``, ``any`` (plus + the synonyms ``string``/``integer``/``number``/``boolean``). A trailing + ``?`` marks the field optional, e.g. ``str?``. +* Lists (as strings): ``list`` (list of any) or ``list[T]`` where ``T`` is a + scalar type name, e.g. ``list[str]``. +* Nested objects (as a mapping): a mapping whose keys are sub-field specs, or + the explicit ``{type: object, fields: {...}}`` form. +* Lists of objects (as a mapping): ``{type: list, items: }`` where + ``items`` is any spec (a scalar string, a nested object mapping, etc.). +""" + +from __future__ import annotations + +__all__ = ["OutputSchemaError", "build_output_model", "validate_output"] + +from typing import Any, Optional + +from pydantic import BaseModel, ConfigDict, create_model + +_SCALARS: dict[str, Any] = { + "str": str, + "string": str, + "int": int, + "integer": int, + "float": float, + "number": float, + "bool": bool, + "boolean": bool, + "any": Any, +} + + +class OutputSchemaError(ValueError): + """Raised when an ``outputs`` schema is malformed or unsupported.""" + + +def _scalar_type(name: str, field: str) -> Any: + key = name.strip().lower() + if key not in _SCALARS: + raise OutputSchemaError(f"unsupported type {name!r} in field {field!r}") + return _SCALARS[key] + + +def _spec_to_type(field: str, spec: Any, model_name: str) -> tuple[Any, bool]: + """Resolve a field spec into ``(python_type, optional)``.""" + if isinstance(spec, str): + s = spec.strip() + optional = s.endswith("?") + if optional: + s = s[:-1].strip() + low = s.lower() + if low == "list": + return list, optional + if low.startswith("list[") and low.endswith("]"): + inner = s[5:-1].strip() + return list[_scalar_type(inner, field)], optional + return _scalar_type(s, field), optional + + if isinstance(spec, dict): + optional = bool(spec.get("optional", False)) + declared = spec.get("type") + if declared is None: + # Nested object shorthand: the mapping's keys are sub-fields. + return _build_model(f"{model_name}_{field}", spec), optional + declared = str(declared).lower() + if declared == "list": + items = spec.get("items", "any") + inner_type, _ = _spec_to_type(field, items, f"{model_name}_{field}") + return list[inner_type], optional + if declared == "object": + fields = spec.get("fields") + if not isinstance(fields, dict): + raise OutputSchemaError( + f"object field {field!r} requires a 'fields' mapping" + ) + return _build_model(f"{model_name}_{field}", fields), optional + # Scalar declared via the ``type`` key, e.g. {type: str}. + return _scalar_type(declared, field), optional + + raise OutputSchemaError(f"invalid type spec for field {field!r}: {spec!r}") + + +def _build_model(name: str, fields: Any) -> type[BaseModel]: + if not isinstance(fields, dict) or not fields: + raise OutputSchemaError(f"schema {name!r} must be a non-empty mapping of fields") + field_defs: dict[str, Any] = {} + for fname, fspec in fields.items(): + if not isinstance(fname, str) or not fname.isidentifier(): + raise OutputSchemaError(f"invalid field name {fname!r} in schema {name!r}") + py_type, optional = _spec_to_type(fname, fspec, name) + if optional: + field_defs[fname] = (Optional[py_type], None) + else: + field_defs[fname] = (py_type, ...) + return create_model(name, __config__=ConfigDict(extra="allow"), **field_defs) + + +def build_output_model(name: str, schema: dict[str, Any]) -> type[BaseModel]: + """Compile an ``outputs`` schema mapping into a Pydantic model class. + + Raises: + OutputSchemaError: If the schema is malformed or uses an unsupported + type. Callers can use this to validate schemas at load time. + """ + return _build_model(name, schema) + + +def validate_output( + schema: dict[str, Any], value: Any, model_name: str = "TaskOutput" +) -> dict[str, Any]: + """Validate/coerce *value* against *schema*, returning a plain dict. + + Raises: + OutputSchemaError: If the schema itself is invalid. + pydantic.ValidationError: If *value* does not satisfy the schema. + """ + model = build_output_model(model_name, schema) + obj = model.model_validate(value) + return obj.model_dump() diff --git a/src/seclab_taskflow_agent/results.py b/src/seclab_taskflow_agent/results.py new file mode 100644 index 00000000..da7c3f95 --- /dev/null +++ b/src/seclab_taskflow_agent/results.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Neutral cross-task result representation and per-run result store. + +Historically the runner passed data between tasks through a single shared +``list[str]`` of backend-specific tool-result JSON envelopes, decoded with a +double ``json.loads`` that only reliably handled the openai-agents +single-text-content shape. The copilot and anthropic adapters had to +*reconstruct* that exact envelope (``json.dumps({"text": ...})``) so the +runner's decode kept working. + +This module replaces that with: + +* :class:`ToolResult` - a neutral, backend-agnostic record of a single tool + call result (``text`` and/or ``structured`` content). +* :func:`normalize_openai_tool_output` - turns the openai-agents MCP + serialization (any of its three shapes) into a :class:`ToolResult`. +* :func:`decode_tool_result` - the single place that turns a + :class:`ToolResult` into the Python value a task consumes. +* :class:`ResultStore` - a per-run store holding the ordered tool results + (for legacy ``repeat_prompt`` carry-over) and named task outputs (for typed + ``outputs.`` passing), with snapshot/restore for session resume. +""" + +from __future__ import annotations + +__all__ = [ + "ResultStore", + "ToolResult", + "decode_tool_result", + "normalize_openai_tool_output", +] + +import json +from typing import Any + +from pydantic import BaseModel, ConfigDict + + +class ToolResult(BaseModel): + """A neutral record of one tool call result. + + ``text`` carries the primary text payload (when the tool returned text + content); ``structured`` carries a decoded object when the tool returned + structured / multi-part content. Exactly which is populated depends on the + tool and backend; :func:`decode_tool_result` prefers ``structured`` and + falls back to parsing ``text``. + """ + + model_config = ConfigDict(extra="allow") + + tool_name: str = "" + text: str | None = None + structured: Any = None + + +def normalize_openai_tool_output(raw: Any, tool_name: str = "") -> ToolResult: + """Normalise an openai-agents MCP tool output into a :class:`ToolResult`. + + The openai-agents MCP shim serialises a tool result as one of: + + * a single text content part: ``{"type": "text", "text": "..."}`` + * multiple content parts: ``[{...}, {...}]`` + * structured content: an arbitrary JSON object + * empty content: ``"[]"`` + + plus the historical bridge envelope ``{"text": "..."}``. This function + accepts all of them (and already-normalised inputs) and never raises. + """ + if isinstance(raw, ToolResult): + return raw + if not isinstance(raw, str): + # Already a structured Python object (e.g. a dict/list). + return _from_parsed(raw, tool_name) + try: + parsed = json.loads(raw) + except (json.JSONDecodeError, ValueError): + # Not JSON at all - keep it as plain text. + return ToolResult(tool_name=tool_name, text=raw) + return _from_parsed(parsed, tool_name) + + +def _from_parsed(parsed: Any, tool_name: str) -> ToolResult: + """Build a :class:`ToolResult` from an already-parsed value.""" + if isinstance(parsed, dict): + # MCP single text content part. + if parsed.get("type") == "text" and isinstance(parsed.get("text"), str): + return ToolResult(tool_name=tool_name, text=parsed["text"]) + # Historical bridge envelope: a lone ``text`` key. + if list(parsed.keys()) == ["text"] and isinstance(parsed.get("text"), str): + return ToolResult(tool_name=tool_name, text=parsed["text"]) + # Anything else is structured content. + return ToolResult(tool_name=tool_name, structured=parsed) + if isinstance(parsed, list): + texts = [ + item.get("text") + for item in parsed + if isinstance(item, dict) and isinstance(item.get("text"), str) + ] + # Pure list of text parts -> join as text; otherwise keep structured. + if texts and len(texts) == len(parsed): + return ToolResult(tool_name=tool_name, text="\n".join(texts)) + return ToolResult(tool_name=tool_name, structured=parsed) + if isinstance(parsed, str): + return ToolResult(tool_name=tool_name, text=parsed) + # Scalars (int/float/bool) are treated as structured values. + return ToolResult(tool_name=tool_name, structured=parsed) + + +def decode_tool_result(tr: ToolResult) -> Any: + """Return the Python value a task consumes from a :class:`ToolResult`. + + Prefers ``structured`` content; otherwise parses ``text`` as JSON. Raises + ``ValueError`` when there is no usable content or the text is not valid + JSON, matching the strictness the legacy ``repeat_prompt`` path required. + """ + if tr.structured is not None: + return tr.structured + if tr.text is None: + raise ValueError("tool result has neither text nor structured content") + try: + return json.loads(tr.text) + except (json.JSONDecodeError, ValueError) as exc: + raise ValueError("tool result text is not valid JSON") from exc + + +class ResultStore: + """Per-run store for cross-task data flow. + + Holds the ordered list of tool results (so legacy ``repeat_prompt`` can + consume the previous task's last result) and a map of named task outputs + (so typed ``outputs.`` passing can address a task's result by name). + Not a module global: one instance per run, threaded through the runner, + which keeps concurrent (multi-model / async) branches from corrupting a + shared list. + """ + + def __init__(self) -> None: + self._results: list[ToolResult] = [] + self._outputs: dict[str, Any] = {} + + def record(self, result: ToolResult) -> None: + """Append a tool result to the ordered carry-over list.""" + self._results.append(result) + + def last(self) -> ToolResult | None: + """Return the most recently recorded tool result, or ``None``.""" + return self._results[-1] if self._results else None + + def pop_last(self) -> None: + """Consume the most recent tool result (legacy repeat_prompt).""" + if self._results: + self._results.pop() + + def set_output(self, name: str, value: Any) -> None: + """Store a named task output for ``outputs.`` addressing.""" + self._outputs[name] = value + + @property + def outputs(self) -> dict[str, Any]: + """The named task outputs mapping.""" + return self._outputs + + @property + def results(self) -> list[ToolResult]: + """The ordered tool-result carry-over list.""" + return self._results + + def snapshot(self) -> dict[str, Any]: + """Serialise the store for session persistence.""" + return { + "results": [r.model_dump() for r in self._results], + "outputs": self._outputs, + } + + @classmethod + def from_snapshot(cls, data: dict[str, Any] | None) -> ResultStore: + """Reconstruct a store from :meth:`snapshot` output.""" + store = cls() + if data: + store._results = [ToolResult.model_validate(r) for r in data.get("results", [])] + store._outputs = dict(data.get("outputs", {})) + return store diff --git a/src/seclab_taskflow_agent/runner.py b/src/seclab_taskflow_agent/runner.py index 01f1d74b..9ddf8ec7 100644 --- a/src/seclab_taskflow_agent/runner.py +++ b/src/seclab_taskflow_agent/runner.py @@ -20,7 +20,6 @@ ] import asyncio -import json import logging import uuid from collections.abc import Awaitable, Callable @@ -39,6 +38,8 @@ from .mcp_utils import compress_name, mcp_client_params from .models import ModelConfigDocument, PersonalityDocument, TaskDefinition from .render_utils import flush_async_output, render_model_output +from .results import ResultStore, ToolResult, decode_tool_result, normalize_openai_tool_output +from .output_schema import validate_output from .sdk import AgentSpec, MCPServerSpec, get_backend, resolve_backend_name from .sdk.errors import ( BackendBadRequestError, @@ -47,7 +48,7 @@ BackendUnexpectedError, ) from .shell_utils import shell_tool_call -from .template_utils import render_template +from .template_utils import evaluate_expression, render_template if TYPE_CHECKING: # Hook callbacks still use openai-agents types; fully decoupling them is a later slice. from agents import Agent, RunContextWrapper, TContext, Tool @@ -267,6 +268,41 @@ def _completion(oks: list[bool], policy: str) -> bool: return all(oks) +def _capture_task_output( + store: ResultStore, + output_id: str, + schema: dict[str, Any], + task_name: str, +) -> None: + """Capture a task's final tool result as a named typed output. + + The task's output is its most recent tool result. When *schema* is + non-empty the decoded value is validated/coerced against it (raising a + clear error on mismatch); otherwise the decoded value is stored as-is, + falling back to the raw text when it is not JSON. The result is exposed to + later tasks as ``outputs.``. + """ + last = store.last() + if last is None: + if schema: + raise ValueError( + f"task {task_name!r} declares 'outputs' but produced no tool result to capture" + ) + store.set_output(output_id, None) + return + + if schema: + value = decode_tool_result(last) + validated = validate_output(schema, value, model_name=f"{output_id}_output") + store.set_output(output_id, validated) + else: + try: + value = decode_tool_result(last) + except ValueError: + value = last.text + store.set_output(output_id, value) + + async def _fan_out_deploys( work_items: list[tuple[Any, ResolvedModel]], deploy: Callable[[Any, ResolvedModel], Awaitable[bool]], @@ -332,58 +368,78 @@ async def _guarded(payload: Any, model: ResolvedModel) -> bool: async def _build_prompts_to_run( task_prompt: str, repeat_prompt: bool, - last_mcp_tool_results: list[str], + store: ResultStore, available_tools: AvailableTools, global_variables: dict[str, Any], inputs: dict[str, Any], + outputs: dict[str, Any] | None = None, + over: str = "", ) -> list[str]: """Build the list of prompts to execute for a task. For regular tasks the list contains a single rendered prompt. When - ``repeat_prompt`` is enabled, the last MCP tool result is parsed as an - iterable and a prompt is rendered for each element. + ``repeat_prompt`` is enabled, an iterable is derived and a prompt is + rendered for each element: + + * If ``over`` is set, it is evaluated as an expression against the + template context (``globals`` / ``inputs`` / ``outputs``) to yield the + iterable directly. This is the explicit, typed path and does not consume + the tool-result carry-over. + * Otherwise the previous task's last tool result is decoded from *store* + (the legacy path), and consumed (popped) after all prompts render. Args: task_prompt: The raw or pre-rendered prompt template string. - repeat_prompt: Whether to expand prompts over MCP tool results. - last_mcp_tool_results: Mutable list of prior MCP tool result strings. + repeat_prompt: Whether to expand prompts over an iterable. + store: Per-run result store providing the last tool result. available_tools: Tool registry (passed through to template rendering). global_variables: Global template variables. inputs: Task-level input variables. + outputs: Named task outputs available as ``outputs.``. + over: Optional expression selecting the iterable explicitly. Returns: List of rendered prompt strings to execute. Raises: - ValueError: If the last MCP result is missing or not valid JSON. + IndexError: If the legacy path has no previous tool result. + ValueError: If the derived value is not valid JSON or not iterable. """ + outputs = outputs or {} prompts_to_run: list[str] = [] if repeat_prompt: if "result" not in task_prompt.lower(): logging.warning("repeat_prompt enabled but no {{ result }} in prompt") - try: - last_result = json.loads(last_mcp_tool_results[-1]) - except IndexError: - logging.critical("No last MCP tool result available") - raise - except json.JSONDecodeError as exc: - logging.critical("Could not parse tool result as JSON: %s", last_mcp_tool_results[-1][:200]) - raise ValueError("Tool result is not valid JSON") from exc - text = last_result.get("text", "") - try: - iterable_result = json.loads(text) - except json.JSONDecodeError as exc: - logging.critical("Could not parse result text: %s", text) - raise ValueError("Result text is not valid JSON") from exc + if over: + # Explicit, typed iterable: evaluate the expression against the + # full template context. Does not consume the carry-over stack. + try: + iterable_result = evaluate_expression( + over, + available_tools, + globals_dict=global_variables, + inputs_dict=inputs, + outputs_dict=outputs, + ) + except jinja2.TemplateError as exc: + logging.critical("Could not evaluate over expression %r: %s", over, exc) + raise ValueError(f"Failed to evaluate 'over' expression: {exc}") from exc + else: + last = store.last() + if last is None: + logging.critical("No last tool result available") + raise IndexError("No last tool result available for repeat_prompt") + iterable_result = decode_tool_result(last) + try: iter(iterable_result) except TypeError: - logging.critical("Last MCP tool result is not iterable") + logging.critical("repeat_prompt iterable is not iterable: %r", iterable_result) raise if not iterable_result: - await render_model_output("** 🤖❗MCP tool result iterable is empty!\n") + await render_model_output("** 🤖❗repeat_prompt iterable is empty!\n") else: logging.debug("Rendering templated prompts for results: %s", iterable_result) for value in iterable_result: @@ -394,15 +450,18 @@ async def _build_prompts_to_run( globals_dict=global_variables, inputs_dict=inputs, result_value=value, + outputs_dict=outputs, ) prompts_to_run.append(rendered_prompt) except jinja2.TemplateError as e: logging.error("Error rendering template for result %s: %s", value, e) raise ValueError(f"Template rendering failed: {e}") - # Consume only after all prompts rendered successfully so that - # the result remains available for retry/resume on failure. - last_mcp_tool_results.pop() + # Legacy path consumes the tool result only after all prompts rendered + # successfully, so it remains available for retry/resume on failure. + # The explicit ``over`` path reads named data and never consumes. + if not over: + store.pop_last() else: prompts_to_run.append(task_prompt) return prompts_to_run @@ -428,6 +487,7 @@ async def deploy_task_agents( run_hooks: TaskRunHooks | None = None, agent_hooks: TaskAgentHooks | None = None, stream_label: str | None = None, + record_tool_result: Callable[[ToolResult], Awaitable[None]] | None = None, ) -> bool: """Deploy and run task agents with MCP servers. @@ -444,6 +504,9 @@ async def deploy_task_agents( stream_label: Optional human-readable label for this run's buffered output block (used to tag per-model streams in multi-model tasks). Only takes effect when ``async_task`` is True. + record_tool_result: Neutral sink for tool results surfaced by backends + that stream ``ToolEnd`` events (copilot/anthropic). The openai + adapter captures results via ``run_hooks.on_tool_end`` instead. Returns: True if the task completed successfully. @@ -591,6 +654,7 @@ async def deploy_task_agents( max_api_retry=MAX_API_RETRY, initial_rate_limit_backoff=RATE_LIMIT_BACKOFF, max_rate_limit_backoff=MAX_RATE_LIMIT_BACKOFF, + record_tool_result=record_tool_result, ) complete = True @@ -678,11 +742,19 @@ async def run_main( # already handle. Idempotent — safe to call on every run_main. start_watchdog() - last_mcp_tool_results: list[str] = [] + store = ResultStore() async def on_tool_end_hook(context: RunContextWrapper[TContext], agent: Agent[TContext], tool: Tool, result: str) -> None: + # openai-agents delivers tool results here as a backend-specific + # serialised string; normalise to a neutral ToolResult before storing. + watchdog_ping() + store.record(normalize_openai_tool_output(result, tool_name=getattr(tool, "name", ""))) + + async def record_tool_result(tool_result: ToolResult) -> None: + # Neutral sink for backends (copilot/anthropic) that surface tool + # results as stream events rather than via openai-agents RunHooks. watchdog_ping() - last_mcp_tool_results.append(result) + store.record(tool_result) async def on_tool_start_hook(context: RunContextWrapper[TContext], agent: Agent[TContext], tool: Tool) -> None: watchdog_ping() @@ -698,6 +770,7 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo {personality_path: personality}, prompt or "", run_hooks=TaskRunHooks(on_tool_end=on_tool_end_hook, on_tool_start=on_tool_start_hook), + record_tool_result=record_tool_result, ) if taskflow_path or resume_session_id: @@ -711,7 +784,7 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo taskflow_path = session.taskflow_path cli_globals = session.cli_globals prompt = session.prompt - last_mcp_tool_results = list(session.last_tool_results) + store = ResultStore.from_snapshot(session.result_snapshot) # Restore persisted model config unless explicitly overridden if not cli_model_config and session.cli_model_config: cli_model_config = session.cli_model_config @@ -794,6 +867,11 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo completion_policy = task.completion # Bound on concurrent model runs (0 == run all models at once). model_concurrency = task.model_concurrency or len(resolved_models) + # Typed named outputs (M2): id names the task's captured output; + # outputs declares its schema; over selects a repeat_prompt iterable. + task_output_id = task.id + task_output_schema = task.outputs or {} + over = task.over or "" # Render prompt template (skip if repeat_prompt — result not yet available) if task_prompt and not repeat_prompt: @@ -803,6 +881,7 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo available_tools=available_tools, globals_dict=global_variables, inputs_dict=inputs, + outputs_dict=store.outputs, ) except jinja2.TemplateError as e: logging.error("Template rendering error: %s", e) @@ -810,16 +889,17 @@ async def on_handoff_hook(context: RunContextWrapper[TContext], agent: Agent[TCo with TmpEnv(env, context={"globals": global_variables}): prompts_to_run: list[str] = await _build_prompts_to_run( - task_prompt, repeat_prompt, last_mcp_tool_results, + task_prompt, repeat_prompt, store, available_tools, global_variables, inputs, + outputs=store.outputs, over=over, ) async def run_prompts(async_task: bool = False, max_concurrent_tasks: int = 5) -> bool: if run: await render_model_output("** 🤖🐚 Executing Shell Task\n") try: - result = shell_tool_call(run).content[0].model_dump_json() - last_mcp_tool_results.append(result) + content = shell_tool_call(run).content[0] + store.record(ToolResult(tool_name="shell", text=getattr(content, "text", ""))) return True except RuntimeError as e: await render_model_output(f"** 🤖❗ Shell Task Exception: {e}\n") @@ -860,20 +940,22 @@ async def run_prompts(async_task: bool = False, max_concurrent_tasks: int = 5) - async def _deploy(payload: tuple[dict[str, Any], str], rm: ResolvedModel) -> bool: ra, pp = payload # Isolate multi-model tool-result capture: concurrent - # models must not interleave into the shared - # last_mcp_tool_results (which feeds downstream - # repeat_prompt / session checkpoints). Single-model - # runs keep the shared sink for backwards compatibility. + # models must not interleave into the shared result + # store (which feeds downstream repeat_prompt / typed + # outputs / session checkpoints). Single-model runs keep + # the shared sink for backwards compatibility. if multi_model: async def _isolated_tool_end(context, agent, tool, result) -> None: # noqa: ANN001 watchdog_ping() run_hooks = TaskRunHooks( on_tool_end=_isolated_tool_end, on_tool_start=on_tool_start_hook ) + branch_record = None else: run_hooks = TaskRunHooks( on_tool_end=on_tool_end_hook, on_tool_start=on_tool_start_hook ) + branch_record = record_tool_result return await deploy_task_agents( available_tools, ra, @@ -885,6 +967,7 @@ async def _isolated_tool_end(context, agent, tool, result) -> None: # noqa: ANN exclude_from_context=exclude_from_context, max_turns=max_turns, run_hooks=run_hooks, + record_tool_result=branch_record, model=rm.model, model_par=rm.model_settings, api_type=rm.api_type, @@ -967,13 +1050,22 @@ async def _isolated_tool_end(context, agent, tool, result) -> None: # noqa: ANN ) break + # Capture this task's typed named output (M2). The task's + # output is its final tool result; when an ``outputs`` schema + # is declared it is validated/coerced before being stored under + # ``outputs.`` for downstream tasks to consume by name. + if task_output_id and not multi_model: + _capture_task_output( + store, task_output_id, task_output_schema, task_name + ) + # Checkpoint after task (must_complete failures break above # without advancing the resume cursor) session.record_task( index=task_index, name=task_name, success=task_complete, - tool_results=list(last_mcp_tool_results), + result_snapshot=store.snapshot(), ) # All tasks completed successfully diff --git a/src/seclab_taskflow_agent/session.py b/src/seclab_taskflow_agent/session.py index d829da45..e46855ee 100644 --- a/src/seclab_taskflow_agent/session.py +++ b/src/seclab_taskflow_agent/session.py @@ -39,7 +39,6 @@ class CompletedTask(BaseModel): index: int name: str = "" result: bool = False - tool_results: list[str] = Field(default_factory=list) class TaskflowSession(BaseModel): @@ -63,8 +62,9 @@ class TaskflowSession(BaseModel): # CLI model config override persisted for deterministic resume cli_model_config: str = "" - # Accumulated tool results carried across tasks (used by repeat_prompt) - last_tool_results: list[str] = Field(default_factory=list) + # Snapshot of the per-run ResultStore (ordered tool results + named + # outputs) carried across tasks and restored on resume. + result_snapshot: dict = Field(default_factory=dict) @property def next_task_index(self) -> int: @@ -91,7 +91,7 @@ def record_task( index: int, name: str, success: bool, - tool_results: list[str] | None = None, + result_snapshot: dict | None = None, ) -> None: """Record a completed task and save the checkpoint.""" self.completed_tasks.append( @@ -99,10 +99,10 @@ def record_task( index=index, name=name, result=success, - tool_results=tool_results or [], ) ) - self.last_tool_results = list(tool_results or []) + if result_snapshot is not None: + self.result_snapshot = result_snapshot self.save() def mark_finished(self) -> None: diff --git a/src/seclab_taskflow_agent/template_utils.py b/src/seclab_taskflow_agent/template_utils.py index 2f21d4a6..024c95dc 100644 --- a/src/seclab_taskflow_agent/template_utils.py +++ b/src/seclab_taskflow_agent/template_utils.py @@ -8,7 +8,7 @@ import jinja2 -__all__ = ["PromptLoader", "create_jinja_environment", "env_function", "render_template"] +__all__ = ["PromptLoader", "create_jinja_environment", "env_function", "evaluate_expression", "render_template"] if TYPE_CHECKING: from .available_tools import AvailableTools @@ -81,6 +81,29 @@ def env_function(var_name: str, default: Optional[str] = None, required: bool = return value or "" +class _DataFirstEnvironment(jinja2.Environment): + """Jinja environment that prefers mapping item access for ``a.b``. + + In stock Jinja, ``foo.bar`` tries ``getattr(foo, 'bar')`` before + ``foo['bar']``. For a data-passing DSL that means dict keys named after + dict methods (``items``, ``keys``, ``values``, ``get``, ``copy``, ...) + resolve to the *method* instead of the data, e.g. ``outputs.x.items`` + returns the ``dict.items`` builtin. This subclass flips the order so + mapping keys win, falling back to attribute access for objects. For keys + that are not dict methods the behaviour is identical to stock Jinja. + """ + + def getattr(self, obj: Any, attribute: str) -> Any: # noqa: N802 - Jinja API + try: + return obj[attribute] + except (TypeError, LookupError): + pass + try: + return getattr(obj, attribute) + except AttributeError: + return self.undefined(obj=obj, name=attribute) + + def create_jinja_environment(available_tools: "AvailableTools") -> jinja2.Environment: """Create configured Jinja2 environment for taskflow templates. @@ -90,7 +113,7 @@ def create_jinja_environment(available_tools: "AvailableTools") -> jinja2.Enviro Returns: Configured Jinja2 Environment """ - env = jinja2.Environment( + env = _DataFirstEnvironment( loader=PromptLoader(available_tools), # Use same delimiters as custom system variable_start_string='{{', @@ -118,6 +141,7 @@ def render_template( globals_dict: Optional[Dict[str, Any]] = None, inputs_dict: Optional[Dict[str, Any]] = None, result_value: Optional[Any] = None, + outputs_dict: Optional[Dict[str, Any]] = None, ) -> str: """Render a template string with provided context. @@ -127,6 +151,7 @@ def render_template( globals_dict: Global variables dict inputs_dict: Input variables dict result_value: Result value for repeat_prompt + outputs_dict: Named task outputs, exposed as ``outputs.`` Returns: Rendered template string @@ -141,27 +166,65 @@ def render_template( # Render with result render_template("{{ result.name }}", tools, result_value={'name': 'test'}) - # Render with all context types + # Render with a named task output render_template( - "{{ globals.x }} {{ inputs.y }} {{ result.z }}", + "{{ outputs.list_functions.functions }}", tools, - globals_dict={'x': 1}, - inputs_dict={'y': 2}, - result_value={'z': 3} + outputs_dict={'list_functions': {'functions': [...]}}, ) """ jinja_env = create_jinja_environment(available_tools) # Build template context - context = { - 'globals': globals_dict or {}, - 'inputs': inputs_dict or {}, - } - - # Add result if provided - if result_value is not None: - context['result'] = result_value + context = _build_context(globals_dict, inputs_dict, outputs_dict, result_value) # Render template template = jinja_env.from_string(template_str) return template.render(**context) + + +def evaluate_expression( + expression: str, + available_tools: "AvailableTools", + globals_dict: Optional[Dict[str, Any]] = None, + inputs_dict: Optional[Dict[str, Any]] = None, + outputs_dict: Optional[Dict[str, Any]] = None, + result_value: Optional[Any] = None, +) -> Any: + """Evaluate a Jinja expression against the template context. + + Unlike :func:`render_template`, this returns the *actual Python object* + the expression evaluates to (e.g. a list), not its string rendering. Used + for the ``over:`` iterable selector so a typed list can be iterated + directly instead of being round-tripped through JSON. + + The expression may be given bare (``outputs.foo.items``) or wrapped in + ``{{ ... }}``; the wrapping is stripped for convenience. + + Raises: + jinja2.TemplateError: On compilation or evaluation errors. + """ + expr = expression.strip() + if expr.startswith("{{") and expr.endswith("}}"): + expr = expr[2:-2].strip() + jinja_env = create_jinja_environment(available_tools) + context = _build_context(globals_dict, inputs_dict, outputs_dict, result_value) + compiled = jinja_env.compile_expression(expr) + return compiled(**context) + + +def _build_context( + globals_dict: Optional[Dict[str, Any]], + inputs_dict: Optional[Dict[str, Any]], + outputs_dict: Optional[Dict[str, Any]], + result_value: Optional[Any], +) -> Dict[str, Any]: + """Assemble the shared Jinja context for rendering and expressions.""" + context: Dict[str, Any] = { + "globals": globals_dict or {}, + "inputs": inputs_dict or {}, + "outputs": outputs_dict or {}, + } + if result_value is not None: + context["result"] = result_value + return context diff --git a/tests/test_models.py b/tests/test_models.py index 59f93ca3..96cec8c6 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -171,6 +171,43 @@ def test_invalid_models_entry_rejected(self): TaskDefinition(user_prompt="hi", models=[123]) +class TestTypedOutputs: + """Test the typed named outputs grammar (id / outputs / over).""" + + def test_defaults(self): + t = TaskDefinition(user_prompt="hi") + assert t.id == "" + assert t.outputs == {} + assert t.over == "" + + def test_id_and_outputs_accepted(self): + t = TaskDefinition( + id="list_functions", + user_prompt="list them", + outputs={"functions": {"type": "list", "items": {"name": "str", "body": "str"}}}, + ) + assert t.id == "list_functions" + assert "functions" in t.outputs + + def test_invalid_outputs_schema_rejected_at_load(self): + with pytest.raises(ValidationError, match="invalid 'outputs' schema"): + TaskDefinition(id="x", user_prompt="hi", outputs={"f": "not-a-real-type"}) + + def test_over_requires_repeat_prompt(self): + with pytest.raises(ValidationError, match="'over' only applies to repeat_prompt"): + TaskDefinition(user_prompt="{{ result }}", over="outputs.x.items") + + def test_over_with_repeat_prompt_ok(self): + t = TaskDefinition(user_prompt="{{ result }}", repeat_prompt=True, over="outputs.x.items") + assert t.over == "outputs.x.items" + + def test_typed_outputs_rejected_on_multi_model(self): + with pytest.raises(ValidationError, match="not yet supported on multi-model"): + TaskDefinition(id="x", user_prompt="hi", models=["a", "b"]) + with pytest.raises(ValidationError, match="not yet supported on multi-model"): + TaskDefinition(user_prompt="hi", models=["a", "b"], outputs={"f": "str"}) + + class TestTaskflowDocument: """Test complete taskflow document parsing.""" diff --git a/tests/test_output_schema.py b/tests/test_output_schema.py new file mode 100644 index 00000000..ee49f5b6 --- /dev/null +++ b/tests/test_output_schema.py @@ -0,0 +1,107 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Tests for the inline outputs schema compiler.""" + +import pytest +from pydantic import ValidationError + +from seclab_taskflow_agent.output_schema import ( + OutputSchemaError, + build_output_model, + validate_output, +) + + +class TestScalars: + def test_scalar_fields(self): + out = validate_output({"name": "str", "count": "int"}, {"name": "f", "count": 3}) + assert out == {"name": "f", "count": 3} + + def test_scalar_coercion(self): + # pydantic coerces a numeric string to int + out = validate_output({"count": "int"}, {"count": "42"}) + assert out["count"] == 42 + + def test_synonyms(self): + out = validate_output( + {"a": "string", "b": "integer", "c": "number", "d": "boolean"}, + {"a": "x", "b": 1, "c": 1.5, "d": True}, + ) + assert out == {"a": "x", "b": 1, "c": 1.5, "d": True} + + def test_any_type(self): + out = validate_output({"v": "any"}, {"v": {"nested": [1, 2]}}) + assert out["v"] == {"nested": [1, 2]} + + def test_optional_field_absent(self): + out = validate_output({"name": "str", "note": "str?"}, {"name": "f"}) + assert out == {"name": "f", "note": None} + + def test_required_field_missing_raises(self): + with pytest.raises(ValidationError): + validate_output({"name": "str"}, {}) + + def test_unsupported_scalar_raises(self): + with pytest.raises(OutputSchemaError, match="unsupported type"): + build_output_model("m", {"x": "decimal"}) + + +class TestLists: + def test_list_of_scalars(self): + out = validate_output({"tags": "list[str]"}, {"tags": ["a", "b"]}) + assert out["tags"] == ["a", "b"] + + def test_bare_list_is_any(self): + out = validate_output({"items": "list"}, {"items": [1, "a", {"k": 1}]}) + assert out["items"] == [1, "a", {"k": 1}] + + def test_list_type_with_scalar_items(self): + out = validate_output({"nums": {"type": "list", "items": "int"}}, {"nums": [1, 2]}) + assert out["nums"] == [1, 2] + + def test_list_of_objects(self): + schema = {"functions": {"type": "list", "items": {"name": "str", "body": "str"}}} + value = {"functions": [{"name": "f", "body": "..."}, {"name": "g", "body": "!"}]} + out = validate_output(schema, value) + assert out["functions"][0] == {"name": "f", "body": "..."} + assert out["functions"][1]["name"] == "g" + + def test_list_element_validation_error(self): + with pytest.raises(ValidationError): + validate_output({"nums": "list[int]"}, {"nums": ["not-an-int"]}) + + +class TestNestedObjects: + def test_nested_object_shorthand(self): + schema = {"meta": {"author": "str", "version": "int"}} + out = validate_output(schema, {"meta": {"author": "a", "version": 2}}) + assert out["meta"] == {"author": "a", "version": 2} + + def test_explicit_object_form(self): + schema = {"meta": {"type": "object", "fields": {"author": "str"}}} + out = validate_output(schema, {"meta": {"author": "a"}}) + assert out["meta"] == {"author": "a"} + + def test_object_missing_fields_raises(self): + with pytest.raises(OutputSchemaError, match="requires a 'fields' mapping"): + build_output_model("m", {"meta": {"type": "object"}}) + + +class TestSchemaErrors: + def test_empty_schema_raises(self): + with pytest.raises(OutputSchemaError, match="non-empty mapping"): + build_output_model("m", {}) + + def test_invalid_field_name_raises(self): + with pytest.raises(OutputSchemaError, match="invalid field name"): + build_output_model("m", {"has-hyphen": "str"}) + + def test_invalid_spec_type_raises(self): + with pytest.raises(OutputSchemaError, match="invalid type spec"): + build_output_model("m", {"x": 123}) + + def test_extra_fields_preserved(self): + # extra="allow": unknown fields in the value are kept + out = validate_output({"name": "str"}, {"name": "f", "extra": 1}) + assert out["extra"] == 1 diff --git a/tests/test_results.py b/tests/test_results.py new file mode 100644 index 00000000..f514bf56 --- /dev/null +++ b/tests/test_results.py @@ -0,0 +1,153 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Tests for the neutral result representation and per-run store.""" + +import json + +import pytest + +from seclab_taskflow_agent.results import ( + ResultStore, + ToolResult, + decode_tool_result, + normalize_openai_tool_output, +) + + +class TestNormalizeOpenAIToolOutput: + """normalize_openai_tool_output handles every backend/serialisation shape.""" + + def test_single_text_content_part(self): + """openai-agents single text content: {"type":"text","text":...}.""" + raw = json.dumps({"type": "text", "text": "[1, 2, 3]", "annotations": None}) + tr = normalize_openai_tool_output(raw) + assert tr.text == "[1, 2, 3]" + assert tr.structured is None + + def test_lone_text_envelope(self): + """Historical bridge envelope: {"text": ...}.""" + raw = json.dumps({"text": json.dumps({"a": 1})}) + tr = normalize_openai_tool_output(raw) + assert tr.text == '{"a": 1}' + assert tr.structured is None + + def test_structured_content_object(self): + """A structured object (no text-part shape) becomes structured.""" + raw = json.dumps({"functions": [{"name": "f", "body": "..."}]}) + tr = normalize_openai_tool_output(raw) + assert tr.text is None + assert tr.structured == {"functions": [{"name": "f", "body": "..."}]} + + def test_multiple_text_parts_joined(self): + """Multiple text content parts join into a single text payload.""" + raw = json.dumps([{"type": "text", "text": "a"}, {"type": "text", "text": "b"}]) + tr = normalize_openai_tool_output(raw) + assert tr.text == "a\nb" + + def test_mixed_content_list_is_structured(self): + """A list whose items are not all text parts stays structured.""" + raw = json.dumps([{"type": "text", "text": "a"}, {"type": "image", "data": "x"}]) + tr = normalize_openai_tool_output(raw) + assert tr.text is None + assert isinstance(tr.structured, list) + + def test_empty_content_list(self): + """openai-agents serialises empty content as "[]".""" + tr = normalize_openai_tool_output("[]") + assert tr.text is None + assert tr.structured == [] + + def test_non_json_text(self): + """A non-JSON string is preserved verbatim as text.""" + tr = normalize_openai_tool_output("plain answer, not json") + assert tr.text == "plain answer, not json" + + def test_already_a_tool_result_passthrough(self): + tr_in = ToolResult(tool_name="x", text="hi") + assert normalize_openai_tool_output(tr_in) is tr_in + + def test_non_string_structured_object(self): + """A pre-parsed dict input is treated as structured content.""" + tr = normalize_openai_tool_output({"k": "v"}, tool_name="t") + assert tr.structured == {"k": "v"} + assert tr.tool_name == "t" + + def test_scalar_is_structured(self): + tr = normalize_openai_tool_output("42") + assert tr.structured == 42 + + +class TestDecodeToolResult: + """decode_tool_result is the single decode path for consuming a result.""" + + def test_structured_preferred(self): + tr = ToolResult(structured={"functions": [1, 2]}) + assert decode_tool_result(tr) == {"functions": [1, 2]} + + def test_json_text_parsed(self): + tr = ToolResult(text=json.dumps([1, 2, 3])) + assert decode_tool_result(tr) == [1, 2, 3] + + def test_non_json_text_raises(self): + tr = ToolResult(text="not json") + with pytest.raises(ValueError, match="not valid JSON"): + decode_tool_result(tr) + + def test_empty_result_raises(self): + with pytest.raises(ValueError, match="neither text nor structured"): + decode_tool_result(ToolResult()) + + def test_roundtrip_from_openai_single_text(self): + """The common path: single text content carrying a JSON array.""" + raw = json.dumps({"type": "text", "text": json.dumps([{"name": "a"}])}) + value = decode_tool_result(normalize_openai_tool_output(raw)) + assert value == [{"name": "a"}] + + +class TestResultStore: + """ResultStore holds ordered results and named outputs with snapshotting.""" + + def test_record_and_last(self): + s = ResultStore() + assert s.last() is None + s.record(ToolResult(text="a")) + s.record(ToolResult(text="b")) + assert s.last().text == "b" + + def test_pop_last(self): + s = ResultStore() + s.record(ToolResult(text="a")) + s.record(ToolResult(text="b")) + s.pop_last() + assert s.last().text == "a" + s.pop_last() + assert s.last() is None + # popping an empty store is a no-op + s.pop_last() + assert s.last() is None + + def test_named_outputs(self): + s = ResultStore() + s.set_output("list_functions", {"functions": [1, 2]}) + assert s.outputs["list_functions"] == {"functions": [1, 2]} + + def test_snapshot_roundtrip(self): + s = ResultStore() + s.record(ToolResult(tool_name="t", text=json.dumps([1, 2]))) + s.record(ToolResult(structured={"k": "v"})) + s.set_output("out", {"functions": ["a"]}) + + snap = s.snapshot() + # snapshot must be JSON-serialisable for session persistence + json.dumps(snap) + + restored = ResultStore.from_snapshot(snap) + assert restored.last().structured == {"k": "v"} + assert restored.results[0].text == json.dumps([1, 2]) + assert restored.outputs["out"] == {"functions": ["a"]} + + def test_from_snapshot_none_is_empty(self): + s = ResultStore.from_snapshot(None) + assert s.last() is None + assert s.outputs == {} diff --git a/tests/test_runner.py b/tests/test_runner.py index e497f9ae..1ee5fbab 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -19,9 +19,11 @@ TaskflowHeader, TaskWrapper, ) +from seclab_taskflow_agent.results import ResultStore, ToolResult from seclab_taskflow_agent.runner import ( ResolvedModel, _build_prompts_to_run, + _capture_task_output, _completion, _fan_out_deploys, _merge_reusable_task, @@ -377,9 +379,12 @@ class TestBuildPromptsToRun: """Tests for _build_prompts_to_run (async, run via asyncio.run).""" @staticmethod - def _result_entry(data: Any) -> str: - """Build a JSON string mimicking an MCP tool result.""" - return json.dumps({"text": json.dumps(data)}) + def _store_with(*values: Any) -> ResultStore: + """A ResultStore whose last recorded result carries JSON of *values[-1]*.""" + store = ResultStore() + for v in values: + store.record(ToolResult(text=json.dumps(v))) + return store @staticmethod def _run(coro): @@ -393,7 +398,7 @@ def test_non_repeat_returns_single_prompt(self): _build_prompts_to_run( task_prompt="hello world", repeat_prompt=False, - last_mcp_tool_results=[], + store=ResultStore(), available_tools=_mock_available_tools(), global_variables={}, inputs={}, @@ -404,12 +409,11 @@ def test_non_repeat_returns_single_prompt(self): def test_repeat_with_json_array(self): """repeat_prompt with a JSON array generates one prompt per element.""" items = [{"name": "apple"}, {"name": "banana"}] - results = [self._result_entry(items)] prompts = self._run( _build_prompts_to_run( task_prompt="Process {{ result.name }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=self._store_with(items), available_tools=_mock_available_tools(), global_variables={}, inputs={}, @@ -419,30 +423,29 @@ def test_repeat_with_json_array(self): assert "apple" in prompts[0] assert "banana" in prompts[1] - def test_repeat_with_dict_items(self): - """repeat_prompt iterates over dict keys when result is a dict.""" - data = {"a": 1, "b": 2} - results = [self._result_entry(data)] + def test_repeat_with_structured_result(self): + """A structured (non-text) tool result is consumed directly.""" + store = ResultStore() + store.record(ToolResult(structured=[1, 2, 3])) prompts = self._run( _build_prompts_to_run( - task_prompt="Key: {{ result }}", + task_prompt="n={{ result }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=store, available_tools=_mock_available_tools(), global_variables={}, inputs={}, ) ) - assert len(prompts) == 2 + assert len(prompts) == 3 def test_repeat_with_empty_iterable(self): """repeat_prompt with an empty list renders no prompts.""" - results = [self._result_entry([])] prompts = self._run( _build_prompts_to_run( task_prompt="Process {{ result }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=self._store_with([]), available_tools=_mock_available_tools(), global_variables={}, inputs={}, @@ -451,13 +454,13 @@ def test_repeat_with_empty_iterable(self): assert prompts == [] def test_raises_index_error_when_no_last_result(self): - """IndexError when last_mcp_tool_results is empty.""" + """IndexError when the store has no previous result.""" with pytest.raises(IndexError): self._run( _build_prompts_to_run( task_prompt="Process {{ result }}", repeat_prompt=True, - last_mcp_tool_results=[], + store=ResultStore(), available_tools=_mock_available_tools(), global_variables={}, inputs={}, @@ -465,14 +468,15 @@ def test_raises_index_error_when_no_last_result(self): ) def test_raises_value_error_on_non_json_result(self): - """ValueError when MCP result text is not valid JSON.""" - results = [json.dumps({"text": "not json!!"})] + """ValueError when the tool result text is not valid JSON.""" + store = ResultStore() + store.record(ToolResult(text="not json!!")) with pytest.raises(ValueError, match="not valid JSON"): self._run( _build_prompts_to_run( task_prompt="Process {{ result }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=store, available_tools=_mock_available_tools(), global_variables={}, inputs={}, @@ -480,29 +484,23 @@ def test_raises_value_error_on_non_json_result(self): ) def test_pop_happens_after_successful_render(self): - """The last result is only consumed after all prompts render.""" - items = [{"name": "x"}] - results = [self._result_entry(items)] - original_len = len(results) - + """The last result is consumed (popped) after all prompts render.""" + store = self._store_with([{"name": "x"}]) self._run( _build_prompts_to_run( task_prompt="Process {{ result.name }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=store, available_tools=_mock_available_tools(), global_variables={}, inputs={}, ) ) - # After success, the entry should be consumed - assert len(results) == original_len - 1 + assert store.last() is None def test_pop_does_not_happen_on_render_failure(self): """On template error the result is NOT consumed (available for retry).""" - items = [{"name": "x"}] - results = [self._result_entry(items)] - + store = self._store_with([{"name": "x"}]) with patch( "seclab_taskflow_agent.runner.render_template", side_effect=Exception("template boom"), @@ -511,30 +509,65 @@ def test_pop_does_not_happen_on_render_failure(self): _build_prompts_to_run( task_prompt="Process {{ result.name }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=store, available_tools=_mock_available_tools(), global_variables={}, inputs={}, ) ) - # Result should still be there for retry - assert len(results) == 1 + assert store.last() is not None def test_raises_type_error_on_non_iterable_result(self): - """TypeError when MCP result parses to a non-iterable (e.g. int).""" - results = [self._result_entry(42)] + """TypeError when the result parses to a non-iterable (e.g. int).""" with pytest.raises(TypeError): self._run( _build_prompts_to_run( task_prompt="Process {{ result }}", repeat_prompt=True, - last_mcp_tool_results=results, + store=self._store_with(42), available_tools=_mock_available_tools(), global_variables={}, inputs={}, ) ) + def test_over_expression_selects_named_output(self): + """An explicit ``over`` expression iterates a named output directly.""" + store = ResultStore() + store.set_output("list_fns", {"functions": [{"name": "a"}, {"name": "b"}]}) + prompts = self._run( + _build_prompts_to_run( + task_prompt="fn={{ result.name }}", + repeat_prompt=True, + store=store, + available_tools=_mock_available_tools(), + global_variables={}, + inputs={}, + outputs=store.outputs, + over="outputs.list_fns.functions", + ) + ) + assert [p for p in prompts] == ["fn=a", "fn=b"] + + def test_over_does_not_consume_tool_result(self): + """The explicit ``over`` path never pops the tool-result carry-over.""" + store = self._store_with(["ignored"]) + store.set_output("nums", [1, 2]) + self._run( + _build_prompts_to_run( + task_prompt="{{ result }}", + repeat_prompt=True, + store=store, + available_tools=_mock_available_tools(), + global_variables={}, + inputs={}, + outputs=store.outputs, + over="outputs.nums", + ) + ) + # the tool result is still present (over reads named data instead) + assert store.last() is not None + # =================================================================== # _resolve_task_models (multi-model resolution) @@ -742,3 +775,55 @@ async def deploy(payload, rm): assert asyncio.run( _fan_out_deploys(items, deploy, concurrent=True, concurrency=2, completion_policy="all") ) is False + + +# =================================================================== +# _capture_task_output (typed named outputs) +# =================================================================== + +class TestCaptureTaskOutput: + """Tests for capturing a task's typed named output into the store.""" + + def test_capture_schemaless_decodes_json(self): + store = ResultStore() + store.record(ToolResult(text=json.dumps({"functions": [1, 2]}))) + _capture_task_output(store, "list_fns", {}, "task-0") + assert store.outputs["list_fns"] == {"functions": [1, 2]} + + def test_capture_schemaless_falls_back_to_text(self): + store = ResultStore() + store.record(ToolResult(text="a plain answer")) + _capture_task_output(store, "answer", {}, "task-0") + assert store.outputs["answer"] == "a plain answer" + + def test_capture_with_schema_validates(self): + store = ResultStore() + store.record(ToolResult(text=json.dumps({"functions": [{"name": "f", "body": "b"}]}))) + schema = {"functions": {"type": "list", "items": {"name": "str", "body": "str"}}} + _capture_task_output(store, "list_fns", schema, "task-0") + assert store.outputs["list_fns"] == {"functions": [{"name": "f", "body": "b"}]} + + def test_capture_with_schema_validation_error(self): + from pydantic import ValidationError + + store = ResultStore() + store.record(ToolResult(text=json.dumps({"functions": "not-a-list"}))) + schema = {"functions": {"type": "list", "items": {"name": "str"}}} + with pytest.raises(ValidationError): + _capture_task_output(store, "list_fns", schema, "task-0") + + def test_capture_no_result_with_schema_raises(self): + store = ResultStore() + with pytest.raises(ValueError, match="produced no tool result"): + _capture_task_output(store, "x", {"f": "str"}, "task-0") + + def test_capture_no_result_schemaless_sets_none(self): + store = ResultStore() + _capture_task_output(store, "x", {}, "task-0") + assert store.outputs["x"] is None + + def test_capture_prefers_structured(self): + store = ResultStore() + store.record(ToolResult(structured={"functions": ["a"]})) + _capture_task_output(store, "out", {}, "task-0") + assert store.outputs["out"] == {"functions": ["a"]} diff --git a/tests/test_session.py b/tests/test_session.py index a6c1765e..64119247 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -22,9 +22,9 @@ def test_create_session(self): def test_record_task_advances_index(self): """Recording a task increments next_task_index.""" s = TaskflowSession(taskflow_path="test.flow") - s.record_task(index=0, name="task-0", success=True, tool_results=["r1"]) + s.record_task(index=0, name="task-0", success=True, result_snapshot={"results": [], "outputs": {"a": 1}}) assert s.next_task_index == 1 - assert s.last_tool_results == ["r1"] + assert s.result_snapshot == {"results": [], "outputs": {"a": 1}} s.record_task(index=1, name="task-1", success=True) assert s.next_task_index == 2 @@ -103,9 +103,8 @@ def test_defaults(self): t = CompletedTask(index=0) assert t.name == "" assert t.result is False - assert t.tool_results == [] - def test_with_results(self): - t = CompletedTask(index=2, name="analyze", result=True, tool_results=["r1", "r2"]) + def test_with_result(self): + t = CompletedTask(index=2, name="analyze", result=True) assert t.index == 2 - assert t.tool_results == ["r1", "r2"] + assert t.result is True diff --git a/tests/test_session_edge.py b/tests/test_session_edge.py index 02cc5714..1ea6f109 100644 --- a/tests/test_session_edge.py +++ b/tests/test_session_edge.py @@ -13,19 +13,19 @@ class TestSessionEdgeCases: """Edge-case tests for TaskflowSession.""" - def test_record_task_empty_tool_results(self, tmp_path, monkeypatch): - """record_task with empty list sets last_tool_results to [].""" + def test_record_task_empty_snapshot(self, tmp_path, monkeypatch): + """record_task with an empty snapshot stores it.""" monkeypatch.setattr("seclab_taskflow_agent.session._data_dir", lambda: tmp_path) s = TaskflowSession(taskflow_path="test.flow") - s.record_task(index=0, name="t0", success=True, tool_results=[]) - assert s.last_tool_results == [] + s.record_task(index=0, name="t0", success=True, result_snapshot={"results": [], "outputs": {}}) + assert s.result_snapshot == {"results": [], "outputs": {}} - def test_record_task_none_tool_results(self, tmp_path, monkeypatch): - """record_task with None tool_results defaults to [].""" + def test_record_task_none_snapshot_leaves_default(self, tmp_path, monkeypatch): + """record_task with None snapshot leaves the default empty dict.""" monkeypatch.setattr("seclab_taskflow_agent.session._data_dir", lambda: tmp_path) s = TaskflowSession(taskflow_path="test.flow") - s.record_task(index=0, name="t0", success=True, tool_results=None) - assert s.last_tool_results == [] + s.record_task(index=0, name="t0", success=True, result_snapshot=None) + assert s.result_snapshot == {} def test_next_task_index_non_sequential(self, tmp_path, monkeypatch): """next_task_index uses max(indices) + 1, even if non-sequential.""" @@ -35,15 +35,16 @@ def test_next_task_index_non_sequential(self, tmp_path, monkeypatch): s.record_task(index=5, name="t5", success=True) assert s.next_task_index == 6 - def test_save_load_roundtrip_preserves_tool_results(self, tmp_path, monkeypatch): - """save + load roundtrip preserves last_tool_results.""" + def test_save_load_roundtrip_preserves_snapshot(self, tmp_path, monkeypatch): + """save + load roundtrip preserves result_snapshot.""" monkeypatch.setattr("seclab_taskflow_agent.session._data_dir", lambda: tmp_path) s = TaskflowSession(taskflow_path="test.flow") - s.record_task(index=0, name="t0", success=True, tool_results=["res1", "res2"]) + snap = {"results": [{"tool_name": "t", "text": "[1]", "structured": None}], "outputs": {"o": [1]}} + s.record_task(index=0, name="t0", success=True, result_snapshot=snap) sid = s.session_id loaded = TaskflowSession.load(sid) - assert loaded.last_tool_results == ["res1", "res2"] + assert loaded.result_snapshot == snap assert loaded.taskflow_path == "test.flow" def test_list_sessions_skips_corrupt_files(self, tmp_path, monkeypatch): @@ -68,17 +69,17 @@ def test_multiple_record_task_accumulate(self, tmp_path, monkeypatch): """Multiple record_task calls accumulate completed_tasks.""" monkeypatch.setattr("seclab_taskflow_agent.session._data_dir", lambda: tmp_path) s = TaskflowSession(taskflow_path="test.flow") - s.record_task(index=0, name="t0", success=True, tool_results=["r0"]) - s.record_task(index=1, name="t1", success=False, tool_results=["r1"]) - s.record_task(index=2, name="t2", success=True, tool_results=["r2"]) + s.record_task(index=0, name="t0", success=True, result_snapshot={"results": [], "outputs": {"a": 0}}) + s.record_task(index=1, name="t1", success=False, result_snapshot={"results": [], "outputs": {"a": 1}}) + s.record_task(index=2, name="t2", success=True, result_snapshot={"results": [], "outputs": {"a": 2}}) assert len(s.completed_tasks) == 3 assert s.completed_tasks[0].name == "t0" assert s.completed_tasks[0].result is True assert s.completed_tasks[1].result is False assert s.completed_tasks[2].name == "t2" - # last_tool_results reflects the last call - assert s.last_tool_results == ["r2"] + # result_snapshot reflects the last call + assert s.result_snapshot == {"results": [], "outputs": {"a": 2}} def test_mark_failed_then_save_preserves_error(self, tmp_path, monkeypatch): """mark_failed persists the error through save/load.""" diff --git a/tests/test_stream.py b/tests/test_stream.py index dfc3f41d..c85dcf0e 100644 --- a/tests/test_stream.py +++ b/tests/test_stream.py @@ -6,15 +6,15 @@ from __future__ import annotations import asyncio -import json from typing import Any import pytest from seclab_taskflow_agent._stream import ( - bridge_copilot_tool_event, drive_backend_stream, + handle_tool_end_event, ) +from seclab_taskflow_agent.results import ToolResult from seclab_taskflow_agent.sdk import TextDelta, ToolEnd from seclab_taskflow_agent.sdk.errors import ( BackendRateLimitError, @@ -34,19 +34,31 @@ async def on_tool_end(self, ctx: Any, agent: Any, tool: Any, result: Any) -> Non self.ends.append((ctx, agent, tool, result)) -def test_bridge_emits_envelope_and_name(): +def _record_sink() -> tuple[list[ToolResult], Any]: + recorded: list[ToolResult] = [] + + async def _record(tr: ToolResult) -> None: + recorded.append(tr) + + return recorded, _record + + +def test_handle_tool_end_records_neutral_result_and_name(): hooks = _RecordingHooks() - asyncio.run(bridge_copilot_tool_event(ToolEnd(tool_name="echo", text="hi"), hooks)) + recorded, sink = _record_sink() + asyncio.run(handle_tool_end_event(ToolEnd(tool_name="echo", text="hi"), hooks, sink)) + # Progress notice rendered via on_tool_start assert len(hooks.starts) == 1 assert hooks.starts[0][2].name == "echo" - assert len(hooks.ends) == 1 - _, _, tool, payload = hooks.ends[0] - assert tool.name == "echo" - assert json.loads(payload) == {"text": "hi"} + # Neutral ToolResult recorded (no faked JSON envelope) + assert len(recorded) == 1 + assert recorded[0].tool_name == "echo" + assert recorded[0].text == "hi" + assert recorded[0].structured is None -def test_bridge_no_hooks_is_noop(): - asyncio.run(bridge_copilot_tool_event(ToolEnd(tool_name="echo", text="hi"), None)) +def test_handle_tool_end_no_hooks_or_sink_is_noop(): + asyncio.run(handle_tool_end_event(ToolEnd(tool_name="echo", text="hi"), None, None)) class _ScriptedBackend: @@ -64,7 +76,7 @@ async def run_streamed(self, _agent: Any, _prompt: str, *, max_turns: int) -> An yield ev -def _drive(backend: _ScriptedBackend, hooks: Any = None, **kwargs: Any) -> None: +def _drive(backend: _ScriptedBackend, hooks: Any = None, record_tool_result: Any = None, **kwargs: Any) -> None: asyncio.run( drive_backend_stream( backend_impl=backend, @@ -77,6 +89,7 @@ def _drive(backend: _ScriptedBackend, hooks: Any = None, **kwargs: Any) -> None: max_api_retry=kwargs.get("max_api_retry", 1), initial_rate_limit_backoff=kwargs.get("initial_rate_limit_backoff", 1), max_rate_limit_backoff=kwargs.get("max_rate_limit_backoff", 4), + record_tool_result=record_tool_result, ) ) @@ -89,13 +102,15 @@ async def _fake_render(text: str, **_kw: Any) -> None: monkeypatch.setattr("seclab_taskflow_agent._stream.render_model_output", _fake_render) hooks = _RecordingHooks() + recorded, sink = _record_sink() backend = _ScriptedBackend([[TextDelta(text="hi"), ToolEnd(tool_name="echo", text="r")]]) - _drive(backend, hooks) + _drive(backend, hooks, record_tool_result=sink) assert "hi" in rendered - assert hooks.ends - assert json.loads(hooks.ends[0][3]) == {"text": "r"} + assert len(recorded) == 1 + assert recorded[0].tool_name == "echo" + assert recorded[0].text == "r" def test_drive_retries_then_succeeds_on_timeout(monkeypatch): diff --git a/tests/test_template_utils.py b/tests/test_template_utils.py index f2f812a5..1a8fb567 100644 --- a/tests/test_template_utils.py +++ b/tests/test_template_utils.py @@ -85,6 +85,55 @@ def test_env_function_in_template(self): class TestRenderTemplate: """Test template rendering.""" + def test_render_outputs_namespace(self): + """Named task outputs are available under the outputs namespace.""" + available_tools = AvailableTools() + result = render_template( + "{{ outputs.list_fns.functions }}", + available_tools, + outputs_dict={'list_fns': {'functions': ['a', 'b']}}, + ) + assert result == "['a', 'b']" + + def test_dict_method_key_names_resolve_to_data(self): + """Keys named after dict methods (items/keys/values) resolve to data. + + Stock Jinja would return the dict.items builtin for ``x.items``; the + data-first environment returns the value under the ``items`` key. + """ + available_tools = AvailableTools() + for key in ("items", "keys", "values", "get"): + rendered = render_template( + "{{ outputs.x." + key + " }}", + available_tools, + outputs_dict={'x': {key: [1, 2]}}, + ) + assert rendered == "[1, 2]" + + def test_evaluate_expression_returns_object(self): + """evaluate_expression returns the actual object, not its string form.""" + from seclab_taskflow_agent.template_utils import evaluate_expression + + available_tools = AvailableTools() + value = evaluate_expression( + "outputs.fruit_list.items", + available_tools, + outputs_dict={'fruit_list': {'items': ['apple', 'banana']}}, + ) + assert value == ['apple', 'banana'] + + def test_evaluate_expression_strips_braces(self): + """A {{ ... }}-wrapped expression is accepted and unwrapped.""" + from seclab_taskflow_agent.template_utils import evaluate_expression + + available_tools = AvailableTools() + value = evaluate_expression( + "{{ outputs.x.nums }}", + available_tools, + outputs_dict={'x': {'nums': [1, 2, 3]}}, + ) + assert value == [1, 2, 3] + def test_render_globals(self): """Test rendering with global variables.""" available_tools = AvailableTools() From 8d42f609d11c5b87f047e13f9fa21cf9575f2366 Mon Sep 17 00:00:00 2001 From: Bas Alberts Date: Wed, 1 Jul 2026 16:45:59 -0400 Subject: [PATCH 03/28] feat(cli): offline taskflow linter, schema export, and corpus-validate gate Adds robustness tooling that catches misconfiguration before any model call (M0 hardening), which also de-risks forward-porting first-party taskflows. - linting.py: lint_taskflow() validates a taskflow and every document it references (personalities, toolboxes, model configs, reusable taskflows) entirely offline. Reports unknown fields (typos; warnings, or errors under --strict), missing references, logical model names absent from the resolved model_config, and malformed Jinja in prompts / over expressions. Pure and fully unit-tested. - cli.py: --lint (with --strict) validates a taskflow and exits non-zero on errors so it can gate CI; --schema prints JSON Schema per grammar document type for editor integration. - tests/test_examples_validate.py: corpus gate that validates every bundled and example grammar document, and lints every example taskflow (no errors), on each test run - turning an accidentally broken example into an instant local failure. - README: documents --lint/--strict/--schema. Full suite 455 passed, 2 skipped; CI-parity lint clean. The corpus gate and linter tests run in CI via `hatch test`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 26 +++- src/seclab_taskflow_agent/cli.py | 43 ++++++ src/seclab_taskflow_agent/linting.py | 201 +++++++++++++++++++++++++++ tests/test_cli.py | 50 +++++++ tests/test_examples_validate.py | 79 +++++++++++ tests/test_linting.py | 185 ++++++++++++++++++++++++ 6 files changed, 583 insertions(+), 1 deletion(-) create mode 100644 src/seclab_taskflow_agent/linting.py create mode 100644 tests/test_examples_validate.py create mode 100644 tests/test_linting.py diff --git a/README.md b/README.md index 82da3162..d10665ba 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ You can find a detailed overview of the taskflow grammar [here](doc/GRAMMAR.md) ``` ┌─────────────────────────────────────────────────────┐ │ CLI (cli.py) │ -│ Typer-based entry point: -p, -t, -l, -g, -m, --resume│ +│ Typer-based entry point: -p, -t, -l, -g, -m, --resume, --lint│ └─────────────────────┬───────────────────────────────┘ │ ┌─────────────────────▼───────────────────────────────┐ @@ -174,6 +174,30 @@ Error: [BadRequestError] model 'foo' not found python -m seclab_taskflow_agent --debug -t examples.taskflows.echo ``` +### Linting and Schema + +Taskflows can be validated offline, without making any model calls, using +`--lint`. This resolves the taskflow and every document it references +(personalities, toolboxes, model configs, reusable taskflows), checks model +names against the model config, validates prompt/`over` template syntax, and +reports unknown fields (likely typos): + +```bash +# Validate a taskflow and its references +python -m seclab_taskflow_agent --lint -t examples.taskflows.echo + +# Treat unknown fields as errors (not just warnings) +python -m seclab_taskflow_agent --lint --strict -t examples.taskflows.echo +``` + +`--lint` exits non-zero if any errors are found, so it can gate CI. The JSON +Schema for each grammar document type can be printed with `--schema` for editor +integration and external validation: + +```bash +python -m seclab_taskflow_agent --schema +``` + ### MCP Environment Denylist By default, MCP server subprocesses inherit the parent environment. To prevent diff --git a/src/seclab_taskflow_agent/cli.py b/src/seclab_taskflow_agent/cli.py index b5bf2ebc..11b6b91d 100644 --- a/src/seclab_taskflow_agent/cli.py +++ b/src/seclab_taskflow_agent/cli.py @@ -78,6 +78,25 @@ def _print_concise_error(exc: BaseException) -> None: typer.echo("(use --debug for full traceback)", err=True) +def _run_lint(available_tools, taskflow: str, *, strict: bool, cli_model_config: str | None) -> int: + """Lint a taskflow and print issues. Returns a process exit code.""" + from .linting import format_issues, lint_taskflow + + issues = lint_taskflow(available_tools, taskflow, strict=strict, cli_model_config=cli_model_config) + typer.echo(format_issues(issues)) + return 1 if any(i.severity == "error" for i in issues) else 0 + + +def _dump_schemas() -> None: + """Print the JSON Schema for each grammar document type.""" + import json + + from .models import DOCUMENT_MODELS + + schemas = {name: model.model_json_schema() for name, model in DOCUMENT_MODELS.items()} + typer.echo(json.dumps(schemas, indent=2)) + + @app.command() def main( personality: Annotated[ @@ -112,6 +131,18 @@ def main( str | None, typer.Option("-m", "--model-config", help="Model configuration module path. Only relevant when running taskflows."), ] = None, + lint: Annotated[ + bool, + typer.Option("--lint", help="Validate a taskflow (-t) and its references offline, without running it."), + ] = False, + strict: Annotated[ + bool, + typer.Option("--strict", help="With --lint, treat unknown fields as errors instead of warnings."), + ] = False, + dump_schema: Annotated[ + bool, + typer.Option("--schema", help="Print the JSON Schema for each grammar document type and exit."), + ] = False, ) -> None: """Run a taskflow or personality-based agent session.""" # Debug mode from flag or env var @@ -131,6 +162,18 @@ def main( available_tools = AvailableTools() + # Schema dump mode (no model calls, no taskflow required) + if dump_schema: + _dump_schemas() + raise typer.Exit() + + # Lint mode (no model calls) + if lint: + if not taskflow: + typer.echo("Error: --lint requires -t/--taskflow.", err=True) + raise typer.Exit(code=1) + raise typer.Exit(code=_run_lint(available_tools, taskflow, strict=strict, cli_model_config=model_config)) + # List models mode if list_models: tool_models = list_tool_call_models(get_AI_token()) diff --git a/src/seclab_taskflow_agent/linting.py b/src/seclab_taskflow_agent/linting.py new file mode 100644 index 00000000..82e1200a --- /dev/null +++ b/src/seclab_taskflow_agent/linting.py @@ -0,0 +1,201 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Offline taskflow linter. + +Validates a taskflow and every document it references without making any +model calls, turning what would otherwise be an expensive runtime failure +into an instant check. Surfaces: + +* grammar/parse errors (via the loader), +* unknown fields (typos) - reported as warnings, or errors in ``strict`` mode, +* missing referenced personalities / toolboxes / reusable taskflows, +* logical model names that are not defined in the resolved ``model_config``, +* malformed Jinja in prompts / ``over`` expressions. + +The core :func:`lint_taskflow` is a pure function returning a list of +:class:`LintIssue`, so it is fully unit-testable offline. +""" + +from __future__ import annotations + +__all__ = ["LintIssue", "format_issues", "lint_taskflow"] + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +import jinja2 + +from .models import ModelEntry, TaskDefinition +from .template_utils import create_jinja_environment + +if TYPE_CHECKING: + from .available_tools import AvailableTools + + +@dataclass +class LintIssue: + """A single problem found while linting a taskflow.""" + + severity: str # "error" | "warning" + code: str + message: str + location: str = "" + + +@dataclass +class _Ctx: + """Shared lint state.""" + + available_tools: AvailableTools + strict: bool + model_dict: dict[str, str] + has_model_config: bool + issues: list[LintIssue] = field(default_factory=list) + + def add(self, severity: str, code: str, message: str, location: str = "") -> None: + self.issues.append(LintIssue(severity, code, message, location)) + + +def _check_unknown_fields(model: object, location: str, ctx: _Ctx) -> None: + """Report ``extra="allow"`` overflow fields (likely typos).""" + extra = getattr(model, "model_extra", None) or {} + for key in extra: + severity = "error" if ctx.strict else "warning" + ctx.add(severity, "unknown-field", f"unknown field {key!r}", location) + + +def _check_reference(loader, name: str, kind: str, location: str, ctx: _Ctx) -> bool: + """Verify a referenced document loads; report an error if not.""" + try: + loader(name) + except Exception as exc: # noqa: BLE001 - loader raises several types + ctx.add("error", f"missing-{kind}", f"cannot load {kind} {name!r}: {exc}", location) + return False + return True + + +def _check_template(template_str: str, what: str, location: str, ctx: _Ctx) -> None: + """Report malformed Jinja syntax (does not render).""" + if not template_str: + return + env = create_jinja_environment(ctx.available_tools) + try: + env.from_string(template_str) + except jinja2.TemplateSyntaxError as exc: + ctx.add("error", "template-syntax", f"invalid Jinja in {what}: {exc}", location) + + +def _check_model_name(name: str, location: str, ctx: _Ctx) -> None: + """Warn when a logical model name is not defined in the model_config.""" + if not name: + return + if ctx.has_model_config and name not in ctx.model_dict: + ctx.add( + "warning", + "unknown-model", + f"model {name!r} is not defined in the model_config; it will be used " + f"as a literal provider id (typo?)", + location, + ) + + +def _lint_task(task: TaskDefinition, location: str, ctx: _Ctx) -> None: + at = ctx.available_tools + _check_unknown_fields(task, location, ctx) + + # Reusable taskflow reference. + if task.uses: + try: + reusable = at.get_taskflow(task.uses) + if len(reusable.taskflow) != 1: + ctx.add( + "error", + "reusable-shape", + f"reusable taskflow {task.uses!r} must contain exactly 1 task", + location, + ) + except Exception as exc: # noqa: BLE001 + ctx.add("error", "missing-uses", f"cannot load reusable taskflow {task.uses!r}: {exc}", location) + + # Agents (personalities) and their toolboxes. + for agent_name in task.agents or []: + if _check_reference(at.get_personality, agent_name, "personality", location, ctx): + personality = at.get_personality(agent_name) + if not (task.toolboxes or []): + for tb in personality.toolboxes or []: + _check_reference(at.get_toolbox, tb, "toolbox", location, ctx) + + # Task-level toolbox overrides. + for tb in task.toolboxes or []: + _check_reference(at.get_toolbox, tb, "toolbox", location, ctx) + + # Model name resolution. + entries: list[ModelEntry] = task.effective_model_entries() + for entry in entries: + _check_model_name(entry.model, location, ctx) + + # Prompt / over template syntax. + _check_template(task.user_prompt, "user_prompt", location, ctx) + _check_template(task.over, "over", location, ctx) + + +def lint_taskflow( + available_tools: AvailableTools, + taskflow_path: str, + *, + strict: bool = False, + cli_model_config: str | None = None, +) -> list[LintIssue]: + """Lint a taskflow and every document it references, offline. + + Args: + available_tools: Tool registry / loader. + taskflow_path: Dotted path of the taskflow to lint. + strict: Treat unknown fields as errors instead of warnings. + cli_model_config: Overrides the taskflow's own ``model_config``. + + Returns: + A list of :class:`LintIssue`. An empty list means no problems. + """ + ctx = _Ctx(available_tools=available_tools, strict=strict, model_dict={}, has_model_config=False) + + # Load the taskflow itself (grammar/parse errors surface here). + try: + doc = available_tools.get_taskflow(taskflow_path) + except Exception as exc: # noqa: BLE001 - loader raises several types + ctx.add("error", "load", f"cannot load taskflow: {exc}", taskflow_path) + return ctx.issues + + _check_unknown_fields(doc, taskflow_path, ctx) + + # Resolve the model_config (CLI override wins), if any. + model_config_ref = cli_model_config or doc.model_config_ref + if model_config_ref: + try: + mc = available_tools.get_model_config(model_config_ref) + ctx.model_dict = mc.models or {} + ctx.has_model_config = True + except Exception as exc: # noqa: BLE001 + ctx.add("error", "model_config", f"cannot load model_config {model_config_ref!r}: {exc}", taskflow_path) + + for i, wrapper in enumerate(doc.taskflow): + task = wrapper.task + location = f"task[{i}]" + (f" ({task.name})" if task.name else "") + _lint_task(task, location, ctx) + + return ctx.issues + + +def format_issues(issues: list[LintIssue]) -> str: + """Render lint issues as human-readable lines.""" + if not issues: + return "No issues found." + lines: list[str] = [] + for issue in issues: + loc = f" [{issue.location}]" if issue.location else "" + lines.append(f"{issue.severity.upper()}: {issue.code}:{loc} {issue.message}") + errors = sum(1 for i in issues if i.severity == "error") + warnings = sum(1 for i in issues if i.severity == "warning") + lines.append(f"({errors} error(s), {warnings} warning(s))") + return "\n".join(lines) diff --git a/tests/test_cli.py b/tests/test_cli.py index 068bf3a8..60948430 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -82,3 +82,53 @@ def test_whitespace_trimmed(self): def test_random_text_is_false(self): assert self._is_debug("enabled") is False + + +class TestLintAndSchema: + """Tests for the --lint and --schema CLI helpers.""" + + def test_run_lint_returns_zero_when_clean(self, monkeypatch): + from seclab_taskflow_agent import cli + + def _no_issues(*_a, **_k): + return [] + + monkeypatch.setattr("seclab_taskflow_agent.linting.lint_taskflow", _no_issues) + assert cli._run_lint(object(), "pkg.flow", strict=False, cli_model_config=None) == 0 + + def test_run_lint_returns_one_on_error(self, monkeypatch): + from seclab_taskflow_agent import cli + from seclab_taskflow_agent.linting import LintIssue + + def _error(*_a, **_k): + return [LintIssue("error", "x", "boom")] + + monkeypatch.setattr("seclab_taskflow_agent.linting.lint_taskflow", _error) + assert cli._run_lint(object(), "pkg.flow", strict=False, cli_model_config=None) == 1 + + def test_run_lint_warnings_only_returns_zero(self, monkeypatch): + from seclab_taskflow_agent import cli + from seclab_taskflow_agent.linting import LintIssue + + def _warn(*_a, **_k): + return [LintIssue("warning", "y", "meh")] + + monkeypatch.setattr("seclab_taskflow_agent.linting.lint_taskflow", _warn) + assert cli._run_lint(object(), "pkg.flow", strict=False, cli_model_config=None) == 0 + + def test_run_lint_integration_on_example(self): + from seclab_taskflow_agent import cli + from seclab_taskflow_agent.available_tools import AvailableTools + + # A shipped example must lint without errors (exit 0). + assert cli._run_lint(AvailableTools(), "examples.taskflows.echo", strict=False, cli_model_config=None) == 0 + + def test_dump_schemas_outputs_all_document_types(self, capsys): + import json + + from seclab_taskflow_agent import cli + + cli._dump_schemas() + out = capsys.readouterr().out + data = json.loads(out) + assert set(data.keys()) == {"taskflow", "personality", "toolbox", "model_config", "prompt"} diff --git a/tests/test_examples_validate.py b/tests/test_examples_validate.py new file mode 100644 index 00000000..60fac613 --- /dev/null +++ b/tests/test_examples_validate.py @@ -0,0 +1,79 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Corpus gate: every bundled/example grammar file must validate and every +example taskflow must lint without errors. + +This turns an accidental breakage of a shipped example (or a grammar change +that invalidates one) into an instant, local test failure instead of a +runtime surprise. +""" + +from __future__ import annotations + +import glob +from pathlib import Path + +import pytest +import yaml + +from seclab_taskflow_agent.available_tools import AvailableTools +from seclab_taskflow_agent.linting import lint_taskflow +from seclab_taskflow_agent.models import DOCUMENT_MODELS + +# Roots that contain shipped grammar documents. +_ROOTS = ["examples", "src/seclab_taskflow_agent"] + + +def _grammar_files() -> list[str]: + files: list[str] = [] + for root in _ROOTS: + files.extend(sorted(glob.glob(f"{root}/**/*.yaml", recursive=True))) + # Keep only files with a taskflow-agent header. + kept: list[str] = [] + for f in files: + try: + data = yaml.safe_load(Path(f).read_text()) + except Exception: # noqa: BLE001 - reported by the validation test + kept.append(f) + continue + if isinstance(data, dict) and "seclab-taskflow-agent" in data: + kept.append(f) + return kept + + +def _dotted(path: str) -> str: + p = path.removeprefix("src/") + return p[: -len(".yaml")].replace("/", ".") + + +def _taskflow_dotted_paths() -> list[str]: + paths: list[str] = [] + for f in sorted(glob.glob("examples/taskflows/**/*.yaml", recursive=True)): + data = yaml.safe_load(Path(f).read_text()) + if isinstance(data, dict) and (data.get("seclab-taskflow-agent") or {}).get("filetype") == "taskflow": + paths.append(_dotted(f)) + return paths + + +@pytest.mark.parametrize("path", _grammar_files()) +def test_bundled_document_validates(path: str) -> None: + """Every shipped grammar document parses and validates against its model.""" + data = yaml.safe_load(Path(path).read_text()) + assert isinstance(data, dict), f"{path}: not a mapping" + filetype = (data.get("seclab-taskflow-agent") or {}).get("filetype") + model = DOCUMENT_MODELS.get(filetype) + assert model is not None, f"{path}: unknown filetype {filetype!r}" + # Raises ValidationError (failing the test) if the document is invalid. + model.model_validate(data) + + +@pytest.mark.parametrize("dotted", _taskflow_dotted_paths()) +def test_example_taskflow_lints_without_errors(dotted: str) -> None: + """Every example taskflow lints clean (warnings allowed, no errors).""" + at = AvailableTools() + issues = lint_taskflow(at, dotted) + errors = [i for i in issues if i.severity == "error"] + assert not errors, f"{dotted} has lint errors:\n" + "\n".join( + f" {i.code}: {i.message} [{i.location}]" for i in errors + ) diff --git a/tests/test_linting.py b/tests/test_linting.py new file mode 100644 index 00000000..101cdd74 --- /dev/null +++ b/tests/test_linting.py @@ -0,0 +1,185 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +"""Tests for the offline taskflow linter.""" + +from unittest.mock import MagicMock + +from seclab_taskflow_agent.linting import LintIssue, format_issues, lint_taskflow +from seclab_taskflow_agent.models import ( + ModelConfigDocument, + PersonalityDocument, + TaskDefinition, + TaskflowDocument, + TaskflowHeader, + ToolboxDocument, + TaskWrapper, +) + + +def _taskflow(tasks, model_config_ref="") -> TaskflowDocument: + return TaskflowDocument( + **{ + "seclab-taskflow-agent": TaskflowHeader(version="1.0", filetype="taskflow"), + "model_config": model_config_ref, + "taskflow": [TaskWrapper(task=t) for t in tasks], + } + ) + + +def _personality(toolboxes=None) -> PersonalityDocument: + return PersonalityDocument( + **{ + "seclab-taskflow-agent": TaskflowHeader(version="1.0", filetype="personality"), + "personality": "p", + "task": "t", + "toolboxes": toolboxes or [], + } + ) + + +def _model_config(models) -> ModelConfigDocument: + return ModelConfigDocument( + **{ + "seclab-taskflow-agent": TaskflowHeader(version="1.0", filetype="model_config"), + "models": models, + } + ) + + +def _toolbox() -> ToolboxDocument: + return ToolboxDocument( + **{ + "seclab-taskflow-agent": TaskflowHeader(version="1.0", filetype="toolbox"), + "server_params": {"kind": "stdio", "command": "echo"}, + } + ) + + +def _at(doc, *, personality=None, model_config=None, toolbox=None): + at = MagicMock() + at.get_taskflow.return_value = doc + at.get_personality.return_value = personality if personality is not None else _personality() + if model_config is not None: + at.get_model_config.return_value = model_config + if toolbox is not None: + at.get_toolbox.return_value = toolbox + else: + at.get_toolbox.return_value = _toolbox() + return at + + +def _codes(issues): + return {i.code for i in issues} + + +class TestLintTaskflow: + def test_clean_taskflow_no_issues(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi")]) + at = _at(doc) + assert lint_taskflow(at, "pkg.flow") == [] + + def test_unknown_field_is_warning(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", must_complte=True)]) + at = _at(doc) + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "unknown-field" and i.severity == "warning" for i in issues) + + def test_unknown_field_is_error_in_strict(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", typo_field=1)]) + at = _at(doc) + issues = lint_taskflow(at, "pkg.flow", strict=True) + assert any(i.code == "unknown-field" and i.severity == "error" for i in issues) + + def test_missing_personality_is_error(self): + doc = _taskflow([TaskDefinition(agents=["pkg.missing"], user_prompt="hi")]) + at = _at(doc) + at.get_personality.side_effect = Exception("nope") + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "missing-personality" and i.severity == "error" for i in issues) + + def test_missing_toolbox_override_is_error(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", toolboxes=["pkg.badtb"])]) + at = _at(doc) + at.get_toolbox.side_effect = Exception("no toolbox") + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "missing-toolbox" for i in issues) + + def test_personality_toolbox_checked_when_no_override(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi")]) + at = _at(doc, personality=_personality(toolboxes=["pkg.ptb"])) + at.get_toolbox.side_effect = Exception("missing") + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "missing-toolbox" for i in issues) + + def test_unknown_model_is_warning(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", model="typo")], model_config_ref="pkg.mc") + at = _at(doc, model_config=_model_config({"fast": "gpt-4o"})) + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "unknown-model" for i in issues) + + def test_known_model_no_warning(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", model="fast")], model_config_ref="pkg.mc") + at = _at(doc, model_config=_model_config({"fast": "gpt-4o"})) + issues = lint_taskflow(at, "pkg.flow") + assert not any(i.code == "unknown-model" for i in issues) + + def test_no_model_config_no_model_warning(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", model="gpt-4o")]) + at = _at(doc) + issues = lint_taskflow(at, "pkg.flow") + assert not any(i.code == "unknown-model" for i in issues) + + def test_bad_model_config_is_error(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi")], model_config_ref="pkg.badmc") + at = _at(doc) + at.get_model_config.side_effect = Exception("bad mc") + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "model_config" and i.severity == "error" for i in issues) + + def test_template_syntax_error_is_error(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="{{ unclosed")]) + at = _at(doc) + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "template-syntax" for i in issues) + + def test_reusable_wrong_shape_is_error(self): + # a task that uses a reusable taskflow with 2 tasks + reusable = _taskflow([TaskDefinition(name="a"), TaskDefinition(name="b")]) + doc = _taskflow([TaskDefinition(uses="pkg.reusable", user_prompt="hi")]) + at = MagicMock() + at.get_taskflow.side_effect = lambda name: doc if name == "pkg.flow" else reusable + at.get_personality.return_value = _personality() + at.get_toolbox.return_value = _toolbox() + issues = lint_taskflow(at, "pkg.flow") + assert any(i.code == "reusable-shape" for i in issues) + + def test_load_failure_short_circuits(self): + at = MagicMock() + at.get_taskflow.side_effect = Exception("cannot parse") + issues = lint_taskflow(at, "pkg.flow") + assert len(issues) == 1 + assert issues[0].code == "load" + + def test_cli_model_config_override_used(self): + doc = _taskflow([TaskDefinition(agents=["pkg.p"], user_prompt="hi", model="fast")]) + at = _at(doc, model_config=_model_config({"other": "gpt-4o"})) + issues = lint_taskflow(at, "pkg.flow", cli_model_config="pkg.override") + at.get_model_config.assert_called_once_with("pkg.override") + # "fast" is not in the override config -> warning + assert any(i.code == "unknown-model" for i in issues) + + +class TestFormatIssues: + def test_empty(self): + assert format_issues([]) == "No issues found." + + def test_counts(self): + issues = [ + LintIssue("error", "x", "boom", "task[0]"), + LintIssue("warning", "y", "meh"), + ] + out = format_issues(issues) + assert "ERROR" in out + assert "WARNING" in out + assert "1 error(s), 1 warning(s)" in out From d106a5a79b46adcd633c11e8ed5ec636c3863d2a Mon Sep 17 00:00:00 2001 From: Bas Alberts Date: Wed, 1 Jul 2026 17:11:10 -0400 Subject: [PATCH 04/28] refactor(output): encapsulate buffered output in a per-run OutputRouter Replace the module-global async_output dict and lock in render_utils with an OutputRouter class that owns the buffered-output state. The active router is resolved from a ContextVar and set per run in run_main, so buffered async and multi-model output streams are isolated per run instead of sharing process-global state, and the buffering behaviour becomes directly testable. The free-function API (render_model_output / flush_async_output) is unchanged, so existing call sites are untouched and delegate to the current-context router. Output strings and buffering semantics are preserved exactly. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/seclab_taskflow_agent/render_utils.py | 119 +++++++++++++++++----- src/seclab_taskflow_agent/runner.py | 6 +- tests/test_render_utils.py | 19 +++- 3 files changed, 114 insertions(+), 30 deletions(-) diff --git a/src/seclab_taskflow_agent/render_utils.py b/src/seclab_taskflow_agent/render_utils.py index 6ccce55a..ded9bd34 100644 --- a/src/seclab_taskflow_agent/render_utils.py +++ b/src/seclab_taskflow_agent/render_utils.py @@ -1,17 +1,31 @@ # SPDX-FileCopyrightText: GitHub, Inc. # SPDX-License-Identifier: MIT -"""Utilities for rendering and buffering streamed model output.""" +"""Rendering and buffering of streamed model output. + +Output routing (live printing plus per-branch buffering for concurrent +async / multi-model runs) is owned by :class:`OutputRouter` instead of module +-global state. The active router is resolved from a +:class:`~contextvars.ContextVar`, so each run gets its own isolated buffers +while the free-function API (:func:`render_model_output` / +:func:`flush_async_output`) that call sites use stays unchanged. +""" + +from __future__ import annotations import asyncio +import contextvars import logging from .path_utils import log_file_name -__all__ = ["flush_async_output", "render_model_output"] - -async_output = {} -async_output_lock = asyncio.Lock() +__all__ = [ + "OutputRouter", + "flush_async_output", + "get_output_router", + "render_model_output", + "use_output_router", +] render_logger = logging.getLogger("render") file_handler = logging.FileHandler(log_file_name("render_stdout.log")) @@ -20,33 +34,86 @@ render_logger.propagate = False +class OutputRouter: + """Owns buffered-output state for one run. + + Live output is printed immediately; output tagged with ``async_task`` and a + ``task_id`` is buffered per branch and flushed as a labelled block when the + branch completes, so concurrent async / multi-model streams do not + interleave. One instance per run keeps these buffers isolated (previously + this was a module-global dict). + """ + + def __init__(self) -> None: + self._buffers: dict[str, str] = {} + self._lock = asyncio.Lock() + + @property + def buffers(self) -> dict[str, str]: + """The per-branch buffer map (primarily for tests/introspection).""" + return self._buffers + + async def render( + self, + data: str, + *, + log: bool = True, + async_task: bool = False, + task_id: str | None = None, + ) -> None: + """Print *data*, buffering it per ``task_id`` for async branches.""" + async with self._lock: + if async_task and task_id: + if task_id in self._buffers: + self._buffers[task_id] += data + data = "" + else: + self._buffers[task_id] = data + data = "** 🤖✏️ Gathering output from async task ... please hold\n" + if data: + if log: + render_logger.info(data) + print(data, end="", flush=True) + + async def flush(self, task_id: str, label: str | None = None) -> None: + """Flush the buffered output for *task_id* as a labelled block.""" + async with self._lock: + if task_id not in self._buffers: + # No buffered output (agent may have failed before producing any). + return + data = self._buffers.pop(task_id) + heading = label if label else f"async task: {task_id}" + await self.render(f"** 🤖✏️ Output for {heading}\n\n") + await self.render(data) + + +_default_router = OutputRouter() +_current_router: contextvars.ContextVar[OutputRouter] = contextvars.ContextVar( + "seclab_output_router", default=_default_router +) + + +def get_output_router() -> OutputRouter: + """Return the output router for the current context.""" + return _current_router.get() + + +def use_output_router(router: OutputRouter) -> contextvars.Token: + """Install *router* as the current-context router; returns a reset token.""" + return _current_router.set(router) + + async def flush_async_output(task_id: str, label: str | None = None) -> None: """Flush buffered async output for *task_id* to the console. When *label* is provided it replaces the default ``async task: `` heading, letting multi-model runs tag each block with its model name. """ - async with async_output_lock: - if task_id not in async_output: - # No buffered output (agent may have failed before producing any). - return - data = async_output.pop(task_id) - heading = label if label else f"async task: {task_id}" - await render_model_output(f"** 🤖✏️ Output for {heading}\n\n") - await render_model_output(data) + await get_output_router().flush(task_id, label=label) -async def render_model_output(data: str, log: bool = True, async_task: bool = False, task_id: str | None = None) -> None: +async def render_model_output( + data: str, log: bool = True, async_task: bool = False, task_id: str | None = None +) -> None: """Print model output to the console, optionally buffering for async tasks.""" - async with async_output_lock: - if async_task and task_id: - if task_id in async_output: - async_output[task_id] += data - data = "" - else: - async_output[task_id] = data - data = "** 🤖✏️ Gathering output from async task ... please hold\n" - if data: - if log: - render_logger.info(data) - print(data, end="", flush=True) + await get_output_router().render(data, log=log, async_task=async_task, task_id=task_id) diff --git a/src/seclab_taskflow_agent/runner.py b/src/seclab_taskflow_agent/runner.py index 9ddf8ec7..2b6a4f9e 100644 --- a/src/seclab_taskflow_agent/runner.py +++ b/src/seclab_taskflow_agent/runner.py @@ -37,7 +37,7 @@ from .mcp_prompt import mcp_system_prompt from .mcp_utils import compress_name, mcp_client_params from .models import ModelConfigDocument, PersonalityDocument, TaskDefinition -from .render_utils import flush_async_output, render_model_output +from .render_utils import OutputRouter, flush_async_output, render_model_output, use_output_router from .results import ResultStore, ToolResult, decode_tool_result, normalize_openai_tool_output from .output_schema import validate_output from .sdk import AgentSpec, MCPServerSpec, get_backend, resolve_backend_name @@ -742,6 +742,10 @@ async def run_main( # already handle. Idempotent — safe to call on every run_main. start_watchdog() + # Give this run its own output router so buffered async / multi-model + # streams stay isolated from any other run sharing the process. + use_output_router(OutputRouter()) + store = ResultStore() async def on_tool_end_hook(context: RunContextWrapper[TContext], agent: Agent[TContext], tool: Tool, result: str) -> None: diff --git a/tests/test_render_utils.py b/tests/test_render_utils.py index e6a71954..9509a66a 100644 --- a/tests/test_render_utils.py +++ b/tests/test_render_utils.py @@ -5,8 +5,21 @@ import asyncio -from seclab_taskflow_agent import render_utils -from seclab_taskflow_agent.render_utils import flush_async_output, render_model_output +import pytest + +from seclab_taskflow_agent.render_utils import ( + OutputRouter, + flush_async_output, + get_output_router, + render_model_output, + use_output_router, +) + + +@pytest.fixture(autouse=True) +def _fresh_router(): + """Give each test an isolated output router (no cross-test buffer leaks).""" + use_output_router(OutputRouter()) def _capture(monkeypatch) -> list[str]: @@ -72,4 +85,4 @@ async def scenario(): assert "A-out" in joined assert "B-out" in joined # Both buffers fully drained. - assert render_utils.async_output == {} + assert get_output_router().buffers == {} From 6747d4455977b201e88fc9470e5fb5c5ff8b0147 Mon Sep 17 00:00:00 2001 From: Bas Alberts Date: Wed, 1 Jul 2026 17:37:20 -0400 Subject: [PATCH 05/28] feat(grammar): multi-model x repeat_prompt cross product with fan-in Allow a task to combine `models` with `repeat_prompt`, running the item x model matrix concurrently. Each cell streams as its own labelled block (" [item ]"), and concurrency is bounded by model_concurrency * async_limit. Give a multi-model task an `id` to fan in results: each branch's final tool result is aggregated into outputs. as a list of {model, item, result} records for downstream tasks to consume. Branches capture into private sinks so the shared result store stays deterministic for the next task's implicit repeat_prompt. The inline `outputs` schema is not accepted on multi-model tasks (the aggregate is a list of records); `id` provides the fan-in instead. Execution is restructured around explicit per-branch descriptors, and the fan-in aggregation is a pure, unit-tested helper. Adds unit tests (grammar combinations, aggregator), a run_main integration test that drives the full matrix through a patched deploy layer and asserts the deploy set, per-branch labels, and outputs. fan-in, an example taskflow, and GRAMMAR docs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/GRAMMAR.md | 21 ++- .../taskflows/example_multi_model_repeat.yaml | 30 ++++ src/seclab_taskflow_agent/models.py | 15 +- src/seclab_taskflow_agent/runner.py | 121 +++++++++++--- tests/test_models.py | 23 ++- tests/test_runner.py | 55 ++++++ tests/test_runner_integration.py | 156 ++++++++++++++++++ 7 files changed, 371 insertions(+), 50 deletions(-) create mode 100644 examples/taskflows/example_multi_model_repeat.yaml create mode 100644 tests/test_runner_integration.py diff --git a/doc/GRAMMAR.md b/doc/GRAMMAR.md index 9ad49a94..e88924a4 100644 --- a/doc/GRAMMAR.md +++ b/doc/GRAMMAR.md @@ -168,11 +168,17 @@ Notes and semantics: - Multi-model output is buffered per model and flushed as a labelled block when each model finishes, so streams from different models do not interleave. -- Multi-model tasks are for parallel evaluation: their tool results are not - threaded into the `repeat_prompt` result channel, and combining `models` - (with more than one entry) with `repeat_prompt` on the same task is not yet - supported. Typed named outputs for consuming multi-model results downstream - are planned in a later milestone. +- `models` can be combined with `repeat_prompt`: the task runs the cross + product of items x models concurrently, bounded by + `model_concurrency * async_limit`. Each branch is streamed as its own block + labelled ` [item ]`. +- Multi-model tool results are not threaded into the implicit last-tool-result + channel that the next task's `repeat_prompt` reads (that stays deterministic). + To consume multi-model results downstream, give the task an `id`: each + branch's final result is aggregated into `outputs.` as a list of records + `{"model": ..., "item": ..., "result": ...}` (see "Typed named outputs"). +- The inline `outputs` schema is not yet supported on multi-model tasks (the + aggregate is a list of records); use `id` for fan-in. ### Completion Requirement @@ -390,8 +396,9 @@ Notes: `values`, ...) resolve to your data, not the method. - Without `id`/`outputs`/`over`, the implicit last-tool-result `repeat_prompt` behaviour is unchanged. -- Typed outputs are not yet supported on multi-model tasks (planned in a later - milestone). +- On multi-model tasks, `id` fans in per-branch results as a list of + `{model, item, result}` records (see "Multiple Models"); the inline `outputs` + schema is not yet supported there. ### Toolboxes / MCP Servers diff --git a/examples/taskflows/example_multi_model_repeat.yaml b/examples/taskflows/example_multi_model_repeat.yaml new file mode 100644 index 00000000..a952ce92 --- /dev/null +++ b/examples/taskflows/example_multi_model_repeat.yaml @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: GitHub, Inc. +# SPDX-License-Identifier: MIT + +# Example: multi-model x repeat_prompt cross product. +# The same prompt is run for every (item, model) pair in parallel, each +# streamed as its own labelled block (" [item ]"). Handy for +# comparing how different models answer across a set of inputs. +# See doc/GRAMMAR.md "Multiple Models" and "Typed named outputs". + +seclab-taskflow-agent: + version: "1.0" + filetype: taskflow + +model_config: examples.model_configs.multi_model + +globals: + topics: ["buffer overflows", "use-after-free bugs"] + +taskflow: + - task: + # fan out across both models ... + models: [gpt_fast, gpt_alt] + # ... and across each topic (the cross product runs concurrently, + # bounded by model_concurrency * async_limit) + repeat_prompt: true + over: "globals.topics" + agents: + - seclab_taskflow_agent.personalities.assistant + user_prompt: | + In one short sentence, explain {{ result }}. diff --git a/src/seclab_taskflow_agent/models.py b/src/seclab_taskflow_agent/models.py index 8744378d..61a77215 100644 --- a/src/seclab_taskflow_agent/models.py +++ b/src/seclab_taskflow_agent/models.py @@ -184,11 +184,6 @@ def _validate_models(self) -> TaskDefinition: "'model' and 'models' are mutually exclusive; use 'model' for a single " "model or 'models' for multi-model fan-out" ) - if len(self.models) > 1 and self.repeat_prompt: - raise ValueError( - "multi-model 'models' is not yet supported together with 'repeat_prompt' " - "(planned as a later milestone); use a single model with repeat_prompt" - ) if self.model_concurrency < 0: raise ValueError("'model_concurrency' must be >= 0") return self @@ -204,13 +199,13 @@ def _validate_outputs(self) -> TaskDefinition: build_output_model(f"{self.id or self.name or 'task'}_output", self.outputs) except OutputSchemaError as exc: raise ValueError(f"invalid 'outputs' schema: {exc}") from exc + if len(self.models) > 1: + raise ValueError( + "'outputs' schema is not yet supported on multi-model tasks; " + "use 'id' to fan-in per-model results as a list" + ) if self.over and not self.repeat_prompt: raise ValueError("'over' only applies to repeat_prompt tasks") - if len(self.models) > 1 and (self.id or self.outputs or self.over): - raise ValueError( - "typed outputs ('id'/'outputs'/'over') are not yet supported on multi-model " - "tasks (planned as a later milestone)" - ) return self def effective_model_entries(self) -> list[ModelEntry]: diff --git a/src/seclab_taskflow_agent/runner.py b/src/seclab_taskflow_agent/runner.py index 2b6a4f9e..10a6d3c4 100644 --- a/src/seclab_taskflow_agent/runner.py +++ b/src/seclab_taskflow_agent/runner.py @@ -23,7 +23,7 @@ import logging import uuid from collections.abc import Awaitable, Callable -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any import jinja2 @@ -211,6 +211,44 @@ class ResolvedModel: label: str +@dataclass +class _Branch: + """One (prompt, model) cell of a task's execution matrix. + + Multi-model branches capture their tool results into a private ``sink`` + (never the shared store) so concurrent branches stay isolated and their + final results can be aggregated for fan-in. + """ + + agents: dict[str, Any] + prompt: str + rm: ResolvedModel + item_index: int + label: str + sink: list[ToolResult] = field(default_factory=list) + + +def _aggregate_fanin(branches: list[_Branch]) -> list[dict[str, Any]]: + """Aggregate each branch's final tool result into fan-in records. + + Produces one record per branch: ``{"model":