workflow

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

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
)

Variables

This section is empty.

Functions

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 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 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 CreateMissingToolEntry added in v0.21.0

func CreateMissingToolEntry(toolName, reason string, verbose bool) error

CreateMissingToolEntry creates a missing-tool entry in the safe outputs file This helper extracts the common pattern shared by Copilot and Codex engines.

Parameters:

  • toolName: The name of the tool that encountered a permission error
  • reason: The reason/error message for the permission denial
  • verbose: Whether to print verbose output

Returns:

  • error: An error if the operation failed, nil otherwise

func ExtractFirstMatch added in v0.0.22

func ExtractFirstMatch(text, pattern string) string

ExtractFirstMatch extracts the first regex match from a string

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 ExtractStopTimeFromLockFile added in v0.14.0

func ExtractStopTimeFromLockFile(lockFilePath string) string

ExtractStopTimeFromLockFile extracts the STOP_TIME value from a compiled workflow lock file

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 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 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 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 GetLogParserScript added in v0.2.5

func GetLogParserScript(name string) string

GetLogParserScript returns the JavaScript content for a log parser by name

func GetSafeOutputsMCPServerScript added in v0.6.3

func GetSafeOutputsMCPServerScript() string

GetSafeOutputsMCPServerScript returns the JavaScript content for the safe-outputs MCP server

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 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 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 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 ResolveRelativeDate added in v0.2.0

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

ResolveRelativeDate resolves a relative date string to an absolute date string suitable for use with GitHub CLI (YYYY-MM-DD format). If the date string is not relative, it returns the original string.

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 ScanLogForPermissionErrors added in v0.21.0

func ScanLogForPermissionErrors(
	logContent string,
	patterns []ErrorPattern,
	extractToolName ToolNameExtractor,
	defaultTool string,
	verbose bool,
)

ScanLogForPermissionErrors scans log content for permission errors and creates missing-tool entries This helper extracts the common pattern shared by Copilot and Codex engines.

Parameters:

  • logContent: The log content to scan for permission errors
  • patterns: The permission error patterns to match against
  • extractToolName: Engine-specific function to extract tool name from context (can be nil)
  • defaultTool: Default tool name to use if extraction fails
  • verbose: Whether to print verbose output

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 SortStrings added in v0.14.3

func SortStrings(s []string)

SortStrings sorts a slice of strings in place using bubble sort

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 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 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

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 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 {
	Allowed        []string `yaml:"allowed,omitempty"`      // Optional list of allowed labels. If omitted, any labels are allowed (including creating new ones).
	Max            int      `yaml:"max,omitempty"`          // Optional maximum number of labels to add (default: 3)
	Min            int      `yaml:"min,omitempty"`          // Optional minimum number of labels to add
	GitHubToken    string   `yaml:"github-token,omitempty"` // GitHub token for this specific output type
	Target         string   `yaml:"target,omitempty"`       // Target for labels: "triggering" (default), "*" (any issue/PR), or explicit issue/PR number
	TargetRepoSlug string   `yaml:"target-repo,omitempty"`  // Target repository in format "owner/repo" for cross-repository labels
}

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

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 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) 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) GetVersionCommand added in v0.11.0

func (e *BaseEngine) GetVersionCommand() string

GetVersionCommand returns empty string by default (engines can override)

func (*BaseEngine) HasDefaultConcurrency added in v0.14.1

func (e *BaseEngine) HasDefaultConcurrency() bool

HasDefaultConcurrency returns the configured value for default concurrency mode

func (*BaseEngine) IsExperimental

func (e *BaseEngine) IsExperimental() 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
	Min         int    `yaml:"min,omitempty"`          // Minimum 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 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 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 including permission-related errors that should be captured as missing tools

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) GetVersionCommand added in v0.11.0

func (e *ClaudeEngine) GetVersionCommand() string

GetVersionCommand returns the command to get Claude's version

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)

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 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) GetVersionCommand added in v0.11.0

func (e *CodexEngine) GetVersionCommand() string

GetVersionCommand returns the command to get Codex's version

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

	// 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

	// GetVersionCommand returns the command to get the version of the agent (e.g., "copilot --version")
	// Returns empty string if the engine does not support version reporting
	GetVersionCommand() string

	// HasDefaultConcurrency returns true if this engine should have default concurrency mode enabled
	// Default concurrency mode applies gh-aw-{engine-id} pattern when no custom concurrency is configured
	HasDefaultConcurrency() bool
}

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

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) 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) 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) 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) SetFileTracker added in v0.0.22

func (c *Compiler) SetFileTracker(tracker FileTracker)

SetFileTracker sets the file tracker for tracking created files

func (*Compiler) SetNoEmit added in v0.5.1

func (c *Compiler) SetNoEmit(noEmit bool)

SetNoEmit configures whether to validate without generating lock files

func (*Compiler) SetSkipValidation

func (c *Compiler) SetSkipValidation(skip bool)

SetSkipValidation configures whether to skip schema validation

func (*Compiler) SetStrictMode added in v0.12.1

func (c *Compiler) SetStrictMode(strict bool)

SetStrictMode configures whether to enable strict validation mode

func (*Compiler) SetTrialLogicalRepoSlug added in v0.16.0

func (c *Compiler) SetTrialLogicalRepoSlug(repo string)

SetTrialLogicalRepoSlug configures the target repository for trial mode

func (*Compiler) SetTrialMode added in v0.12.0

func (c *Compiler) SetTrialMode(trialMode bool)

SetTrialMode configures whether to run in trial mode (suppresses safe outputs)

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, min int) 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) GetDeclaredOutputFiles added in v0.9.0

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

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) 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) GetVersionCommand added in v0.11.0

