workflow

package
v0.31.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package workflow provides agent file and feature support validation.

Agent Validation

This file validates agent-specific configuration and feature compatibility for agentic workflows. It ensures that:

  • Custom agent files exist when specified
  • Engine features are supported (HTTP transport, max-turns, web-search)
  • Workflow triggers have appropriate security constraints

Validation Functions

  • validateAgentFile() - Validates custom agent file exists
  • validateHTTPTransportSupport() - Validates HTTP MCP compatibility with engine
  • validateMaxTurnsSupport() - Validates max-turns feature support
  • validateWebSearchSupport() - Validates web-search feature support (warning)
  • validateWorkflowRunBranches() - Validates workflow_run has branch restrictions

Validation Patterns

This file uses several patterns:

  • File existence validation: Agent files
  • Feature compatibility checks: Engine capabilities
  • Security validation: workflow_run branch restrictions
  • Warning vs error: Some validations warn instead of fail

Security Considerations

The validateWorkflowRunBranches function enforces security best practices:

  • In strict mode: Errors when workflow_run lacks branch restrictions
  • In normal mode: Warns when workflow_run lacks branch restrictions

When to Add Validation Here

Add validation to this file when:

  • It validates custom agent file configuration
  • It checks engine feature compatibility
  • It validates agent-specific requirements
  • It enforces security constraints on triggers

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides JavaScript bundler validation for agentic workflows.

JavaScript Bundler Validation

This file validates bundled JavaScript to ensure that all local module dependencies have been properly inlined during the bundling process. This prevents runtime errors from missing local modules when JavaScript is executed in GitHub Actions.

Validation Functions

  • validateNoLocalRequires() - Validates bundled JavaScript has no local require() statements
  • isInsideStringLiteralAt() - Helper to detect if a position is inside a string literal

Validation Pattern: Bundling Verification

Bundler validation ensures that local require() statements are inlined:

  • Scans bundled JavaScript for require('./...') or require('../...') patterns
  • Ignores require statements inside string literals
  • Returns hard errors if local requires are found (indicates bundling failure)
  • Helps prevent runtime module-not-found errors

When to Add Validation Here

Add validation to this file when:

  • It validates JavaScript bundling correctness
  • It checks for missing module dependencies
  • It validates CommonJS require() statement resolution
  • It validates JavaScript code structure

For bundling functions, see bundler.go. For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides Docker image validation for agentic workflows.

Docker Image Validation

This file validates Docker container images used in MCP configurations. Validation ensures that Docker images specified in workflows exist and are accessible, preventing runtime failures due to typos or non-existent images.

Validation Functions

  • validateDockerImage() - Validates a single Docker image exists and is accessible

Validation Pattern: Warning vs Error

Docker image validation uses a flexible approach:

  • If Docker is not available, a warning is emitted but validation is skipped
  • If an image cannot be pulled due to authentication (private repo), validation passes
  • If an image truly doesn't exist, validation fails with an error
  • Verbose mode provides detailed validation feedback

When to Add Validation Here

Add validation to this file when:

  • It validates Docker images
  • It checks container image accessibility
  • It validates Docker-specific configurations

For Docker image collection functions, see docker.go. For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides engine validation for agentic workflows.

Engine Validation

This file validates engine configurations used in agentic workflows. Validation ensures that engine IDs are supported and that only one engine specification exists across the main workflow and all included files.

Validation Functions

  • validateEngine() - Validates that a given engine ID is supported
  • validateSingleEngineSpecification() - Validates that only one engine field exists across all files

Validation Pattern: Engine Registry

Engine validation uses the compiler's engine registry:

  • Supports exact engine ID matching (e.g., "copilot", "claude")
  • Supports prefix matching for backward compatibility (e.g., "codex-experimental")
  • Empty engine IDs are valid and use the default engine
  • Detailed logging of validation steps for debugging

When to Add Validation Here

Add validation to this file when:

  • It validates engine IDs or engine configurations
  • It checks engine registry entries
  • It validates engine-specific settings
  • It validates engine field consistency across imports

For engine configuration extraction, see engine.go. For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides GitHub Actions expression security validation.

Expression Safety Validation

This file validates that GitHub Actions expressions used in workflow markdown are safe and authorized. It prevents injection attacks and ensures workflows only use approved expression patterns.

Validation Functions

  • validateExpressionSafety() - Validates all expressions in markdown content
  • validateSingleExpression() - Validates individual expression syntax

Validation Pattern: Allowlist Security

Expression validation uses a strict allowlist approach:

  • Only pre-approved GitHub context expressions are allowed
  • Unauthorized expressions cause compilation to fail
  • Prevents injection of secrets or environment variables
  • Uses regex patterns to match allowed expression formats

Allowed Expression Patterns

Expressions must match one of these patterns:

  • github.event.* (event context properties)
  • github.actor, github.repository, etc. (core GitHub context)
  • needs.*.outputs.* (job dependencies)
  • steps.*.outputs.* (step outputs)
  • github.event.inputs.* (workflow_dispatch inputs)

See pkg/constants for the complete list of allowed expressions.

When to Add Validation Here

Add validation to this file when:

  • It validates GitHub Actions expression parsing
  • It enforces expression security policies
  • It prevents expression injection attacks
  • It validates expression syntax and structure

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides MCP (Model Context Protocol) configuration validation.

MCP Configuration Validation

This file validates MCP server configurations in agentic workflows. It ensures that MCP configurations have required fields, correct types, and satisfy type-specific requirements (stdio vs http).

Validation Functions

  • ValidateMCPConfigs() - Validates all MCP configurations in tools section
  • validateStringProperty() - Validates that a property is a string type
  • validateMCPRequirements() - Validates type-specific MCP requirements

Validation Pattern: Schema and Requirements Validation

MCP validation uses multiple patterns:

  • Type inference: Determines MCP type from fields if not explicit
  • Required field validation: Ensures necessary fields exist
  • Type-specific validation: Different requirements for stdio vs http
  • Property type checking: Validates field types match expectations

MCP Types and Requirements

## stdio type

  • Requires either 'command' or 'container' (but not both)
  • Optional: version, args, entrypointArgs, env, proxy-args, registry

## http type

  • Requires 'url' field
  • Cannot use 'container' field
  • Optional: headers, registry

When to Add Validation Here

Add validation to this file when:

  • It validates MCP server configuration
  • It checks MCP-specific field requirements
  • It validates MCP type compatibility
  • It ensures MCP configuration correctness

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides NPM package extraction utilities for agentic workflows.

NPM Package Extraction

This file provides utilities to extract NPM package names from workflow data for packages used with npx (Node Package Execute). The extracted packages can be validated by the validation functions in validation.go.

Extraction Functions

  • extractNpxPackages() - Extracts npm packages used with npx launcher
  • extractNpxFromCommands() - Parses command strings to find npx packages

For package validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides NPM package validation for agentic workflows.

NPM Package Validation

This file validates NPM package availability on the npm registry for packages used with npx (Node Package Execute). Validation ensures that Node.js packages specified in workflows exist and can be installed at runtime.

Validation Functions

  • validateNpxPackages() - Validates npm packages used with npx launcher

Validation Pattern: External Registry Check

NPM package validation queries the npm registry using the npm CLI:

  • Uses `npm view <package> name` to check package existence
  • Returns hard errors if packages don't exist (unlike pip validation)
  • Requires npm to be installed on the system

When to Add Validation Here

Add validation to this file when:

  • It validates Node.js/npm ecosystem packages
  • It checks npm registry package existence
  • It validates npx launcher packages
  • It validates Node.js version compatibility

For package extraction functions, see npm.go. For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides generic package extraction utilities for agentic workflows.

Package Extraction Framework

This file provides a reusable, configurable framework for extracting package names from command strings. The PackageExtractor type eliminates code duplication by providing a single abstraction that handles different package managers (npm, pip, uv, go, etc.) with minimal configuration.

Purpose and Benefits

The PackageExtractor pattern exists to:

  • Prevent code duplication across package manager extraction functions
  • Provide a consistent interface for command parsing
  • Centralize package name extraction logic
  • Reduce maintenance burden by having a single implementation

Usage Pattern

Instead of implementing custom extraction logic, configure a PackageExtractor with the appropriate settings for your package manager:

extractor := PackageExtractor{
    CommandNames:       []string{"pip", "pip3"},
    RequiredSubcommand: "install",
    TrimSuffixes:       "&|;",
}
packages := extractor.ExtractPackages("pip install requests")
// Returns: []string{"requests"}

Package Manager Examples

NPM (npx):

extractor := PackageExtractor{
    CommandNames:       []string{"npx"},
    RequiredSubcommand: "",           // No subcommand needed
    TrimSuffixes:       "&|;",
}
packages := extractor.ExtractPackages("npx @playwright/mcp@latest")
// Returns: []string{"@playwright/mcp@latest"}

Python (pip):

extractor := PackageExtractor{
    CommandNames:       []string{"pip", "pip3"},
    RequiredSubcommand: "install",    // Must have "install" subcommand
    TrimSuffixes:       "&|;",
}
packages := extractor.ExtractPackages("pip install requests==2.28.0")
// Returns: []string{"requests==2.28.0"}

Go (with multiple subcommands):

extractor := PackageExtractor{
    CommandNames:        []string{"go"},
    RequiredSubcommands: []string{"install", "get"},
    TrimSuffixes:        "&|;",
}
packages := extractor.ExtractPackages("go install github.com/user/tool@v1.0.0")
// Returns: []string{"github.com/user/tool@v1.0.0"}

Python (uv):

extractor := PackageExtractor{
    CommandNames:       []string{"uvx"},
    RequiredSubcommand: "",
    TrimSuffixes:       "&|;",
}
packages := extractor.ExtractPackages("uvx black")
// Returns: []string{"black"}

Best Practices

  • ALWAYS use PackageExtractor instead of reimplementing extraction logic
  • Configure CommandNames for all variations of the command (e.g., ["pip", "pip3"])
  • Set RequiredSubcommand only when the package manager requires it (e.g., "install" for pip)
  • Include common shell operators in TrimSuffixes (typically "&|;")
  • For special cases, use the exported FindPackageName method to reuse logic

Configuration Details

  • CommandNames: List of command names to match (case-sensitive)
  • RequiredSubcommand: Subcommand that must appear before the package name (empty string if package comes directly after command)
  • TrimSuffixes: Characters to remove from the end of package names (useful for shell operators like "&", "|", ";")

For package-specific extraction implementations, see:

  • npm.go (npx packages)
  • pip.go (pip and uv packages)
  • dependabot.go (go packages)

For package validation, see validation.go.

Package workflow provides Python package extraction for agentic workflows.

Python Package Extraction

This file extracts Python package names from workflow configurations using pip and uv package managers. Extraction functions parse commands and configuration to identify packages that will be installed at runtime.

Extraction Functions

  • extractPipPackages() - Extracts pip packages from workflow configuration
  • extractPipFromCommands() - Extracts pip packages from command strings
  • extractUvPackages() - Extracts uv packages from workflow configuration
  • extractUvFromCommands() - Extracts uv packages from command strings

When to Add Extraction Here

Add extraction to this file when:

  • It parses Python/pip ecosystem package names
  • It identifies packages from shell commands
  • It extracts packages from workflow steps
  • It detects uv package manager usage

For package validation functions, see pip_validation.go. For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides Python package validation for agentic workflows.

Python Package Validation

This file validates Python package availability on PyPI using pip and uv package managers. Validation ensures that Python packages specified in workflows exist and can be installed at runtime, preventing failures due to typos or non-existent packages.

Validation Functions

  • validatePythonPackagesWithPip() - Generic pip validation helper
  • validatePipPackages() - Validates pip packages from workflow configuration
  • validateUvPackages() - Validates uv packages from workflow configuration
  • validateUvPackagesWithPip() - Validates uv packages using pip index

Validation Pattern: Warning vs Error

Python package validation uses a warning-based approach rather than hard errors:

  • If pip validation fails, a warning is emitted but compilation continues
  • This allows for experimental packages or packages not yet published
  • Verbose mode provides detailed validation feedback

When to Add Validation Here

Add validation to this file when:

  • It validates Python/pip ecosystem packages
  • It checks PyPI package existence
  • It validates Python version compatibility
  • It validates uv package manager packages

For package extraction functions, see pip.go. For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides repository feature detection and validation.

Repository Features Validation

This file validates that required repository features (discussions, issues) are enabled when safe-outputs are configured that depend on them. It provides caching to minimize API calls when checking repository capabilities.

Validation Functions

  • validateRepositoryFeatures() - Main orchestrator validating safe-outputs requirements
  • getCurrentRepository() - Gets current repository from git context (cached)
  • getRepositoryFeatures() - Gets repository features with caching (discussions, issues)
  • checkRepositoryHasDiscussions() - Checks if discussions are enabled (cached)
  • checkRepositoryHasIssues() - Checks if issues are enabled (cached)
  • ClearRepositoryFeaturesCache() - Clears all repository feature caches

Validation Pattern: Feature Detection with Caching

Repository feature validation uses a caching pattern to amortize expensive API calls:

  • sync.Map for thread-safe cache storage
  • sync.Once for single-fetch guarantee
  • Atomic LoadOrStore for race-free caching
  • Separate logged cache to avoid duplicate success messages

When to Add Validation Here

Add validation to this file when:

  • It checks repository capabilities (discussions, issues, projects, etc.)
  • It validates safe-outputs dependencies on repository features
  • It requires GitHub API calls to check repository settings
  • It benefits from caching to reduce API usage

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides runtime validation for packages, containers, and expressions.

Runtime Validation

This file validates runtime dependencies and configuration for agentic workflows. It ensures that:

  • Container images exist and are accessible
  • Runtime packages (npm, pip, uv) are available
  • Expression sizes don't exceed GitHub Actions limits
  • Secret references are valid
  • Cache IDs are unique

Validation Functions

  • validateExpressionSizes() - Validates expression size limits (21KB max)
  • validateContainerImages() - Validates Docker images exist
  • validateRuntimePackages() - Validates npm, pip, uv packages
  • collectPackagesFromWorkflow() - Generic package collection helper
  • validateNoDuplicateCacheIDs() - Validates unique cache-memory IDs
  • validateSecretReferences() - Validates secret name format

Validation Patterns

This file uses several patterns:

  • External resource validation: Docker images, npm/pip packages
  • Size limit validation: Expression sizes, file sizes
  • Format validation: Secret names, cache IDs
  • Collection and deduplication: Package extraction

Size Limits

GitHub Actions has a 21KB limit for expression values including environment variables. This validation prevents compilation of workflows that will fail at runtime.

When to Add Validation Here

Add validation to this file when:

  • It validates runtime dependencies (packages, containers)
  • It checks expression or content size limits
  • It validates configuration format (secrets, cache IDs)
  • It requires external resource checking

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides GitHub Actions schema validation for compiled workflows.

GitHub Actions Schema Validation

This file validates that compiled workflow YAML conforms to the official GitHub Actions workflow schema. It uses JSON Schema validation with caching to avoid recompiling the schema on every validation.

Validation Functions

  • validateGitHubActionsSchema() - Validates YAML against GitHub Actions schema
  • getCompiledSchema() - Returns cached compiled schema (compiled once)

Validation Pattern: Schema Validation with Caching

Schema validation uses a singleton pattern for efficiency:

  • sync.Once ensures schema is compiled only once
  • Schema is embedded in the binary as githubWorkflowSchema
  • Cached compiled schema is reused across all validations
  • YAML is parsed directly and validated without JSON conversion

Schema Source

The GitHub Actions workflow schema is embedded from:

https://json.schemastore.org/github-workflow.json

When to Add Validation Here

Add validation to this file when:

  • It validates against JSON schemas
  • It checks GitHub Actions YAML structure
  • It verifies workflow syntax correctness
  • It requires schema compilation and caching

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides a ScriptRegistry for managing JavaScript script bundling.

Script Registry Pattern

The ScriptRegistry eliminates the repetitive sync.Once pattern found throughout the codebase for lazy script bundling. Instead of declaring separate variables and getter functions for each script, register scripts once and retrieve them by name.

Before (repetitive pattern):

var (
    createIssueScript     string
    createIssueScriptOnce sync.Once
)

func getCreateIssueScript() string {
    createIssueScriptOnce.Do(func() {
        sources := GetJavaScriptSources()
        bundled, err := BundleJavaScriptFromSources(createIssueScriptSource, sources, "")
        if err != nil {
            createIssueScript = createIssueScriptSource
        } else {
            createIssueScript = bundled
        }
    })
    return createIssueScript
}

After (using registry):

// Registration at package init
DefaultScriptRegistry.Register("create_issue", createIssueScriptSource)

// Usage anywhere
script := DefaultScriptRegistry.Get("create_issue")

Benefits

  • Eliminates ~15 lines of boilerplate per script (variable pair + getter function)
  • Centralizes bundling logic
  • Consistent error handling
  • Thread-safe lazy initialization
  • Easy to add new scripts

Package workflow provides embedded JavaScript scripts for GitHub Actions workflows.

Script Registry Pattern

This file uses the ScriptRegistry pattern to manage lazy bundling of JavaScript scripts. Instead of having separate sync.Once patterns for each script, all scripts are registered with the DefaultScriptRegistry and bundled on-demand.

See script_registry.go for the ScriptRegistry implementation.

Package workflow provides strict mode security validation for agentic workflows.

Strict Mode Validation

This file contains strict mode validation functions that enforce security and safety constraints when workflows are compiled with the --strict flag.

Strict mode is designed for production workflows that require enhanced security guarantees. It enforces constraints on:

  • Write permissions on sensitive scopes
  • Network access configuration
  • Custom MCP server network settings
  • Bash wildcard tool usage

Validation Functions

The strict mode validator performs progressive validation:

  1. validateStrictMode() - Main orchestrator that coordinates all strict mode checks
  2. validateStrictPermissions() - Refuses write permissions on sensitive scopes
  3. validateStrictNetwork() - Requires explicit network configuration
  4. validateStrictMCPNetwork() - Requires network config on custom MCP servers

Integration with Security Scanners

Strict mode also affects the zizmor security scanner behavior (see pkg/cli/zizmor.go). When zizmor is enabled with --zizmor flag, strict mode treats any security findings as compilation errors rather than warnings.

When to Add Validation Here

Add validation to this file when:

  • It enforces a strict mode security policy
  • It restricts permissions or access in production workflows
  • It validates network access controls
  • It enforces tool usage restrictions for security

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides utilities for processing GitHub Agentic Workflows.

String Processing Patterns

This package implements two distinct patterns for string processing:

## Sanitize Pattern: Character Validity

Sanitize functions remove or replace invalid characters to create valid identifiers, file names, or artifact names. Use sanitize functions when you need to ensure a string contains only valid characters for a specific context.

Functions:

  • SanitizeName: Configurable sanitization with character preservation options
  • SanitizeWorkflowName: Sanitizes for artifact names and file paths (preserves dots, underscores)
  • SanitizeIdentifier (workflow_name.go): Creates clean identifiers for user agents

Example:

// User input with invalid characters
input := "My Workflow: Test/Build"
result := SanitizeWorkflowName(input)
// Returns: "my-workflow-test-build"

## Normalize Pattern: Format Standardization

Normalize functions standardize format by removing extensions, converting between naming conventions, or applying consistent formatting rules. Use normalize functions when converting between different representations of the same logical entity.

Functions:

  • normalizeWorkflowName (resolve.go): Removes file extensions (.md, .lock.yml)
  • normalizeSafeOutputIdentifier (safe_outputs.go): Converts dashes to underscores

Example:

// File name to base identifier
input := "weekly-research.md"
result := normalizeWorkflowName(input)
// Returns: "weekly-research"

## When to Use Each Pattern

Use SANITIZE when:

  • Processing user input that may contain invalid characters
  • Creating identifiers, artifact names, or file paths
  • Need to ensure character validity for a specific context

Use NORMALIZE when:

  • Converting between file names and identifiers (removing extensions)
  • Standardizing naming conventions (dashes to underscores)
  • Input is already valid but needs format conversion

See specs/string-sanitization-normalization.md for detailed guidance.

Package workflow provides template structure validation for agentic workflows.

Template Validation

This file validates template conditionals and their interaction with other workflow features. It ensures that import directives and template regions don't conflict.

Validation Functions

  • validateNoIncludesInTemplateRegions() - Validates that imports are not inside template blocks

Validation Pattern: Structure Validation

