### Install and Start Runner Service with .env File Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Demonstrates how to install and start the GitHub Actions runner as a service, and how to append environment variables to the .env file. ```bash github-act-runner svc install echo "DOCKER_HOST=unix:///var/run/docker.sock" >> .env github-act-runner svc start ``` -------------------------------- ### FailInitJob Example Usage Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Illustrates calling FailInitJob when an error occurs during a critical setup phase, such as setting up Docker, to immediately report the failure. ```go if err := setupDocker(); err != nil { wc.FailInitJob("Setup Docker", err.Error()) return } ``` -------------------------------- ### Interactive Runner Configuration Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Demonstrates how to configure a runner interactively using the ConfigureRunner.Configure method. This example sets up basic configuration and saves the resulting settings to a JSON file. ```go config := &ConfigureRunner{ URL: "https://github.com/owner/repo", Token: "token_from_github", Name: "my-runner", Labels: []string{"custom-label"}, } settings, err := config.Configure(nil, &InteractiveSurvey{}, nil) if err != nil { log.Fatal(err) } // Save settings common.WriteJSON("settings.json", settings) ``` -------------------------------- ### Programmatic Runner Registration Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Shows how to register a runner programmatically by reading configuration from environment variables. This is useful for unattended or automated setups. ```go config := &ConfigureRunner{ URL: os.Getenv("GITHUB_URL"), Token: os.Getenv("RUNNER_TOKEN"), Name: os.Getenv("RUNNER_NAME"), Unattended: true, } settings, err := config.Configure(nil, nil, nil) ``` -------------------------------- ### Configuration Persistence Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Illustrates the pattern for persisting configuration. ```text Configuration persistence example ``` -------------------------------- ### Start GitHub Actions Runner Service Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Start the installed GitHub Actions runner service. This command usually requires administrator privileges. ```bash github-act-runner svc start ``` -------------------------------- ### Run the Runner from Source Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Start the github-act-runner service after it has been configured. ```bash go run . run ``` -------------------------------- ### Install github-act-runner via APT Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Update your package list and install the github-act-runner package using apt. ```bash sudo apt update sudo apt install github-act-runner ``` -------------------------------- ### Complete Configuration Cycle Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/common-utilities.md Demonstrates a full cycle of reading existing settings, configuring a new instance, validating the configuration, persisting it, and cleaning up legacy files. ```go // 1. Read existing settings settings := &runnerconfiguration.RunnerSettings{} if err := common.ReadJSON("settings.json", settings); err != nil && !errors.Is(err, os.ErrNotExist) { log.Fatal(err) } // 2. Configure new instance config := &ConfigureRunner{ URL: "https://github.com/owner/repo", Token: os.Getenv("RUNNER_TOKEN"), } newSettings, err := config.Configure(settings, survey, nil) if err != nil { log.Fatal(err) } // 3. Validate configuration for _, inst := range newSettings.Instances { if err := inst.EnsurePKey(); err != nil { log.Fatal(err) } } // 4. Persist configuration if err := common.WriteJSON("settings.json", newSettings); err != nil { log.Fatal(err) } // 5. Clean up legacy files os.Remove("agent.json") os.Remove("auth.json") os.Remove("cred.pkcs1") fmt.Println("Configuration saved successfully") ``` -------------------------------- ### Go API Request/Response Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/README.md Demonstrates how to make a request and handle a response using the VssConnection in Go. Ensure the VssConnection is properly initialized. ```go type SomeRequest struct { Field1 string Field2 int } type SomeResponse struct { Result string Data interface{} } conn := &VssConnection{...} req := &SomeRequest{...} resp := &SomeResponse{} err := conn.Request(serviceID, protocol, method, params, query, req, resp) ``` -------------------------------- ### Job Execution Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Demonstrates how a job is executed by the runner. ```text Job execution example ``` -------------------------------- ### Registration Flow Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Illustrates the process of registering a runner. ```text Registration flow example ``` -------------------------------- ### Install GitHub Actions Runner Service Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Install the GitHub Actions runner as a system service. This command typically requires administrator privileges. ```bash github-act-runner svc install ``` -------------------------------- ### Runner Registration Flow Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Illustrates a typical runner registration flow, showing how to create a TaskAgent and obtain an access token using the Authorize method. ```APIDOC ## Runner Registration Flow ### Description Illustrates a typical runner registration flow, showing how to create a TaskAgent and obtain an access token using the Authorize method. ```go // 1. TaskAgent created by GitHub during registration agent := &TaskAgent{ ID: 12345, Name: "my-runner", Authorization: TaskAgentAuthorization{ ClientID: "runner-id", AuthorizationURL: "https://github.com/api/v3/auth", PublicKey: TaskAgentPublicKey{ Exponent: "AQAB", Modulus: "...", }, }, } // 2. Get access token for this session httpClient := &http.Client{Timeout: 30 * time.Second} tokenResp, err := agent.Authorize(httpClient, privateKey) // Use tokenResp.AccessToken in subsequent API calls ``` ``` -------------------------------- ### Authorize Method Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Demonstrates how to use the Authorize method on a TaskAgent to obtain an OAuth access token. Requires an HTTP client and an RSA private key for signing. ```go agent := &TaskAgent{ Authorization: TaskAgentAuthorization{ AuthorizationURL: "https://github.com/api/v3/oauth/authorize", ClientID: "abc123def456", }, } tokenResp, err := agent.Authorize(httpClient, privateKey) if err != nil { log.Fatal(err) } fmt.Println("Token:", tokenResp.AccessToken) fmt.Println("Expires in:", tokenResp.ExpiresIn, "seconds") ``` -------------------------------- ### Go Configuration Persistence Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/README.md Shows how to load, modify, and save runner settings using JSON files in Go. Ensure the file paths are correct and the settings struct is defined. ```go // Load settings := &RunnerSettings{} _ = common.ReadJSON("settings.json", settings) // Modify settings.Instances = append(settings.Instances, newInstance) // Save _ = common.WriteJSON("settings.json", settings) ``` -------------------------------- ### ConvertSteps Example Usage Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Demonstrates how to use the ConvertSteps function to convert job request steps and handle potential errors. ```go steps, err := actionsdotnetactcompat.ConvertSteps(jobReq.Steps) if err != nil { return err } // Use steps in act execution ``` -------------------------------- ### Runner Removal Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Illustrates how to deregister a runner using the RemoveRunner.Remove method. This example specifies the runner's details and uses current settings to find and remove the instance. ```go remove := &RemoveRunner{ URL: "https://github.com/owner/repo", Token: "remove_token_from_github", Name: "my-runner", } settings, err := remove.Remove(currentSettings, nil, nil) ``` -------------------------------- ### Complete Job Execution Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Demonstrates the typical lifecycle of a job execution using DefaultWorkerContext, from receiving a request to completing the job with results. ```go // 1. Receive job request jobReq := &protocol.AgentJobRequestMessage{ JobID: "job-123", JobDisplayName: "Build and Test", // ... other fields } // 2. Create worker context ctx, cancel := context.WithCancel(context.Background()) def cancel() wc := &DefaultWorkerContext{ RunnerMessage: jobReq, JobExecutionContext: ctx, RunnerLogger: &myLogger, } // 3. Initialize connections wc.Init() // 4. Run steps and collect outputs outputs := make(map[string]protocol.VariableValue) for _, step := range jobReq.Steps { result := executeStep(step) outputs[step.ID] = protocol.VariableValue{ Value: result, IsSecret: false, } wc.Logger().Log(result) } // 5. Complete job wc.FinishJob("success", &outputs) ``` -------------------------------- ### Error Handling Patterns Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Demonstrates common patterns for handling errors. ```text Error handling patterns ``` -------------------------------- ### Property Lookup Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Shows how to use LookupString to retrieve a string property from the agent's properties collection and handle cases where the property might not exist or is not a string. ```go agent := &TaskAgent{ Properties: PropertiesCollection{ "ServerUrlV2": PropertyValue{ Type: "System.String", Value: "https://github.actions.com", }, }, } if url, ok := agent.Properties.LookupString("ServerUrlV2"); ok { fmt.Println("Using V2 protocol at:", url) } else { fmt.Println("Using standard protocol") } ``` -------------------------------- ### Message Decryption Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Shows how to decrypt messages. ```text Message decryption example ``` -------------------------------- ### FinishJob Example Usage Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Demonstrates how to call the FinishJob method with job results and outputs, including secret values. Outputs are sent regardless of secret content. ```go outputs := map[string]protocol.VariableValue{ "result": {Value: "success", IsSecret: false}, "token": {Value: "abc123", IsSecret: true}, } wc.FinishJob("success", &outputs) ``` -------------------------------- ### Run Method Signature Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/run-runner.md The Run method starts the runner and begins listening for jobs. It requires a RunnerEnvironment, a listener context, and a core context for managing job acceptance and cancellation. ```go func (run *RunRunner) Run( runnerenv RunnerEnvironment, listenerctx context.Context, corectx context.Context, ) error ``` -------------------------------- ### Add Debian Repository Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Add the official Debian repository to your system's sources list to install the github-act-runner. ```bash deb https://gagis.hopto.org/repo/chrishx/deb all main ``` -------------------------------- ### Property Lookup Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Demonstrates how to use LookupString to retrieve a string property from a PropertiesCollection and handle cases where the property might not exist or be of the wrong type. ```APIDOC ## Property Lookup Example ### Description Demonstrates how to use LookupString to retrieve a string property from a PropertiesCollection and handle cases where the property might not exist or be of the wrong type. ```go agent := &TaskAgent{ Properties: PropertiesCollection{ "ServerUrlV2": PropertyValue{ Type: "System.String", Value: "https://github.actions.com", }, }, } if url, ok := agent.Properties.LookupString("ServerUrlV2"); ok { fmt.Println("Using V2 protocol at:", url) } else { fmt.Println("Using standard protocol") } ``` ``` -------------------------------- ### RunRunner.Run Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/run-runner.md Starts the runner and begins listening for jobs from the GitHub Actions service. It manages job acquisition, dispatches execution to workers, and handles job lifecycle. ```APIDOC ## RunRunner.Run ### Description Starts the runner and begins listening for jobs from GitHub Actions service. It manages job acquisition, dispatches execution to workers, and handles job lifecycle. ### Method func (run *RunRunner) Run( runnerenv RunnerEnvironment, listenerctx context.Context, corectx context.Context, ) error ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Returns nil if the exit is clean. #### Response Example None ### Error Handling Returns an error if a fatal failure occurs during startup or operation. ``` -------------------------------- ### FailInitJob Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Marks job initialization failure and reports the error to GitHub. This method is crucial for handling setup errors gracefully by logging the failure and ensuring the job is marked as failed. ```APIDOC ## FailInitJob ### Description Marks job initialization failure and reports the error to GitHub. This method is crucial for handling setup errors gracefully by logging the failure and ensuring the job is marked as failed. ### Method Internal call to `FinishJob` after logging failure. ### Endpoint N/A (internal method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go if err := setupDocker(); err != nil { wc.FailInitJob("Setup Docker", err.Error()) return } ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Complete Message Poll Loop Example Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent-session.md Demonstrates a complete message poll loop using AgentMessageConnection.GetNextMessage. It includes context management, error handling, message decryption, and JSON unmarshalling for job requests. ```go session := &AgentMessageConnection{ VssConnection: vssConnection, TaskAgentSession: taskAgentSession, Status: "Online", } for { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) message, err := session.GetNextMessage(ctx) cancel() if err != nil { log.Printf("Failed to get message: %v", err) continue } plaintext, err := message.Decrypt(session) if err != nil { log.Printf("Failed to decrypt: %v", err) continue } var jobReq JobRequest if err := json.Unmarshal(plaintext, &jobReq); err != nil { log.Printf("Invalid job request: %v", err) continue } // Process jobReq... } ``` -------------------------------- ### Environment Variables for Runner Service Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Example of an .env file used for persistent environment variables when running the runner in service mode. This file can be updated to include variables like DOCKER_HOST. ```dotenv HOME=/home/github-runner PATH=/usr/local/bin:/usr/bin DOCKER_HOST=unix:///var/run/docker.sock DEBUG=1 ``` -------------------------------- ### Survey Interface Definition Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Defines the interface for interactive prompts used during runner configuration. It includes methods for getting single-line input, select input, and multi-select input. ```go type Survey interface { GetInput(prompt, def string) string GetSelectInput(prompt string, options []string, def string) string GetMultiSelectInput(prompt string, options []string) []string } ``` -------------------------------- ### Initialize and Run the GitHub Actions Runner Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/run-runner.md This Go code snippet demonstrates how to load configuration, initialize the RunRunner with specific settings, and manage its execution context using signals for graceful shutdown. It requires a custom runner environment implementation. ```Go settings, _ := loadConfiguration() runner := &RunRunner{ Once: false, // Keep running Trace: false, // No debug tracing Version: "0.13.0", Settings: settings, } ctx := context.Background() listenerCtx, cancelListener := context.WithCancel(ctx) execCtx, cancelExec := context.WithCancel(ctx) // Handle signals to initiate graceful shutdown go func() { sig := <-signalChan if sig == SIGTERM { cancelExec() // Force cancel jobs } else { cancelListener() // Stop accepting new jobs } }() env := &MyRunnerEnvironment{} if err := runner.Run(env, listenerCtx, execCtx); err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Job Execution Context Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Retrieves the context.Context for the current job execution, which can be used for cancellation signals. ```go func (wc *DefaultWorkerContext) JobExecCtx() context.Context ``` -------------------------------- ### Configure Runner from Source Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Configure a new runner by specifying the GitHub URL, runner name, labels, and registration token. Requires Go 1.21+. ```bash go run . configure --url --name -l label1,label2 --token ``` -------------------------------- ### Load Runner Configuration and State Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/common-utilities.md Demonstrates loading runner configuration, sessions, and job state from JSON files using `ReadJSON`. Handles potential errors like missing files. ```Go // Load configuration settings := &runnerconfiguration.RunnerSettings{} if err := common.ReadJSON("settings.json", settings); err != nil { log.Fatal(err) } // Load sessions var sessions []*protocol.TaskAgentSession{} _ = common.ReadJSON("sessions.json", &sessions) // OK if missing // Load job state jobrun := &JobRun{} if err := common.ReadJSON("jobrun.json", jobrun); err == nil { // Resume interrupted job } ``` -------------------------------- ### ConvertServiceContainer Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Converts service container specifications from a job request into the act format, enabling the setup of service containers for job execution. ```APIDOC ## ConvertServiceContainer ### Description Converts service container specifications from a job to act format. This allows for the definition and execution of service containers required by the job. ### Method `ConvertServiceContainer` ### Parameters #### Path Parameters - **jobServiceContainers** (*protocol.TemplateToken) - Required - Service container definition ### Returns - Map of service name to container spec, or error ### Container Configuration - Image reference - Port mappings - Environment variables - Volume mounts - Logging options ### Supported Actions - Docker registry pull - Environment variable resolution - Network configuration ``` -------------------------------- ### Remove Runner Locally Only Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Remove the runner configuration locally without interacting with the GitHub API. This is useful for cleaning up local runner installations. ```bash github-act-runner remove --local ``` -------------------------------- ### Common Property Keys Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Details common property keys used within the Properties field, including their type, purpose, and example values. ```APIDOC ## Common Property Keys ### Description Details common property keys used within the Properties field, including their type, purpose, and example values. | Property Name | Type | Purpose | Example | |---------------|------|---------|---------| | `RequireFipsCryptography` | boolean | Use FIPS-compliant PS256 signing | true/false | | `ServerUrlV2` | string | Use V2 server protocol | URL string | | `SupportedCapabilities` | string | Runner capability flags | "ubuntu-20.04,docker" | ``` -------------------------------- ### Configure Runner with URL and Token Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Configure a new runner by providing the GitHub repository URL and a registration token. The `--unattended` flag suppresses interactive prompts. ```bash github-act-runner configure \ --url https://github.com/YOUR-USERNAME/YOUR-REPOSITORY \ --token YOUR-REGISTRATION-TOKEN \ --unattended ``` -------------------------------- ### Runner Registration Flow Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Demonstrates the typical flow for registering a Task Agent, including creating the agent object and obtaining an access token using the Authorize method. ```go // 1. TaskAgent created by GitHub during registration agent := &TaskAgent{ ID: 12345, Name: "my-runner", Authorization: TaskAgentAuthorization{ ClientID: "runner-id", AuthorizationURL: "https://github.com/api/v3/auth", PublicKey: TaskAgentPublicKey{ Exponent: "AQAB", Modulus: "...", }, }, } // 2. Get access token for this session httpClient := &http.Client{Timeout: 30 * time.Second} tokenResp, err := agent.Authorize(httpClient, privateKey) // Use tokenResp.AccessToken in subsequent API calls ``` -------------------------------- ### Read Configuration with Fail Fast Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/common-utilities.md Reads essential configuration settings from a JSON file. Exits the program immediately if the configuration file cannot be loaded. ```go // Configuration must exist settings := &runnerconfiguration.RunnerSettings{} if err := common.ReadJSON("settings.json", settings); err != nil { fmt.Printf("Failed to load configuration: %v\n", err) os.Exit(1) } ``` -------------------------------- ### Display Runner Help Information Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md View the help information for the github-act-runner command to understand available options and commands. ```bash github-act-runner --help ``` -------------------------------- ### LaunchActionCache Fetch Method Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Fetches action code from a repository, cloning or updating the cache if necessary. Supports public and private repositories and caches indefinitely. ```go type LaunchActionCache struct {} func (cache *LaunchActionCache) Fetch( ctx context.Context, cacheDir string, url string, ref string, token string, ) (string, error) ``` -------------------------------- ### Init Method Signature Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Signature for the Init method, responsible for initializing the worker context by setting up necessary connections and loggers. ```go func (wc *DefaultWorkerContext) Init() ``` -------------------------------- ### Configure Runner with PAT and Labels Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Configure a runner using a Personal Access Token (PAT) and custom labels. The `--no-default-labels` flag prevents the addition of default system labels. ```bash github-act-runner configure \ --url https://github.com/YOUR-USERNAME/YOUR-REPOSITORY \ --pat YOUR-PAT \ --name my-custom-runner \ --labels "label1,label2" \ --no-default-labels ``` -------------------------------- ### Go Error Handling Patterns Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/README.md Illustrates different strategies for handling errors in Go, including fatal, retryable, and graceful degradation scenarios. Adjust retry logic and sleep durations as needed. ```go // Fatal errors if err := criticalOperation(); err != nil { fmt.Printf("Fatal error: %v\n", err) os.Exit(1) } // Retry errors for attempt := 0; attempt < maxRetries; attempt++ { if err := retryableOperation(); err == nil { break } else if attempt < maxRetries-1 { time.Sleep(retryDelay) } } // Graceful degradation if err := optionalOperation(); err != nil { logger.Printf("Warning: %v (continuing anyway)\n", err) } ``` -------------------------------- ### ConfigureRunner.Configure Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Registers a new runner with GitHub. It validates required fields, authenticates with the GitHub API, retrieves runner pool information, creates a TaskAgent, generates an RSA key pair, requests a session, and returns updated settings. It also handles ephemeral runner flags, label exclusions, and applies custom and system labels. ```APIDOC ## ConfigureRunner.Configure ### Description Registers a new runner with GitHub. This method handles the entire process from validation and authentication to session request and settings update. ### Method (Implicitly a method call on ConfigureRunner struct) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed as arguments) ### Parameters (as arguments) - **settings** (*runnerconfiguration.RunnerSettings) - Optional - Existing settings to append to (or nil for new). - **survey** (Survey) - Required - Interactive prompt interface. - **client** (*http.Client) - Optional - Custom HTTP client (or nil for default). ### Returns - **runnerconfiguration.RunnerSettings** - Updated settings with new instance. - **error** - An error if the configuration fails. ### Behavior Details 1. Validates required fields (URL, token or PAT) 2. Authenticates with GitHub API 3. Retrieves runner pool information 4. Creates TaskAgent on GitHub 5. Generates RSA key pair 6. Requests session from GitHub 7. Returns updated settings with new instance appended 8. If `Ephemeral`, sets Agent.Ephemeral flag 9. If `NoDefaultLabels`, excludes self-hosted/OS/arch labels 10. Applies custom labels and system labels ### Error Cases - Invalid GitHub URL - Authentication failure - Network errors - API validation errors - Encryption/key generation failures ``` -------------------------------- ### Error Handling Pattern for Step Conversion Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Demonstrates a consistent error handling pattern for converting job requests and steps, ensuring proper error propagation and handling of empty steps. ```go if jobReq == nil { return nil, fmt.Errorf("job request required") } if jobReq.Steps == nil { return []*model.Step{}, nil // Empty steps is valid } steps := make([]*model.Step, 0, len(jobReq.Steps)) for i, step := range jobReq.Steps { converted, err := convertStep(&step) if err != nil { return nil, fmt.Errorf("step %d: %w", i, err) } steps = append(steps, converted) } return steps, nil ``` -------------------------------- ### Register a New Runner Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Register a new runner with GitHub by providing the repository/organization URL, runner name, labels, and registration token. ```bash github-act-runner new --url --name --labels --token ``` -------------------------------- ### settings.json Structure Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md The main runner configuration file. It defines pool details, registration URLs, and runner instances with their authentication and agent metadata. ```json { "poolId": 1, "registrationUrl": "https://github.com", "instances": [ { "poolId": 1, "registrationUrl": "https://github.com", "auth": { "url": "https://github.com", "token_schema": "Bearer", "token": "ghu_xxxxx...", "use_v2_flow": false }, "agent": { "authorization": { "authorizationUrl": "https://github.com/api/v3/oauth/authorize", "clientId": "runner-id-uuid", "publicKey": { "exponent": "AQAB", "modulus": "..." } }, "id": 123456, "name": "my-runner", "version": "2.319.0", "osDescription": "Linux 5.15.0", "provisioningState": "Provisioned", "createdOn": "2024-01-01T00:00:00.0000000Z", "ephemeral": false, "disableUpdate": false, "maxParallelism": 1, "labels": [ {"id": 1, "name": "self-hosted", "type": "read-only"}, {"id": 2, "name": "Linux", "type": "read-only"}, {"id": 3, "name": "X64", "type": "read-only"}, {"id": 4, "name": "custom-label", "type": "user"} ], "properties": {} }, "key": "base64-encoded-rsa-private-key" } ] } ``` -------------------------------- ### Run GitHub Actions Runner Service with Environment File Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Run the GitHub Actions runner service, loading environment variables from a specified .env file. This allows for external configuration of service parameters. ```bash github-act-runner svc run --env-file .env ``` -------------------------------- ### RunnerInstance Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Configuration for a single runner instance, containing pool ID, authentication details, agent information, and work folder. ```go type RunnerInstance struct { PoolID int64 RegistrationURL string Auth *protocol.GitHubAuthResult Agent *protocol.TaskAgent Key string PKey *rsa.PrivateKey RunnerGuard string WorkFolder string } ``` -------------------------------- ### Import Repository Public Key Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Import the public key for the Debian repository to verify package authenticity. ```bash curl -sS https://gagis.hopto.org/repo/chrishx/pubkey.gpg | sudo tee -a /etc/apt/trusted.gpg.d/chrishx-github-act-runner.asc ``` -------------------------------- ### Typical Execution Flow in ActRunner Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Illustrates the standard sequence of operations for executing a worker job, from receiving the request to reporting completion. ```go // 1. Receive job request jobReq := &protocol.AgentJobRequestMessage{} // 2. Create worker context wc := &DefaultWorkerContext{ RunnerMessage: jobReq, } wc.Init() // 3. Convert to act format steps, _ := ConvertSteps(jobReq.Steps) env, _ := ConvertEnvironment(jobReq.EnvironmentVariables) services, _ := ConvertServiceContainer(jobReq.JobServiceContainers) // 4. Execute via act runner := &ActRunner{} err := runner.ExecWorker(run, wc, jobReq, nil) // 5. Report completion if err != nil { wc.FailInitJob("Execution failed", err.Error()) } else { wc.FinishJob("success", &outputs) } ``` -------------------------------- ### Set JIT Configuration for Runner Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Use this command to set the JIT configuration for the runner. This is useful for ephemeral runners or when not using a persistent configuration file. ```bash export ACTIONS_RUNNER_INPUT_JITCONFIG='' github-act-runner run ``` -------------------------------- ### Save New Settings After Registration Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/common-utilities.md Saves new configuration settings to a JSON file after registration. Handles potential errors during the write operation. ```go settings, _ := config.Configure(nil, survey, nil) if err := common.WriteJSON("settings.json", settings); err != nil { log.Fatal(err) } ``` -------------------------------- ### ConfigureRunner.Configure Function Signature Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Defines the signature for configuring a new runner. It accepts existing settings, a survey interface for interactive prompts, and an HTTP client. ```go func (config *ConfigureRunner) Configure( settings *runnerconfiguration.RunnerSettings, survey Survey, client *http.Client, ) (*runnerconfiguration.RunnerSettings, error) ``` -------------------------------- ### BuildURL Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/vss-connection.md Constructs a fully-formed URL with path parameters and query string parameters. ```APIDOC ## BuildURL ### Description Constructs a fully-formed URL with path parameters and query string parameters. ### Method `BuildURL` ### Parameters #### Path Parameters - **relativePath** (string) - API endpoint path with placeholders like `/{id}/action` - **ppath** (map[string]string) - Path parameter replacements, keys without braces - **query** (map[string]string) - Query string parameters ### Returns - string: Fully-formed URL string - error: Error if URL construction fails ### Example ```go url, err := vss.BuildURL( "/repos/{owner}/{repo}/actions/runners", map[string]string{"owner": "user", "repo": "repo"}, map[string]string{"state": "online"}, ) // Result: "https://github.com/api/v3/repos/user/repo/actions/runners?state=online" ``` ``` -------------------------------- ### ConfigureRemoveRunner Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Shared base configuration for both configuring and removing runners. Includes client, URL, name, and authentication details. ```go type ConfigureRemoveRunner struct { Client *http.Client URL string Name string Token string Pat string Unattended bool Trace bool } ``` -------------------------------- ### TaskOrchestrationPlanReference Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/types.md Represents a reference to a job plan. ```go type TaskOrchestrationPlanReference struct { ScopeIdentifier string PlanID string PlanType string Version int32 } ``` -------------------------------- ### Create GithubApiUrlBuilder Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Creates a URL builder for a given GitHub instance. Handles normalization for GitHub.com, Enterprise SaaS, and GHE Server. ```go func NewGithubApiUrlBuilder(baseURLString string) (*GithubApiUrlBuilder, error) ``` ```go builder, err := NewGithubApiUrlBuilder("https://github.com") // builder.URL.Host = "api.github.com" // builder.ApiScope = "" builder, err := NewGithubApiUrlBuilder("https://github.company.com") // builder.URL.Host = "github.company.com" // builder.ApiScope = "/api/v3" ``` -------------------------------- ### RunnerEnvironment Interface Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the RunnerEnvironment interface, detailing its methods and signatures. ```APIDOC ## RunnerEnvironment Interface ### Description Defines the contract for the runner environment, providing access to system-level information and operations. ### Methods - **getRunnerVersion(): string** - Returns the current runner version. - **getRunnerOs(): string** - Returns the operating system of the runner. - **getRunnerArchitecture(): string** - Returns the architecture of the runner. - **getWorkingDirectory(): string** - Returns the current working directory. - **getTempDirectory(): string** - Returns the temporary directory path. - **getAgentId(): string** - Returns the agent identifier. - **getJobId(): string** - Returns the job identifier. - **getPlanUrl(): string** - Returns the URL of the agent plan. ``` -------------------------------- ### BuildURL with Path and Query Parameters Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/vss-connection.md Constructs a fully-formed URL for VSS API endpoints, supporting path and query parameter replacements. Use this to dynamically build API request URLs. ```Go url, err := vss.BuildURL( "/repos/{owner}/{repo}/actions/runners", map[string]string{"owner": "user", "repo": "repo"}, map[string]string{"state": "online"}, ) // Result: "https://github.com/api/v3/repos/user/repo/actions/runners?state=online" ``` -------------------------------- ### Run with Terminal Allocation and Tracing Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/configuration.md Run the GitHub Actions runner, allocating a pseudo-terminal (PTY) if possible and enabling HTTP communication tracing. This can be helpful for debugging. ```bash github-act-runner run --terminal --trace ``` -------------------------------- ### ConfigureRunner Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Defines the options for registering a new GitHub Actions runner. It includes labels, group, and other configuration settings. ```go type ConfigureRunner struct { ConfigureRemoveRunner Labels []string NoDefaultLabels bool SystemLabels []string RunnerGroup string Ephemeral bool RunnerGuard string Replace bool DisableUpdate bool WorkFolder string } ``` -------------------------------- ### LaunchActionCache.Fetch Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Caches action code from a repository. It clones the repository if not already cached, updates existing caches, and supports both public and private repositories without an expiration. ```APIDOC ## LaunchActionCache.Fetch ### Description Caches action code from a repository. It clones the repository if not already cached, updates existing caches, and supports both public and private repositories without an expiration. ### Method Not applicable (Go method) ### Endpoint Not applicable (Go method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Path to cached action code (string) #### Response Example "/path/to/cached/action" ``` -------------------------------- ### FailInitJob Method Signature Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/worker-context.md Signature for the FailInitJob method, used to report initialization failures of a job to GitHub with a title and detailed message. ```go func (wc *DefaultWorkerContext) FailInitJob(title string, message string) ``` -------------------------------- ### RunnerSettings Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Represents the complete configuration for a runner, including pool ID and a list of runner instances. Used for persisting settings. ```go type RunnerSettings struct { PoolID int64 RegistrationURL string Instances []*RunnerInstance } ``` -------------------------------- ### VssActionCache Fetch Method Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md An alternative caching method using the VSS protocol, offering more reliability for enterprise scenarios and respecting network policies. ```go type VssActionCache struct {} func (cache *VssActionCache) Fetch( ctx context.Context, cacheDir string, url string, ref string, token string, ) (string, error) ``` -------------------------------- ### TaskAgent Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/types.md Represents a runner instance registered with GitHub. Used for registration, authorization, and session creation. ```go type TaskAgent struct { Authorization TaskAgentAuthorization Labels []AgentLabel MaxParallelism int ID int64 Name string Version string OSDescription string Enabled *bool ProvisioningState string AccessPoint string CreatedOn string Ephemeral bool DisableUpdate bool Properties PropertiesCollection } ``` -------------------------------- ### Construct Absolute API URL Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/runner-configuration.md Constructs the full API URL for a given path using the configured builder. Useful for direct API calls. ```go func (apiBuilder *GithubApiUrlBuilder) AbsoluteApiUrl(p string) string ``` ```go url := builder.AbsoluteApiUrl("/user") // For github.com: "https://api.github.com/user" // For GHE: "https://github.company.com/api/v3/user" ``` -------------------------------- ### HTTPClient Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/vss-connection.md Returns the HTTP client, creating a default one if needed with proper TLS and timeout configuration. ```APIDOC ## HTTPClient ### Description Returns the HTTP client, creating a default one if needed with proper TLS and timeout configuration. ### Method `HTTPClient` ### Returns - *http.Client: Configured `*http.Client` with: - 1 max idle connection - 100 second idle timeout - Optional TLS verification skip if `SKIP_TLS_CERT_VALIDATION` environment variable is set - 100 second request timeout - Maximum 10 redirects ``` -------------------------------- ### ActionStep Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/types.md Defines a single step within a workflow. ```go type ActionStep struct { ID string Type string Reference ActionStepDefinitionReference DisplayNameToken *TemplateToken ContextName string Environment *TemplateToken Inputs *TemplateToken Condition string ContinueOnError *TemplateToken TimeoutInMinutes *TemplateToken } ``` -------------------------------- ### BasicLogger Interface Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the BasicLogger interface, outlining its logging methods. ```APIDOC ## BasicLogger Interface ### Description Provides a basic logging interface for emitting messages. ### Methods - **debug(message: string): void** - Logs a debug message. - **info(message: string): void** - Logs an informational message. - **warning(message: string): void** - Logs a warning message. - **error(message: string): void** - Logs an error message. - **fatal(message: string): void** - Logs a fatal error message. ``` -------------------------------- ### TaskAgentSessionKey Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/types.md Manages encryption keys for agent sessions. ```go type TaskAgentSessionKey struct { Encrypted bool Value string } ``` -------------------------------- ### TaskAgentAuthorization Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/types.md Holds OAuth and signing credentials for a Task Agent. ```go type TaskAgentAuthorization struct { AuthorizationURL string ClientID string PublicKey TaskAgentPublicKey } ``` -------------------------------- ### Clone the Runner Source Code Source: https://github.com/christopherhx/github-act-runner/blob/main/README.md Clone the github-act-runner repository from GitHub, including submodules, to build from source. ```bash git clone https://github.com/ChristopherHX/github-act-runner.git --recursive ``` -------------------------------- ### ConvertMatrixInstance Function Signature Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Provides the function signature for ConvertMatrixInstance, which converts workflow context to matrix instance values. ```go func ConvertMatrixInstance(contextData map[string]protocol.PipelineContextData) (map[string]interface{}, error) ``` -------------------------------- ### Retrieve and Cache Connection Data with Retries Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/vss-connection.md Fetches service location information from GitHub, caching the result and retrying with exponential backoff on failure. This method ensures robust retrieval of essential service endpoint data. ```Go vssConnection.GetConnectionData() ``` -------------------------------- ### TaskAgentPublicKey Struct Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/types.md Contains metadata for an RSA public key used by a Task Agent. ```go type TaskAgentPublicKey struct { Exponent string Modulus string } ``` -------------------------------- ### API Reference Overview Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt The API reference details 40 public methods across 8 modules, with comprehensive error handling and integration patterns. ```APIDOC ## API Reference ### Description Provides documentation for all public methods, modules, constants, and type definitions within the github-act-runner project. ### Modules - vss-connection.md - task-agent.md - task-agent-session.md - run-runner.md - worker-context.md - runner-configuration.md - common-utilities.md - action-execution.md ### Key Features - 40 public methods fully documented - 8 API modules with examples - Error handling for each method - Integration patterns shown - Constants and type definitions included ``` -------------------------------- ### ConvertDefaults Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Converts job default configurations, such as the default shell and working directory, into the act format. ```APIDOC ## ConvertDefaults ### Description Converts job defaults, such as the default shell and working directory, into a format compatible with act execution. ### Method `ConvertDefaults` ### Returns - Defaults configuration or error ### Defaults Include - Default shell for run steps - Working directory - Environment variables at job level - Shell options ``` -------------------------------- ### Write JSON with Fallback Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/common-utilities.md Attempts to write JSON data to a file. If the write operation fails, it logs a warning but continues execution, potentially losing session data if a crash occurs. ```go // Try to save, log if fails if err := common.WriteJSON("sessions.json", sessions); err != nil { runner.Printf("Warning: Cannot persist sessions: %v\n", err) // Continue anyway, sessions lost if crash } ``` -------------------------------- ### toStringMap Utility Function Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/action-execution.md Recursively converts arbitrary maps to have string keys, which is a requirement for some step formatters. ```go func toStringMap(src interface{}) interface{} ``` -------------------------------- ### WorkerContext Interface Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the WorkerContext interface, outlining its methods and signatures. ```APIDOC ## WorkerContext Interface ### Description Defines the contract for worker context, providing essential methods for interacting with the runner environment. ### Methods - **log(message: string): void** - Logs a message to the worker's output. - **getVariable(name: string): string | undefined** - Retrieves an environment variable. - **getSecret(name: string): string | undefined** - Retrieves a secret value. - **getTaskInput(name: string): string** - Retrieves a task input value. - **setResult(result: TaskResult): void** - Sets the result of the current task. - **addAttachment(name: string, path: string): Promise** - Adds a file attachment to the task output. - **downloadArtifact(name: string, path: string): Promise** - Downloads a specified artifact. - **uploadArtifact(name: string, path: string): Promise** - Uploads a specified artifact. ``` -------------------------------- ### Constants Source: https://github.com/christopherhx/github-act-runner/blob/main/_autodocs/api-reference/task-agent.md Lists constants used within the system, including their name, value, and purpose. ```APIDOC ## Constants ### Description Lists constants used within the system, including their name, value, and purpose. | Name | Value | Purpose | |------|-------|---------| | `jwtExpiration` | `5 minutes` | JWT token lifetime | | `authFailurePrefix` | `"Failed to Authorize: "` | Error message prefix | ```