func (e *CopilotEngine) GetVersionCommand() string

GetVersionCommand returns the command to get Copilot CLI's version

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 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
	TargetRepoSlug       string `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository discussions
}

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"`
	TargetRepoSlug       string   `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository issues
}

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"`
	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 shared logic with Claude engine

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 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
}

EngineConfig represents the parsed engine configuration

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 {
	// 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 FilterPermissionErrorPatterns added in v0.21.0

func FilterPermissionErrorPatterns(allPatterns []ErrorPattern) []ErrorPattern

FilterPermissionErrorPatterns filters error patterns to only those related to permissions This helper extracts the common pattern shared by Copilot and Codex engines.

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 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 FileTracker added in v0.0.22

type FileTracker interface {
	TrackCreated(filePath string)
}

FileTracker interface for tracking files created during compilation

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 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

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 GenerateRuntimeSetupSteps added in v0.16.0

func GenerateRuntimeSetupSteps(requirements []RuntimeRequirement) []GitHubActionStep

GenerateRuntimeSetupSteps creates GitHub Actions steps for runtime setup

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 GITHUB_AW_AGENT_OUTPUT
	CustomEnvVars []string

	// JavaScript script constant to format and include
	Script string

	// Token configuration (passed to addSafeOutputGitHubTokenForConfig)
	Token string
}

GitHubScriptStepConfig holds configuration for building a GitHub Script step

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 Job

type Job struct {
	Name           string
	DisplayName    string // Optional display name for the job (name property in YAML)
	RunsOn         string
	If             string
	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
}

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) 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 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
}

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 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 engine configurations

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
}

NetworkPermissions represents network access permissions

type NotNode

type NotNode struct {
	Child ConditionNode
}

NotNode represents a NOT operation on a condition

func (*NotNode) Render

func (n *NotNode) Render() string

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 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"

type PlaywrightDockerArgs added in v0.6.1

type PlaywrightDockerArgs struct {
	ImageVersion   string
	AllowedDomains []string
}

PlaywrightDockerArgs represents the common Docker arguments for Playwright container

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")
}

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

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
}

RuntimeRequirement represents a detected runtime requirement

func DetectRuntimeRequirements added in v0.16.0

func DetectRuntimeRequirements(workflowData *WorkflowData) []RuntimeRequirement

DetectRuntimeRequirements analyzes workflow data to detect required runtimes

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]*SafeJobInput `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 SafeJobInput added in v0.9.0

type SafeJobInput struct {
	Description string   `yaml:"description,omitempty"`
	Required    bool     `yaml:"required,omitempty"`
	Default     string   `yaml:"default,omitempty"`
	Type        string   `yaml:"type,omitempty"`
	Options     []string `yaml:"options,omitempty"`
}

SafeJobInput defines an input parameter for a safe job, using workflow_dispatch syntax

type SafeOutputsConfig added in v0.2.3

type SafeOutputsConfig struct {
	CreateIssues                    *CreateIssuesConfig                    `yaml:"create-issues,omitempty"`
	CreateDiscussions               *CreateDiscussionsConfig               `yaml:"create-discussions,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"`
	UpdateIssues                    *UpdateIssuesConfig                    `yaml:"update-issues,omitempty"`
	PushToPullRequestBranch         *PushToPullRequestBranchConfig         `yaml:"push-to-pull-request-branch,omitempty"`
	UploadAssets                    *UploadAssetsConfig                    `yaml:"upload-assets,omitempty"`
	MissingTool                     *MissingToolConfig                     `yaml:"missing-tool,omitempty"`     // Optional for reporting missing functionality
	ThreatDetection                 *ThreatDetectionConfig                 `yaml:"threat-detection,omitempty"` // Threat detection configuration
	Jobs                            map[string]*SafeJobConfig              `yaml:"jobs,omitempty"`             // Safe-jobs configuration (moved from top-level)
	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
}

SafeOutputsConfig holds configuration for automatic output routes

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 {
	Enabled      bool          `yaml:"enabled,omitempty"`       // Whether threat detection is enabled
	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
}

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
	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 ToolNameExtractor added in v0.21.0

type ToolNameExtractor func(lines []string, errorLineIndex int, defaultTool string) string

ToolNameExtractor is a function type that extracts tool name from log context Used by ScanLogForPermissionErrors to allow engine-specific tool name extraction

type UpdateIssuesConfig added in v0.2.12

type UpdateIssuesConfig struct {
	BaseSafeOutputConfig `yaml:",inline"`
	Status               *bool  `yaml:"status,omitempty"`      // Allow updating issue status (open/closed) - presence indicates field can be updated
	Target               string `yaml:"target,omitempty"`      // Target for updates: "triggering" (default), "*" (any issue), or explicit issue number
	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
	TargetRepoSlug       string `yaml:"target-repo,omitempty"` // Target repository in format "owner/repo" for cross-repository issue updates
}

UpdateIssuesConfig holds configuration for updating GitHub issues 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 WorkflowData

type WorkflowData struct {
	Name               string
	TrialMode          bool     // whether the workflow is running in trial mode
	TrialTargetRepo    string   // target repository slug for trial mode (owner/repo)
	FrontmatterName    string   // name field from frontmatter (for code scanning alert driver default)
	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
	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)
	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
	MarkdownContent    string
	AI                 string        // "claude" or "codex" (for backwards compatibility)
	EngineConfig       *EngineConfig // Extended engine configuration
	StopTime           string
	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
	SafeOutputs        *SafeOutputsConfig  // output configuration for automatic output routes
	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
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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