Template validation uses structure checking:

  • Parses template conditional blocks ({{#if...}}{{/if}})
  • Checks for import directives within template regions
  • Prevents import processing conflicts with template rendering

When to Add Validation Here

Add validation to this file when:

  • It validates template structure or syntax
  • It checks template conditional blocks
  • It validates template-related features
  • It ensures template compatibility with other features

For general validation, see validation.go. For detailed documentation, see specs/validation-architecture.md

Package workflow provides validation functions for agentic workflow compilation.

Validation Architecture

The validation system for agentic workflows is organized into focused, domain-specific files to maintain clarity and single responsibility:

  • validation.go: This file - package documentation only
  • strict_mode_validation.go: Security and strict mode validation
  • repository_features_validation.go: Repository capability detection
  • schema_validation.go: GitHub Actions schema validation
  • runtime_validation.go: Runtime packages, containers, expressions
  • agent_validation.go: Agent files and feature support
  • pip_validation.go: Python package validation
  • npm_validation.go: NPM package validation
  • docker_validation.go: Docker image validation
  • expression_safety.go: GitHub Actions expression security
  • engine_validation.go: AI engine configuration validation
  • mcp_config_validation.go: MCP server configuration validation
  • template_validation.go: Template structure validation

When to Add New Validation

Add validation to existing domain files when:

  • It fits the domain (e.g., package validation → pip_validation.go)
  • It extends existing functionality

Create a new validation file when:

  • It represents a distinct validation domain
  • It has multiple related validation functions
  • It requires its own caching or state management

Validation Patterns

The validation system uses several patterns:

  • Schema validation: JSON schema validation with caching
  • External resource validation: Docker images, npm/pip packages
  • Size limit validation: Expression sizes, file sizes
  • Feature detection: Repository capabilities
  • Security validation: Permission restrictions, expression safety

For detailed documentation on validation architecture, see: .github/instructions/developer.instructions.md#validation-architecture

Index

Constants

View Source
const (
	// MaxLockFileSize is the maximum allowed size for generated lock workflow files (1MB)
	MaxLockFileSize = 1048576 // 1MB in bytes

	// MaxExpressionSize is the maximum allowed size for GitHub Actions expression values (21KB)
	// This includes environment variable values, if conditions, and other expression contexts
	// See: https://docs.github.com/en/actions/learn-github-actions/usage-limits-billing-and-administration
	MaxExpressionSize = 21000 // 21KB in bytes

	// MaxPromptChunkSize is the maximum size for each chunk when splitting prompt text (20KB)
	// This limit ensures each heredoc block stays under GitHub Actions step size limits (21KB)
	MaxPromptChunkSize = 20000 // 20KB limit for each chunk

	// MaxPromptChunks is the maximum number of chunks allowed when splitting prompt text
	// This prevents excessive step generation for extremely large prompt texts
	MaxPromptChunks = 5 // Maximum number of chunks
)
View Source
const (
	// MCPGatewayFeatureFlag is the feature flag name for enabling MCP gateway
	MCPGatewayFeatureFlag = "mcp-gateway"
	// DefaultMCPGatewayPort is the default port for the MCP gateway
	DefaultMCPGatewayPort = 8080
	// MCPGatewayLogsFolder is the folder where MCP gateway logs are stored
	MCPGatewayLogsFolder = "/tmp/gh-aw/mcp-gateway-logs"
)
View Source
const (
	MaxBodyLength           = 65000
	MaxGitHubUsernameLength = 39
)

Constants for validation

View Source
const (
	// CacheFileName is the name of the cache file in .github/aw/
	CacheFileName = "actions-lock.json"
)
View Source
const RedactedURLsLogPath = "/tmp/gh-aw/redacted-urls.log"

RedactedURLsLogPath is the path where redacted URL domains are logged during sanitization

View Source
const SafeInputsDirectory = "/tmp/gh-aw/safe-inputs"

SafeInputsDirectory is the directory where safe-inputs files are generated

View Source
const SafeInputsFeatureFlag = "safe-inputs"

SafeInputsFeatureFlag is the name of the feature flag for safe-inputs

Variables

View Source
var ActionFriendlyGitHubToolsets = []string{"context", "repos", "issues", "pull_requests"}

ActionFriendlyGitHubToolsets defines the default toolsets that work with GitHub Actions tokens. This excludes "users" toolset because GitHub Actions tokens do not support user operations. Use this when the workflow will run in GitHub Actions with GITHUB_TOKEN.

View Source
var CopilotDefaultDomains = []string{
	"api.enterprise.githubcopilot.com",
	"api.github.com",
	"github.com",
	"raw.githubusercontent.com",
	"registry.npmjs.org",
}

CopilotDefaultDomains are the default domains required for GitHub Copilot CLI authentication and operation

View Source
var DefaultGitHubToolsets = []string{"context", "repos", "issues", "pull_requests", "users"}

DefaultGitHubToolsets defines the toolsets that are enabled by default when toolsets are not explicitly specified in the GitHub MCP configuration. These match the documented default toolsets in github-mcp-server.instructions.md

View Source
var DefaultScriptRegistry = NewScriptRegistry()

DefaultScriptRegistry is the global script registry used by the workflow package. Scripts are registered during package initialization via init() functions.

View Source
var GitHubToolToToolsetMap map[string]string

GitHubToolToToolsetMap maps individual GitHub MCP tools to their respective toolsets This mapping is loaded from an embedded JSON file based on the documentation in .github/instructions/github-mcp-server.instructions.md

View Source
var ValidationConfig = map[string]TypeValidationConfig{
	"create_issue": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"title":        {Required: true, Type: "string", Sanitize: true, MaxLength: 128},
			"body":         {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"labels":       {Type: "array", ItemType: "string", ItemSanitize: true, ItemMaxLength: 128},
			"parent":       {IssueOrPRNumber: true},
			"temporary_id": {Type: "string"},
			"repo":         {Type: "string", MaxLength: 256},
		},
	},
	"create_agent_task": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"body": {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
		},
	},
	"add_comment": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"body":        {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"item_number": {IssueOrPRNumber: true},
		},
	},
	"create_pull_request": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"title":  {Required: true, Type: "string", Sanitize: true, MaxLength: 128},
			"body":   {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"branch": {Required: true, Type: "string", Sanitize: true, MaxLength: 256},
			"labels": {Type: "array", ItemType: "string", ItemSanitize: true, ItemMaxLength: 128},
		},
	},
	"add_labels": {
		DefaultMax: 5,
		Fields: map[string]FieldValidation{
			"labels":      {Required: true, Type: "array", ItemType: "string", ItemSanitize: true, ItemMaxLength: 128},
			"item_number": {IssueOrPRNumber: true},
		},
	},
	"add_reviewer": {
		DefaultMax: 3,
		Fields: map[string]FieldValidation{
			"reviewers":           {Required: true, Type: "array", ItemType: "string", ItemSanitize: true, ItemMaxLength: MaxGitHubUsernameLength},
			"pull_request_number": {IssueOrPRNumber: true},
		},
	},
	"assign_milestone": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"issue_number":     {IssueOrPRNumber: true},
			"milestone_number": {Required: true, PositiveInteger: true},
		},
	},
	"assign_to_agent": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"issue_number": {Required: true, PositiveInteger: true},
			"agent":        {Type: "string", Sanitize: true, MaxLength: 128},
		},
	},
	"assign_to_user": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"issue_number": {IssueOrPRNumber: true},
			"assignees":    {Type: "[]string", Sanitize: true, MaxLength: 39},
			"assignee":     {Type: "string", Sanitize: true, MaxLength: 39},
		},
	},
	"update_issue": {
		DefaultMax:       1,
		CustomValidation: "requiresOneOf:status,title,body",
		Fields: map[string]FieldValidation{
			"status":       {Type: "string", Enum: []string{"open", "closed"}},
			"title":        {Type: "string", Sanitize: true, MaxLength: 128},
			"body":         {Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"issue_number": {IssueOrPRNumber: true},
		},
	},
	"update_pull_request": {
		DefaultMax:       1,
		CustomValidation: "requiresOneOf:title,body",
		Fields: map[string]FieldValidation{
			"title":               {Type: "string", Sanitize: true, MaxLength: 256},
			"body":                {Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"operation":           {Type: "string", Enum: []string{"replace", "append", "prepend"}},
			"pull_request_number": {IssueOrPRNumber: true},
		},
	},
	"push_to_pull_request_branch": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"branch":              {Required: true, Type: "string", Sanitize: true, MaxLength: 256},
			"message":             {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"pull_request_number": {IssueOrPRNumber: true},
		},
	},
	"create_pull_request_review_comment": {
		DefaultMax:       1,
		CustomValidation: "startLineLessOrEqualLine",
		Fields: map[string]FieldValidation{
			"path":       {Required: true, Type: "string"},
			"line":       {Required: true, PositiveInteger: true},
			"body":       {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"start_line": {OptionalPositiveInteger: true},
			"side":       {Type: "string", Enum: []string{"LEFT", "RIGHT"}},
		},
	},
	"create_discussion": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"title":    {Required: true, Type: "string", Sanitize: true, MaxLength: 128},
			"body":     {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"category": {Type: "string", Sanitize: true, MaxLength: 128},
			"repo":     {Type: "string", MaxLength: 256},
		},
	},
	"close_discussion": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"body":              {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"reason":            {Type: "string", Enum: []string{"RESOLVED", "DUPLICATE", "OUTDATED", "ANSWERED"}},
			"discussion_number": {OptionalPositiveInteger: true},
		},
	},
	"close_issue": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"body":         {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"issue_number": {OptionalPositiveInteger: true},
		},
	},
	"close_pull_request": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"body":                {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
			"pull_request_number": {OptionalPositiveInteger: true},
		},
	},
	"missing_tool": {
		DefaultMax: 20,
		Fields: map[string]FieldValidation{
			"tool":         {Required: true, Type: "string", Sanitize: true, MaxLength: 128},
			"reason":       {Required: true, Type: "string", Sanitize: true, MaxLength: 256},
			"alternatives": {Type: "string", Sanitize: true, MaxLength: 512},
		},
	},
	"update_release": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"tag":       {Type: "string", Sanitize: true, MaxLength: 256},
			"operation": {Required: true, Type: "string", Enum: []string{"replace", "append", "prepend"}},
			"body":      {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
		},
	},
	"upload_asset": {
		DefaultMax: 10,
		Fields: map[string]FieldValidation{
			"path": {Required: true, Type: "string"},
		},
	},
	"noop": {
		DefaultMax: 1,
		Fields: map[string]FieldValidation{
			"message": {Required: true, Type: "string", Sanitize: true, MaxLength: MaxBodyLength},
		},
	},
	"create_code_scanning_alert": {
		DefaultMax: 40,
		Fields: map[string]FieldValidation{
			"file":         {Required: true, Type: "string", Sanitize: true, MaxLength: 512},
			"line":         {Required: true, PositiveInteger: true},
			"severity":     {Required: true, Type: "string", Enum: []string{"error", "warning", "info", "note"}},
			"message":      {Required: true, Type: "string", Sanitize: true, MaxLength: 2048},
			"column":       {OptionalPositiveInteger: true},
			"ruleIdSuffix": {Type: "string", Pattern: "^[a-zA-Z0-9_-]+$", PatternError: "must contain only alphanumeric characters, hyphens, and underscores", Sanitize: true, MaxLength: 128},
		},
	},
	"link_sub_issue": {
		DefaultMax:       5,
		CustomValidation: "parentAndSubDifferent",
		Fields: map[string]FieldValidation{
			"parent_issue_number": {Required: true, IssueNumberOrTemporaryID: true},
			"sub_issue_number":    {Required: true, IssueNumberOrTemporaryID: true},
		},
	},
}

ValidationConfig contains all safe output type validation rules This is the single source of truth for validation rules

Functions

func AddDetectionSuccessCheck added in v0.28.7

func AddDetectionSuccessCheck(existingCondition string) string

AddDetectionSuccessCheck adds a check for detection job success to an existing condition This ensures safe output jobs only run when threat detection passes

func AddMCPFetchServerIfNeeded added in v0.12.1

func AddMCPFetchServerIfNeeded(tools map[string]any, engine CodingAgentEngine) (map[string]any, []string)

AddMCPFetchServerIfNeeded adds the mcp/fetch dockerized MCP server to the tools configuration if the engine doesn't have built-in web-fetch support and web-fetch tool is requested

func ApplyActionPinToStep added in v0.25.0

func ApplyActionPinToStep(stepMap map[string]any, data *WorkflowData) map[string]any

ApplyActionPinToStep applies SHA pinning to a step map if it contains a "uses" field with a pinned action. Returns a modified copy of the step map with pinned references. If the step doesn't use an action or the action is not pinned, returns the original map.

func ApplyActionPinsToSteps added in v0.25.0

func ApplyActionPinsToSteps(steps []any, data *WorkflowData) []any

ApplyActionPinsToSteps applies SHA pinning to a slice of step maps Returns a new slice with pinned references

func BreakAtParentheses added in v0.5.2

func BreakAtParentheses(expression string) []string

BreakAtParentheses attempts to break long lines at parentheses for function calls

func BreakLongExpression added in v0.5.2

func BreakLongExpression(expression string) []string

BreakLongExpression breaks a long expression into multiple lines at logical points such as after || and && operators for better readability

func BuildAllowedListEnvVar added in v0.31.4

func BuildAllowedListEnvVar(envVarName string, allowed []string) []string

BuildAllowedListEnvVar builds an allowed list environment variable line for safe-output jobs. envVarName should be the full env var name like "GH_AW_LABELS_ALLOWED". Always outputs the env var, even when empty (empty string means "allow all").

func BuildCloseJobEnvVars added in v0.31.4

func BuildCloseJobEnvVars(prefix string, config CloseJobConfig) []string

BuildCloseJobEnvVars builds common environment variables for close operations. prefix should be like "GH_AW_CLOSE_ISSUE" or "GH_AW_CLOSE_PR". Returns a slice of environment variable lines.

func BuildListJobEnvVars added in v0.31.4

func BuildListJobEnvVars(prefix string, config ListJobConfig, maxCount int) []string

BuildListJobEnvVars builds common environment variables for list-based operations. prefix should be like "GH_AW_LABELS" or "GH_AW_REVIEWERS". Returns a slice of environment variable lines.

func BuildMaxCountEnvVar added in v0.31.4

func BuildMaxCountEnvVar(envVarName string, maxCount int) []string

BuildMaxCountEnvVar builds a max count environment variable line for safe-output jobs. envVarName should be the full env var name like "GH_AW_CLOSE_ISSUE_MAX_COUNT".

func BuildRequiredCategoryEnvVar added in v0.31.4

func BuildRequiredCategoryEnvVar(envVarName string, requiredCategory string) []string

BuildRequiredCategoryEnvVar builds a required-category environment variable line for discussion safe-output jobs. envVarName should be the full env var name like "GH_AW_CLOSE_DISCUSSION_REQUIRED_CATEGORY". Returns an empty slice if requiredCategory is empty.

func BuildRequiredLabelsEnvVar added in v0.31.4

func BuildRequiredLabelsEnvVar(envVarName string, requiredLabels []string) []string

BuildRequiredLabelsEnvVar builds a required-labels environment variable line for safe-output jobs. envVarName should be the full env var name like "GH_AW_CLOSE_ISSUE_REQUIRED_LABELS". Returns an empty slice if requiredLabels is empty.

func BuildRequiredTitlePrefixEnvVar added in v0.31.4

func BuildRequiredTitlePrefixEnvVar(envVarName string, requiredTitlePrefix string) []string

BuildRequiredTitlePrefixEnvVar builds a required-title-prefix environment variable line for safe-output jobs. envVarName should be the full env var name like "GH_AW_CLOSE_ISSUE_REQUIRED_TITLE_PREFIX". Returns an empty slice if requiredTitlePrefix is empty.

func BuildTargetEnvVar added in v0.31.4

func BuildTargetEnvVar(envVarName string, target string) []string

BuildTargetEnvVar builds a target environment variable line for safe-output jobs. envVarName should be the full env var name like "GH_AW_CLOSE_ISSUE_TARGET". Returns an empty slice if target is empty.

func BundleJavaScriptFromSources added in v0.28.0

func BundleJavaScriptFromSources(mainContent string, sources map[string]string, basePath string) (string, error)

BundleJavaScriptFromSources bundles JavaScript from in-memory sources sources is a map where keys are file paths (e.g., "sanitize.cjs") and values are the content mainContent is the main JavaScript content that may contain require() calls basePath is the base directory path for resolving relative imports (e.g., "js")

func ClearRepositoryFeaturesCache added in v0.25.0

func ClearRepositoryFeaturesCache()

ClearRepositoryFeaturesCache clears the repository features cache This is useful for testing or when repository settings might have changed

func CollectSecretReferences added in v0.14.3

func CollectSecretReferences(yamlContent string) []string

CollectSecretReferences extracts all secret references from the workflow YAML This scans for patterns like ${{ secrets.SECRET_NAME }} or secrets.SECRET_NAME

func ContainsCheckout added in v0.9.0

func ContainsCheckout(customSteps string) bool

ContainsCheckout returns true if the given custom steps contain an actions/checkout step

func ConvertStepToYAML added in v0.5.1

func ConvertStepToYAML(stepMap map[string]any) (string, error)

ConvertStepToYAML converts a step map to YAML string with proper indentation This is a shared utility function used by all engines and the compiler

func ConvertToFloat added in v0.0.22

func ConvertToFloat(val any) float64

ConvertToFloat safely converts any to float64

func ConvertToInt added in v0.0.22

func ConvertToInt(val any) int

ConvertToInt safely converts any to int

func CountErrors added in v0.16.0

func CountErrors(errors []LogError) int

CountErrors counts the number of errors in the slice

func CountWarnings added in v0.16.0

func CountWarnings(errors []LogError) int

CountWarnings counts the number of warnings in the slice

func ExecGH added in v0.29.0

func ExecGH(args ...string) *exec.Cmd

ExecGH wraps gh CLI calls and ensures proper token configuration. It uses go-gh/v2 to execute gh commands when GH_TOKEN or GITHUB_TOKEN is available, otherwise falls back to direct exec.Command for backward compatibility.

Usage:

cmd := ExecGH("api", "/user")
output, err := cmd.Output()

func ExecGHWithOutput added in v0.29.0

func ExecGHWithOutput(args ...string) (stdout, stderr bytes.Buffer, err error)

ExecGHWithOutput executes a gh CLI command using go-gh/v2 and returns stdout, stderr, and error. This is a convenience wrapper that directly uses go-gh/v2's Exec function.

Usage:

stdout, stderr, err := ExecGHWithOutput("api", "/user")

func ExtractAgentIdentifier added in v0.28.7

func ExtractAgentIdentifier(agentFile string) string

ExtractAgentIdentifier extracts the agent identifier (filename without extension) from an agent file path. This is used by the Copilot CLI which expects agent identifiers, not full paths.

Parameters:

  • agentFile: The relative path to the agent file (e.g., ".github/agents/test-agent.md")

Returns:

  • string: The agent identifier (e.g., "test-agent")

Example:

identifier := ExtractAgentIdentifier(".github/agents/my-agent.md")
// Returns: "my-agent"

func ExtractFirstMatch added in v0.0.22

func ExtractFirstMatch(text, pattern string) string

ExtractFirstMatch extracts the first regex match from a string Note: This function compiles the regex on each call. For frequently-used patterns, consider pre-compiling at package level or caching the compiled regex.

func ExtractJSONCost added in v0.0.22

func ExtractJSONCost(data map[string]any) float64

ExtractJSONCost extracts cost information from JSON data

func ExtractJSONTokenUsage added in v0.0.22

func ExtractJSONTokenUsage(data map[string]any) int

ExtractJSONTokenUsage extracts token usage from JSON data

func ExtractMCPServer added in v0.5.1

func ExtractMCPServer(toolName string) string

ExtractMCPServer extracts the MCP server name from a tool name

func ExtractSecretName added in v0.28.7

func ExtractSecretName(value string) string

ExtractSecretName extracts just the secret name from a GitHub Actions expression Examples:

  • "${{ secrets.DD_API_KEY }}" -> "DD_API_KEY"
  • "${{ secrets.DD_SITE || 'datadoghq.com' }}" -> "DD_SITE"
  • "plain value" -> ""

func ExtractSecretsFromMap added in v0.28.7

func ExtractSecretsFromMap(values map[string]string) map[string]string

ExtractSecretsFromMap extracts all secrets from a map of string values Returns a map of environment variable names to their full secret expressions Example:

Input: {"DD_API_KEY": "${{ secrets.DD_API_KEY }}", "DD_SITE": "${{ secrets.DD_SITE || 'default' }}"}
Output: {"DD_API_KEY": "${{ secrets.DD_API_KEY }}", "DD_SITE": "${{ secrets.DD_SITE || 'default' }}"}

func ExtractSecretsFromValue added in v0.28.7

func ExtractSecretsFromValue(value string) map[string]string

ExtractSecretsFromValue extracts all GitHub Actions secret expressions from a string value Returns a map of environment variable names to their full secret expressions Examples:

  • "${{ secrets.DD_API_KEY }}" -> {"DD_API_KEY": "${{ secrets.DD_API_KEY }}"}
  • "${{ secrets.DD_SITE || 'datadoghq.com' }}" -> {"DD_SITE": "${{ secrets.DD_SITE || 'datadoghq.com' }}"}
  • "Bearer ${{ secrets.TOKEN }}" -> {"TOKEN": "${{ secrets.TOKEN }}"}

func ExtractStopTimeFromLockFile added in v0.14.0

func ExtractStopTimeFromLockFile(lockFilePath string) string

ExtractStopTimeFromLockFile extracts the STOP_TIME value from a compiled workflow lock file

func FinalizeToolCallsAndSequence added in v0.30.0

func FinalizeToolCallsAndSequence(
	metrics *LogMetrics,
	toolCallMap map[string]*ToolCallInfo,
	currentSequence []string,
)

FinalizeToolCallsAndSequence completes the tool call and sequence finalization. Use this function when the engine extracts token usage and turns from structured result entries, rather than accumulating them during line-by-line log parsing. This is a lighter version of FinalizeToolMetrics for engines that do not need to finalize token usage and turns here.

func FinalizeToolMetrics added in v0.30.0

func FinalizeToolMetrics(
	metrics *LogMetrics,
	toolCallMap map[string]*ToolCallInfo,
	currentSequence []string,
	turns int,
	tokenUsage int,
	logContent string,
	errorPatterns []ErrorPattern,
)

FinalizeToolMetrics completes the metric collection process by finalizing sequences, converting tool call maps to sorted slices, and optionally counting errors using patterns. This function is called by engine-specific ParseLogMetrics implementations to avoid code duplication.

func FindJavaScriptDependencies added in v0.31.9

func FindJavaScriptDependencies(mainContent string, sources map[string]string, basePath string) (map[string]bool, error)

FindJavaScriptDependencies analyzes a JavaScript file and recursively finds all its dependencies without actually bundling the code. Returns a map of file paths that are required.

Parameters:

  • mainContent: The JavaScript content to analyze
  • sources: Map of file paths to their content
  • basePath: Base directory path for resolving relative imports (e.g., "js")

Returns:

  • Map of file paths (relative to basePath) that are dependencies
  • Error if a required file is not found in sources

func FormatJavaScriptForYAML added in v0.2.0

func FormatJavaScriptForYAML(script string) []string

FormatJavaScriptForYAML formats a JavaScript script with proper indentation for embedding in YAML

func FormatStepWithCommandAndEnv added in v0.22.10

func FormatStepWithCommandAndEnv(stepLines []string, command string, env map[string]string) []string

RenderCustomMCPToolConfigHandler is a function type that engines must provide to render their specific MCP config FormatStepWithCommandAndEnv formats a GitHub Actions step with command and environment variables. This shared function extracts the common pattern used by Copilot and Codex engines.

Parameters:

  • stepLines: Existing step lines to append to (e.g., name, id, comments, timeout)
  • command: The command to execute (may contain multiple lines)
  • env: Map of environment variables to include in the step

Returns:

  • []string: Complete step lines including run command and env section

func FormatValidationMessage added in v0.27.0

func FormatValidationMessage(result *PermissionsValidationResult, strict bool) string

FormatValidationMessage formats the validation result into a human-readable message

func GenerateConcurrencyConfig

func GenerateConcurrencyConfig(workflowData *WorkflowData, isCommandTrigger bool) string

GenerateConcurrencyConfig generates the concurrency configuration for a workflow based on its trigger types and characteristics.

func GenerateJobConcurrencyConfig added in v0.14.1

func GenerateJobConcurrencyConfig(workflowData *WorkflowData) string

GenerateJobConcurrencyConfig generates the agent concurrency configuration for the agent job based on engine.concurrency field

func GetActionPin added in v0.25.0

func GetActionPin(actionRepo string) string

GetActionPin returns the pinned action reference for a given action repository It uses the golden/default version defined in actionPins If no pin is found, it returns an empty string The returned reference includes a comment with the version tag (e.g., "repo@sha # v1")

func GetActionPinWithData added in v0.26.0

func GetActionPinWithData(actionRepo, version string, data *WorkflowData) (string, error)

GetActionPinWithData returns the pinned action reference for a given action@version It tries dynamic resolution first, then falls back to hardcoded pins If strictMode is true and resolution fails, it returns an error The returned reference includes a comment with the version tag (e.g., "repo@sha # v1")

func GetActualGitHubEventName added in v0.13.1

func GetActualGitHubEventName(identifier string) string

GetActualGitHubEventName returns the actual GitHub Actions event name for a given identifier This maps pull_request_comment to issue_comment since that's the actual event in GitHub Actions

func GetAllowedDomains added in v0.2.3

func GetAllowedDomains(network *NetworkPermissions) []string

GetAllowedDomains returns the allowed domains from network permissions Returns default allow-list if no network permissions configured or in "defaults" mode Returns empty slice if network permissions configured but no domains allowed (deny all) Returns domain list if network permissions configured with allowed domains Supports ecosystem identifiers:

  • "defaults": basic infrastructure (certs, JSON schema, Ubuntu, common package mirrors, Microsoft sources)
  • "containers": container registries (Docker, GitHub Container Registry, etc.)
  • "dotnet": .NET and NuGet ecosystem
  • "dart": Dart/Flutter ecosystem
  • "github": GitHub domains
  • "go": Go ecosystem
  • "terraform": HashiCorp/Terraform
  • "haskell": Haskell ecosystem
  • "java": Java/Maven/Gradle
  • "linux-distros": Linux distribution package repositories
  • "node": Node.js/NPM/Yarn
  • "perl": Perl/CPAN
  • "php": PHP/Composer
  • "playwright": Playwright testing framework
  • "python": Python/PyPI/Conda
  • "ruby": Ruby/RubyGems
  • "rust": Rust/Cargo/Crates
  • "swift": Swift/CocoaPods
  • "github-actions": GitHub Actions domains

func GetCommentEventNames added in v0.13.1

func GetCommentEventNames(mappings []CommentEventMapping) []string

GetCommentEventNames returns just the event names from a list of mappings

func GetCopilotAgentPlaywrightTools added in v0.6.3

func GetCopilotAgentPlaywrightTools() []any

GetCopilotAgentPlaywrightTools returns the list of playwright tools available in the copilot agent This matches the tools available in the copilot agent MCP server configuration This is a shared function used by all engines for consistent playwright tool configuration

func GetCopilotAllowedDomains added in v0.24.0

func GetCopilotAllowedDomains(network *NetworkPermissions) string

GetCopilotAllowedDomains merges Copilot default domains with NetworkPermissions allowed domains Returns a deduplicated, sorted, comma-separated string suitable for AWF's --allow-domains flag

func GetDefaultMaxForType added in v0.31.4

func GetDefaultMaxForType(typeName string) int

GetDefaultMaxForType returns the default max for a type

func GetDomainEcosystem added in v0.4.0

func GetDomainEcosystem(domain string) string

GetDomainEcosystem returns the ecosystem identifier for a given domain, or empty string if not found

func GetJavaScriptSources added in v0.28.0

func GetJavaScriptSources() map[string]string

GetJavaScriptSources returns a map of all embedded JavaScript sources The keys are the relative paths from the js directory

func GetLogParserBootstrap added in v0.28.6

func GetLogParserBootstrap() string

GetLogParserBootstrap returns the JavaScript content for the log parser bootstrap helper

func GetLogParserScript added in v0.2.5

func GetLogParserScript(name string) string

GetLogParserScript returns the JavaScript content for a log parser by name

func GetMCPHandlerPythonScript added in v0.31.9

func GetMCPHandlerPythonScript() string

GetMCPHandlerPythonScript returns the embedded mcp_handler_python.cjs script

func GetMCPHandlerShellScript added in v0.31.9

func GetMCPHandlerShellScript() string

GetMCPHandlerShellScript returns the embedded mcp_handler_shell.cjs script

func GetMCPServerCoreScript added in v0.31.4

func GetMCPServerCoreScript() string

GetMCPServerCoreScript returns the embedded mcp_server_core.cjs script

func GetReadBufferScript added in v0.31.4

func GetReadBufferScript() string

GetReadBufferScript returns the embedded read_buffer.cjs script

func GetSafeInputsConfigLoaderScript added in v0.31.9

func GetSafeInputsConfigLoaderScript() string

GetSafeInputsConfigLoaderScript returns the embedded safe_inputs_config_loader.cjs script

