runner

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-2-Clause Imports: 42 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package runner is the jargo development runner. It runs a bot and provides what the bot needs around it: answering WebRTC connections, minting LiveKit tokens, and accepting telephony and WebSocket connections, behind one HTTP server that serves all of them at once.

A bot is a Bot function. The runner calls it once for each session, with the arguments for the transport the session arrived on, and CreateTransport turns those arguments into a transport:

func bot(ctx context.Context, args runner.Arguments) error {
	t, err := runner.CreateTransport(ctx, args, runner.TransportParams{
		WebRTC: func() transport.Params { return transport.DefaultParams() },
	})
	if err != nil {
		return err
	}
	// Build the pipeline around t.Input() and t.Output() and run it.
}

func main() { runner.Main(bot) }

A bot that needs to know its transport switches on the arguments' type: *WebRTCRunnerArguments, *WebSocketRunnerArguments or *LiveKitRunnerArguments.

Clients declare the transport they want in the transport field of POST /start, which defaults to "webrtc":

{
	"transport": "webrtc",  // webrtc, livekit, websocket, twilio, telnyx, plivo or exotel
	"enableDefaultIceServers": false,  // WebRTC only
	"body": {...}
}

The supported transports are:

  • WebRTC: the browser client at /client, signaling at /api/offer.
  • LiveKit: mints room tokens and runs the bot as a participant.
  • Telephony: the webhook and the media WebSocket (/ws) for Twilio, Telnyx, Plivo and Exotel, the provider detected from its first messages.
  • WebSocket: plain WebSocket clients at /ws-client.
  • WhatsApp: the calling webhook at /whatsapp, with --whatsapp.

To run a bot locally:

  • All transports (default): go run .
  • WebRTC only: go run . -t webrtc
  • ESP32: go run . -t webrtc --esp32 --host 192.168.1.100
  • WebRTC with custom STUN/TURN: go run . -t webrtc --ice-servers stun:stun.l.google.com:19302 --ice-servers '{"urls": "turn:turn.example.com:3478", "username": "user", "credential": "pass"}' (or set JARGO_ICE_SERVERS)
  • Telephony: go run . -t twilio -x your_username.ngrok.io
  • Exotel: go run . -t exotel (no proxy needed, but a tunnel to port 7860 is)
  • LiveKit only: go run . -t livekit
  • WhatsApp: go run . --whatsapp

Unlike the rest of jargo, the runner reads its configuration from the command line and the environment, a .env file included: it is the entry point of an application, not a library a program configures.

Example

A bot is one function, called for every session. It builds the session's transport, its pipeline around it, and runs it. This one says one sentence to whoever connects, then hangs up. Main serves it, with a browser client at http://localhost:7860.

package main

import (
	"context"
	"os"

	"github.com/gojargo/jargo/frames"
	"github.com/gojargo/jargo/pipeline"
	"github.com/gojargo/jargo/provider/cartesia"
	"github.com/gojargo/jargo/runner"
	"github.com/gojargo/jargo/transport"
	"github.com/gojargo/jargo/utils/events"
)

func main() {
	bot := func(ctx context.Context, args runner.Arguments) error {
		t, err := runner.CreateTransport(ctx, args, runner.TransportParams{
			WebRTC: transport.DefaultParams,
		})
		if err != nil {
			return err
		}
		tts := cartesia.NewTTS(cartesia.Config{
			APIKey:  os.Getenv("CARTESIA_API_KEY"),
			VoiceID: "86e30c1d-714b-4074-a1f2-1cb6b552fb49",
		})
		worker := pipeline.NewWorker(pipeline.New(tts, t.Output()), pipeline.WorkerConfig{
			IdleTimeout: args.Base().PipelineIdleTimeout,
		})
		events.On(t.Events(), transport.EventClientConnected, func(context.Context, any) {
			worker.QueueFrames([]frames.Frame{frames.NewTTSSpeakFrame("Hello there!"), frames.NewEndFrame()})
		})
		return worker.Run(ctx)
	}

	runner.Main(bot)
}

Index

Examples

Constants

This section is empty.

Variables

App is the runner's HTTP router. Add routes of your own to it before calling Main:

runner.App.HandleFunc("GET /my-route", myHandler)
runner.Main(bot)
View Source
var ErrHandshakeClosed = errors.New("runner: WebSocket closed before receiving telephony handshake messages")

ErrHandshakeClosed is returned when a telephony WebSocket closes before it sends any message.

View Source
var ErrInvalidArgs = errors.New("runner: invalid arguments")

ErrInvalidArgs reports command-line arguments the runner cannot start with.

View Source
var ErrInvalidICEServer = errors.New("runner: invalid ICE server")

ErrInvalidICEServer reports an ICE server entry that cannot be used.

View Source
var ErrLiveKitNotConfigured = errors.New(
	"runner: LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be set in environment variables")

ErrLiveKitNotConfigured is returned when the LiveKit server or its credentials are not set in the environment.

View Source
var ErrLiveKitRoomNotSet = errors.New(
	"runner: no LiveKit room specified: set LIVEKIT_ROOM_NAME in your environment")

