# HTTP service

> Start zelk sessions over HTTP, stream durable events and continue after restart.

The service owns one workspace and an agent in plan mode. It starts a run
on a service context so returning from the POST leaves the run going. The
host supplies a file store and a file lease. Both point to the same state
on each restart. Shutdown waits for in-flight handlers even after a forced
connection close, then closes the agent before its dependencies.

```go
// examples/httpservice/main.go
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"sync"
	"time"

	zelk "github.com/barevoidco/zelk/core"
	"github.com/barevoidco/zelk/core/env/local"
	filelease "github.com/barevoidco/zelk/core/lease/file"
	"github.com/barevoidco/zelk/core/permission"
	"github.com/barevoidco/zelk/core/provider"
	"github.com/barevoidco/zelk/core/provider/openaicompat"
	filestore "github.com/barevoidco/zelk/core/store/file"
)

func main() {
	cfg, err := parseConfig(os.Args[1:], os.Getenv)
	if errors.Is(err, flag.ErrHelp) {
		return
	}
	if err != nil {
		log.Fatal(err)
	}
	p, err := openaicompat.New(cfg.baseURL, openaicompat.WithAPIKey(cfg.apiKey))
	if err != nil {
		log.Fatal(err)
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	err = errors.Join(listenAndServe(ctx, p, cfg), p.Close())
	stop()
	if err != nil {
		log.Fatal(err)
	}
}

// config is what the command line and environment say about one run.
type config struct {
	model, workspace, state, addr string
	baseURL, apiKey               string
}

// parseConfig reads the flags in args and the provider settings from getenv.
// It refuses to start without a provider, as [zelk.Run] does, so a missing key
// is reported before the service accepts a prompt rather than as a failed run.
func parseConfig(args []string, getenv func(string) string) (config, error) {
	var cfg config
	flags := flag.NewFlagSet("httpservice", flag.ContinueOnError)
	flags.StringVar(&cfg.model, "model", "", "model to call")
	flags.StringVar(&cfg.workspace, "workspace", ".", "fixed workspace directory")
	flags.StringVar(&cfg.state, "state", "", "private state directory outside the workspace")
	flags.StringVar(&cfg.addr, "addr", "127.0.0.1:8080", "address to listen on")
	if err := flags.Parse(args); err != nil {
		return config{}, err
	}
	if cfg.model == "" || cfg.state == "" {
		return config{}, errors.New("-model and -state are required")
	}
	cfg.apiKey, cfg.baseURL = getenv("OPENAI_API_KEY"), getenv("OPENAI_BASE_URL")
	if cfg.baseURL == "" {
		if cfg.apiKey == "" {
			return config{}, zelk.ErrNoProvider
		}
		cfg.baseURL = zelk.DefaultBaseURL
	}
	return cfg, nil
}

func listenAndServe(ctx context.Context, p provider.Provider, cfg config) error {
	listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", cfg.addr)
	if err != nil {
		return err
	}
	log.Printf("listening on %s", listener.Addr())
	return serve(ctx, listener, p, cfg.model, cfg.workspace, cfg.state)
}

func serve(ctx context.Context, listener net.Listener, p provider.Provider, model, workspace, state string) (err error) {
	// Serve closes the listener after startup. This defer covers setup failures.
	started := false
	defer func() {
		if !started {
			err = errors.Join(err, listener.Close())
		}
	}()
	workspace, err = filepath.Abs(workspace)
	if err != nil {
		return err
	}
	state, err = filepath.Abs(state)
	if err != nil {
		return err
	}
	leasesDir := filepath.Join(state, "leases")
	if err := os.MkdirAll(leasesDir, 0o700); err != nil {
		return err
	}
	leases, err := filelease.New(leasesDir)
	if err != nil {
		return err
	}
	logs, err := filestore.New(ctx, state)
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, logs.Close()) }()
	env, err := local.New(ctx, workspace)
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, env.Close()) }()
	agent, err := zelk.New(ctx, p, zelk.WithModel(model),
		zelk.WithEnvironment(env, filepath.ToSlash(workspace)),
		zelk.WithStore(logs), zelk.WithLease(leases),
		zelk.WithPermissionMode(permission.ModePlan), zelk.WithAllowedTools("Read", "Glob", "Grep", "ReportOutcome"),
		zelk.WithoutProjectInstructions(), zelk.WithoutSubagents(), zelk.WithInputDeny())
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, agent.Close(context.WithoutCancel(ctx))) }()

	service, cancel := context.WithCancel(ctx)
	defer cancel()
	started = true
	return serveHTTP(service, cancel, listener, serviceRoutes(service, agent))
}

func serveHTTP(service context.Context, cancel context.CancelFunc, listener net.Listener, handler http.Handler) error {
	requests := &activeHandlers{handler: handler}
	server := &http.Server{
		Handler:           requests,
		BaseContext:       func(net.Listener) context.Context { return service },
		ReadHeaderTimeout: 5 * time.Second,
	}
	done := make(chan error, 1)
	go func() { done <- server.Serve(listener) }()
	select {
	case err := <-done:
		cancel()
		return errors.Join(serveError(err), requests.shutdown(service, server))
	case <-service.Done():
		// Shutdown closes the listener so Serve can be joined below.
		shutdownErr := requests.shutdown(service, server)
		return errors.Join(shutdownErr, serveError(<-done))
	}
}

type activeHandlers struct {
	handler http.Handler
	mu      sync.Mutex
	closing bool
	active  sync.WaitGroup
}

func (h *activeHandlers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	h.mu.Lock()
	if h.closing {
		h.mu.Unlock()
		http.Error(w, "service shutting down", http.StatusServiceUnavailable)
		return
	}
	h.active.Add(1)
	h.mu.Unlock()
	defer h.active.Done()
	h.handler.ServeHTTP(w, r)
}

func (h *activeHandlers) shutdown(ctx context.Context, server *http.Server) error {
	// Stop admitting requests before waiting, including any whose connection
	// was already accepted. Close can stop sockets without joining handlers.
	h.mu.Lock()
	h.closing = true
	h.mu.Unlock()
	defer h.active.Wait()

	ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		return errors.Join(err, server.Close())
	}
	return nil
}

func serveError(err error) error {
	if err != nil && !errors.Is(err, http.ErrServerClosed) {
		return fmt.Errorf("serve HTTP: %w", err)
	}
	return nil
}
```