func GetSafeInputsMCPServerScript added in v0.31.4

func GetSafeInputsMCPServerScript() string

GetSafeInputsMCPServerScript returns the embedded safe_inputs_mcp_server.cjs script

func GetSafeInputsToolFactoryScript added in v0.31.9

func GetSafeInputsToolFactoryScript() string

GetSafeInputsToolFactoryScript returns the embedded safe_inputs_tool_factory.cjs script

func GetSafeOutputsAppendScript added in v0.31.9

func GetSafeOutputsAppendScript() string

GetSafeOutputsAppendScript returns the embedded safe_outputs_append.cjs script

func GetSafeOutputsConfigScript added in v0.31.9

func GetSafeOutputsConfigScript() string

GetSafeOutputsConfigScript returns the embedded safe_outputs_config.cjs script

func GetSafeOutputsHandlersScript added in v0.31.9

func GetSafeOutputsHandlersScript() string

GetSafeOutputsHandlersScript returns the embedded safe_outputs_handlers.cjs script

func GetSafeOutputsMCPServerScript added in v0.6.3

func GetSafeOutputsMCPServerScript() string

GetSafeOutputsMCPServerScript returns the JavaScript content for the GitHub Agentic Workflows Safe Outputs MCP server

func GetSafeOutputsToolsJSON added in v0.30.0

func GetSafeOutputsToolsJSON() string

GetSafeOutputsToolsJSON returns the JSON content for the safe outputs tools definitions

func GetSafeOutputsToolsLoaderScript added in v0.31.9

func GetSafeOutputsToolsLoaderScript() string

GetSafeOutputsToolsLoaderScript returns the embedded safe_outputs_tools_loader.cjs script

func GetScript added in v0.31.3

func GetScript(name string) string

GetScript retrieves a bundled script from the default registry. This is a convenience function equivalent to DefaultScriptRegistry.Get(name).

func GetValidationConfigJSON added in v0.31.4

func GetValidationConfigJSON(enabledTypes []string) (string, error)

GetValidationConfigJSON returns the validation configuration as indented JSON If enabledTypes is empty or nil, returns all validation configs If enabledTypes is provided, returns only configs for the specified types

func HandleCustomMCPToolInSwitch added in v0.22.4

func HandleCustomMCPToolInSwitch(
	yaml *strings.Builder,
	toolName string,
	tools map[string]any,
	isLast bool,
	renderFunc RenderCustomMCPToolConfigHandler,
) bool

HandleCustomMCPToolInSwitch processes custom MCP tools in the default case of a switch statement. This shared function extracts the common pattern used across all workflow engines.

Parameters:

  • yaml: The string builder for YAML output
  • toolName: The name of the tool being processed
  • tools: The tools map containing tool configurations (supports both expanded and non-expanded tools)
  • isLast: Whether this is the last tool in the list
  • renderFunc: Engine-specific function to render the MCP configuration

Returns:

  • bool: true if a custom MCP tool was handled, false otherwise

func HasMCPServers added in v0.12.4

func HasMCPServers(workflowData *WorkflowData) bool

hasMCPServers checks if the workflow has any MCP servers configured

func HasNetworkPermissions added in v0.2.3

func HasNetworkPermissions(engineConfig *EngineConfig) bool

HasNetworkPermissions is deprecated - use ShouldEnforceNetworkPermissions instead Kept for backwards compatibility but will be removed in future versions

func HasSafeInputs added in v0.31.4

func HasSafeInputs(safeInputs *SafeInputsConfig) bool

HasSafeInputs checks if safe-inputs are configured

func HasSafeJobsEnabled added in v0.9.0

func HasSafeJobsEnabled(safeJobs map[string]*SafeJobConfig) bool

HasSafeJobsEnabled checks if any safe-jobs are enabled at the top level

func HasSafeOutputsEnabled added in v0.6.3

func HasSafeOutputsEnabled(safeOutputs *SafeOutputsConfig) bool

HasSafeOutputsEnabled checks if any safe-outputs are enabled

func IsSafeInputsEnabled added in v0.31.4

func IsSafeInputsEnabled(safeInputs *SafeInputsConfig, workflowData *WorkflowData) bool

IsSafeInputsEnabled checks if safe-inputs are configured. Safe-inputs are enabled by default when configured in the workflow. The workflowData parameter is kept for backward compatibility but is not used.

func MarshalWithFieldOrder added in v0.14.0

func MarshalWithFieldOrder(data map[string]any, priorityFields []string) ([]byte, error)

MarshalWithFieldOrder marshals a map to YAML with fields in a specific order. Priority fields are emitted first in the order specified, then remaining fields alphabetically. This is used to ensure GitHub Actions workflow fields appear in a conventional order.

func NormalizeExpressionForComparison added in v0.5.2

func NormalizeExpressionForComparison(expression string) string

NormalizeExpressionForComparison normalizes an expression by removing extra spaces and newlines This is used for comparing multiline expressions with their single-line equivalents

func OrderMapFields added in v0.14.0

func OrderMapFields(data map[string]any, priorityFields []string) yaml.MapSlice

OrderMapFields converts a map to yaml.MapSlice with fields in a specific order. Priority fields are emitted first in the order specified, then remaining fields alphabetically. This is a helper function that can be used when you need the MapSlice directly.

func ParseCommandEvents added in v0.13.1

func ParseCommandEvents(eventsValue any) []string

ParseCommandEvents parses the events field from command configuration Returns a list of event identifiers to enable, or nil for default (all events)

func ParseGitHubToolsets added in v0.27.0

func ParseGitHubToolsets(toolsetsStr string) []string

ParseGitHubToolsets parses the toolsets string and expands "default" and "all" into their constituent toolsets. It handles comma-separated lists and deduplicates.

func ParseInputDefinitions added in v0.31.4

func ParseInputDefinitions(inputsMap map[string]any) map[string]*InputDefinition

ParseInputDefinitions parses a map of input definitions from a frontmatter map. Returns a map of input name to InputDefinition.

func ParseStringArrayFromConfig added in v0.31.4

func ParseStringArrayFromConfig(configMap map[string]any, key string) []string

ParseStringArrayFromConfig extracts a string array from a config map by key. Returns the slice of strings, or nil if not present or not an array.

func ParseStringFromConfig added in v0.31.4

func ParseStringFromConfig(configMap map[string]any, key string) string

ParseStringFromConfig extracts a string value from a config map by key. Returns the string value, or empty string if not present or not a string.

func PrettifyToolName added in v0.5.1

func PrettifyToolName(toolName string) string

PrettifyToolName removes "mcp__" prefix and formats tool names nicely

func RenderConditionAsIf added in v0.12.1

func RenderConditionAsIf(yaml *strings.Builder, condition ConditionNode, indent string)

RenderConditionAsIf renders a ConditionNode as an 'if' condition with proper YAML indentation

func RenderGitHubMCPDockerConfig added in v0.24.0

func RenderGitHubMCPDockerConfig(yaml *strings.Builder, options GitHubMCPDockerOptions)

RenderGitHubMCPDockerConfig renders the GitHub MCP server configuration for Docker (local mode). This shared function extracts the duplicate pattern from Claude and Copilot engines.

Parameters:

  • yaml: The string builder for YAML output
  • options: GitHub MCP Docker rendering options

func RenderGitHubMCPRemoteConfig added in v0.25.0

func RenderGitHubMCPRemoteConfig(yaml *strings.Builder, options GitHubMCPRemoteOptions)

RenderGitHubMCPRemoteConfig renders the GitHub MCP server configuration for remote (hosted) mode. This shared function extracts the duplicate pattern from Claude and Copilot engines.

Parameters:

  • yaml: The string builder for YAML output
  • options: GitHub MCP remote rendering options

func RenderJSONMCPConfig added in v0.23.2

func RenderJSONMCPConfig(
	yaml *strings.Builder,
	tools map[string]any,
	mcpTools []string,
	workflowData *WorkflowData,
	options JSONMCPConfigOptions,
)

RenderJSONMCPConfig renders MCP configuration in JSON format with the common mcpServers structure. This shared function extracts the duplicate pattern from Claude, Copilot, and Custom engines.

Parameters:

  • yaml: The string builder for YAML output
  • tools: Map of tool configurations
  • mcpTools: Ordered list of MCP tool names to render
  • workflowData: Workflow configuration data
  • options: JSON MCP config rendering options

func ReplaceSecretsWithEnvVars added in v0.28.7

func ReplaceSecretsWithEnvVars(value string, secrets map[string]string) string

ReplaceSecretsWithEnvVars replaces secret expressions in a value with environment variable references Example: "${{ secrets.DD_API_KEY }}" -> "\${DD_API_KEY}" The backslash is used to escape the ${} for proper JSON rendering in Copilot configs

func ResolveAgentFilePath added in v0.28.3

func ResolveAgentFilePath(agentFile string) string

ResolveAgentFilePath returns the properly quoted agent file path with GITHUB_WORKSPACE prefix. This helper extracts the common pattern shared by Copilot, Codex, and Claude engines.

The agent file path is relative to the repository root, so we prefix it with ${GITHUB_WORKSPACE} and wrap the entire expression in double quotes to handle paths with spaces while allowing shell variable expansion.

Parameters:

  • agentFile: The relative path to the agent file (e.g., ".github/agents/test-agent.md")

Returns:

  • string: The double-quoted path with GITHUB_WORKSPACE prefix (e.g., "${GITHUB_WORKSPACE}/.github/agents/test-agent.md")

Example:

agentPath := ResolveAgentFilePath(".github/agents/my-agent.md")
// Returns: "${GITHUB_WORKSPACE}/.github/agents/my-agent.md"

Note: The entire path is wrapped in double quotes (not just the variable) to ensure:

  1. The shellEscapeArg function recognizes it as already-quoted and doesn't add single quotes
  2. Shell variable expansion works (${GITHUB_WORKSPACE} gets expanded inside double quotes)
  3. Paths with spaces are properly handled

func ResolveRelativeDate added in v0.2.0

func ResolveRelativeDate(dateStr string, baseTime time.Time) (string, error)

ResolveRelativeDate resolves a relative date string to an absolute timestamp suitable for use with GitHub CLI. If the date string is not relative, it returns the original string.

Returns a full ISO 8601 timestamp (YYYY-MM-DDTHH:MM:SSZ) for precise filtering.

func ResolveWorkflowName

func ResolveWorkflowName(workflowInput string) (string, error)

ResolveWorkflowName converts an agentic workflow ID to the GitHub Actions workflow name. It normalizes the input by removing .md and .lock.yml extensions, then finds the corresponding workflow files and extracts the actual workflow name from the lock.yml file.

The agentic workflow ID is the basename of the markdown file without the .md extension. The GitHub Actions workflow name is extracted from the "name:" field in the corresponding .lock.yml file.

Examples:

  • "weekly-research" -> "Weekly Research" (from weekly-research.lock.yml name field)
  • "weekly-research.md" -> "Weekly Research" (from weekly-research.lock.yml name field)
  • "weekly-research.lock.yml" -> "Weekly Research" (from weekly-research.lock.yml name field)

func SanitizeIdentifier added in v0.26.0

func SanitizeIdentifier(name string) string

SanitizeIdentifier sanitizes a workflow name to create a safe identifier suitable for use as a user agent string or similar context.

This is a SANITIZE function (character validity pattern). Use this when creating identifiers that must be purely alphanumeric with hyphens, with no special characters preserved. Unlike SanitizeWorkflowName which preserves dots and underscores, this function removes ALL special characters except hyphens.

The function:

  • Converts to lowercase
  • Replaces spaces and underscores with hyphens
  • Removes non-alphanumeric characters (except hyphens)
  • Consolidates multiple hyphens into a single hyphen
  • Trims leading and trailing hyphens
  • Returns "github-agentic-workflow" if the result would be empty

Example inputs and outputs:

SanitizeIdentifier("My Workflow")         // returns "my-workflow"
SanitizeIdentifier("test_workflow")       // returns "test-workflow"
SanitizeIdentifier("@@@")                 // returns "github-agentic-workflow" (default)
SanitizeIdentifier("Weekly v2.0")         // returns "weekly-v2-0"

This function uses the unified SanitizeName function with options configured to trim leading/trailing hyphens and return a default value for empty results. Hyphens are preserved by default in SanitizeName, not via PreserveSpecialChars.

See package documentation for guidance on when to use sanitize vs normalize patterns.

func SanitizeName added in v0.28.0

func SanitizeName(name string, opts *SanitizeOptions) string

SanitizeName sanitizes a string for use as an identifier, file name, or similar context. It provides configurable behavior through the SanitizeOptions parameter.

The function performs the following transformations:

  • Converts to lowercase
  • Replaces common separators (colons, slashes, backslashes, spaces) with hyphens
  • Replaces underscores with hyphens unless preserved in opts.PreserveSpecialChars
  • Removes or replaces characters based on opts.PreserveSpecialChars
  • Consolidates multiple consecutive hyphens into a single hyphen
  • Optionally trims leading/trailing hyphens (controlled by opts.TrimHyphens)
  • Returns opts.DefaultValue if the result is empty (controlled by opts.DefaultValue)

Example:

// Preserve dots and underscores (like SanitizeWorkflowName)
opts := &SanitizeOptions{
    PreserveSpecialChars: []rune{'.', '_'},
}
SanitizeName("My.Workflow_Name", opts) // returns "my.workflow_name"

// Trim hyphens and use default (like SanitizeIdentifier)
opts := &SanitizeOptions{
    TrimHyphens:  true,
    DefaultValue: "default-name",
}
SanitizeName("@@@", opts) // returns "default-name"

func SanitizeWorkflowName added in v0.25.1

func SanitizeWorkflowName(name string) string

SanitizeWorkflowName sanitizes a workflow name for use in artifact names and file paths. It converts the name to lowercase and replaces or removes characters that are invalid in YAML artifact names or filesystem paths.

This is a SANITIZE function (character validity pattern). Use this when processing user input or workflow names that may contain invalid characters. Do NOT use this for removing file extensions - use normalizeWorkflowName (resolve.go) instead.

The function performs the following transformations:

  • Converts to lowercase
  • Replaces colons, slashes, backslashes, and spaces with hyphens
  • Replaces any remaining special characters (except dots, underscores, and hyphens) with hyphens
  • Consolidates multiple consecutive hyphens into a single hyphen

Example inputs and outputs:

SanitizeWorkflowName("My Workflow: Test/Build")  // returns "my-workflow-test-build"
SanitizeWorkflowName("Weekly Research v2.0")     // returns "weekly-research-v2.0"
SanitizeWorkflowName("test_workflow")            // returns "test_workflow"

See package documentation for guidance on when to use sanitize vs normalize patterns.

func ShortenCommand added in v0.26.0

func ShortenCommand(command string) string

ShortenCommand creates a short identifier for bash commands. It replaces newlines with spaces and truncates to 20 characters if needed.

func ShouldEnforceNetworkPermissions added in v0.2.3

func ShouldEnforceNetworkPermissions(network *NetworkPermissions) bool

ShouldEnforceNetworkPermissions checks if network permissions should be enforced Returns true if network permissions are configured and not in "defaults" mode

func ShouldSkipRuntimeSetup added in v0.16.0

func ShouldSkipRuntimeSetup(workflowData *WorkflowData) bool

ShouldSkipRuntimeSetup checks if we should skip automatic runtime setup Deprecated: Runtime detection now smartly filters out existing runtimes instead of skipping entirely This function now always returns false for backward compatibility

func SortPermissionScopes added in v0.27.0

func SortPermissionScopes(s []PermissionScope)

SortPermissionScopes sorts a slice of PermissionScope in place using bubble sort

func SortStrings added in v0.14.3

func SortStrings(s []string)

SortStrings sorts a slice of strings in place using bubble sort

func SubstituteImportInputs added in v0.31.4

func SubstituteImportInputs(content string, importInputs map[string]any) string

SubstituteImportInputs replaces ${{ github.aw.inputs.<key> }} expressions with the corresponding values from the importInputs map. This is called before expression extraction to inject import input values.

func UnquoteYAMLKey added in v0.14.0

func UnquoteYAMLKey(yamlStr string, key string) string

UnquoteYAMLKey removes quotes from a YAML key at the start of a line. This is necessary because yaml.Marshal adds quotes around reserved words like "on". The function only replaces the quoted key if it appears at the start of a line (optionally preceded by whitespace) to avoid replacing quoted strings in values.

func ValidateActionSHAsInLockFile added in v0.28.7

func ValidateActionSHAsInLockFile(lockFilePath string, cache *ActionCache, verbose bool) error

ValidateActionSHAsInLockFile validates action SHAs in a lock file and emits warnings

func ValidateExpressionSafetyPublic added in v0.31.4

func ValidateExpressionSafetyPublic(markdownContent string) error

ValidateExpressionSafetyPublic is a public wrapper for validateExpressionSafety that allows testing expression validation from external packages

func ValidateGitHubToolsAgainstToolsets added in v0.27.0

func ValidateGitHubToolsAgainstToolsets(allowedTools []string, enabledToolsets []string) error

ValidateGitHubToolsAgainstToolsets validates that all allowed GitHub tools have their corresponding toolsets enabled in the configuration

func ValidateMCPConfigs

func ValidateMCPConfigs(tools map[string]any) error

ValidateMCPConfigs validates all MCP configurations in the tools section using JSON schema

func VisitExpressionTree added in v0.5.1

func VisitExpressionTree(node ConditionNode, visitor func(expr *ExpressionNode) error) error

VisitExpressionTree walks through an expression tree and calls the visitor function for each ExpressionNode (literal expression) found in the tree

func WriteJavaScriptToYAML added in v0.2.0

func WriteJavaScriptToYAML(yaml *strings.Builder, script string)

WriteJavaScriptToYAML writes a JavaScript script with proper indentation to a strings.Builder

func WriteJavaScriptToYAMLPreservingComments added in v0.24.0

func WriteJavaScriptToYAMLPreservingComments(yaml *strings.Builder, script string)

WriteJavaScriptToYAMLPreservingComments writes a JavaScript script with proper indentation to a strings.Builder while preserving JSDoc and inline comments, but removing TypeScript-specific comments. Used for security-sensitive scripts like redact_secrets.

func WritePromptTextToYAML added in v0.12.1

func WritePromptTextToYAML(yaml *strings.Builder, text string, indent string)

WritePromptTextToYAML writes prompt text to a YAML heredoc with proper indentation. It chunks the text into groups of lines of less than MaxPromptChunkSize characters, with a maximum of MaxPromptChunks chunks. Each chunk is written as a separate heredoc to avoid GitHub Actions step size limits (21KB).

func WriteShellScriptToYAML added in v0.12.1

func WriteShellScriptToYAML(yaml *strings.Builder, script string, indent string)

WriteShellScriptToYAML writes a shell script with proper indentation to a strings.Builder

Types

type ActionCache added in v0.26.0

type ActionCache struct {
	Entries map[string]ActionCacheEntry `json:"entries"` // key: "repo@version"
	// contains filtered or unexported fields
}

ActionCache manages cached action pin resolutions

func NewActionCache added in v0.26.0

func NewActionCache(repoRoot string) *ActionCache

NewActionCache creates a new action cache instance

func (*ActionCache) Get added in v0.26.0

func (c *ActionCache) Get(repo, version string) (string, bool)

Get retrieves a cached entry if it exists

func (*ActionCache) GetCachePath added in v0.26.0

func (c *ActionCache) GetCachePath() string

GetCachePath returns the path to the cache file

func (*ActionCache) Load added in v0.26.0

func (c *ActionCache) Load() error

Load loads the cache from disk

func (*ActionCache) Save added in v0.26.0

func (c *ActionCache) Save() error

Save saves the cache to disk with sorted entries If the cache is empty, the file is not created or is deleted if it exists

func (*ActionCache) Set added in v0.26.0

func (c *ActionCache) Set(repo, version, sha string)

Set stores a new cache entry

type ActionCacheEntry added in v0.26.0

type ActionCacheEntry struct {
	Repo    string `json:"repo"`
	Version string `json:"version"`
	SHA     string `json:"sha"`
}

ActionCacheEntry represents a cached action pin resolution

type ActionPin added in v0.25.0

type ActionPin struct {
	Repo    string `json:"repo"`    // e.g., "actions/checkout"
	Version string `json:"version"` // e.g., "v5" - the golden/default version
	SHA     string `json:"sha"`     // Full commit SHA for the pinned version
}

ActionPin represents a pinned GitHub Action with its commit SHA

func GetActionPinByRepo added in v0.26.0

func GetActionPinByRepo(repo string) (ActionPin, bool)

GetActionPinByRepo returns the ActionPin for a given repository, if it exists

type ActionPinsData added in v0.27.0

type ActionPinsData struct {
	Entries map[string]ActionPin `json:"entries"` // key: "repo@version"
}

ActionPinsData represents the structure of the embedded JSON file This matches the schema used by ActionCache for consistency

type ActionResolver added in v0.26.0

type ActionResolver struct {
	// contains filtered or unexported fields
}

ActionResolver handles resolving action SHAs using GitHub CLI

func NewActionResolver added in v0.26.0

func NewActionResolver(cache *ActionCache) *ActionResolver

NewActionResolver creates a new action resolver

func (*ActionResolver) ResolveSHA added in v0.26.0

func (r *ActionResolver) ResolveSHA(repo, version string) (string, error)

ResolveSHA resolves the SHA for a given action@version using GitHub CLI Returns the SHA and an error if resolution fails

type ActionUpdateCheck added in v0.28.7

type ActionUpdateCheck struct {
	Action      ActionUsage
	NeedsUpdate bool
	LatestSHA   string
	Message     string
}

ActionUpdateCheck represents the result of checking if an action needs updating

func CheckActionSHAUpdates added in v0.28.7

func CheckActionSHAUpdates(actions []ActionUsage, resolver *ActionResolver) []ActionUpdateCheck

CheckActionSHAUpdates checks if actions need updating by comparing with latest SHAs

type ActionUsage added in v0.28.7

type ActionUsage struct {
	Repo    string // e.g., "actions/checkout"
	SHA     string // The SHA currently used
	Version string // The version tag if available (e.g., "v5")
}

ActionUsage represents an action used in a workflow with its SHA

func ExtractActionsFromLockFile added in v0.28.7

func ExtractActionsFromLockFile(lockFilePath string) ([]ActionUsage, error)

ExtractActionsFromLockFile parses a lock.yml file and extracts all action usages

type AddCommentConfig added in v0.7.1

type AddCommentConfig struct {
}

AddCommentConfig holds configuration for creating GitHub issue/PR comments from agent output (deprecated, use AddCommentsConfig)

type AddCommentsConfig added in v0.7.1

type AddCommentsConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	Target               string `yaml:"target,omitempty"`      // Target for comments: "triggering" (default), "*" (any issue), or explicit issue number
	TargetRepoSlug       string `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository comments
	Discussion           *bool  `yaml:"discussion,omitempty"`  // Target discussion comments instead of issue/PR comments. Must be true if present.
}

AddCommentsConfig holds configuration for creating GitHub issue/PR comments from agent output

type AddLabelsConfig added in v0.7.1

type AddLabelsConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	Allowed                []string `yaml:"allowed,omitempty"` // Optional list of allowed labels. If omitted, any labels are allowed (including creating new ones).
}

AddLabelsConfig holds configuration for adding labels to issues/PRs from agent output

type AddReviewerConfig added in v0.30.5

type AddReviewerConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	Reviewers              []string `yaml:"reviewers,omitempty"` // Optional list of allowed reviewers. If omitted, any reviewers are allowed.
}

AddReviewerConfig holds configuration for adding reviewers to PRs from agent output

type AgentSandboxConfig added in v0.31.4

type AgentSandboxConfig struct {
	ID       string                `yaml:"id,omitempty"`      // Agent ID: "awf" or "srt" (replaces Type in new object format)
	Type     SandboxType           `yaml:"type,omitempty"`    // Sandbox type: "awf" or "srt" (legacy, use ID instead)
	Disabled bool                  `yaml:"-"`                 // True when agent is explicitly set to false (disables firewall). This is a runtime flag, not serialized to YAML.
	Config   *SandboxRuntimeConfig `yaml:"config,omitempty"`  // Custom SRT config (optional)
	Command  string                `yaml:"command,omitempty"` // Custom command to replace AWF or SRT installation
	Args     []string              `yaml:"args,omitempty"`    // Additional arguments to append to the command
	Env      map[string]string     `yaml:"env,omitempty"`     // Environment variables to set on the step
}

AgentSandboxConfig represents the agent sandbox configuration

type AgenticWorkflowsToolConfig added in v0.22.9

type AgenticWorkflowsToolConfig struct {
	// Can be boolean or nil
	Enabled bool `yaml:"-"`
}

AgenticWorkflowsToolConfig represents the configuration for the agentic-workflows tool

type AndNode

type AndNode struct {
	Left, Right ConditionNode
}

AndNode represents an AND operation between two conditions

func (*AndNode) Render

func (a *AndNode) Render() string

type ArtifactDownloadConfig added in v0.22.10

type ArtifactDownloadConfig struct {
	ArtifactName string // Name of the artifact to download (e.g., "agent_output.json", "prompt.txt")
	DownloadPath string // Path where artifact will be downloaded (e.g., "/tmp/gh-aw/safeoutputs/")
	SetupEnvStep bool   // Whether to add environment variable setup step
	EnvVarName   string // Environment variable name to set (e.g., "GH_AW_AGENT_OUTPUT")
	StepName     string // Optional custom step name (defaults to "Download {artifact} artifact")
}

ArtifactDownloadConfig holds configuration for building artifact download steps

type AssignMilestoneConfig added in v0.30.1

type AssignMilestoneConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	Allowed                []string `yaml:"allowed,omitempty"` // Optional list of allowed milestone titles or IDs
}

AssignMilestoneConfig holds configuration for assigning milestones to issues from agent output

type AssignToAgentConfig added in v0.31.0

type AssignToAgentConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	DefaultAgent           string `yaml:"name,omitempty"` // Default agent to assign (e.g., "copilot")
}

AssignToAgentConfig holds configuration for assigning agents to issues from agent output

type AssignToUserConfig added in v0.31.4

type AssignToUserConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	Allowed                []string `yaml:"allowed,omitempty"` // Optional list of allowed usernames. If omitted, any users are allowed.
}

AssignToUserConfig holds configuration for assigning users to issues from agent output

type BaseEngine

type BaseEngine struct {
	// contains filtered or unexported fields
}

BaseEngine provides common functionality for agentic engines

func (*BaseEngine) GetDeclaredOutputFiles added in v0.2.0

func (e *BaseEngine) GetDeclaredOutputFiles() []string

GetDeclaredOutputFiles returns an empty list by default (engines can override)

func (*BaseEngine) GetDefaultDetectionModel added in v0.31.4

func (e *BaseEngine) GetDefaultDetectionModel() string

GetDefaultDetectionModel returns empty string by default (no default model) Engines can override this to provide a cost-effective default for detection jobs

func (*BaseEngine) GetDescription

func (e *BaseEngine) GetDescription() string

func (*BaseEngine) GetDisplayName

func (e *BaseEngine) GetDisplayName() string

func (*BaseEngine) GetErrorPatterns added in v0.6.0

func (e *BaseEngine) GetErrorPatterns() []ErrorPattern

GetErrorPatterns returns an empty list by default (engines can override)

func (*BaseEngine) GetID

func (e *BaseEngine) GetID() string

func (*BaseEngine) GetLogFileForParsing added in v0.16.0

func (e *BaseEngine) GetLogFileForParsing() string

GetLogFileForParsing returns the default log file path for parsing Engines can override this to use engine-specific log files

func (*BaseEngine) IsExperimental

func (e *BaseEngine) IsExperimental() bool

func (*BaseEngine) SupportsFirewall added in v0.25.0

func (e *BaseEngine) SupportsFirewall() bool

func (*BaseEngine) SupportsHTTPTransport

func (e *BaseEngine) SupportsHTTPTransport() bool

func (*BaseEngine) SupportsMaxTurns added in v0.1.0

func (e *BaseEngine) SupportsMaxTurns() bool

func (*BaseEngine) SupportsToolsAllowlist added in v0.8.2

func (e *BaseEngine) SupportsToolsAllowlist() bool

func (*BaseEngine) SupportsWebFetch added in v0.12.1

func (e *BaseEngine) SupportsWebFetch() bool

func (*BaseEngine) SupportsWebSearch added in v0.12.1

func (e *BaseEngine) SupportsWebSearch() bool

type BaseSafeOutputConfig added in v0.10.0

type BaseSafeOutputConfig struct {
	Max         int    `yaml:"max,omitempty"`          // Maximum number of items to create
	GitHubToken string `yaml:"github-token,omitempty"` // GitHub token for this specific output type
}

BaseSafeOutputConfig holds common configuration fields for all safe output types

type BashToolConfig added in v0.22.9

type BashToolConfig struct {
	AllowedCommands []string `yaml:"-"` // List of allowed bash commands
}

BashToolConfig represents the configuration for the Bash tool Can be nil (all commands allowed) or an array of allowed commands

type BooleanLiteralNode

type BooleanLiteralNode struct {
	Value bool
}

BooleanLiteralNode represents a boolean literal value

func BuildBooleanLiteral

func BuildBooleanLiteral(value bool) *BooleanLiteralNode

BuildBooleanLiteral creates a boolean literal node

func (*BooleanLiteralNode) Render

func (b *BooleanLiteralNode) Render() string

type CacheMemoryConfig added in v0.6.2

type CacheMemoryConfig struct {
	Caches []CacheMemoryEntry `yaml:"caches,omitempty"` // cache configurations
}

CacheMemoryConfig holds configuration for cache-memory functionality

type CacheMemoryEntry added in v0.21.0

type CacheMemoryEntry struct {
	ID            string `yaml:"id"`                       // cache identifier (required for array notation)
	Key           string `yaml:"key,omitempty"`            // custom cache key
	Description   string `yaml:"description,omitempty"`    // optional description for this cache
	RetentionDays *int   `yaml:"retention-days,omitempty"` // retention days for upload-artifact action
}

CacheMemoryEntry represents a single cache-memory configuration

type CacheMemoryToolConfig added in v0.22.9

type CacheMemoryToolConfig struct {
	// Can be boolean, object, or array - handled by cache.go
	Raw any `yaml:"-"`
}

CacheMemoryToolConfig represents the configuration for cache-memory This is handled separately by the existing CacheMemoryConfig in cache.go

type ClaudeEngine

type ClaudeEngine struct {
	BaseEngine
}

ClaudeEngine represents the Claude Code agentic engine

func NewClaudeEngine

func NewClaudeEngine() *ClaudeEngine

func (*ClaudeEngine) GetDeclaredOutputFiles added in v0.2.0

func (e *ClaudeEngine) GetDeclaredOutputFiles() []string

GetDeclaredOutputFiles returns the output files that Claude may produce

func (*ClaudeEngine) GetErrorPatterns added in v0.10.0

func (e *ClaudeEngine) GetErrorPatterns() []ErrorPattern

GetErrorPatterns returns regex patterns for extracting error messages from Claude logs

func (*ClaudeEngine) GetExecutionSteps added in v0.5.0

func (e *ClaudeEngine) GetExecutionSteps(workflowData *WorkflowData, logFile string) []GitHubActionStep

GetExecutionSteps returns the GitHub Actions steps for executing Claude

func (*ClaudeEngine) GetInstallationSteps

func (e *ClaudeEngine) GetInstallationSteps(workflowData *WorkflowData) []GitHubActionStep

func (*ClaudeEngine) GetLogParserScriptId added in v0.6.3

func (e *ClaudeEngine) GetLogParserScriptId() string

GetLogParserScriptId returns the JavaScript script name for parsing Claude logs

func (*ClaudeEngine) ParseLogMetrics added in v0.0.22

func (e *ClaudeEngine) ParseLogMetrics(logContent string, verbose bool) LogMetrics

ParseLogMetrics implements engine-specific log parsing for Claude

func (*ClaudeEngine) RenderMCPConfig

func (e *ClaudeEngine) RenderMCPConfig(yaml *strings.Builder, tools map[string]any, mcpTools []string, workflowData *WorkflowData)

RenderMCPConfig renders the MCP configuration for Claude engine

type ClaudeSettings added in v0.2.3

type ClaudeSettings struct {
	Hooks *HookConfiguration `json:"hooks,omitempty"`
}

ClaudeSettings represents the structure of Claude Code settings.json

type ClaudeSettingsGenerator added in v0.2.3

type ClaudeSettingsGenerator struct{}

ClaudeSettingsGenerator generates Claude Code settings configurations

func (*ClaudeSettingsGenerator) GenerateSettingsJSON added in v0.2.3

func (g *ClaudeSettingsGenerator) GenerateSettingsJSON() string

GenerateSettingsJSON generates Claude Code settings JSON for network permissions

func (*ClaudeSettingsGenerator) GenerateSettingsWorkflowStep added in v0.2.3

func (g *ClaudeSettingsGenerator) GenerateSettingsWorkflowStep() GitHubActionStep

GenerateSettingsWorkflowStep generates a GitHub Actions workflow step that creates the settings file

type CloseDiscussionsConfig added in v0.30.2

type CloseDiscussionsConfig struct {
	BaseSafeOutputConfig             `yaml:",inline"`
	SafeOutputTargetConfig           `yaml:",inline"`
	SafeOutputDiscussionFilterConfig `yaml:",inline"`
}

CloseDiscussionsConfig holds configuration for closing GitHub discussions from agent output

type CloseIssuesConfig added in v0.30.5

type CloseIssuesConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	SafeOutputFilterConfig `yaml:",inline"`
}

CloseIssuesConfig holds configuration for closing GitHub issues from agent output

type CloseJobConfig added in v0.31.4

type CloseJobConfig struct {
	SafeOutputTargetConfig `yaml:",inline"`
	SafeOutputFilterConfig `yaml:",inline"`
}

CloseJobConfig represents common configuration for close operations (close-issue, close-discussion, close-pull-request)

func ParseCloseJobConfig added in v0.31.4

func ParseCloseJobConfig(configMap map[string]any) (CloseJobConfig, bool)

ParseCloseJobConfig parses common close job fields from a config map. Returns the parsed CloseJobConfig and a boolean indicating if there was a validation error.

type ClosePullRequestsConfig added in v0.30.5

type ClosePullRequestsConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	SafeOutputFilterConfig `yaml:",inline"`
}

ClosePullRequestsConfig holds configuration for closing GitHub pull requests from agent output

type CodexEngine

type CodexEngine struct {
	BaseEngine
}

CodexEngine represents the Codex agentic engine (experimental)

func NewCodexEngine

func NewCodexEngine() *CodexEngine

func (*CodexEngine) GetDeclaredOutputFiles added in v0.16.0

func (e *CodexEngine) GetDeclaredOutputFiles() []string

GetDeclaredOutputFiles returns the output files that Codex may produce Codex (written in Rust) writes logs to ~/.codex/log/codex-tui.log

func (*CodexEngine) GetErrorPatterns added in v0.6.0

func (e *CodexEngine) GetErrorPatterns() []ErrorPattern

GetErrorPatterns returns regex patterns for extracting error messages from Codex logs

func (*CodexEngine) GetExecutionSteps added in v0.5.0

func (e *CodexEngine) GetExecutionSteps(workflowData *WorkflowData, logFile string) []GitHubActionStep

GetExecutionSteps returns the GitHub Actions steps for executing Codex

func (*CodexEngine) GetInstallationSteps

func (e *CodexEngine) GetInstallationSteps(workflowData *WorkflowData) []GitHubActionStep

func (*CodexEngine) GetLogParserScriptId added in v0.6.3

func (e *CodexEngine) GetLogParserScriptId() string

GetLogParserScriptId returns the JavaScript script name for parsing Codex logs

func (*CodexEngine) ParseLogMetrics added in v0.0.22

func (e *CodexEngine) ParseLogMetrics(logContent string, verbose bool) LogMetrics

ParseLogMetrics implements engine-specific log parsing for Codex

func (*CodexEngine) RenderMCPConfig

func (e *CodexEngine) RenderMCPConfig(yaml *strings.Builder, tools map[string]any, mcpTools []string, workflowData *WorkflowData)

type CodingAgentEngine added in v0.5.0

type CodingAgentEngine interface {
	// GetID returns the unique identifier for this engine
	GetID() string

	// GetDisplayName returns the human-readable name for this engine
	GetDisplayName() string

	// GetDescription returns a description of this engine's capabilities
	GetDescription() string

	// IsExperimental returns true if this engine is experimental
	IsExperimental() bool

	// SupportsToolsAllowlist returns true if this engine supports MCP tool allow-listing
	SupportsToolsAllowlist() bool

	// SupportsHTTPTransport returns true if this engine supports HTTP transport for MCP servers
	SupportsHTTPTransport() bool

	// SupportsMaxTurns returns true if this engine supports the max-turns feature
	SupportsMaxTurns() bool

	// SupportsWebFetch returns true if this engine has built-in support for the web-fetch tool
	SupportsWebFetch() bool

	// SupportsWebSearch returns true if this engine has built-in support for the web-search tool
	SupportsWebSearch() bool

	// SupportsFirewall returns true if this engine supports network firewalling/sandboxing
	// When true, the engine can enforce network restrictions defined in the workflow
	SupportsFirewall() bool

	// GetDeclaredOutputFiles returns a list of output files that this engine may produce
	// These files will be automatically uploaded as artifacts if they exist
	GetDeclaredOutputFiles() []string

	// GetInstallationSteps returns the GitHub Actions steps needed to install this engine
	GetInstallationSteps(workflowData *WorkflowData) []GitHubActionStep

	// GetExecutionSteps returns the GitHub Actions steps for executing this engine
	GetExecutionSteps(workflowData *WorkflowData, logFile string) []GitHubActionStep

	// RenderMCPConfig renders the MCP configuration for this engine to the given YAML builder
	RenderMCPConfig(yaml *strings.Builder, tools map[string]any, mcpTools []string, workflowData *WorkflowData)

	// ParseLogMetrics extracts metrics from engine-specific log content
	ParseLogMetrics(logContent string, verbose bool) LogMetrics

	// GetLogParserScriptId returns the name of the JavaScript script to parse logs for this engine
	GetLogParserScriptId() string

	// GetLogFileForParsing returns the log file path to use for JavaScript parsing in the workflow
	// This may be different from the stdout/stderr log file if the engine produces separate detailed logs
	GetLogFileForParsing() string

	// GetErrorPatterns returns regex patterns for extracting error messages from logs
	GetErrorPatterns() []ErrorPattern

	// GetDefaultDetectionModel returns the default model to use for threat detection
	// If empty, no default model is applied and the engine uses its standard default
	GetDefaultDetectionModel() string
}

CodingAgentEngine represents an AI coding agent that can be used as an engine to execute agentic workflows

type CommentEventMapping added in v0.13.1

type CommentEventMapping struct {
	EventName      string   // GitHub Actions event name (e.g., "issues", "issue_comment")
	Types          []string // Event types (e.g., ["opened", "edited", "reopened"])
	IsPRComment    bool     // True if this is pull_request_comment (issue_comment on PRs only)
	IsIssueComment bool     // True if this is issue_comment (issue_comment on issues only)
}

CommentEventMapping defines the mapping between event identifiers and their GitHub Actions event configurations

func FilterCommentEvents added in v0.13.1

func FilterCommentEvents(identifiers []string) []CommentEventMapping

FilterCommentEvents returns only the comment events specified by the identifiers If identifiers is nil or empty, returns all comment events

func GetAllCommentEvents added in v0.13.1

func GetAllCommentEvents() []CommentEventMapping

GetAllCommentEvents returns all possible comment-related events for command triggers

func GetCommentEventByIdentifier added in v0.13.1

func GetCommentEventByIdentifier(identifier string) *CommentEventMapping

GetCommentEventByIdentifier returns the event mapping for a given identifier Uses GitHub Actions event names (e.g., "issues", "issue_comment", "pull_request_comment", "pull_request", "pull_request_review_comment")

func MergeEventsForYAML added in v0.13.1

func MergeEventsForYAML(mappings []CommentEventMapping) []CommentEventMapping

MergeEventsForYAML merges comment events for YAML generation, combining pull_request_comment and issue_comment

type ComparisonNode

type ComparisonNode struct {
	Left     ConditionNode
	Operator string
	Right    ConditionNode
}

ComparisonNode represents comparison operations like ==, !=, <, >, <=, >=

func BuildActionEquals

func BuildActionEquals(action string) *ComparisonNode

BuildActionEquals creates a condition to check if the event action equals a specific value

func BuildComparison

func BuildComparison(left ConditionNode, operator string, right ConditionNode) *ComparisonNode

BuildComparison creates a comparison node with the specified operator

func BuildEquals

func BuildEquals(left ConditionNode, right ConditionNode) *ComparisonNode

BuildEquals creates an equality comparison

func BuildEventTypeEquals

func BuildEventTypeEquals(eventType string) *ComparisonNode

BuildEventTypeEquals creates a condition to check if the event type equals a specific value

func BuildNotEquals

func BuildNotEquals(left ConditionNode, right ConditionNode) *ComparisonNode

BuildNotEquals creates an inequality comparison

func BuildNotFromFork added in v0.4.0

func BuildNotFromFork() *ComparisonNode

BuildNotFromFork creates a condition to check that a pull request is not from a forked repository This prevents the job from running on forked PRs where write permissions are not available Uses repository ID comparison instead of full name for more reliable matching

func (*ComparisonNode) Render

func (c *ComparisonNode) Render() string

type Compiler

type Compiler struct {
	// contains filtered or unexported fields
}

Compiler handles converting markdown workflows to GitHub Actions YAML

func NewCompiler

func NewCompiler(verbose bool, engineOverride string, version string) *Compiler

NewCompiler creates a new workflow compiler with optional configuration

func NewCompilerWithCustomOutput

func NewCompilerWithCustomOutput(verbose bool, engineOverride string, customOutput string, version string) *Compiler

NewCompilerWithCustomOutput creates a new workflow compiler with custom output path

func (*Compiler) CompileWorkflow

func (c *Compiler) CompileWorkflow(markdownPath string) error

CompileWorkflow converts a markdown workflow to GitHub Actions YAML

func (*Compiler) CompileWorkflowData added in v0.25.0

func (c *Compiler) CompileWorkflowData(workflowData *WorkflowData, markdownPath string) error

CompileWorkflowData compiles a workflow from already-parsed WorkflowData This avoids re-parsing when the data has already been parsed

func (*Compiler) ExtractEngineConfig added in v0.14.0

func (c *Compiler) ExtractEngineConfig(frontmatter map[string]any) (string, *EngineConfig)

ExtractEngineConfig extracts engine configuration from frontmatter, supporting both string and object formats

func (*Compiler) GenerateDependabotManifests added in v0.25.0

func (c *Compiler) GenerateDependabotManifests(workflowDataList []*WorkflowData, workflowDir string, forceOverwrite bool) error

GenerateDependabotManifests generates manifest files and dependabot.yml for detected dependencies

func (*Compiler) GetSharedActionCache added in v0.28.7

func (c *Compiler) GetSharedActionCache() *ActionCache

GetSharedActionCache returns the shared action cache used by this compiler instance. The cache is lazily initialized on first access and shared across all workflows. This allows action SHA validation and other operations to reuse cached resolutions.

func (*Compiler) GetWarningCount added in v0.22.0

func (c *Compiler) GetWarningCount() int

GetWarningCount returns the current warning count

func (*Compiler) IncrementWarningCount added in v0.22.0

func (c *Compiler) IncrementWarningCount()

IncrementWarningCount increments the warning counter

func (*Compiler) MergeMCPServers added in v0.16.0

func (c *Compiler) MergeMCPServers(topMCPServers map[string]any, importedMCPServersJSON string) (map[string]any, error)

MergeMCPServers merges mcp-servers from imports with top-level mcp-servers Takes object maps and merges them directly

func (*Compiler) MergeNetworkPermissions added in v0.25.0

func (c *Compiler) MergeNetworkPermissions(topNetwork *NetworkPermissions, importedNetworkJSON string) (*NetworkPermissions, error)

MergeNetworkPermissions merges network permissions from imports with top-level network permissions Combines allowed domains from both sources into a single list

func (*Compiler) MergeSafeOutputs added in v0.31.3

func (c *Compiler) MergeSafeOutputs(topSafeOutputs *SafeOutputsConfig, importedSafeOutputsJSON []string) (*SafeOutputsConfig, error)

MergeSafeOutputs merges safe-outputs configurations from imports into the top-level safe-outputs Returns an error if a conflict is detected (same safe-output type defined in both main and imported)

func (*Compiler) MergeSecretMasking added in v0.28.0

func (c *Compiler) MergeSecretMasking(topConfig *SecretMaskingConfig, importedSecretMaskingJSON string) (*SecretMaskingConfig, error)

MergeSecretMasking merges secret-masking configurations from imports with top-level config

func (*Compiler) MergeTools added in v0.16.0

func (c *Compiler) MergeTools(topTools map[string]any, includedToolsJSON string) (map[string]any, error)

MergeTools merges two tools maps, combining allowed arrays when keys coincide Handles newline-separated JSON objects from multiple imports/includes

func (*Compiler) ParseWorkflowFile added in v0.12.0

func (c *Compiler) ParseWorkflowFile(markdownPath string) (*WorkflowData, error)

ParseWorkflowFile parses a markdown workflow file and extracts all necessary data

func (*Compiler) ResetWarningCount added in v0.22.0

func (c *Compiler) ResetWarningCount()

ResetWarningCount resets the warning counter to zero

func (*Compiler) SetFileTracker added in v0.0.22

func (c *Compiler) SetFileTracker(tracker FileTracker)

Sets the file tracker for tracking created files

func (*Compiler) SetNoEmit added in v0.5.1

func (c *Compiler) SetNoEmit(noEmit bool)

Configures whether to validate without generating lock files

func (*Compiler) SetRefreshStopTime added in v0.29.0

func (c *Compiler) SetRefreshStopTime(refresh bool)

Configures whether to force regeneration of stop-after times

func (*Compiler) SetSkipValidation

func (c *Compiler) SetSkipValidation(skip bool)

Configures whether to skip schema validation

func (*Compiler) SetStrictMode added in v0.12.1

func (c *Compiler) SetStrictMode(strict bool)

Configures whether to enable strict validation mode

func (*Compiler) SetTrialLogicalRepoSlug added in v0.16.0

func (c *Compiler) SetTrialLogicalRepoSlug(repo string)

Configures the target repository for trial mode

func (*Compiler) SetTrialMode added in v0.12.0

func (c *Compiler) SetTrialMode(trialMode bool)

Configures whether to run in trial mode (suppresses safe outputs)

func (*Compiler) ValidateIncludedPermissions added in v0.28.7

func (c *Compiler) ValidateIncludedPermissions(topPermissionsYAML string, importedPermissionsJSON string) error

ValidateIncludedPermissions validates that the main workflow permissions satisfy the imported workflow requirements This function is specifically used when merging included/imported workflow files to ensure the main workflow has sufficient permissions to support the requirements from all imported files. Takes the top-level permissions YAML string and imported permissions JSON string Returns an error if the main workflow permissions are insufficient

Use ValidatePermissions (in permissions_validator.go) for general permission validation against GitHub MCP toolsets. Use ValidateIncludedPermissions (this function) when validating permissions from included/imported workflow files.

type ConditionNode

type ConditionNode interface {
	Render() string
}

ConditionNode represents a node in a condition expression tree

func BuildFromAllowedForks added in v0.4.0

func BuildFromAllowedForks(allowedForks []string) ConditionNode

BuildFromAllowedForks creates a condition to check if a pull request is from an allowed fork Supports glob patterns like "org/*" and exact matches like "org/repo"

func BuildPRCommentCondition added in v0.12.1

func BuildPRCommentCondition() ConditionNode

BuildPRCommentCondition creates a condition to check if the event is a comment on a pull request This checks for: - issue_comment on a PR (github.event.issue.pull_request != null) - pull_request_review_comment - pull_request_review

func BuildSafeOutputType added in v0.10.0

func BuildSafeOutputType(outputType string) ConditionNode

func ParseExpression added in v0.5.1

func ParseExpression(expression string) (ConditionNode, error)

ParseExpression parses a string expression into a ConditionNode tree Supports && (AND), || (OR), ! (NOT), and parentheses for grouping Example: "condition1 && (condition2 || !condition3)"

type ContainsNode

type ContainsNode struct {
	Array ConditionNode
	Value ConditionNode
}

ContainsNode represents array membership checks using contains() function

func BuildContains

func BuildContains(array ConditionNode, value ConditionNode) *ContainsNode

BuildContains creates a contains() function call node

func BuildLabelContains

func BuildLabelContains(labelName string) *ContainsNode

BuildLabelContains creates a condition to check if an issue/PR contains a specific label

func (*ContainsNode) Render

func (c *ContainsNode) Render() string

type CopilotEngine added in v0.9.0

type CopilotEngine struct {
	BaseEngine
}

CopilotEngine represents the GitHub Copilot CLI agentic engine

func NewCopilotEngine added in v0.9.0

func NewCopilotEngine() *CopilotEngine

func (*CopilotEngine) GetCleanupStep added in v0.24.0

func (e *CopilotEngine) GetCleanupStep(workflowData *WorkflowData) GitHubActionStep

GetCleanupStep returns the post-execution cleanup step

func (*CopilotEngine) GetDeclaredOutputFiles added in v0.9.0

func (e *CopilotEngine) GetDeclaredOutputFiles() []string

func (*CopilotEngine) GetDefaultDetectionModel added in v0.31.4

func (e *CopilotEngine) GetDefaultDetectionModel() string

GetDefaultDetectionModel returns the default model for threat detection Uses gpt-5-mini as a cost-effective model for detection tasks

func (*CopilotEngine) GetErrorPatterns added in v0.9.0

func (e *CopilotEngine) GetErrorPatterns() []ErrorPattern

GetErrorPatterns returns regex patterns for extracting error messages from Copilot CLI logs

func (*CopilotEngine) GetExecutionSteps added in v0.9.0

func (e *CopilotEngine) GetExecutionSteps(workflowData *WorkflowData, logFile string) []GitHubActionStep

GetExecutionSteps returns the GitHub Actions steps for executing GitHub Copilot CLI

func (*CopilotEngine) GetFirewallLogsCollectionStep added in v0.31.4

func (e *CopilotEngine) GetFirewallLogsCollectionStep(workflowData *WorkflowData) []GitHubActionStep

GetFirewallLogsCollectionStep returns the step for collecting firewall logs (before secret redaction) No longer needed since we know where the logs are in the sandbox folder structure

func (*CopilotEngine) GetInstallationSteps added in v0.9.0

func (e *CopilotEngine) GetInstallationSteps(workflowData *WorkflowData) []GitHubActionStep

func (*CopilotEngine) GetLogFileForParsing added in v0.16.0

func (e *CopilotEngine) GetLogFileForParsing() string

GetLogFileForParsing returns the log directory for Copilot CLI logs Copilot writes detailed debug logs to /tmp/gh-aw/.copilot/logs/ which should be parsed instead of the agent-stdio.log file

func (*CopilotEngine) GetLogParserScriptId added in v0.9.0

func (e *CopilotEngine) GetLogParserScriptId() string

GetLogParserScript returns the JavaScript script name for parsing Copilot logs

func (*CopilotEngine) GetSquidLogsSteps added in v0.24.0

func (e *CopilotEngine) GetSquidLogsSteps(workflowData *WorkflowData) []GitHubActionStep

GetSquidLogsSteps returns the steps for uploading and parsing Squid logs (after secret redaction)

func (*CopilotEngine) ParseLogMetrics added in v0.9.0

func (e *CopilotEngine) ParseLogMetrics(logContent string, verbose bool) LogMetrics

ParseLogMetrics implements engine-specific log parsing for Copilot CLI

func (*CopilotEngine) RenderMCPConfig added in v0.9.0

func (e *CopilotEngine) RenderMCPConfig(yaml *strings.Builder, tools map[string]any, mcpTools []string, workflowData *WorkflowData)

type CopilotParticipantConfig added in v0.26.0

type CopilotParticipantConfig struct {
	// Participants is the list of users/bots to assign/review
	Participants []string
	// ParticipantType is either "assignee" or "reviewer"
	ParticipantType string
	// CustomToken is the custom GitHub token from the safe output config
	CustomToken string
	// SafeOutputsToken is the GitHub token from the safe-outputs config
	SafeOutputsToken string
	// WorkflowToken is the top-level GitHub token from the workflow
	WorkflowToken string
	// ConditionStepID is the step ID to check for output (e.g., "create_issue", "create_pull_request")
	ConditionStepID string
	// ConditionOutputKey is the output key to check (e.g., "issue_number", "pull_request_url")
	ConditionOutputKey string
}

CopilotParticipantConfig holds configuration for generating Copilot participant steps

type CreateAgentTaskConfig added in v0.23.0

type CreateAgentTaskConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	Base                 string `yaml:"base,omitempty"`        // Base branch for the pull request
	TargetRepoSlug       string `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository agent tasks
}