ErrLiveKitRoomNotSet is returned by ConfigureLiveKit when no room is named.

View Source
var ErrMissingTransportParams = errors.New("runner: missing transport params")

ErrMissingTransportParams is returned when a session arrives on a transport TransportParams does not configure.

View Source
var ErrSerializerRequired = errors.New("runner: WebSocketParams.Serializer is required for a plain WebSocket")

ErrSerializerRequired is returned when a plain WebSocket session has no serializer configured.

View Source
var ErrUnsupportedArguments = errors.New("runner: unsupported runner arguments type")

ErrUnsupportedArguments is returned for runner arguments CreateTransport cannot build a transport for.

View Source
var ErrUnsupportedProvider = errors.New(
	"runner: unsupported telephony provider; supported providers: twilio, telnyx, plivo, exotel")

ErrUnsupportedProvider is returned for a telephony provider the runner does not recognize.

View Source
var Frontend = prebuilt.Handler()

Frontend is the browser client the runner serves at /client, with / sending there. It is the prebuilt client (github.com/gojargo/jargo-web/prebuilt) by default; set it to another handler before Main to serve your own, or to nil to serve none.

Functions

func ConfigureLiveKit

func ConfigureLiveKit() (url, token, roomName string, err error)

ConfigureLiveKit reads the LiveKit server, credentials and room from the environment (LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_ROOM_NAME) and mints the bot's token for the room. It also mints a token for a user and logs it, for testing.

func CreateTransport

func CreateTransport(ctx context.Context, args Arguments, params TransportParams) (transport.Transport, error)

CreateTransport builds the transport for a session from the arguments the runner handed the bot, configured by params.

A WebSocket session that is not a plain WebSocket client is a telephony call: its provider is detected from its first messages, and args.TransportType and args.CallData are set from what they say, so the bot can personalize the call without parsing them again.

func GenerateSessionTokens

func GenerateSessionTokens(roomName, sessionID, apiKey, apiSecret string) (agentToken, userToken string, err error)

GenerateSessionTokens mints distinct tokens for the bot and the caller of one session. The identities carry the start of the session id, so sessions sharing a room do not collide: LiveKit evicts the earlier connection when another joins with the same identity.

func GenerateToken

func GenerateToken(roomName, participantName, apiKey, apiSecret string) (string, error)

GenerateToken mints a LiveKit access token for a participant to join roomName.

func GenerateTokenWithAgent

func GenerateTokenWithAgent(roomName, participantName, apiKey, apiSecret string) (string, error)

GenerateTokenWithAgent mints a LiveKit access token for an agent participant, so LiveKit clients know an agent has joined.

func LiveKitCredentials

func LiveKitCredentials() (url, apiKey, apiSecret string, err error)

LiveKitCredentials returns the LiveKit server URL, API key and API secret from LIVEKIT_URL, LIVEKIT_API_KEY and LIVEKIT_API_SECRET.

func Main

func Main(bot Bot)

Main starts the development runner and serves until it is interrupted. It parses the command line, loads a .env file if there is one, and starts a server that serves every transport at once, so a client chooses its own in the transport field of POST /start. With -t the server serves only that one and prints where to reach it.

The runner runs bot for each session it starts. To add command-line flags of your own, register them on flag.CommandLine before calling Main; they are parsed with the runner's.

Main exits the process when the runner cannot start.

func Run

func Run(ctx context.Context, fs *flag.FlagSet, arguments []string, bot Bot) error

Run is Main with an explicit flag set and arguments. It returns when ctx is canceled or the process is interrupted, once the server has shut down.

func RunnerDownloadsFolder

func RunnerDownloadsFolder() string

RunnerDownloadsFolder returns the folder the runner serves files for download from, or "" when it serves none.

func RunnerHost

func RunnerHost() string

RunnerHost returns the host the runner listens on.

func RunnerPort

func RunnerPort() int

RunnerPort returns the port the runner listens on.

Types

type Args

type Args struct {
	// Host and Port are where the server listens.
	Host string
	Port int
	// Transport restricts the server to one transport and makes it the default
	// for /start; empty serves them all.
	Transport string
	// Proxy is the public host name telephony providers reach the server on.
	Proxy string
	// DownloadsFolder holds the files served for download at /files.
	DownloadsFolder string
	// RunnerBody is a YAML or JSON file read as the body of each WebSocket
	// session.
	RunnerBody string
	// Verbose raises the logging verbosity.
	Verbose int
	// ESP32 rewrites WebRTC answers for ESP32 clients.
	ESP32 bool
	// WhatsApp serves the WhatsApp webhook.
	WhatsApp bool
	// WSAuth is "token" to require a token from /start on the WebSocket routes,
	// or "none".
	WSAuth string
	// ICEServers are the STUN and TURN servers for WebRTC, as given.
	ICEServers []map[string]any
	// AllowedOrigins limit the origins of HTTP and WebSocket requests; empty
	// allows all.
	AllowedOrigins []string
}

Args are the runner's parsed command-line arguments.

type Arguments

type Arguments interface {
	// Base returns the fields every session has.
	Base() *RunnerArguments
}

