runWorkflow method

Future<WorkflowResult> runWorkflow({
  1. required String scriptPath,
  2. String description = '',
  3. Map<String, Object?>? args,
})

Executes a Python workflow script through the harness's sandbox.

~ is expanded, and a relative scriptPath is resolved against the first workspace that contains it, otherwise against the current directory. The script is checked with validateWorkflowSource before the model is asked to run it.

args are input arguments exposed to the script as workflows.args (args). They must be JSON-encodable; an empty or null map sends no arguments.

Throws an ArgumentError if scriptPath is empty, BuiltinTools.runWorkflow is not enabled, or args is not JSON-encodable; a FileSystemException if the script does not exist; a WorkflowException if it fails validation; and a ToolExecutionException if the model does not run the workflow or the workflow fails.

Implementation

Future<WorkflowResult> runWorkflow({
  required String scriptPath,
  String description = '',
  Map<String, Object?>? args,
}) async {
  final conversation = _agent.conversation;
  final capabilities = _config.capabilities;
  final active =
      capabilities.enabledTools?.toSet() ??
      BuiltinTools.defaultTools().toSet().difference(
        capabilities.disabledTools?.toSet() ?? {},
      );
  if (!capabilities.enableSubagents ||
      !active.contains(BuiltinTools.runWorkflow)) {
    throw ArgumentError(
      'BuiltinTools.runWorkflow is not enabled on this agent.',
    );
  }
  if (scriptPath.trim().isEmpty) {
    throw ArgumentError('scriptPath must not be empty.');
  }
  String? argsJson;
  if (args != null && args.isNotEmpty) {
    try {
      argsJson = _encodePythonJson(args);
    } on Object catch (e) {
      throw ArgumentError.value(
        args,
        'args',
        'runWorkflow() `args` must be JSON-serializable: $e',
      );
    }
  }
  var file = File(normalizeWorkspacePath(scriptPath));
  final isRelative = !p.isAbsolute(scriptPath) && !scriptPath.startsWith('~');
  if (isRelative) {
    for (final workspace in _config.workspaces) {
      final candidate = File(
        p.join(normalizeWorkspacePath(workspace), scriptPath),
      );
      if (await candidate.exists()) {
        file = candidate;
        break;
      }
    }
  }
  if (!await file.exists()) {
    throw FileSystemException('Workflow script not found', file.path);
  }
  validateWorkflowSource(utf8.decode(await file.readAsBytes()));
  final resolvedPath = await file.resolveSymbolicLinks();
  final effectiveDescription = description.isEmpty
      ? 'Run workflow ${file.uri.pathSegments.last}'
      : description;
  final historyStart = conversation.history.length;
  final argsClause = argsJson == null ? '' : ' with Args `$argsJson`';
  final response = await _agent.chat(
    'Run the workflow script at `$resolvedPath` ($effectiveDescription)'
    '$argsClause using the `run_workflow` tool.',
  );
  final responseText = await response.text();
  Step? workflowStep;
  for (final step
      in conversation.history.skip(historyStart).toList().reversed) {
    if (step.depth != 0 || step.parentTrajectoryId.isNotEmpty) continue;
    if (step.workflowProgress != null ||
        step.toolCalls.any((t) => t.name == 'run_workflow')) {
      workflowStep = step;
      break;
    }
  }
  if (workflowStep == null) {
    throw ToolExecutionException(
      'The model did not invoke the run_workflow tool.',
      toolName: 'run_workflow',
    );
  }
  if (workflowStep.status == StepStatus.error) {
    throw ToolExecutionException(
      workflowStep.error.isEmpty
          ? 'Workflow execution failed.'
          : workflowStep.error,
      toolName: 'run_workflow',
    );
  }
  final progress = workflowStep.workflowProgress;
  return WorkflowResult.fromResponse(
    response,
    scriptPath: progress == null || progress.scriptPath.isEmpty
        ? resolvedPath
        : progress.scriptPath,
    script: progress?.script ?? '',
    description: progress == null || progress.description.isEmpty
        ? effectiveDescription
        : progress.description,
    output: progress?.output ?? '',
    responseText: responseText,
  );
}