CreateAgentTaskConfig holds configuration for creating GitHub Copilot agent tasks from agent output

type CreateCodeScanningAlertsConfig added in v0.6.0

type CreateCodeScanningAlertsConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	Driver               string `yaml:"driver,omitempty"` // Driver name for SARIF tool.driver.name field (default: "GitHub Agentic Workflows Security Scanner")
}

CreateCodeScanningAlertsConfig holds configuration for creating repository security advisories (SARIF format) from agent output

type CreateDiscussionsConfig added in v0.4.0

type CreateDiscussionsConfig struct {
	BaseSafeOutputConfig  `yaml:",inline"`
	TitlePrefix           string   `yaml:"title-prefix,omitempty"`
	Category              string   `yaml:"category,omitempty"`                // Discussion category ID or name
	Labels                []string `yaml:"labels,omitempty"`                  // Labels to attach to discussions and match when closing older ones
	AllowedLabels         []string `yaml:"allowed-labels,omitempty"`          // Optional list of allowed labels. If omitted, any labels are allowed (including creating new ones).
	TargetRepoSlug        string   `yaml:"target-repo,omitempty"`             // Target repository in format "owner/repo" for cross-repository discussions
	AllowedRepos          []string `yaml:"allowed-repos,omitempty"`           // List of additional repositories that discussions can be created in
	CloseOlderDiscussions bool     `yaml:"close-older-discussions,omitempty"` // When true, close older discussions with same title prefix or labels as outdated
}

CreateDiscussionsConfig holds configuration for creating GitHub discussions from agent output

type CreateIssuesConfig added in v0.2.11

type CreateIssuesConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	TitlePrefix          string   `yaml:"title-prefix,omitempty"`
	Labels               []string `yaml:"labels,omitempty"`
	AllowedLabels        []string `yaml:"allowed-labels,omitempty"` // Optional list of allowed labels. If omitted, any labels are allowed (including creating new ones).
	Assignees            []string `yaml:"assignees,omitempty"`      // List of users/bots to assign the issue to
	TargetRepoSlug       string   `yaml:"target-repo,omitempty"`    // Target repository in format "owner/repo" for cross-repository issues
	AllowedRepos         []string `yaml:"allowed-repos,omitempty"`  // List of additional repositories that issues can be created in
}

CreateIssuesConfig holds configuration for creating GitHub issues from agent output

type CreatePullRequestReviewCommentsConfig added in v0.4.0

type CreatePullRequestReviewCommentsConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	Side                 string `yaml:"side,omitempty"`        // Side of the diff: "LEFT" or "RIGHT" (default: "RIGHT")
	Target               string `yaml:"target,omitempty"`      // Target for comments: "triggering" (default), "*" (any PR), or explicit PR number
	TargetRepoSlug       string `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository PR review comments
}

CreatePullRequestReviewCommentsConfig holds configuration for creating GitHub pull request review comments from agent output

type CreatePullRequestsConfig added in v0.2.11

type CreatePullRequestsConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	TitlePrefix          string   `yaml:"title-prefix,omitempty"`
	Labels               []string `yaml:"labels,omitempty"`
	AllowedLabels        []string `yaml:"allowed-labels,omitempty"` // Optional list of allowed labels. If omitted, any labels are allowed (including creating new ones).
	Reviewers            []string `yaml:"reviewers,omitempty"`      // List of users/bots to assign as reviewers to the pull request
	Draft                *bool    `yaml:"draft,omitempty"`          // Pointer to distinguish between unset (nil) and explicitly false
	IfNoChanges          string   `yaml:"if-no-changes,omitempty"`  // Behavior when no changes to push: "warn" (default), "error", or "ignore"
	TargetRepoSlug       string   `yaml:"target-repo,omitempty"`    // Target repository in format "owner/repo" for cross-repository pull requests
}

CreatePullRequestsConfig holds configuration for creating GitHub pull requests from agent output

type CustomEngine added in v0.5.0

type CustomEngine struct {
	BaseEngine
}

CustomEngine represents a custom agentic engine that executes user-defined GitHub Actions steps

func NewCustomEngine added in v0.5.0

func NewCustomEngine() *CustomEngine

NewCustomEngine creates a new CustomEngine instance

func (*CustomEngine) GetExecutionSteps added in v0.5.0

func (e *CustomEngine) GetExecutionSteps(workflowData *WorkflowData, logFile string) []GitHubActionStep

GetExecutionSteps returns the GitHub Actions steps for executing custom steps

func (*CustomEngine) GetInstallationSteps added in v0.5.0

func (e *CustomEngine) GetInstallationSteps(workflowData *WorkflowData) []GitHubActionStep

GetInstallationSteps returns empty installation steps since custom engine doesn't need installation

func (*CustomEngine) GetLogParserScriptId added in v0.6.3

func (e *CustomEngine) GetLogParserScriptId() string

GetLogParserScriptId returns the JavaScript script name for parsing custom engine logs

func (*CustomEngine) ParseLogMetrics added in v0.5.0

func (e *CustomEngine) ParseLogMetrics(logContent string, verbose bool) LogMetrics

ParseLogMetrics implements basic log parsing for custom engine For custom engines, try both Claude and Codex parsing approaches to extract turn information

func (*CustomEngine) RenderMCPConfig added in v0.5.0

func (e *CustomEngine) RenderMCPConfig(yaml *strings.Builder, tools map[string]any, mcpTools []string, workflowData *WorkflowData)

RenderMCPConfig renders MCP configuration using unified renderer

type DependabotConfig added in v0.25.0

type DependabotConfig struct {
	Version int                     `yaml:"version"`
	Updates []DependabotUpdateEntry `yaml:"updates"`
}

DependabotConfig represents the structure of .github/dependabot.yml

type DependabotUpdateEntry added in v0.25.0

type DependabotUpdateEntry struct {
	PackageEcosystem string `yaml:"package-ecosystem"`
	Directory        string `yaml:"directory"`
	Schedule         struct {
		Interval string `yaml:"interval"`
	} `yaml:"schedule"`
}

DependabotUpdateEntry represents a single update configuration in dependabot.yml

type DisjunctionNode

type DisjunctionNode struct {
	Terms     []ConditionNode
	Multiline bool // If true, render each term on separate line with comments
}

DisjunctionNode represents an OR operation with multiple terms to avoid deep nesting

func BuildDisjunction added in v0.13.1

func BuildDisjunction(multiline bool, terms ...ConditionNode) *DisjunctionNode

BuildDisjunction creates a disjunction node (OR operation) from the given terms Handles arrays of size 0, 1, or more correctly The multiline parameter controls whether to render each term on a separate line

func (*DisjunctionNode) Render

func (d *DisjunctionNode) Render() string

func (*DisjunctionNode) RenderMultiline

func (d *DisjunctionNode) RenderMultiline() string

RenderMultiline renders the disjunction with each term on a separate line, including comments for expressions that have descriptions

type EditToolConfig added in v0.22.9

type EditToolConfig struct {
}

EditToolConfig represents the configuration for the edit tool

type EngineConfig

type EngineConfig struct {
	ID            string
	Version       string
	Model         string
	MaxTurns      string
	Concurrency   string // Agent job-level concurrency configuration (YAML format)
	UserAgent     string
	Env           map[string]string
	Steps         []map[string]any
	ErrorPatterns []ErrorPattern
	Config        string
	Args          []string
	Firewall      *FirewallConfig // AWF firewall configuration
}

EngineConfig represents the parsed engine configuration

type EngineInstallConfig added in v0.31.4

type EngineInstallConfig struct {
	// Secrets is a list of secret names to validate (at least one must be set)
	Secrets []string
	// DocsURL is the documentation URL shown when secret validation fails
	DocsURL string
	// NpmPackage is the npm package name (e.g., "@github/copilot")
	NpmPackage string
	// Version is the default version of the npm package
	Version string
	// Name is the engine display name for secret validation messages (e.g., "Claude Code")
	Name string
	// CliName is the CLI name used for cache key prefix (e.g., "copilot")
	CliName string
	// InstallStepName is the display name for the npm install step (e.g., "Install Claude Code CLI")
	InstallStepName string
}

EngineInstallConfig contains configuration for engine installation steps. This struct centralizes the configuration needed to generate the common installation steps shared by all engines (secret validation and npm installation).

type EngineNetworkConfig added in v0.3.4

type EngineNetworkConfig struct {
	Engine  *EngineConfig
	Network *NetworkPermissions
}

EngineNetworkConfig combines engine configuration with top-level network permissions

type EngineRegistry

type EngineRegistry struct {
	// contains filtered or unexported fields
}

EngineRegistry manages available agentic engines

func GetGlobalEngineRegistry added in v0.0.22

func GetGlobalEngineRegistry() *EngineRegistry

GetGlobalEngineRegistry returns the singleton engine registry

func NewEngineRegistry

func NewEngineRegistry() *EngineRegistry

NewEngineRegistry creates a new engine registry with built-in engines

func (*EngineRegistry) GetAllEngines added in v0.0.22

func (r *EngineRegistry) GetAllEngines() []CodingAgentEngine

GetAllEngines returns all registered engines

func (*EngineRegistry) GetDefaultEngine

func (r *EngineRegistry) GetDefaultEngine() CodingAgentEngine

GetDefaultEngine returns the default engine (Copilot)

func (*EngineRegistry) GetEngine

func (r *EngineRegistry) GetEngine(id string) (CodingAgentEngine, error)

GetEngine retrieves an engine by ID

func (*EngineRegistry) GetEngineByPrefix

func (r *EngineRegistry) GetEngineByPrefix(prefix string) (CodingAgentEngine, error)

GetEngineByPrefix returns an engine that matches the given prefix This is useful for backward compatibility with strings like "codex-experimental"

func (*EngineRegistry) GetSupportedEngines

func (r *EngineRegistry) GetSupportedEngines() []string

GetSupportedEngines returns a list of all supported engine IDs

func (*EngineRegistry) IsValidEngine

func (r *EngineRegistry) IsValidEngine(id string) bool

IsValidEngine checks if an engine ID is valid

func (*EngineRegistry) Register

func (r *EngineRegistry) Register(engine CodingAgentEngine)

Register adds an engine to the registry

type ErrorPattern added in v0.6.0

type ErrorPattern struct {
	// ID is a unique identifier for this error pattern
	ID string `json:"id"`
	// Pattern is the regular expression to match log lines
	Pattern string `json:"pattern"`
	// LevelGroup is the capture group index (1-based) that contains the error level (error, warning, etc.)
	// If 0, the level will be inferred from the pattern name or content
	LevelGroup int `json:"level_group"`
	// MessageGroup is the capture group index (1-based) that contains the error message
	// If 0, the entire match will be used as the message
	MessageGroup int `json:"message_group"`
	// Description is a human-readable description of what this pattern matches
	Description string `json:"description"`
	// Severity explicitly sets the level for this pattern, overriding inference
	// Valid values: "error", "warning", or empty string (use inference)
	Severity string `json:"severity,omitempty"`
}

ErrorPattern represents a regex pattern for extracting error information from logs

func GetCommonErrorPatterns added in v0.21.0

func GetCommonErrorPatterns() []ErrorPattern

GetCommonErrorPatterns returns error patterns that are common across all engines. These patterns detect standard GitHub Actions workflow commands and other universal error formats.

type ExpressionExtractor added in v0.28.0

type ExpressionExtractor struct {
	// contains filtered or unexported fields
}

ExpressionExtractor extracts GitHub Actions expressions from markdown content and creates environment variable mappings for them

func NewExpressionExtractor added in v0.28.0

func NewExpressionExtractor() *ExpressionExtractor

NewExpressionExtractor creates a new ExpressionExtractor

func (*ExpressionExtractor) ExtractExpressions added in v0.28.0

func (e *ExpressionExtractor) ExtractExpressions(markdown string) ([]*ExpressionMapping, error)

ExtractExpressions extracts all ${{ ... }} expressions from the markdown content and creates environment variable mappings for each unique expression

func (*ExpressionExtractor) GetMappings added in v0.28.0

func (e *ExpressionExtractor) GetMappings() []*ExpressionMapping

GetMappings returns all expression mappings

func (*ExpressionExtractor) ReplaceExpressionsWithEnvVars added in v0.28.0

func (e *ExpressionExtractor) ReplaceExpressionsWithEnvVars(markdown string) string

ReplaceExpressionsWithEnvVars replaces all ${{ ... }} expressions in the markdown with references to their corresponding environment variables

type ExpressionMapping added in v0.28.0

type ExpressionMapping struct {
	Original string // The original ${{ ... }} expression
	EnvVar   string // The GH_AW_ prefixed environment variable name
	Content  string // The expression content without ${{ }}
}

ExpressionMapping represents a mapping between a GitHub expression and its environment variable

type ExpressionNode

type ExpressionNode struct {
	Expression  string
	Description string // Optional comment/description for the expression
}

ExpressionNode represents a leaf expression

func BuildExpressionWithDescription

func BuildExpressionWithDescription(expression, description string) *ExpressionNode

BuildExpressionWithDescription creates an expression node with an optional description

func BuildNullLiteral added in v0.13.1

func BuildNullLiteral() *ExpressionNode

BuildNullLiteral creates a null literal node

func (*ExpressionNode) Render

func (e *ExpressionNode) Render() string

type ExpressionParser added in v0.5.1

type ExpressionParser struct {
	// contains filtered or unexported fields
}

ExpressionParser handles parsing of expression strings into ConditionNode trees

type FieldValidation added in v0.31.4

type FieldValidation struct {
	Required                 bool     `json:"required,omitempty"`
	Type                     string   `json:"type,omitempty"`
	Sanitize                 bool     `json:"sanitize,omitempty"`
	MaxLength                int      `json:"maxLength,omitempty"`
	PositiveInteger          bool     `json:"positiveInteger,omitempty"`
	OptionalPositiveInteger  bool     `json:"optionalPositiveInteger,omitempty"`
	IssueOrPRNumber          bool     `json:"issueOrPRNumber,omitempty"`
	IssueNumberOrTemporaryID bool     `json:"issueNumberOrTemporaryId,omitempty"`
	Enum                     []string `json:"enum,omitempty"`
	ItemType                 string   `json:"itemType,omitempty"`
	ItemSanitize             bool     `json:"itemSanitize,omitempty"`
	ItemMaxLength            int      `json:"itemMaxLength,omitempty"`
	Pattern                  string   `json:"pattern,omitempty"`
	PatternError             string   `json:"patternError,omitempty"`
	TemporaryID              bool     `json:"temporaryId,omitempty"`
}

FieldValidation defines validation rules for a single field

type FileTracker added in v0.0.22

type FileTracker interface {
	TrackCreated(filePath string)
}

FileTracker interface for tracking files created during compilation

type FirewallConfig added in v0.24.0

type FirewallConfig struct {
	Enabled       bool     `yaml:"enabled,omitempty"`        // Enable/disable AWF (default: true for copilot when network restrictions present)
	Version       string   `yaml:"version,omitempty"`        // AWF version (empty = latest)
	Args          []string `yaml:"args,omitempty"`           // Additional arguments to pass to AWF
	LogLevel      string   `yaml:"log_level,omitempty"`      // AWF log level (default: "info")
	CleanupScript string   `yaml:"cleanup_script,omitempty"` // Cleanup script path (default: "./scripts/ci/cleanup.sh")
}

FirewallConfig represents AWF (gh-aw-firewall) configuration for network egress control

type FunctionCallNode

type FunctionCallNode struct {
	FunctionName string
	Arguments    []ConditionNode
}

FunctionCallNode represents a function call expression like contains(array, value)

func BuildFunctionCall

func BuildFunctionCall(functionName string, args ...ConditionNode) *FunctionCallNode

BuildFunctionCall creates a function call node

func BuildRefStartsWith

func BuildRefStartsWith(prefix string) *FunctionCallNode

BuildRefStartsWith creates a condition to check if github.ref starts with a prefix

func (*FunctionCallNode) Render

func (f *FunctionCallNode) Render() string

type GitHubActionStep

type GitHubActionStep []string

GitHubActionStep represents the YAML lines for a single step in a GitHub Actions workflow

func BuildStandardNpmEngineInstallSteps added in v0.21.0

func BuildStandardNpmEngineInstallSteps(
	packageName string,
	defaultVersion string,
	stepName string,
	cacheKeyPrefix string,
	workflowData *WorkflowData,
) []GitHubActionStep

BuildStandardNpmEngineInstallSteps creates standard npm installation steps for engines This helper extracts the common pattern shared by Copilot, Codex, and Claude engines.

Parameters:

  • packageName: The npm package name (e.g., "@github/copilot")
  • defaultVersion: The default version constant (e.g., constants.DefaultCopilotVersion)
  • stepName: The display name for the install step (e.g., "Install GitHub Copilot CLI")
  • cacheKeyPrefix: The cache key prefix (e.g., "copilot")
  • workflowData: The workflow data containing engine configuration

Returns:

  • []GitHubActionStep: The installation steps including Node.js setup

func GenerateMultiSecretValidationStep added in v0.22.0

func GenerateMultiSecretValidationStep(secretNames []string, engineName, docsURL string) GitHubActionStep

GenerateMultiSecretValidationStep creates a GitHub Actions step that validates at least one of multiple secrets is available secretNames: slice of secret names to validate (e.g., []string{"CODEX_API_KEY", "OPENAI_API_KEY"}) engineName: the display name of the engine (e.g., "Codex") docsURL: URL to the documentation page for setting up the secret

func GenerateNodeJsSetupStep added in v0.14.0

func GenerateNodeJsSetupStep() GitHubActionStep

GenerateNodeJsSetupStep creates a GitHub Actions step for setting up Node.js Returns a step that installs Node.js v24 Caching is disabled by default to prevent cache poisoning vulnerabilities in release workflows

func GenerateNpmInstallSteps added in v0.14.0

func GenerateNpmInstallSteps(packageName, version, stepName, cacheKeyPrefix string, includeNodeSetup bool) []GitHubActionStep

GenerateNpmInstallSteps creates GitHub Actions steps for installing an npm package globally Parameters:

  • packageName: The npm package name (e.g., "@anthropic-ai/claude-code")
  • version: The package version to install
  • stepName: The name to display for the install step (e.g., "Install Claude Code CLI")
  • cacheKeyPrefix: The prefix for the cache key (unused, kept for API compatibility)
  • includeNodeSetup: If true, includes Node.js setup step before npm install

Returns steps for installing the npm package (optionally with Node.js setup)

func GenerateNpmInstallStepsWithScope added in v0.31.4

func GenerateNpmInstallStepsWithScope(packageName, version, stepName, cacheKeyPrefix string, includeNodeSetup bool, isGlobal bool) []GitHubActionStep

GenerateNpmInstallStepsWithScope generates npm installation steps with control over global vs local installation

func GenerateRuntimeSetupSteps added in v0.16.0

func GenerateRuntimeSetupSteps(requirements []RuntimeRequirement) []GitHubActionStep

GenerateRuntimeSetupSteps creates GitHub Actions steps for runtime setup

func GenerateSecretValidationStep added in v0.22.0

func GenerateSecretValidationStep(secretName, engineName, docsURL string) GitHubActionStep

GenerateSecretValidationStep creates a GitHub Actions step that validates required secrets are available secretName: the name of the secret to validate (e.g., "ANTHROPIC_API_KEY") engineName: the display name of the engine (e.g., "Claude Code") docsURL: URL to the documentation page for setting up the secret

func GenerateSerenaLanguageServiceSteps added in v0.30.5

func GenerateSerenaLanguageServiceSteps(tools map[string]any) []GitHubActionStep

GenerateSerenaLanguageServiceSteps creates installation steps for Serena language services This is called after runtime detection to install the language servers needed by Serena

func GetBaseInstallationSteps added in v0.31.4

func GetBaseInstallationSteps(config EngineInstallConfig, workflowData *WorkflowData) []GitHubActionStep

GetBaseInstallationSteps returns the common installation steps for an engine. This includes secret validation and npm package installation steps that are shared across all engines.

Parameters:

  • config: Engine-specific configuration for installation
  • workflowData: The workflow data containing engine configuration

Returns:

  • []GitHubActionStep: The base installation steps (secret validation + npm install)

func InjectCustomEngineSteps added in v0.22.4

func InjectCustomEngineSteps(
	workflowData *WorkflowData,
	convertStepFunc func(map[string]any) (string, error),
) []GitHubActionStep

InjectCustomEngineSteps processes custom steps from engine config and converts them to GitHubActionSteps. This shared function extracts the common pattern used by Copilot, Codex, and Claude engines.

Parameters:

  • workflowData: The workflow data containing engine configuration
  • convertStepFunc: A function that converts a step map to YAML string (engine-specific)

Returns:

  • []GitHubActionStep: Array of custom steps ready to be included in the execution pipeline

type GitHubAppConfig added in v0.30.2

type GitHubAppConfig struct {
	AppID        string   `yaml:"app-id,omitempty"`       // GitHub App ID (e.g., "${{ vars.APP_ID }}")
	PrivateKey   string   `yaml:"private-key,omitempty"`  // GitHub App private key (e.g., "${{ secrets.APP_PRIVATE_KEY }}")
	Owner        string   `yaml:"owner,omitempty"`        // Optional: owner of the GitHub App installation (defaults to current repository owner)
	Repositories []string `yaml:"repositories,omitempty"` // Optional: comma or newline-separated list of repositories to grant access to
}

GitHubAppConfig holds configuration for GitHub App-based token minting

type GitHubMCPDockerOptions added in v0.24.0

type GitHubMCPDockerOptions struct {
	// ReadOnly enables read-only mode for GitHub API operations
	ReadOnly bool
	// Lockdown enables lockdown mode for GitHub MCP server (limits content from public repos)
	Lockdown bool
	// Toolsets specifies the GitHub toolsets to enable
	Toolsets string
	// DockerImageVersion specifies the GitHub MCP server Docker image version
	DockerImageVersion string
	// CustomArgs are additional arguments to append to the Docker command
	CustomArgs []string
	// IncludeTypeField indicates whether to include the "type": "local" field (Copilot needs it, Claude doesn't)
	IncludeTypeField bool
	// AllowedTools specifies the list of allowed tools (Copilot uses this, Claude doesn't)
	AllowedTools []string
	// EffectiveToken is the GitHub token to use (Claude uses this, Copilot uses env passthrough)
	EffectiveToken string
}

GitHubMCPDockerOptions defines configuration for GitHub MCP Docker rendering

type GitHubMCPRemoteOptions added in v0.25.0

type GitHubMCPRemoteOptions struct {
	// ReadOnly enables read-only mode for GitHub API operations
	ReadOnly bool
	// Lockdown enables lockdown mode for GitHub MCP server (limits content from public repos)
	Lockdown bool
	// Toolsets specifies the GitHub toolsets to enable
	Toolsets string
	// AuthorizationValue is the value for the Authorization header
	// For Claude: "Bearer {effectiveToken}"
	// For Copilot: "Bearer \\${GITHUB_PERSONAL_ACCESS_TOKEN}"
	AuthorizationValue string
	// IncludeToolsField indicates whether to include the "tools" field (Copilot needs it, Claude doesn't)
	IncludeToolsField bool
	// AllowedTools specifies the list of allowed tools (Copilot uses this, Claude doesn't)
	AllowedTools []string
	// IncludeEnvSection indicates whether to include the env section (Copilot needs it, Claude doesn't)
	IncludeEnvSection bool
}

GitHubMCPRemoteOptions defines configuration for GitHub MCP remote mode rendering

type GitHubScriptStepConfig added in v0.16.0

type GitHubScriptStepConfig struct {
	// Step metadata
	StepName string // e.g., "Create Output Issue"
	StepID   string // e.g., "create_issue"

	// Main job reference for agent output
	MainJobName string

	// Environment variables specific to this safe output type
	// These are added after GH_AW_AGENT_OUTPUT
	CustomEnvVars []string

	// JavaScript script constant to format and include
	Script string

	// Token configuration (passed to addSafeOutputGitHubTokenForConfig or addSafeOutputCopilotGitHubTokenForConfig)
	Token string

	// UseCopilotToken indicates whether to use the Copilot token preference chain
	// (COPILOT_GITHUB_TOKEN > COPILOT_CLI_TOKEN > GH_AW_COPILOT_TOKEN (legacy) > GH_AW_GITHUB_TOKEN (legacy))
	// This should be true for Copilot-related operations like creating agent tasks,
	// assigning copilot to issues, or adding copilot as PR reviewer
	UseCopilotToken bool

	// UseAgentToken indicates whether to use the agent token preference chain
	// (config token > GH_AW_AGENT_TOKEN)
	// This should be true for agent assignment operations (assign-to-agent)
	UseAgentToken bool
}

GitHubScriptStepConfig holds configuration for building a GitHub Script step

type GitHubToolConfig added in v0.22.9

type GitHubToolConfig struct {
	Allowed     []string `yaml:"allowed,omitempty"`
	Mode        string   `yaml:"mode,omitempty"`
	Version     string   `yaml:"version,omitempty"`
	Args        []string `yaml:"args,omitempty"`
	ReadOnly    bool     `yaml:"read-only,omitempty"`
	GitHubToken string   `yaml:"github-token,omitempty"`
	Toolset     []string `yaml:"toolsets,omitempty"`
	Lockdown    bool     `yaml:"lockdown,omitempty"`
}

GitHubToolConfig represents the configuration for the GitHub tool Can be nil (enabled with defaults), string, or an object with specific settings

type GitHubToolsetPermissions added in v0.27.0

type GitHubToolsetPermissions struct {
	ReadPermissions  []PermissionScope
	WritePermissions []PermissionScope
	Tools            []string // List of tools in this toolset (for verification)
}

GitHubToolsetPermissions maps GitHub MCP toolsets to their required permissions

type GitHubToolsetValidationError added in v0.27.0

type GitHubToolsetValidationError struct {
	// MissingToolsets maps toolset name to the list of tools that require it
	MissingToolsets map[string][]string
}

GitHubToolsetValidationError represents an error when GitHub tools are specified but their required toolsets are not enabled

func NewGitHubToolsetValidationError added in v0.27.0

func NewGitHubToolsetValidationError(missingToolsets map[string][]string) *GitHubToolsetValidationError

NewGitHubToolsetValidationError creates a new validation error

func (*GitHubToolsetValidationError) Error added in v0.27.0

Error implements the error interface

type GitHubToolsetsData added in v0.27.0

type GitHubToolsetsData struct {
	Version     string `json:"version"`
	Description string `json:"description"`
	Toolsets    map[string]struct {
		Description      string   `json:"description"`
		ReadPermissions  []string `json:"read_permissions"`
		WritePermissions []string `json:"write_permissions"`
		Tools            []string `json:"tools"`
	} `json:"toolsets"`
}

GitHubToolsetsData represents the structure of the embedded JSON file

func GetToolsetsData added in v0.27.0

func GetToolsetsData() GitHubToolsetsData

GetToolsetsData returns the parsed GitHub toolsets data (for use by workflows)

type GoDependency added in v0.25.0

type GoDependency struct {
	Path    string // import path (e.g., github.com/user/repo)
	Version string // version or pseudo-version
}

GoDependency represents a parsed Go package

type HookConfiguration added in v0.2.3

type HookConfiguration struct {
	PreToolUse []PreToolUseHook `json:"PreToolUse,omitempty"`
}

HookConfiguration represents the hooks section of settings

type HookEntry added in v0.2.3

type HookEntry struct {
	Type    string `json:"type"`
	Command string `json:"command"`
}

HookEntry represents a single hook entry

type InputDefinition added in v0.31.4

type InputDefinition struct {
	Description string   `yaml:"description,omitempty" json:"description,omitempty"`
	Required    bool     `yaml:"required,omitempty" json:"required,omitempty"`
	Default     any      `yaml:"default,omitempty" json:"default,omitempty"` // Can be string, number, or boolean
	Type        string   `yaml:"type,omitempty" json:"type,omitempty"`       // "string", "choice", "boolean", "number"
	Options     []string `yaml:"options,omitempty" json:"options,omitempty"` // Options for choice type
}

InputDefinition defines an input parameter for workflows, safe-jobs, and imported workflows. This is a unified type that consolidates the common input schema used across: - workflow_dispatch inputs (GitHub Actions native) - safe-jobs inputs (safe-outputs.jobs.[name].inputs) - imported workflow inputs (imports with inputs parameter)

The structure follows the workflow_dispatch input schema from GitHub Actions: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#onworkflow_dispatchinputs

func ParseInputDefinition added in v0.31.4

func ParseInputDefinition(inputConfig map[string]any) *InputDefinition

ParseInputDefinition parses an input definition from a map. This is a shared helper function that handles the common parsing logic for input definitions regardless of their source (safe-jobs, imports, etc.).

func (*InputDefinition) GetDefaultAsString added in v0.31.4

func (i *InputDefinition) GetDefaultAsString() string

GetDefaultAsString returns the default value as a string. Useful for backwards compatibility with code that expects string defaults.

type JSONMCPConfigOptions added in v0.23.2

type JSONMCPConfigOptions struct {
	// ConfigPath is the file path for the MCP config (e.g., "/tmp/gh-aw/mcp-config/mcp-servers.json")
	ConfigPath string
	// Renderers contains engine-specific rendering functions for each tool
	Renderers MCPToolRenderers
	// FilterTool is an optional function to filter out tools before processing
	// Returns true if the tool should be included, false to skip it
	FilterTool func(toolName string) bool
	// PostEOFCommands is an optional function to add commands after the EOF (e.g., debug output)
	PostEOFCommands func(yaml *strings.Builder)
}

JSONMCPConfigOptions defines configuration for JSON-based MCP config rendering

type Job

type Job struct {
	Name                       string
	DisplayName                string // Optional display name for the job (name property in YAML)
	RunsOn                     string
	If                         string
	HasWorkflowRunSafetyChecks bool // If true, the job's if condition includes workflow_run safety checks
	Permissions                string
	TimeoutMinutes             int
	Concurrency                string            // Job-level concurrency configuration
	Environment                string            // Job environment configuration
	Container                  string            // Job container configuration
	Services                   string            // Job services configuration
	Env                        map[string]string // Job-level environment variables
	Steps                      []string
	Needs                      []string // Job dependencies (needs clause)
	Outputs                    map[string]string

	// Reusable workflow call properties
	Uses    string            // Path to reusable workflow (e.g., ./.github/workflows/reusable.yml)
	With    map[string]any    // Input parameters for reusable workflow
	Secrets map[string]string // Secrets for reusable workflow
}

Job represents a GitHub Actions job with all its properties

type JobManager

type JobManager struct {
	// contains filtered or unexported fields
}

JobManager manages a collection of jobs and handles dependency validation

func NewJobManager

func NewJobManager() *JobManager

NewJobManager creates a new JobManager instance

func (*JobManager) AddJob

func (jm *JobManager) AddJob(job *Job) error

AddJob adds a job to the manager

func (*JobManager) GenerateMermaidGraph added in v0.22.1

func (jm *JobManager) GenerateMermaidGraph() string

GenerateMermaidGraph generates a Mermaid flowchart diagram of the job dependency graph

func (*JobManager) GetAllJobs

func (jm *JobManager) GetAllJobs() map[string]*Job

GetAllJobs returns all jobs in the manager

func (*JobManager) GetJob

func (jm *JobManager) GetJob(name string) (*Job, bool)

GetJob retrieves a job by name

func (*JobManager) GetTopologicalOrder

func (jm *JobManager) GetTopologicalOrder() ([]string, error)

GetTopologicalOrder returns jobs in topological order (dependencies before dependents)

func (*JobManager) RenderToYAML

func (jm *JobManager) RenderToYAML() string

RenderToYAML generates the jobs section of a GitHub Actions workflow

func (*JobManager) ValidateDependencies

func (jm *JobManager) ValidateDependencies() error

ValidateDependencies checks that all job dependencies exist and there are no cycles

type LinkSubIssueConfig added in v0.31.4

type LinkSubIssueConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	ParentRequiredLabels   []string `yaml:"parent-required-labels,omitempty"` // Required labels the parent issue must have
	ParentTitlePrefix      string   `yaml:"parent-title-prefix,omitempty"`    // Required title prefix for parent issue
	SubRequiredLabels      []string `yaml:"sub-required-labels,omitempty"`    // Required labels the sub-issue must have
	SubTitlePrefix         string   `yaml:"sub-title-prefix,omitempty"`       // Required title prefix for sub-issue
}

LinkSubIssueConfig holds configuration for linking issues as sub-issues from agent output

type ListJobConfig added in v0.31.4

type ListJobConfig struct {
	SafeOutputTargetConfig `yaml:",inline"`
	Allowed                []string `yaml:"allowed,omitempty"` // Optional list of allowed values
}

ListJobConfig represents common configuration for list-based operations (add-labels, add-reviewer, assign-milestone)

func ParseListJobConfig added in v0.31.4

func ParseListJobConfig(configMap map[string]any, allowedKey string) (ListJobConfig, bool)

ParseListJobConfig parses common list job fields from a config map. Returns the parsed ListJobConfig and a boolean indicating if there was a validation error.

type LogError added in v0.16.0

type LogError struct {
	File      string // File path (usually the log file)
	Line      int    // Line number in the log file
	Type      string // "error" or "warning"
	Message   string // Error/warning message
	PatternID string // ID of the error pattern that matched (if available)
}

LogError represents a single error or warning from the log

func CountErrorsAndWarningsWithPatterns added in v0.9.0

func CountErrorsAndWarningsWithPatterns(logContent string, patterns []ErrorPattern) []LogError

CountErrorsAndWarningsWithPatterns extracts errors and warnings using regex patterns This is more accurate than simple string matching and uses the same logic as validate_errors.cjs

type LogMetrics added in v0.0.22

type LogMetrics struct {
	TokenUsage    int
	EstimatedCost float64
	Errors        []LogError     // Individual error and warning details
	Turns         int            // Number of turns needed to complete the task
	ToolCalls     []ToolCallInfo // Tool call statistics
	ToolSequences [][]string     // Sequences of tool calls preserving order

}

LogMetrics represents extracted metrics from log files

func ExtractJSONMetrics added in v0.0.22

func ExtractJSONMetrics(line string, verbose bool) LogMetrics

ExtractJSONMetrics extracts metrics from streaming JSON log lines

type MCPConfigRenderer

type MCPConfigRenderer struct {
	// IndentLevel controls the indentation level for properties (e.g., "                " for JSON, "          " for TOML)
	IndentLevel string
	// Format specifies the output format ("json" for JSON-like, "toml" for TOML-like)
	Format string
	// RequiresCopilotFields indicates if the engine requires "type" and "tools" fields (true for copilot engine)
	RequiresCopilotFields bool
}

MCPConfigRenderer contains configuration options for rendering MCP config

type MCPConfigRendererUnified added in v0.30.0

type MCPConfigRendererUnified struct {
	// contains filtered or unexported fields
}

MCPConfigRendererUnified provides unified rendering methods for MCP configurations across different engines (Claude, Copilot, Codex, Custom)

func NewMCPConfigRenderer added in v0.30.0

func NewMCPConfigRenderer(opts MCPRendererOptions) *MCPConfigRendererUnified

NewMCPConfigRenderer creates a new unified MCP config renderer with the specified options

func (*MCPConfigRendererUnified) RenderAgenticWorkflowsMCP added in v0.30.0

func (r *MCPConfigRendererUnified) RenderAgenticWorkflowsMCP(yaml *strings.Builder)

RenderAgenticWorkflowsMCP generates the Agentic Workflows MCP server configuration

func (*MCPConfigRendererUnified) RenderGitHubMCP added in v0.30.0

func (r *MCPConfigRendererUnified) RenderGitHubMCP(yaml *strings.Builder, githubTool any, workflowData *WorkflowData)

RenderGitHubMCP generates the GitHub MCP server configuration Supports both local (Docker) and remote (hosted) modes

func (*MCPConfigRendererUnified) RenderPlaywrightMCP added in v0.30.0

func (r *MCPConfigRendererUnified) RenderPlaywrightMCP(yaml *strings.Builder, playwrightTool any)

RenderPlaywrightMCP generates the Playwright MCP server configuration

func (*MCPConfigRendererUnified) RenderSafeInputsMCP added in v0.31.4

func (r *MCPConfigRendererUnified) RenderSafeInputsMCP(yaml *strings.Builder, safeInputs *SafeInputsConfig)

RenderSafeInputsMCP generates the Safe Inputs MCP server configuration

func (*MCPConfigRendererUnified) RenderSafeOutputsMCP added in v0.30.0

func (r *MCPConfigRendererUnified) RenderSafeOutputsMCP(yaml *strings.Builder)

RenderSafeOutputsMCP generates the Safe Outputs MCP server configuration

func (*MCPConfigRendererUnified) RenderSerenaMCP added in v0.30.5

func (r *MCPConfigRendererUnified) RenderSerenaMCP(yaml *strings.Builder, serenaTool any)

RenderSerenaMCP generates Serena MCP server configuration

type MCPGatewayConfig added in v0.31.4

type MCPGatewayConfig struct {
	Container      string            `yaml:"container,omitempty"`      // Container image for the gateway
	Version        string            `yaml:"version,omitempty"`        // Optional version/tag for the container
	Args           []string          `yaml:"args,omitempty"`           // Arguments for container execution
	EntrypointArgs []string          `yaml:"entrypointArgs,omitempty"` // Arguments after the container image
	Env            map[string]string `yaml:"env,omitempty"`            // Environment variables for the gateway
	Port           int               `yaml:"port,omitempty"`           // Port for the gateway HTTP server (default: 8080)
	APIKey         string            `yaml:"api-key,omitempty"`        // API key for gateway authentication
}

MCPGatewayConfig represents the configuration for the MCP gateway The gateway routes MCP server calls through a unified HTTP endpoint

type MCPGatewaySettings added in v0.31.4

type MCPGatewaySettings struct {
	Port   int    `json:"port"`
	APIKey string `json:"apiKey,omitempty"`
}

MCPGatewaySettings represents the gateway-specific settings

type MCPGatewayStdinConfig added in v0.31.4

type MCPGatewayStdinConfig struct {
	MCPServers map[string]any     `json:"mcpServers"`
	Gateway    MCPGatewaySettings `json:"gateway"`
}

MCPGatewayStdinConfig represents the configuration passed to the MCP gateway via stdin

type MCPRendererOptions added in v0.30.0

type MCPRendererOptions struct {
	// IncludeCopilotFields indicates if the engine requires "type" and "tools" fields (true for copilot engine)
	IncludeCopilotFields bool
	// InlineArgs indicates if args should be rendered inline (true for copilot) or multi-line (false for claude/custom)
	InlineArgs bool
	// Format specifies the output format ("json" for JSON-like, "toml" for TOML-like)
	Format string
	// IsLast indicates if this is the last server in the configuration (affects trailing comma)
	IsLast bool
}

MCPRendererOptions contains configuration options for the unified MCP renderer

type MCPToolRenderers added in v0.23.2

type MCPToolRenderers struct {
	RenderGitHub           func(yaml *strings.Builder, githubTool any, isLast bool, workflowData *WorkflowData)
	RenderPlaywright       func(yaml *strings.Builder, playwrightTool any, isLast bool)
	RenderSerena           func(yaml *strings.Builder, serenaTool any, isLast bool)
	RenderCacheMemory      func(yaml *strings.Builder, isLast bool, workflowData *WorkflowData)
	RenderAgenticWorkflows func(yaml *strings.Builder, isLast bool)
	RenderSafeOutputs      func(yaml *strings.Builder, isLast bool)
	RenderSafeInputs       func(yaml *strings.Builder, safeInputs *SafeInputsConfig, isLast bool)
	RenderWebFetch         func(yaml *strings.Builder, isLast bool)
	RenderCustomMCPConfig  RenderCustomMCPToolConfigHandler
}

MCPToolRenderers holds engine-specific rendering functions for each MCP tool type

type MapToolConfig added in v0.9.0

type MapToolConfig map[string]any

MapToolConfig implements ToolConfig for map[string]any

func (MapToolConfig) GetAny added in v0.9.0

func (m MapToolConfig) GetAny(key string) (any, bool)

func (MapToolConfig) GetString added in v0.9.0

func (m MapToolConfig) GetString(key string) (string, bool)

func (MapToolConfig) GetStringArray added in v0.9.0

func (m MapToolConfig) GetStringArray(key string) ([]string, bool)

func (MapToolConfig) GetStringMap added in v0.9.0

func (m MapToolConfig) GetStringMap(key string) (map[string]string, bool)

type MissingToolConfig added in v0.4.0

type MissingToolConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
}

MissingToolConfig holds configuration for reporting missing tools or functionality

type NetworkHookGenerator added in v0.2.3

type NetworkHookGenerator struct{}

NetworkHookGenerator generates network permission hooks for AI engines Network permissions are configured at the workflow level using the top-level "network" field

func (*NetworkHookGenerator) GenerateNetworkHookScript added in v0.2.3

func (g *NetworkHookGenerator) GenerateNetworkHookScript(allowedDomains []string) string

GenerateNetworkHookScript generates a Python hook script for network permissions

func (*NetworkHookGenerator) GenerateNetworkHookWorkflowStep added in v0.2.3

func (g *NetworkHookGenerator) GenerateNetworkHookWorkflowStep(allowedDomains []string) GitHubActionStep

GenerateNetworkHookWorkflowStep generates a GitHub Actions workflow step that creates the network permissions hook

type NetworkPermissions added in v0.2.3

type NetworkPermissions struct {
	Mode              string          `yaml:"mode,omitempty"`     // "defaults" for default access
	Allowed           []string        `yaml:"allowed,omitempty"`  // List of allowed domains
	Firewall          *FirewallConfig `yaml:"firewall,omitempty"` // AWF firewall configuration (see firewall.go)
	ExplicitlyDefined bool            `yaml:"-"`                  // Internal flag: true if network field was explicitly set in frontmatter
}

NetworkPermissions represents network access permissions

type NoOpConfig added in v0.30.1

type NoOpConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
}

NoOpConfig holds configuration for no-op safe output (logging only)

type NotNode

type NotNode struct {
	Child ConditionNode
}

NotNode represents a NOT operation on a condition

func (*NotNode) Render

func (n *NotNode) Render() string

type NpmDependency added in v0.25.0

type NpmDependency struct {
	Name    string
	Version string // semver range or specific version
}

NpmDependency represents a parsed npm package with version

type NumberLiteralNode

type NumberLiteralNode struct {
	Value string
}

NumberLiteralNode represents a numeric literal value

func BuildNumberLiteral

func BuildNumberLiteral(value string) *NumberLiteralNode

BuildNumberLiteral creates a number literal node

func (*NumberLiteralNode) Render

func (n *NumberLiteralNode) Render() string

type OrNode

type OrNode struct {
	Left, Right ConditionNode
}

OrNode represents an OR operation between two conditions

func (*OrNode) Render

func (o *OrNode) Render() string

type PackageExtractor added in v0.28.7

type PackageExtractor struct {
	// CommandNames is the list of command names to look for.
	// Include all variations of the command (e.g., ["pip", "pip3"]).
	// Matching is case-sensitive and exact.
	//
	// Examples:
	//   - ["npx"] for npm packages
	//   - ["pip", "pip3"] for Python packages
	//   - ["go"] for Go packages
	//   - ["uvx"] for uv tool packages
	CommandNames []string

	// RequiredSubcommand is the subcommand that must follow the command name
	// before the package name appears. Set to empty string if the package name
	// comes directly after the command.
	//
	// Examples:
	//   - "install" for pip (pip install <package>)
	//   - "get" for go (go get <package>)
	//   - "" for npx (npx <package>)
	//
	// Deprecated: Use RequiredSubcommands for multiple subcommand support.
	// This field is maintained for backward compatibility.
	RequiredSubcommand string

	// RequiredSubcommands is a list of subcommands that can follow the command name
	// before the package name appears. If any of these subcommands is found, the
	// package name following it will be extracted. Set to empty slice if the package
	// name comes directly after the command.
	//
	// This field takes precedence over RequiredSubcommand if both are set.
	//
	// Examples:
	//   - ["install"] for pip (pip install <package>)
	//   - ["install", "get"] for go (go install <pkg> or go get <pkg>)
	//   - [] for npx (npx <package>)
	RequiredSubcommands []string

	// TrimSuffixes is a string of characters to trim from the end of package names.
	// This is useful for removing shell operators that may appear after package names
	// in command strings.
	//
	// Recommended value: "&|;" (covers common shell operators)
	//
	// Examples:
	//   - "pip install requests;" → extracts "requests" (trims ";")
	//   - "npx playwright&" → extracts "playwright" (trims "&")
	TrimSuffixes string
}

PackageExtractor provides a configurable framework for extracting package names from command-line strings. It can be configured to handle different package managers (npm, pip, uv, go) by setting the appropriate command names and options.

This type is the core of the package extraction pattern. Use it instead of writing custom parsing logic to avoid code duplication.

Configuration:

  • Set CommandNames to all variants of the command (e.g., ["pip", "pip3"])
  • Set RequiredSubcommand if the package manager requires a subcommand (e.g., "install" for pip, "get" for go)
  • Set TrimSuffixes to remove shell operators from package names (typically "&|;")

Examples:

// For npx (no subcommand):
extractor := PackageExtractor{
    CommandNames:       []string{"npx"},
    RequiredSubcommand: "",
    TrimSuffixes:       "&|;",
}

// For pip (with "install" subcommand):
extractor := PackageExtractor{
    CommandNames:       []string{"pip", "pip3"},
    RequiredSubcommand: "install",
    TrimSuffixes:       "&|;",
}

func (*PackageExtractor) ExtractPackages added in v0.28.7

func (pe *PackageExtractor) ExtractPackages(commands string) []string

ExtractPackages extracts package names from command strings using the configured extraction rules. It processes multi-line command strings and returns all found package names.

This is the main entry point for package extraction. Call this method with your command string(s) after configuring the PackageExtractor.

The extraction process:

  1. Split commands by newlines
  2. Split each line into words
  3. Find command name matches (from CommandNames)
  4. If RequiredSubcommand is set, look for that subcommand
  5. Skip flags (words starting with -)
  6. Extract package name and trim configured suffixes
  7. Return first package found per command invocation

Multi-line commands are supported:

commands := `pip install requests
pip install numpy`
packages := extractor.ExtractPackages(commands)
// Returns: []string{"requests", "numpy"}

Flags are automatically skipped:

packages := extractor.ExtractPackages("pip install --upgrade requests")
// Returns: []string{"requests"}

Shell operators are automatically trimmed:

packages := extractor.ExtractPackages("npx playwright;")
// Returns: []string{"playwright"}

Example usage with pip:

extractor := PackageExtractor{
    CommandNames:       []string{"pip", "pip3"},
    RequiredSubcommand: "install",
    TrimSuffixes:       "&|;",
}
packages := extractor.ExtractPackages("pip install requests==2.28.0")
// Returns: []string{"requests==2.28.0"}

Example usage with npx:

extractor := PackageExtractor{
    CommandNames:       []string{"npx"},
    RequiredSubcommand: "",
    TrimSuffixes:       "&|;",
}
packages := extractor.ExtractPackages("npx @playwright/mcp@latest")
// Returns: []string{"@playwright/mcp@latest"}

func (*PackageExtractor) FindPackageName added in v0.28.7

func (pe *PackageExtractor) FindPackageName(words []string, startIndex int) string

findPackageName finds and processes the package name starting at the given index. It skips flags (words starting with -) and returns the first non-flag word, trimming configured suffixes.

This method is exported to allow special-case extraction patterns (like uv) to reuse the package finding logic.

type PackageJSON added in v0.25.0

type PackageJSON struct {
	Name            string            `json:"name"`
	Private         bool              `json:"private"`
	License         string            `json:"license,omitempty"`
	Dependencies    map[string]string `json:"dependencies,omitempty"`
	DevDependencies map[string]string `json:"devDependencies,omitempty"`
}

PackageJSON represents the structure of a package.json file

type ParenthesesNode added in v0.25.0

type ParenthesesNode struct {
	Child ConditionNode
}

ParenthesesNode wraps a condition in parentheses for proper YAML interpretation

func (*ParenthesesNode) Render added in v0.25.0

func (p *ParenthesesNode) Render() string

type PermissionLevel added in v0.22.10

type PermissionLevel string

PermissionLevel represents the level of access (read, write, none)

const (
	PermissionRead  PermissionLevel = "read"
	PermissionWrite PermissionLevel = "write"
	PermissionNone  PermissionLevel = "none"
)

type PermissionScope added in v0.22.10

type PermissionScope string

PermissionScope represents a GitHub Actions permission scope

const (
	PermissionActions        PermissionScope = "actions"
	PermissionAttestations   PermissionScope = "attestations"
	PermissionChecks         PermissionScope = "checks"
	PermissionContents       PermissionScope = "contents"
	PermissionDeployments    PermissionScope = "deployments"
	PermissionDiscussions    PermissionScope = "discussions"
	PermissionIdToken        PermissionScope = "id-token"
	PermissionIssues         PermissionScope = "issues"
	PermissionModels         PermissionScope = "models"
	PermissionPackages       PermissionScope = "packages"
	PermissionPages          PermissionScope = "pages"
	PermissionPullRequests   PermissionScope = "pull-requests"
	PermissionRepositoryProj PermissionScope = "repository-projects"
	PermissionSecurityEvents PermissionScope = "security-events"
	PermissionStatuses       PermissionScope = "statuses"
)

func GetAllPermissionScopes added in v0.23.2

func GetAllPermissionScopes() []PermissionScope

GetAllPermissionScopes returns all available permission scopes

type Permissions added in v0.22.10

type Permissions struct {
	// contains filtered or unexported fields
}

Permissions represents GitHub Actions permissions It can be a shorthand (read-all, write-all, read, write, none) or a map of scopes to levels It can also have an "all" permission that expands to all scopes

func NewPermissions added in v0.22.10

func NewPermissions() *Permissions

NewPermissions creates a new Permissions with an empty map

func NewPermissionsActionsWriteContentsWriteIssuesWritePRWrite added in v0.31.0

func NewPermissionsActionsWriteContentsWriteIssuesWritePRWrite() *Permissions

NewPermissionsActionsWriteContentsWriteIssuesWritePRWrite creates permissions with actions: write, contents: write, issues: write, pull-requests: write This is required for the replaceActorsForAssignable GraphQL mutation used to assign GitHub Copilot agents to issues

func NewPermissionsAllRead added in v0.23.2

func NewPermissionsAllRead() *Permissions

NewPermissionsAllRead creates a Permissions with all: read

func NewPermissionsContentsRead added in v0.22.10

func NewPermissionsContentsRead() *Permissions

NewPermissionsContentsRead creates permissions with contents: read

func NewPermissionsContentsReadDiscussionsWrite added in v0.22.10

func NewPermissionsContentsReadDiscussionsWrite() *Permissions

NewPermissionsContentsReadDiscussionsWrite creates permissions with contents: read and discussions: write

func NewPermissionsContentsReadIssuesWrite added in v0.22.10

func NewPermissionsContentsReadIssuesWrite() *Permissions

NewPermissionsContentsReadIssuesWrite creates permissions with contents: read and issues: write

func NewPermissionsContentsReadIssuesWritePRWrite added in v0.22.10

func NewPermissionsContentsReadIssuesWritePRWrite() *Permissions

NewPermissionsContentsReadIssuesWritePRWrite creates permissions with contents: read, issues: write, pull-requests: write

func NewPermissionsContentsReadIssuesWritePRWriteDiscussionsWrite added in v0.22.10

func NewPermissionsContentsReadIssuesWritePRWriteDiscussionsWrite() *Permissions

NewPermissionsContentsReadIssuesWritePRWriteDiscussionsWrite creates permissions with contents: read, issues: write, pull-requests: write, discussions: write

func NewPermissionsContentsReadPRWrite added in v0.22.10

func NewPermissionsContentsReadPRWrite() *Permissions

NewPermissionsContentsReadPRWrite creates permissions with contents: read and pull-requests: write

func NewPermissionsContentsReadProjectsWrite added in v0.30.0

func NewPermissionsContentsReadProjectsWrite() *Permissions

NewPermissionsContentsReadProjectsWrite creates permissions with contents: read and repository-projects: write

func NewPermissionsContentsReadSecurityEventsWrite added in v0.22.10

func NewPermissionsContentsReadSecurityEventsWrite() *Permissions

NewPermissionsContentsReadSecurityEventsWrite creates permissions with contents: read and security-events: write

func NewPermissionsContentsReadSecurityEventsWriteActionsRead added in v0.22.10

func NewPermissionsContentsReadSecurityEventsWriteActionsRead() *Permissions

NewPermissionsContentsReadSecurityEventsWriteActionsRead creates permissions with contents: read, security-events: write, actions: read

func NewPermissionsContentsWrite added in v0.22.10

func NewPermissionsContentsWrite() *Permissions

NewPermissionsContentsWrite creates permissions with contents: write

func NewPermissionsContentsWriteIssuesWritePRWrite added in v0.22.10

func NewPermissionsContentsWriteIssuesWritePRWrite() *Permissions

NewPermissionsContentsWriteIssuesWritePRWrite creates permissions with contents: write, issues: write, pull-requests: write

func NewPermissionsContentsWriteIssuesWritePRWriteDiscussionsWrite added in v0.30.2

func NewPermissionsContentsWriteIssuesWritePRWriteDiscussionsWrite() *Permissions

NewPermissionsContentsWriteIssuesWritePRWriteDiscussionsWrite creates permissions with contents: write, issues: write, pull-requests: write, discussions: write

func NewPermissionsContentsWritePRReadIssuesRead added in v0.22.10

func NewPermissionsContentsWritePRReadIssuesRead() *Permissions

NewPermissionsContentsWritePRReadIssuesRead creates permissions with contents: write, pull-requests: read, issues: read

func NewPermissionsDiscussionsWrite added in v0.22.10

func NewPermissionsDiscussionsWrite() *Permissions

NewPermissionsDiscussionsWrite creates permissions with discussions: write

func NewPermissionsEmpty added in v0.26.0

func NewPermissionsEmpty() *Permissions

NewPermissionsEmpty creates a Permissions that explicitly renders as "permissions: {}"

func NewPermissionsFromMap added in v0.22.10

func NewPermissionsFromMap(perms map[PermissionScope]PermissionLevel) *Permissions

NewPermissionsFromMap creates a Permissions from a map of scopes to levels

func NewPermissionsNone added in v0.22.10

func NewPermissionsNone() *Permissions

NewPermissionsNone creates a Permissions with none shorthand

func NewPermissionsRead added in v0.22.10

func NewPermissionsRead() *Permissions

NewPermissionsRead creates a Permissions with read shorthand

func NewPermissionsReadAll added in v0.22.10

func NewPermissionsReadAll() *Permissions

NewPermissionsReadAll creates a Permissions with read-all shorthand

func NewPermissionsWrite added in v0.22.10

func NewPermissionsWrite() *Permissions

NewPermissionsWrite creates a Permissions with write shorthand

func NewPermissionsWriteAll added in v0.22.10

func NewPermissionsWriteAll() *Permissions

NewPermissionsWriteAll creates a Permissions with write-all shorthand

func (*Permissions) Get added in v0.22.10

Get gets the permission level for a specific scope

func (*Permissions) Merge added in v0.22.10

func (p *Permissions) Merge(other *Permissions)

Merge merges another Permissions into this one Write permission takes precedence over read (write implies read) Individual scope permissions override shorthand

func (*Permissions) RenderToYAML added in v0.22.10

func (p *Permissions) RenderToYAML() string

RenderToYAML renders the Permissions to GitHub Actions YAML format

func (*Permissions) Set added in v0.22.10

func (p *Permissions) Set(scope PermissionScope, level PermissionLevel)

Set sets a permission for a specific scope

type PermissionsParser added in v0.9.0

type PermissionsParser struct {
	// contains filtered or unexported fields
}

PermissionsParser provides functionality to parse and analyze GitHub Actions permissions

func NewPermissionsParser added in v0.9.0

func NewPermissionsParser(permissionsYAML string) *PermissionsParser

NewPermissionsParser creates a new PermissionsParser instance

func NewPermissionsParserFromValue added in v0.12.1

func NewPermissionsParserFromValue(permissionsValue any) *PermissionsParser

NewPermissionsParserFromValue creates a PermissionsParser from a frontmatter value (any type)

func (*PermissionsParser) HasContentsReadAccess added in v0.9.0

func (p *PermissionsParser) HasContentsReadAccess() bool

HasContentsReadAccess returns true if the permissions allow reading contents

func (*PermissionsParser) IsAllowed added in v0.12.1

func (p *PermissionsParser) IsAllowed(scope, level string) bool

IsAllowed checks if a specific permission scope has the specified access level scope: "contents", "issues", "pull-requests", etc. level: "read", "write", "none"

func (*PermissionsParser) ToPermissions added in v0.23.2

func (p *PermissionsParser) ToPermissions() *Permissions

ToPermissions converts a PermissionsParser to a Permissions object

type PermissionsValidationResult added in v0.27.0

type PermissionsValidationResult struct {
	MissingPermissions    map[PermissionScope]PermissionLevel // Permissions required but not granted
	ReadOnlyMode          bool                                // Whether the GitHub MCP is in read-only mode
	HasValidationIssues   bool                                // Whether there are any validation issues
	MissingToolsetDetails map[string][]PermissionScope        // Maps toolset name to missing permissions
}

PermissionsValidationResult contains the result of permissions validation

func ValidatePermissions added in v0.27.0

func ValidatePermissions(permissions *Permissions, githubTool any) *PermissionsValidationResult

ValidatePermissions validates that workflow permissions match the required GitHub MCP toolsets This is the general-purpose permission validator used during workflow compilation to check that the declared permissions are sufficient for the GitHub MCP toolsets being used.

Use ValidatePermissions (this function) for general permission validation against GitHub MCP toolsets. Use ValidateIncludedPermissions (in imports.go) when validating permissions from included/imported workflow files.

type PipDependency added in v0.25.0

type PipDependency struct {
	Name    string
	Version string // version specifier (e.g., ==1.0.0, >=2.0.0)
}

PipDependency represents a parsed pip package with version

type PlaywrightDockerArgs added in v0.6.1

type PlaywrightDockerArgs struct {
	ImageVersion      string // Version for Docker image (mcr.microsoft.com/playwright:version)
	MCPPackageVersion string // Version for NPM package (@playwright/mcp@version)
	AllowedDomains    []string
}

PlaywrightDockerArgs represents the common Docker arguments for Playwright container

type PlaywrightToolConfig added in v0.22.9

type PlaywrightToolConfig struct {
	Version        string   `yaml:"version,omitempty"`
	AllowedDomains []string `yaml:"allowed_domains,omitempty"`
	Args           []string `yaml:"args,omitempty"`
}

PlaywrightToolConfig represents the configuration for the Playwright tool

type PreToolUseHook added in v0.2.3

type PreToolUseHook struct {
	Matcher string      `json:"matcher"`
	Hooks   []HookEntry `json:"hooks"`
}

PreToolUseHook represents a pre-tool-use hook configuration

type PropertyAccessNode

type PropertyAccessNode struct {
	PropertyPath string
}

PropertyAccessNode represents property access like github.event.action

func BuildPropertyAccess

func BuildPropertyAccess(path string) *PropertyAccessNode

BuildPropertyAccess creates a property access node for GitHub context properties

func (*PropertyAccessNode) Render

func (p *PropertyAccessNode) Render() string

type PushToPullRequestBranchConfig added in v0.6.0

type PushToPullRequestBranchConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	Target               string   `yaml:"target,omitempty"`              // Target for push-to-pull-request-branch: like add-comment but for pull requests
	TitlePrefix          string   `yaml:"title-prefix,omitempty"`        // Required title prefix for pull request validation
	Labels               []string `yaml:"labels,omitempty"`              // Required labels for pull request validation
	IfNoChanges          string   `yaml:"if-no-changes,omitempty"`       // Behavior when no changes to push: "warn", "error", or "ignore" (default: "warn")
	CommitTitleSuffix    string   `yaml:"commit-title-suffix,omitempty"` // Optional suffix to append to generated commit titles
}

PushToPullRequestBranchConfig holds configuration for pushing changes to a specific branch from agent output

type RenderCustomMCPToolConfigHandler added in v0.22.4

type RenderCustomMCPToolConfigHandler func(yaml *strings.Builder, toolName string, toolConfig map[string]any, isLast bool) error

RenderCustomMCPToolConfigHandler is a function type for rendering custom MCP tool configurations

type RepositoryFeatures added in v0.25.0

type RepositoryFeatures struct {
	HasDiscussions bool
	HasIssues      bool
}

RepositoryFeatures holds cached information about repository capabilities

type Runtime added in v0.16.0

type Runtime struct {
	ID              string            // Unique identifier (e.g., "node", "python")
	Name            string            // Display name (e.g., "Node.js", "Python")
	ActionRepo      string            // GitHub Actions repository (e.g., "actions/setup-node")
	ActionVersion   string            // Action version (e.g., "v4", without @ prefix)
	VersionField    string            // Field name for version in action (e.g., "node-version")
	DefaultVersion  string            // Default version to use
	Commands        []string          // Commands that indicate this runtime is needed
	ExtraWithFields map[string]string // Additional 'with' fields for the action
}

Runtime represents configuration for a runtime environment

type RuntimeRequirement added in v0.16.0

type RuntimeRequirement struct {
	Runtime     *Runtime
	Version     string         // Empty string means use default
	ExtraFields map[string]any // Additional 'with' fields from user's setup step (e.g., cache settings)
	GoModFile   string         // Path to go.mod file for Go runtime (Go-specific)
}

RuntimeRequirement represents a detected runtime requirement

func DeduplicateRuntimeSetupStepsFromCustomSteps added in v0.30.0

func DeduplicateRuntimeSetupStepsFromCustomSteps(customSteps string, runtimeRequirements []RuntimeRequirement) (string, []RuntimeRequirement, error)

DeduplicateRuntimeSetupStepsFromCustomSteps removes runtime setup action steps from custom steps to avoid duplication when runtime steps are added before custom steps. This function parses the YAML custom steps, removes any steps that use runtime setup actions, and returns the deduplicated YAML.

It preserves user-customized setup actions (e.g., with specific versions) and filters the corresponding runtime from the requirements so we don't generate a duplicate runtime setup step.

func DetectRuntimeRequirements added in v0.16.0

func DetectRuntimeRequirements(workflowData *WorkflowData) []RuntimeRequirement

DetectRuntimeRequirements analyzes workflow data to detect required runtimes

type SRTFilesystemConfig added in v0.31.4

type SRTFilesystemConfig struct {
	DenyRead   []string `yaml:"denyRead" json:"denyRead"`
	AllowWrite []string `yaml:"allowWrite,omitempty" json:"allowWrite,omitempty"`
	DenyWrite  []string `yaml:"denyWrite" json:"denyWrite"`
}

SRTFilesystemConfig represents filesystem configuration for SRT

type SRTNetworkConfig added in v0.31.4

type SRTNetworkConfig struct {
	AllowedDomains      []string `yaml:"allowedDomains,omitempty" json:"allowedDomains,omitempty"`
	DeniedDomains       []string `yaml:"deniedDomains,omitempty" json:"deniedDomains"`
	AllowUnixSockets    []string `yaml:"allowUnixSockets,omitempty" json:"allowUnixSockets,omitempty"`
	AllowLocalBinding   bool     `yaml:"allowLocalBinding" json:"allowLocalBinding"`
	AllowAllUnixSockets bool     `yaml:"allowAllUnixSockets" json:"allowAllUnixSockets"`
}

SRTNetworkConfig represents network configuration for SRT

type SafeInputParam added in v0.31.4

type SafeInputParam struct {
	Type        string // JSON schema type (string, number, boolean, array, object)
	Description string // Description of the parameter
	Required    bool   // Whether the parameter is required
	Default     any    // Default value
}

SafeInputParam holds the configuration for a tool input parameter

type SafeInputToolConfig added in v0.31.4

type SafeInputToolConfig struct {
	Name        string                     // Tool name (key from the config)
	Description string                     // Required: tool description
	Inputs      map[string]*SafeInputParam // Optional: input parameters
	Script      string                     // JavaScript implementation (mutually exclusive with Run and Py)
	Run         string                     // Shell script implementation (mutually exclusive with Script and Py)
	Py          string                     // Python script implementation (mutually exclusive with Script and Run)
	Env         map[string]string          // Environment variables (typically for secrets)
}

SafeInputToolConfig holds the configuration for a single safe-input tool

type SafeInputsConfig added in v0.31.4

type SafeInputsConfig struct {
	Tools map[string]*SafeInputToolConfig
}

SafeInputsConfig holds the configuration for safe-inputs custom tools

func ParseSafeInputs added in v0.31.4

func ParseSafeInputs(frontmatter map[string]any) *SafeInputsConfig

ParseSafeInputs parses safe-inputs configuration from frontmatter (standalone function for testing)

type SafeInputsConfigJSON added in v0.31.4

type SafeInputsConfigJSON struct {
	ServerName string               `json:"serverName"`
	Version    string               `json:"version"`
	LogDir     string               `json:"logDir,omitempty"`
	Tools      []SafeInputsToolJSON `json:"tools"`
}

SafeInputsConfigJSON represents the tools.json configuration file structure

type SafeInputsToolJSON added in v0.31.4

type SafeInputsToolJSON struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"inputSchema"`
	Handler     string         `json:"handler,omitempty"`
}