Each SSE frame carries the sequence number of a durable event. To reconnect,
send the last processed ID in `Last-Event-ID`. The handler calls
`Session.Follow` from the next sequence, then waits for events from future
executions. A client that wants just one run can read through
`run_finished` and close the stream. Inside a Go host,
`Execution.Subscribe` gives a finite per-execution stream.

Both POST routes use `Session.Send` on the service context and wait for
durable command admission on the request context before returning
`202 Accepted`. If initial admission fails, the request gets an error
without a session URL. A client disconnect ends its wait and leaves the
service in charge of the execution.

```go
// examples/httpservice/http.go
package main

import (
	"context"
	"crypto/rand"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	zelk "github.com/barevoidco/zelk/core"
	"github.com/barevoidco/zelk/core/event"
)

func serviceRoutes(service context.Context, agent *zelk.Agent) http.Handler {
	// Both new and resumed executions belong to the service. Handlers use
	// the request context to follow events and wait for command admission.
	admit := func(ctx context.Context, s *zelk.Session, message string, opts ...zelk.StartOption) error {
		_, ack, err := s.Send(service, zelk.UserMessage(message), opts...)
		if err != nil {
			return err
		}
		_, err = ack.Wait(ctx)
		return err
	}
	mux := http.NewServeMux()
	mux.HandleFunc("POST /sessions", func(w http.ResponseWriter, r *http.Request) {
		message, ok := readMessage(w, r)
		if !ok {
			return
		}
		id := rand.Text()
		s, err := agent.Session(r.Context(), id)
		if err == nil {
			err = admit(r.Context(), s, message)
		}
		if err != nil {
			sessionError(w, err)
			return
		}
		w.Header().Set("Location", "/sessions/"+id+"/events")
		w.WriteHeader(http.StatusAccepted)
	})
	mux.HandleFunc("POST /sessions/{id}/messages", func(w http.ResponseWriter, r *http.Request) {
		message, ok := readMessage(w, r)
		if !ok {
			return
		}
		s, err := agent.Session(r.Context(), r.PathValue("id"))
		if err != nil {
			http.Error(w, "invalid session ID", http.StatusBadRequest)
			return
		}
		// A disconnect can stop the wait for admission, while the execution
		// and its queued command belong to the service.
		if err := admit(r.Context(), s, message, zelk.WithExistingSession()); err != nil {
			sessionError(w, err)
			return
		}
		w.WriteHeader(http.StatusAccepted)
	})
	mux.HandleFunc("GET /sessions/{id}/events", func(w http.ResponseWriter, r *http.Request) {
		s, err := agent.Session(r.Context(), r.PathValue("id"))
		if err != nil {
			http.Error(w, "invalid session ID", http.StatusBadRequest)
			return
		}
		streamEvents(w, r, s)
	})
	return mux
}

func readMessage(w http.ResponseWriter, r *http.Request) (string, bool) {
	var body struct {
		Message string `json:"message"`
	}
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10))
	if err := decoder.Decode(&body); err != nil || strings.TrimSpace(body.Message) == "" {
		http.Error(w, "expected a JSON message", http.StatusBadRequest)
		return "", false
	}
	return body.Message, true
}

func sessionError(w http.ResponseWriter, err error) {
	if errors.Is(err, zelk.ErrNoSession) {
		http.Error(w, "unknown session", http.StatusNotFound)
		return
	}
	http.Error(w, "session operation failed", http.StatusInternalServerError)
}

func streamEvents(w http.ResponseWriter, r *http.Request, s *zelk.Session) {
	var last uint64
	if raw := r.Header.Get("Last-Event-ID"); raw != "" {
		var err error
		last, err = strconv.ParseUint(raw, 10, 64)
		if err != nil || last == ^uint64(0) {
			http.Error(w, "invalid event ID", http.StatusBadRequest)
			return
		}
	}
	if _, err := s.Status(r.Context()); err != nil {
		sessionError(w, err)
		return
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	stream := http.NewResponseController(w)
	if stream.Flush() != nil {
		return
	}
	for update, err := range s.Follow(r.Context(), last+1, 16) {
		if err != nil {
			return
		}
		if update.Event == nil {
			continue
		}
		ev := *update.Event
		data, err := event.Encode(ev)
		if err != nil {
			return
		}
		if _, err := fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", ev.Seq, ev.Kind(), data); err != nil {
			return
		}
		if err := stream.Flush(); err != nil {
			return
		}
	}
}
```