Arguments is what the runner hands a bot for one session. Each transport has its own type, which a bot can switch on: *WebRTCRunnerArguments, *WebSocketRunnerArguments, *LiveKitRunnerArguments, or the plain *RunnerArguments.

type Bot

type Bot func(ctx context.Context, args Arguments) error

Bot runs one session. The runner calls it for every session it starts, with the arguments for the transport the session arrived on, and the session lasts as long as the call. ctx is canceled when the runner shuts down.

type CallData

type CallData struct {
	// StreamID is the provider's media-stream identifier.
	StreamID string `json:"stream_id,omitempty"`
	// CallID is the provider's call identifier, normalized across providers:
	// Twilio's callSid, Plivo's callId, Exotel's call_sid, Telnyx's
	// call_control_id.
	CallID string `json:"call_id,omitempty"`
	// FromNumber is the caller's number.
	FromNumber string `json:"from,omitempty"`
	// ToNumber is the dialed number.
	ToNumber string `json:"to,omitempty"`
	// Body holds the custom parameters the provider sent, such as Twilio's TwiML
	// stream parameters.
	Body map[string]any `json:"body,omitempty"`

	// OutboundEncoding is Telnyx's outbound media encoding.
	OutboundEncoding string `json:"outbound_encoding,omitempty"`
	// AccountSID is Exotel's account sid.
	AccountSID string `json:"account_sid,omitempty"`
	// CustomParameters are Exotel's custom parameters, a string or an object.
	CustomParameters any `json:"custom_parameters,omitempty"`
}

CallData is what a telephony provider's opening WebSocket messages say about the call, parsed by ParseTelephonyWebSocket and exposed on the bot's arguments by CreateTransport. Fields a provider does not send stay empty.

func ParseTelephonyWebSocket

func ParseTelephonyWebSocket(ctx context.Context, args *WebSocketRunnerArguments) (string, *CallData, error)

ParseTelephonyWebSocket reads a telephony provider's opening messages and reports which provider it is and what it says about the call.

It reads the first message, which is required, and a second one, which some providers never send. It is idempotent: the messages it reads are gone from the socket, so the first parse is kept on args and returned again, and the transport CreateTransport builds is handed the messages to deserialize first.

type LiveKitRunnerArguments

type LiveKitRunnerArguments struct {
	RunnerArguments
	// RoomName is the room to join.
	RoomName string
	// URL is the LiveKit server URL.
	URL string
	// Token is the bot's access token for the room.
	Token string
}

LiveKitRunnerArguments is a session in a LiveKit room the bot joins.

type RunnerArguments

type RunnerArguments struct {
	// HandleSigint and HandleSigterm say whether the bot should install its own
	// signal handlers. The runner handles signals itself, so both are false.
	HandleSigint  bool
	HandleSigterm bool
	// PipelineIdleTimeout is how long the pipeline may stay idle before shutting
	// down; zero disables it. The runner sets 300 seconds.
	PipelineIdleTimeout time.Duration
	// Body is the request data passed from the runner's entry point, as JSON. It
	// is nil when none was given, which a bot can tell from an empty object.
	Body json.RawMessage
	// CallData is the parsed telephony handshake, set by CreateTransport for a
	// telephony connection and nil otherwise.
	CallData *CallData
	// SessionID identifies this session.
	SessionID string
	// CLIArgs are the runner's parsed command-line arguments.
	CLIArgs *Args
}

RunnerArguments holds what every session has, whatever its transport.

func (*RunnerArguments) Base

func (a *RunnerArguments) Base() *RunnerArguments

Base returns the arguments themselves.

type TransportParams

type TransportParams struct {
	WebRTC    func() transport.Params
	LiveKit   func() transport.Params
	WebSocket func() WebSocketParams
	Twilio    func() WebSocketParams
	Telnyx    func() WebSocketParams
	Plivo     func() WebSocketParams
	Exotel    func() WebSocketParams
}

TransportParams says how to configure each transport a session may arrive on. Each field builds the parameters when its transport is selected; a transport whose field is nil cannot be used.

type WebRTCRunnerArguments

type WebRTCRunnerArguments struct {
	RunnerArguments
	// WebRTCConnection is the session's peer connection.
	WebRTCConnection *rtc.Connection
}

WebRTCRunnerArguments is a session over a WebRTC peer connection the runner has already answered.

type WebSocketParams

type WebSocketParams struct {
	wsserver.Params
	Serializer wsserver.Serializer
}

WebSocketParams configures a WebSocket transport: its transport parameters and the serializer for its wire format. For a telephony provider the runner sets the serializer itself.

type WebSocketRunnerArguments

type WebSocketRunnerArguments struct {
	RunnerArguments
	// WebSocket is the accepted connection.
	WebSocket *websocket.Conn
	// TransportType is "websocket" for a plain WebSocket client. Empty means a
	// telephony provider, detected from its first messages; CreateTransport
	// then sets it to the provider it found (for example "twilio").
	TransportType string
	// contains filtered or unexported fields
}

WebSocketRunnerArguments is a session over a WebSocket the runner has accepted: a telephony provider's media stream, or a plain WebSocket client.

Jump to

Keyboard shortcuts

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