SafeInputsToolJSON represents a tool configuration for the tools.json file

type SafeJobConfig added in v0.9.0

type SafeJobConfig struct {
	// Standard GitHub Actions job properties
	Name        string            `yaml:"name,omitempty"`
	Description string            `yaml:"description,omitempty"`
	RunsOn      any               `yaml:"runs-on,omitempty"`
	If          string            `yaml:"if,omitempty"`
	Needs       []string          `yaml:"needs,omitempty"`
	Steps       []any             `yaml:"steps,omitempty"`
	Env         map[string]string `yaml:"env,omitempty"`
	Permissions map[string]string `yaml:"permissions,omitempty"`

	// Additional safe-job specific properties
	Inputs      map[string]*InputDefinition `yaml:"inputs,omitempty"`
	GitHubToken string                      `yaml:"github-token,omitempty"`
	Output      string                      `yaml:"output,omitempty"`
}

SafeJobConfig defines a safe job configuration with GitHub Actions job properties

type SafeOutputDiscussionFilterConfig added in v0.31.4

type SafeOutputDiscussionFilterConfig struct {
	SafeOutputFilterConfig `yaml:",inline"`
	RequiredCategory       string `yaml:"required-category,omitempty"` // Required category for discussion operations
}

SafeOutputDiscussionFilterConfig extends SafeOutputFilterConfig with discussion-specific fields.

func ParseDiscussionFilterConfig added in v0.31.4

func ParseDiscussionFilterConfig(configMap map[string]any) SafeOutputDiscussionFilterConfig

ParseDiscussionFilterConfig parses filter config plus required-category for discussion operations.

type SafeOutputFilterConfig added in v0.31.4

type SafeOutputFilterConfig struct {
	RequiredLabels      []string `yaml:"required-labels,omitempty"`       // Required labels for the operation
	RequiredTitlePrefix string   `yaml:"required-title-prefix,omitempty"` // Required title prefix for the operation
}

SafeOutputFilterConfig contains common filtering fields for safe output configurations. Embed this in safe output config structs that support filtering by labels or title prefix.

func ParseFilterConfig added in v0.31.4

func ParseFilterConfig(configMap map[string]any) SafeOutputFilterConfig

ParseFilterConfig parses required-labels and required-title-prefix fields from a config map.

type SafeOutputJobConfig added in v0.28.3

type SafeOutputJobConfig struct {
	// Job metadata
	JobName     string // e.g., "create_issue"
	StepName    string // e.g., "Create Output Issue"
	StepID      string // e.g., "create_issue"
	MainJobName string // Main workflow job name for dependencies

	// Custom environment variables specific to this safe output type
	CustomEnvVars []string

	// JavaScript script constant to include in the GitHub Script step
	Script string

	// Job configuration
	Permissions     *Permissions      // Job permissions
	Outputs         map[string]string // Job outputs
	Condition       ConditionNode     // Job condition (if clause)
	Needs           []string          // Job dependencies
	PreSteps        []string          // Optional steps to run before the GitHub Script step
	PostSteps       []string          // Optional steps to run after the GitHub Script step
	Token           string            // GitHub token for this output type
	UseCopilotToken bool              // Whether to use Copilot token preference chain
	UseAgentToken   bool              // Whether to use agent token preference chain (config token > GH_AW_AGENT_TOKEN)
	TargetRepoSlug  string            // Target repository for cross-repo operations
}

SafeOutputJobConfig holds configuration for building a safe output job This config struct extracts the common parameters across all safe output job builders

type SafeOutputMessagesConfig added in v0.31.4

type SafeOutputMessagesConfig struct {
	Footer            string `yaml:"footer,omitempty" json:"footer,omitempty"`                        // Custom footer message template
	FooterInstall     string `yaml:"footer-install,omitempty" json:"footerInstall,omitempty"`         // Custom installation instructions template
	StagedTitle       string `yaml:"staged-title,omitempty" json:"stagedTitle,omitempty"`             // Custom staged mode title template
	StagedDescription string `yaml:"staged-description,omitempty" json:"stagedDescription,omitempty"` // Custom staged mode description template
	RunStarted        string `yaml:"run-started,omitempty" json:"runStarted,omitempty"`               // Custom workflow activation message template
	RunSuccess        string `yaml:"run-success,omitempty" json:"runSuccess,omitempty"`               // Custom workflow success message template
	RunFailure        string `yaml:"run-failure,omitempty" json:"runFailure,omitempty"`               // Custom workflow failure message template
}

SafeOutputMessagesConfig holds custom message templates for safe-output footer and notification messages

type SafeOutputTargetConfig added in v0.31.4