## Run it

This needs [a clone of the repository](/start/get/#from-a-clone): run it from
the clone's `examples` directory. Set `OPENAI_API_KEY` and start the
service. Set `OPENAI_BASE_URL` for another OpenAI-compatible endpoint. With
neither set, the service refuses to start and says which to set, rather than
accepting prompts it can't answer.

```sh
go run ./httpservice -model gpt-4.1-mini -workspace /path/to/project -state /path/to/private-state
```

```text
2026/12/02 06:24:28 listening on 127.0.0.1:8080
```

`-model` is required: unlike the `zelk` command, whose default is `gpt-5`, this
service has no default model, so name one your endpoint serves. `gpt-4.1-mini`
is only an example of a small one. The service listens on `127.0.0.1:8080`;
`-addr` picks another address. Keep it on loopback unless you add
authentication.

```sh
curl -i -X POST http://127.0.0.1:8080/sessions \
  -H 'Content-Type: application/json' -d '{"message":"Summarize this project."}'
curl -N http://127.0.0.1:8080/sessions/ID/events
curl -i -X POST http://127.0.0.1:8080/sessions/ID/messages \
  -H 'Content-Type: application/json' -d '{"message":"What should I read first?"}'
```

The first POST answers once the prompt is durably admitted, with the stream's
path in `Location`. The ID is generated, so yours differs:

```text
HTTP/1.1 202 Accepted
Location: /sessions/QX2NGNYPVRHY74NHVXXX3DC3W2/events
Date: Wed, 02 Dec 2026 06:24:54 GMT
Content-Length: 0
```

Use that path for the stream and substitute the same ID in the messages
route; the messages POST answers `202 Accepted` the same way. Each frame of
the stream is `id`, `event` and a JSON `data` line, and the stream stays open
for later runs. After one prompt and one message, the `id` and `event`
fields read (the `data` is the full event, so the first frame alone is
several kilobytes):

```text
id: 1   event: session_started
id: 2   event: command_accepted
id: 3   event: run_started
id: 4   event: file_versions_saved
id: 5   event: workspace_baseline
id: 6   event: effect_started
id: 7   event: effect_finished
id: 8   event: completion_checked
id: 9   event: turn_diff
id: 10  event: report_recorded
id: 11  event: run_finished
id: 12  event: command_accepted
id: 13  event: run_started
…
id: 21  event: run_finished
```

The model's answer is the `summary` in the `report_recorded` event, and
`run_finished` carries the outcome, `success` when the run's report checked
out. Restart with the same workspace and state, then send another message or
reconnect with `-H 'Last-Event-ID: N'`: the stream continues at `N + 1` with
nothing repeated.

This output came from a scripted model server on loopback; a real model adds
tool calls, so more events, and its own wording.

For your own service, choose the agent's workspace in host configuration
and keep the state outside it. Authenticate clients and check session
ownership if you expose the routes beyond local use. The integration test
runs the whole service against a loopback model and checks its event cursor
across restart.

```sh
go test -race -tags=integration ./httpservice
```