type SafeOutputTargetConfig struct {
	Target         string `yaml:"target,omitempty"`      // Target for the operation: "triggering" (default), "*" (any item), or explicit number
	TargetRepoSlug string `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository operations
}

SafeOutputTargetConfig contains common target-related fields for safe output configurations. Embed this in safe output config structs that support targeting specific items.

func ParseTargetConfig added in v0.31.4

func ParseTargetConfig(configMap map[string]any) (SafeOutputTargetConfig, bool)

ParseTargetConfig parses target and target-repo fields from a config map. Returns the parsed SafeOutputTargetConfig and a boolean indicating if there was a validation error. If target-repo is "*" (wildcard), it returns an error (second return value is true).

type SafeOutputsConfig added in v0.2.3

type SafeOutputsConfig struct {
	CreateIssues                    *CreateIssuesConfig                    `yaml:"create-issues,omitempty"`
	CreateDiscussions               *CreateDiscussionsConfig               `yaml:"create-discussions,omitempty"`
	CloseDiscussions                *CloseDiscussionsConfig                `yaml:"close-discussions,omitempty"`
	CloseIssues                     *CloseIssuesConfig                     `yaml:"close-issue,omitempty"`
	ClosePullRequests               *ClosePullRequestsConfig               `yaml:"close-pull-request,omitempty"`
	AddComments                     *AddCommentsConfig                     `yaml:"add-comments,omitempty"`
	CreatePullRequests              *CreatePullRequestsConfig              `yaml:"create-pull-requests,omitempty"`
	CreatePullRequestReviewComments *CreatePullRequestReviewCommentsConfig `yaml:"create-pull-request-review-comments,omitempty"`
	CreateCodeScanningAlerts        *CreateCodeScanningAlertsConfig        `yaml:"create-code-scanning-alerts,omitempty"`
	AddLabels                       *AddLabelsConfig                       `yaml:"add-labels,omitempty"`
	AddReviewer                     *AddReviewerConfig                     `yaml:"add-reviewer,omitempty"`
	AssignMilestone                 *AssignMilestoneConfig                 `yaml:"assign-milestone,omitempty"`
	AssignToAgent                   *AssignToAgentConfig                   `yaml:"assign-to-agent,omitempty"`
	AssignToUser                    *AssignToUserConfig                    `yaml:"assign-to-user,omitempty"` // Assign users to issues
	UpdateIssues                    *UpdateIssuesConfig                    `yaml:"update-issues,omitempty"`
	UpdatePullRequests              *UpdatePullRequestsConfig              `yaml:"update-pull-request,omitempty"` // Update GitHub pull request title/body
	PushToPullRequestBranch         *PushToPullRequestBranchConfig         `yaml:"push-to-pull-request-branch,omitempty"`
	UploadAssets                    *UploadAssetsConfig                    `yaml:"upload-assets,omitempty"`
	UpdateRelease                   *UpdateReleaseConfig                   `yaml:"update-release,omitempty"`    // Update GitHub release descriptions
	CreateAgentTasks                *CreateAgentTaskConfig                 `yaml:"create-agent-task,omitempty"` // Create GitHub Copilot agent tasks
	UpdateProjects                  *UpdateProjectConfig                   `yaml:"update-project,omitempty"`    // Smart project board management (create/add/update)
	LinkSubIssue                    *LinkSubIssueConfig                    `yaml:"link-sub-issue,omitempty"`    // Link issues as sub-issues
	MissingTool                     *MissingToolConfig                     `yaml:"missing-tool,omitempty"`      // Optional for reporting missing functionality
	NoOp                            *NoOpConfig                            `yaml:"noop,omitempty"`              // No-op output for logging only (always available as fallback)
	ThreatDetection                 *ThreatDetectionConfig                 `yaml:"threat-detection,omitempty"`  // Threat detection configuration
	Jobs                            map[string]*SafeJobConfig              `yaml:"jobs,omitempty"`              // Safe-jobs configuration (moved from top-level)
	App                             *GitHubAppConfig                       `yaml:"app,omitempty"`               // GitHub App credentials for token minting
	AllowedDomains                  []string                               `yaml:"allowed-domains,omitempty"`
	Staged                          bool                                   `yaml:"staged,omitempty"`         // If true, emit step summary messages instead of making GitHub API calls
	Env                             map[string]string                      `yaml:"env,omitempty"`            // Environment variables to pass to safe output jobs
	GitHubToken                     string                                 `yaml:"github-token,omitempty"`   // GitHub token for safe output jobs
	MaximumPatchSize                int                                    `yaml:"max-patch-size,omitempty"` // Maximum allowed patch size in KB (defaults to 1024)
	RunsOn                          string                                 `yaml:"runs-on,omitempty"`        // Runner configuration for safe-outputs jobs
	Messages                        *SafeOutputMessagesConfig              `yaml:"messages,omitempty"`       // Custom message templates for footer and notifications
}

SafeOutputsConfig holds configuration for automatic output routes

type SandboxConfig added in v0.31.4

type SandboxConfig struct {
	// New fields
	Agent *AgentSandboxConfig `yaml:"agent,omitempty"` // Agent sandbox configuration
	MCP   *MCPGatewayConfig   `yaml:"mcp,omitempty"`   // MCP gateway configuration

	// Legacy fields (for backward compatibility)
	Type   SandboxType           `yaml:"type,omitempty"`   // Sandbox type: "default" or "sandbox-runtime"
	Config *SandboxRuntimeConfig `yaml:"config,omitempty"` // Custom SRT config (optional)
}

SandboxConfig represents the top-level sandbox configuration from front matter New format: { agent: "awf"|"srt"|{type, config}, mcp: {...} } Legacy format: "default"|"sandbox-runtime" or { type, config }

type SandboxRuntimeConfig added in v0.31.4

type SandboxRuntimeConfig struct {
	// Network is only used internally for generating SRT settings JSON output.
	// It is NOT user-configurable from sandbox.agent.config (yaml:"-" prevents parsing).
	// The json tag is needed for output serialization to .srt-settings.json.
	Network                   *SRTNetworkConfig    `yaml:"-" json:"network,omitempty"`
	Filesystem                *SRTFilesystemConfig `yaml:"filesystem,omitempty" json:"filesystem,omitempty"`
	IgnoreViolations          map[string][]string  `yaml:"ignoreViolations,omitempty" json:"ignoreViolations,omitempty"`
	EnableWeakerNestedSandbox bool                 `yaml:"enableWeakerNestedSandbox" json:"enableWeakerNestedSandbox"`
}

SandboxRuntimeConfig represents the Anthropic Sandbox Runtime configuration This matches the TypeScript SandboxRuntimeConfig interface Note: Network configuration is controlled by the top-level 'network' field, not this struct

type SandboxType added in v0.31.4

type SandboxType string

SandboxType represents the type of sandbox to use

const (
	SandboxTypeAWF     SandboxType = "awf"             // Uses AWF (Agent Workflow Firewall)
	SandboxTypeSRT     SandboxType = "srt"             // Uses Anthropic Sandbox Runtime
	SandboxTypeDefault SandboxType = "default"         // Alias for AWF (backward compat)
	SandboxTypeRuntime SandboxType = "sandbox-runtime" // Alias for SRT (backward compat)
)

type SanitizeOptions added in v0.28.0

type SanitizeOptions struct {
	// PreserveSpecialChars is a list of special characters to preserve during sanitization.
	// Common characters include '.', '_'. If nil or empty, only alphanumeric and hyphens are preserved.
	PreserveSpecialChars []rune

	// TrimHyphens controls whether leading and trailing hyphens are removed from the result.
	// When true, hyphens at the start and end of the sanitized name are trimmed.
	TrimHyphens bool

	// DefaultValue is returned when the sanitized name is empty after all transformations.
	// If empty string, no default is applied.
	DefaultValue string
}

SanitizeOptions configures the behavior of the SanitizeName function.

type ScriptRegistry added in v0.31.3

type ScriptRegistry struct {
	// contains filtered or unexported fields
}

ScriptRegistry manages lazy bundling of JavaScript scripts. It provides a centralized place to register source scripts and retrieve bundled versions on-demand with caching.

Thread-safe: All operations use internal synchronization.

Usage:

registry := NewScriptRegistry()
registry.Register("my_script", myScriptSource)
bundled := registry.Get("my_script")

func NewScriptRegistry added in v0.31.3

func NewScriptRegistry() *ScriptRegistry

NewScriptRegistry creates a new empty script registry.

func (*ScriptRegistry) Get added in v0.31.3

func (r *ScriptRegistry) Get(name string) string

Get retrieves a bundled script by name. Bundling is performed lazily on first access and cached for subsequent calls.

If bundling fails, the original source is returned as a fallback. If the script is not registered, an empty string is returned.

Thread-safe: Multiple goroutines can call Get concurrently.

func (*ScriptRegistry) GetSource added in v0.31.3

func (r *ScriptRegistry) GetSource(name string) string

GetSource retrieves the original (unbundled) source for a script. Useful for testing or when bundling is not needed.

func (*ScriptRegistry) Has added in v0.31.3

func (r *ScriptRegistry) Has(name string) bool

Has checks if a script is registered in the registry.

func (*ScriptRegistry) Names added in v0.31.3

func (r *ScriptRegistry) Names() []string

Names returns a list of all registered script names. Useful for debugging and testing.

func (*ScriptRegistry) Register added in v0.31.3

func (r *ScriptRegistry) Register(name string, source string)

Register adds a script source to the registry. The script will be bundled lazily on first access via Get().

Parameters:

  • name: Unique identifier for the script (e.g., "create_issue", "add_comment")
  • source: The raw JavaScript source code (typically from go:embed)

If a script with the same name already exists, it will be overwritten. This is useful for testing but should be avoided in production.

type SecretExpression added in v0.28.7

type SecretExpression struct {
	VarName  string // The secret variable name (e.g., "DD_API_KEY")
	FullExpr string // The full expression (e.g., "${{ secrets.DD_API_KEY }}")
}

SecretExpression represents a parsed secret expression

type SecretMaskingConfig added in v0.28.0

type SecretMaskingConfig struct {
	Steps []map[string]any `yaml:"steps,omitempty"` // Additional secret redaction steps to inject after built-in redaction
}

SecretMaskingConfig holds configuration for secret redaction behavior

type SerenaLangConfig added in v0.30.5

type SerenaLangConfig struct {
	Version      string `yaml:"version,omitempty"`
	GoModFile    string `yaml:"go-mod-file,omitempty"`   // Path to go.mod file (Go only)
	GoplsVersion string `yaml:"gopls-version,omitempty"` // Version of gopls to install (Go only)
}

SerenaLangConfig represents per-language configuration for Serena

type SerenaToolConfig added in v0.30.5

type SerenaToolConfig struct {
	Version   string                       `yaml:"version,omitempty"`
	Args      []string                     `yaml:"args,omitempty"`
	Languages map[string]*SerenaLangConfig `yaml:"languages,omitempty"`
	// ShortSyntax stores the array of language names when using short syntax (e.g., ["go", "typescript"])
	ShortSyntax []string `yaml:"-"`
}

SerenaToolConfig represents the configuration for the Serena MCP tool

type SkipIfMatchConfig added in v0.30.5

type SkipIfMatchConfig struct {
	Query string // GitHub search query to check before running workflow
	Max   int    // Maximum number of matches before skipping (defaults to 1)
}

SkipIfMatchConfig holds the configuration for skip-if-match conditions

type StepOrderTracker added in v0.24.0

type StepOrderTracker struct {
	// contains filtered or unexported fields
}

StepOrderTracker tracks the order of steps generated during compilation

func NewStepOrderTracker added in v0.24.0

func NewStepOrderTracker() *StepOrderTracker

NewStepOrderTracker creates a new step order tracker

func (*StepOrderTracker) MarkAgentExecutionComplete added in v0.24.0

func (t *StepOrderTracker) MarkAgentExecutionComplete()

MarkAgentExecutionComplete marks that we've passed the agent execution step Validation only applies to steps after this point

func (*StepOrderTracker) RecordArtifactUpload added in v0.24.0

func (t *StepOrderTracker) RecordArtifactUpload(stepName string, uploadPaths []string)

RecordArtifactUpload records that an artifact upload step was added

func (*StepOrderTracker) RecordSecretRedaction added in v0.24.0

func (t *StepOrderTracker) RecordSecretRedaction(stepName string)

RecordSecretRedaction records that a secret redaction step was added

func (*StepOrderTracker) ValidateStepOrdering added in v0.24.0

func (t *StepOrderTracker) ValidateStepOrdering() error

ValidateStepOrdering validates that secret redaction happens before artifact uploads and that all uploaded paths are covered by secret redaction

type StepRecord added in v0.24.0

type StepRecord struct {
	Type        StepType
	Name        string
	Order       int      // Order in which this step was added
	UploadPaths []string // For artifact upload steps, the paths being uploaded
}

StepRecord tracks a step that was generated during compilation

type StepType added in v0.24.0

type StepType int

StepType represents the type of step being generated

const (
	StepTypeSecretRedaction StepType = iota
	StepTypeArtifactUpload
	StepTypeOther
)

type StringLiteralNode

type StringLiteralNode struct {
	Value string
}

StringLiteralNode represents a string literal value

func BuildStringLiteral

func BuildStringLiteral(value string) *StringLiteralNode

BuildStringLiteral creates a string literal node

func (*StringLiteralNode) Render

func (s *StringLiteralNode) Render() string

type TernaryNode

type TernaryNode struct {
	Condition  ConditionNode
	TrueValue  ConditionNode
	FalseValue ConditionNode
}

TernaryNode represents ternary conditional expressions like condition ? true_value : false_value

func BuildTernary

func BuildTernary(condition ConditionNode, trueValue ConditionNode, falseValue ConditionNode) *TernaryNode

BuildTernary creates a ternary conditional expression

func (*TernaryNode) Render

func (t *TernaryNode) Render() string

type ThreatDetectionConfig added in v0.12.2

type ThreatDetectionConfig struct {
	Prompt         string        `yaml:"prompt,omitempty"`        // Additional custom prompt instructions to append
	Steps          []any         `yaml:"steps,omitempty"`         // Array of extra job steps
	EngineConfig   *EngineConfig `yaml:"engine-config,omitempty"` // Extended engine configuration for threat detection
	EngineDisabled bool          `yaml:"-"`                       // Internal flag: true when engine is explicitly set to false
}

ThreatDetectionConfig holds configuration for threat detection in agent output

type TimeDelta added in v0.1.0

type TimeDelta struct {
	Hours   int
	Days    int
	Minutes int
	Weeks   int
	Months  int
}

TimeDelta represents a time duration that can be added to a base time

func (*TimeDelta) String added in v0.1.0

func (td *TimeDelta) String() string

String returns a human-readable representation of the TimeDelta

type ToolCallInfo added in v0.5.1

type ToolCallInfo struct {
	Name          string        // Prettified tool name (e.g., "github::search_issues", "bash")
	CallCount     int           // Number of times this tool was called
	MaxInputSize  int           // Maximum input size in tokens for any call
	MaxOutputSize int           // Maximum output size in tokens for any call
	MaxDuration   time.Duration // Maximum execution duration for any call
}

ToolCallInfo represents statistics for a single tool

type ToolConfig added in v0.9.0

type ToolConfig interface {
	GetString(key string) (string, bool)
	GetStringArray(key string) ([]string, bool)
	GetStringMap(key string) (map[string]string, bool)
	GetAny(key string) (any, bool)
}

ToolConfig represents a tool configuration interface for type safety

type Tools added in v0.22.9

type Tools = ToolsConfig

Tools is a type alias for ToolsConfig for backward compatibility. New code should prefer using ToolsConfig to be explicit about the unified configuration pattern.

func NewTools added in v0.22.9

func NewTools(toolsMap map[string]any) *Tools

NewTools creates a new Tools instance from a map

func (*Tools) GetToolNames added in v0.22.9

func (t *Tools) GetToolNames() []string

GetToolNames returns a list of all tool names configured

func (*Tools) HasTool added in v0.22.9

func (t *Tools) HasTool(name string) bool

HasTool checks if a tool is present in the configuration

type ToolsConfig added in v0.30.0

type ToolsConfig struct {
	// Built-in tools - using pointers to distinguish between "not set" and "set to nil/empty"
	GitHub           *GitHubToolConfig           `yaml:"github,omitempty"`
	Bash             *BashToolConfig             `yaml:"bash,omitempty"`
	WebFetch         *WebFetchToolConfig         `yaml:"web-fetch,omitempty"`
	WebSearch        *WebSearchToolConfig        `yaml:"web-search,omitempty"`
	Edit             *EditToolConfig             `yaml:"edit,omitempty"`
	Playwright       *PlaywrightToolConfig       `yaml:"playwright,omitempty"`
	Serena           *SerenaToolConfig           `yaml:"serena,omitempty"`
	AgenticWorkflows *AgenticWorkflowsToolConfig `yaml:"agentic-workflows,omitempty"`
	CacheMemory      *CacheMemoryToolConfig      `yaml:"cache-memory,omitempty"`
	SafetyPrompt     *bool                       `yaml:"safety-prompt,omitempty"`
	Timeout          *int                        `yaml:"timeout,omitempty"`
	StartupTimeout   *int                        `yaml:"startup-timeout,omitempty"`

	// Custom MCP tools (anything not in the above list)
	Custom map[string]any `yaml:",inline"`
	// contains filtered or unexported fields
}

ToolsConfig represents the unified configuration for all tools in a workflow. This type provides a structured alternative to the pervasive map[string]any pattern. It includes strongly-typed fields for built-in tools and a flexible Custom map for MCP server configurations.

Migration Pattern

This unified type helps eliminate unnecessary type assertions and runtime validation by replacing map[string]any with strongly-typed configuration structs.

Usage Examples

Creating a ToolsConfig from a map[string]any:

toolsMap := map[string]any{
    "github": map[string]any{"allowed": []any{"issue_read"}},
    "bash":   []any{"echo", "ls"},
}
config, err := ParseToolsConfig(toolsMap)
if err != nil {
    // handle error
}

Converting back to map[string]any for legacy code:

toolsMap := config.ToMap()

Backward Compatibility

For functions that currently accept map[string]any, create wrapper functions that handle conversion:

// New signature using ToolsConfig
func processTools(config *ToolsConfig) error {
    if config.GitHub != nil {
        // Access strongly-typed GitHub config
    }
    return nil
}

// Backward compatibility wrapper
func processToolsFromMap(tools map[string]any) error {
    config, err := ParseToolsConfig(tools)
    if err != nil {
        return err
    }
    return processTools(config)
}

Design Notes

  • Built-in tool fields use pointers to distinguish between "not configured" (nil) and "configured with defaults" (non-nil but empty struct)
  • The Custom map stores MCP server configurations that aren't built-in tools
  • The raw map is preserved for perfect round-trip conversion when needed
  • Type alias Tools = ToolsConfig provides backward compatibility for existing code

func ParseToolsConfig added in v0.30.0

func ParseToolsConfig(toolsMap map[string]any) (*ToolsConfig, error)

ParseToolsConfig creates a ToolsConfig from a map[string]any. This function provides backward compatibility for code that uses map[string]any. It parses all known tool types into their strongly-typed equivalents and stores unknown tools in the Custom map.

func (*ToolsConfig) ToMap added in v0.30.0

func (t *ToolsConfig) ToMap() map[string]any

ToMap converts the ToolsConfig back to a map[string]any for backward compatibility. This is useful when interfacing with legacy code that expects map[string]any.

type TypeValidationConfig added in v0.31.4

type TypeValidationConfig struct {
	DefaultMax       int                        `json:"defaultMax"`
	Fields           map[string]FieldValidation `json:"fields"`
	CustomValidation string                     `json:"customValidation,omitempty"`
}

TypeValidationConfig defines validation configuration for a safe output type

func GetValidationConfigForType added in v0.31.4

func GetValidationConfigForType(typeName string) (TypeValidationConfig, bool)

GetValidationConfigForType returns the validation config for a specific type

type UpdateIssuesConfig added in v0.2.12

type UpdateIssuesConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	Status                 *bool `yaml:"status,omitempty"` // Allow updating issue status (open/closed) - presence indicates field can be updated
	Title                  *bool `yaml:"title,omitempty"`  // Allow updating issue title - presence indicates field can be updated
	Body                   *bool `yaml:"body,omitempty"`   // Allow updating issue body - presence indicates field can be updated
}

UpdateIssuesConfig holds configuration for updating GitHub issues from agent output

type UpdateProjectConfig added in v0.30.0

type UpdateProjectConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	GitHubToken          string `yaml:"github-token,omitempty"`
}

UpdateProjectConfig holds configuration for unified project board management

type UpdatePullRequestsConfig added in v0.31.4

type UpdatePullRequestsConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
	Title                  *bool `yaml:"title,omitempty"` // Allow updating PR title - defaults to true, set to false to disable
	Body                   *bool `yaml:"body,omitempty"`  // Allow updating PR body - defaults to true, set to false to disable
}

UpdatePullRequestsConfig holds configuration for updating GitHub pull requests from agent output

type UpdateReleaseConfig added in v0.30.1

type UpdateReleaseConfig struct {
	BaseSafeOutputConfig   `yaml:",inline"`
	SafeOutputTargetConfig `yaml:",inline"`
}

UpdateReleaseConfig holds configuration for updating GitHub releases from agent output

type UploadAssetsConfig added in v0.8.3

type UploadAssetsConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	BranchName           string   `yaml:"branch,omitempty"`       // Branch name (default: "assets/${{ github.workflow }}")
	MaxSizeKB            int      `yaml:"max-size,omitempty"`     // Maximum file size in KB (default: 10240 = 10MB)
	AllowedExts          []string `yaml:"allowed-exts,omitempty"` // Allowed file extensions (default: common non-executable types)
}

UploadAssetsConfig holds configuration for publishing assets to an orphaned git branch

type WebFetchToolConfig added in v0.22.9

type WebFetchToolConfig struct {
}

WebFetchToolConfig represents the configuration for the web-fetch tool

type WebSearchToolConfig added in v0.22.9

type WebSearchToolConfig struct {
}

WebSearchToolConfig represents the configuration for the web-search tool

type WorkflowData

type WorkflowData struct {
	Name                string
	TrialMode           bool           // whether the workflow is running in trial mode
	TrialLogicalRepo    string         // target repository slug for trial mode (owner/repo)
	FrontmatterName     string         // name field from frontmatter (for code scanning alert driver default)
	FrontmatterYAML     string         // raw frontmatter YAML content (rendered as comment in lock file for reference)
	Description         string         // optional description rendered as comment in lock file
	Source              string         // optional source field (owner/repo@ref/path) rendered as comment in lock file
	TrackerID           string         // optional tracker identifier for created assets (min 8 chars, alphanumeric + hyphens/underscores)
	ImportedFiles       []string       // list of files imported via imports field (rendered as comment in lock file)
	IncludedFiles       []string       // list of files included via @include directives (rendered as comment in lock file)
	ImportInputs        map[string]any // input values from imports with inputs (for github.aw.inputs.* substitution)
	On                  string
	Permissions         string
	Network             string // top-level network permissions configuration
	Concurrency         string // workflow-level concurrency configuration
	RunName             string
	Env                 string
	If                  string
	TimeoutMinutes      string
	CustomSteps         string
	PostSteps           string // steps to run after AI execution
	RunsOn              string
	Environment         string // environment setting for the main job
	Container           string // container setting for the main job
	Services            string // services setting for the main job
	Tools               map[string]any
	ParsedTools         *Tools // Structured tools configuration (NEW: parsed from Tools map)
	MarkdownContent     string
	AI                  string        // "claude" or "codex" (for backwards compatibility)
	EngineConfig        *EngineConfig // Extended engine configuration
	AgentFile           string        // Path to custom agent file (from imports)
	StopTime            string
	SkipIfMatch         *SkipIfMatchConfig   // skip-if-match configuration with query and max threshold
	ManualApproval      string               // environment name for manual approval from on: section
	Command             string               // for /command trigger support
	CommandEvents       []string             // events where command should be active (nil = all events)
	CommandOtherEvents  map[string]any       // for merging command with other events
	AIReaction          string               // AI reaction type like "eyes", "heart", etc.
	Jobs                map[string]any       // custom job configurations with dependencies
	Cache               string               // cache configuration
	NeedsTextOutput     bool                 // whether the workflow uses ${{ needs.task.outputs.text }}
	NetworkPermissions  *NetworkPermissions  // parsed network permissions
	SandboxConfig       *SandboxConfig       // parsed sandbox configuration (AWF or SRT)
	SafeOutputs         *SafeOutputsConfig   // output configuration for automatic output routes
	SafeInputs          *SafeInputsConfig    // safe-inputs configuration for custom MCP tools
	Roles               []string             // permission levels required to trigger workflow
	CacheMemoryConfig   *CacheMemoryConfig   // parsed cache-memory configuration
	SafetyPrompt        bool                 // whether to include XPIA safety prompt (default true)
	Runtimes            map[string]any       // runtime version overrides from frontmatter
	ToolsTimeout        int                  // timeout in seconds for tool/MCP operations (0 = use engine default)
	GitHubToken         string               // top-level github-token expression from frontmatter
	ToolsStartupTimeout int                  // timeout in seconds for MCP server startup (0 = use engine default)
	Features            map[string]bool      // feature flags from frontmatter
	ActionCache         *ActionCache         // cache for action pin resolutions
	ActionResolver      *ActionResolver      // resolver for action pins
	StrictMode          bool                 // strict mode for action pinning
	SecretMasking       *SecretMaskingConfig // secret masking configuration
}

WorkflowData holds all the data needed to generate a GitHub Actions workflow

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL