# Support ticket worker

> Triage a queue with typed tools, host approvals and a recoverable write.

The worker takes ticket IDs as its queue and uses each ID to name a session.
The model looks up the ticket and can request a priority label. With default
permission mode and `WithInputSuspend`, a write approval comes back to the
host in `Result.Requests`. The worker asks its approval function and starts
the same session with the response. A restarted worker reads pending
requests from `Session.Status` and submits the initial prompt for an
unfinished job with the same command ID. This covers a restart after session
creation and before prompt admission. An already admitted prompt keeps its
original acceptance.

```go
// examples/worker/main.go
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"os/signal"
	"path/filepath"

	zelk "github.com/barevoidco/zelk/core"
	"github.com/barevoidco/zelk/core/event"
	"github.com/barevoidco/zelk/core/lease"
	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"
	"github.com/barevoidco/zelk/core/store"
	filestore "github.com/barevoidco/zelk/core/store/file"
)

func main() {
	model := flag.String("model", "", "model to call")
	state := flag.String("state", "", "private state directory")
	allow := flag.Bool("approve", false, "authorize priority labels on the queued tickets")
	flag.Parse()
	if *model == "" || *state == "" || flag.NArg() == 0 {
		log.Fatal("usage: worker -model MODEL -state DIR [-approve] TICKET ...")
	}
	baseURL := os.Getenv("OPENAI_BASE_URL")
	if baseURL == "" {
		baseURL = "https://api.openai.com/v1"
	}
	p, err := openaicompat.New(baseURL, openaicompat.WithAPIKey(os.Getenv("OPENAI_API_KEY")))
	if err != nil {
		log.Fatal(err)
	}
	approve := func(_ context.Context, id string, req zelk.InputRequest) (bool, error) {
		log.Printf("ticket %s requested %s (%s): approved=%t", id, req.Approval.Tool, req.Approval.Reason, *allow)
		return *allow, nil
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	err = errors.Join(run(ctx, p, *model, *state, flag.Args(), approve, os.Stdout), p.Close())
	stop()
	if err != nil {
		log.Fatal(err)
	}
}

type approval func(context.Context, string, zelk.InputRequest) (bool, error)

func run(ctx context.Context, p provider.Provider, model, state string, jobs []string, approve approval, out io.Writer) (err error) {
	logs, leases, tickets, err := openState(ctx, state)
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, logs.Close()) }()
	return work(ctx, p, model, logs, leases, tickets, jobs, approve, out)
}

func openState(ctx context.Context, state string) (*filestore.Store, *filelease.Lease, ticketStore, error) {
	state, err := filepath.Abs(state)
	if err != nil {
		return nil, nil, ticketStore{}, err
	}
	leaseDir, ticketDir := filepath.Join(state, "leases"), filepath.Join(state, "tickets")
	for _, dir := range []string{leaseDir, ticketDir} {
		if err := os.MkdirAll(dir, 0o700); err != nil {
			return nil, nil, ticketStore{}, err
		}
	}
	leases, err := filelease.New(leaseDir)
	if err != nil {
		return nil, nil, ticketStore{}, err
	}
	logs, err := filestore.New(ctx, state)
	return logs, leases, ticketStore{dir: ticketDir}, err
}

func work(ctx context.Context, p provider.Provider, model string, logs store.LogStore, leases lease.Lease, tickets ticketStore, jobs []string, approve approval, out io.Writer) (err error) {
	for _, id := range jobs {
		if _, ok := ticketBody(id); !ok {
			return fmt.Errorf("unknown ticket %q", id)
		}
	}
	tools, err := ticketTools(tickets)
	if err != nil {
		return err
	}
	agent, err := zelk.New(ctx, p, zelk.WithModel(model), zelk.WithStore(logs), zelk.WithLease(leases),
		zelk.WithPermissionMode(permission.ModeDefault), zelk.WithInputSuspend(),
		zelk.WithTools(tools...), zelk.WithoutSubagents(),
		zelk.WithAllowedTools("LookupTicket", "LabelPriority", "ReportOutcome"))
	if err != nil {
		return err
	}
	defer func() { err = errors.Join(err, agent.Close(context.WithoutCancel(ctx))) }()
	for _, id := range jobs {
		res, err := triage(ctx, agent, id, approve)
		if err != nil {
			return fmt.Errorf("triage %s: %w", id, err)
		}
		if _, err := fmt.Fprintf(out, "%s (%s): %s\n", id, res.Outcome, res.Text); err != nil {
			return err
		}
		if res.Outcome != event.RunSuccess {
			return fmt.Errorf("triage %s ended with %s", id, res.Outcome)
		}
	}
	return nil
}

func triage(ctx context.Context, agent *zelk.Agent, id string, approve approval) (zelk.Result, error) {
	session, err := agent.Session(ctx, "triage-"+id)
	if err != nil {
		return zelk.Result{}, err
	}
	status, err := session.Status(ctx)
	if err != nil && !errors.Is(err, zelk.ErrNoSession) {
		return zelk.Result{}, err
	}
	if !status.Running && status.Last != nil {
		text := "already finished"
		if status.Last.Outcome != event.RunSuccess {
			text = "previous run failed"
		}
		return zelk.Result{Outcome: status.Last.Outcome, Text: text}, nil
	}
	// Session creation and command admission are separate writes. Submit the
	// same command on restart so either side of that cut is recoverable.
	initial := zelk.UserMessage("Triage ticket " + id + ". Look it up, request a priority label if urgent, then summarize what happened.")
	initial.ID = "initial-triage"
	commands := []zelk.Command{initial}
	for {
		for _, req := range status.Requests {
			if req.Approval == nil || req.Approval.Tool != "LabelPriority" {
				return zelk.Result{}, fmt.Errorf("unexpected input request %q", req.Kind)
			}
			ok, err := approve(ctx, id, req)
			if err != nil {
				return zelk.Result{}, err
			}
			answer := req.Deny("The ticket owner declined the priority label.")
			if ok {
				answer = req.AllowOnce()
			}
			commands = append(commands, zelk.Respond(answer))
		}
		execution, err := session.Start(ctx, zelk.WithCommands(commands...))
		if err != nil {
			return zelk.Result{}, err
		}
		res, err := execution.Wait(ctx)
		if !errors.Is(err, zelk.ErrSuspended) {
			return res, err
		}
		commands = nil
		status.Requests = res.Requests
	}
}
```

The tool argument schema comes from a Go type. The tools also check that
the requested ticket belongs to the current job. The mutating tool uses
`Call.IdempotencyKey()` and commits it together with the label. If the
worker loses the result append after the label commits, the same call can
be attempted again with the same key and leave one label record.

```go
// examples/worker/tickets.go
package main

import (
	"context"
	"crypto/sha256"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

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

type ticketStore struct{ dir string }

func ticketBody(id string) (string, bool) {
	switch id {
	case "T-101":
		return "The customer cannot sign in after resetting their password.", true
	case "T-102":
		return "The customer asks where to download last month's invoice.", true
	default:
		return "", false
	}
}

func (s ticketStore) priority(ctx context.Context, id string) (bool, error) {
	if err := ctx.Err(); err != nil {
		return false, err
	}
	entries, err := os.ReadDir(s.dir)
	if err != nil {
		return false, err
	}
	for _, entry := range entries {
		if entry.IsDir() && strings.HasPrefix(entry.Name(), id+"-priority-") {
			return true, nil
		}
	}
	return false, nil
}

func (s ticketStore) labelPriority(ctx context.Context, id, key string) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	if key == "" {
		return errors.New("missing idempotency key")
	}
	// The directory is both the mutation and its key. Mkdir commits the
	// whole record in one filesystem operation, including across processes.
	// Recovery of this sample covers process restarts on a local filesystem.
	record := fmt.Sprintf("%s-priority-%x", id, sha256.Sum256([]byte(key)))
	err := os.Mkdir(filepath.Join(s.dir, record), 0o700)
	if errors.Is(err, fs.ErrExist) {
		return nil // The same action already committed.
	}
	return err
}

type ticketInput struct {
	ID string `json:"id" desc:"Ticket ID from the current job"`
}

func ticketTools(tickets ticketStore) ([]*tool.Tool, error) {
	lookup, err := tool.DefineCall("LookupTicket", "Read the current support ticket and its priority status.",
		func(ctx context.Context, call tool.Call, in ticketInput) (tool.Result, error) {
			body, ok := ticketBody(in.ID)
			if !ok || call.Session() != "triage-"+in.ID {
				return tool.Failuref("ticket %q is outside the current job", in.ID), nil
			}
			priority, err := tickets.priority(ctx, in.ID)
			if err != nil {
				return tool.Result{}, err
			}
			return tool.Text(fmt.Sprintf("%s Priority: %t.", body, priority)), nil
		}, tool.WithReadOnly(), tool.WithIdempotent())
	if err != nil {
		return nil, err
	}
	label, err := tool.DefineCall("LabelPriority", "Apply the priority label to the current ticket.",
		func(ctx context.Context, call tool.Call, in ticketInput) (tool.Result, error) {
			if _, ok := ticketBody(in.ID); !ok || call.Session() != "triage-"+in.ID {
				return tool.Failuref("ticket %q is outside the current job", in.ID), nil
			}
			if err := tickets.labelPriority(ctx, in.ID, call.IdempotencyKey()); err != nil {
				return tool.Result{}, err
			}
			return tool.Text("Priority label applied."), nil
		}, tool.WithEnforcedIdempotency())
	if err != nil {
		return nil, err
	}
	return []*tool.Tool{lookup, label}, nil
}
```

## 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`. Set `OPENAI_BASE_URL`
if you use another OpenAI-compatible endpoint. `-model` is required, as in
[the HTTP service](/examples/http-service/#run-it).

The tickets are sample data. `T-101` ("The customer cannot sign in after
resetting their password.") and `T-102` ("The customer asks where to download
last month's invoice.") are the two tickets `tickets.go` defines, and any other
ID fails before the agent starts with `unknown ticket`. In your own worker
they come from your queue.

```sh
go run ./worker -model gpt-4.1-mini -state ./worker-state -approve T-101 T-102
```

Each ticket is triaged in turn and prints one line on standard output. The
approval function logs the request on standard error, so a run in which the
model asks for the label looks like this (the wording after the outcome is the
model's):

```text
2026/12/02 06:24:19 ticket T-101 requested LabelPriority (no rule allows it): approved=true
T-101 (success): T-101 is a sign-in problem after a password reset; I labelled it priority.
T-102 (success): T-102 asks where to download last month's invoice; it is not urgent.
```

This output came from a scripted model server on loopback; a real model
decides for itself which tickets are urgent. A ticket the model doesn't label
produces no approval line.

Remove `-approve` to deny label changes. To resume an unfinished job, keep
its state and ID. A recorded unsuccessful outcome stops the batch with a
nonzero exit each time the worker encounters it. Use a fresh state directory
to retry such a job deliberately or repeat a successful job.

Replace the command-line ticket list with your queue and the approval
function with your team's review process. Store the idempotency key in the
same transaction as the mutation before declaring `WithEnforcedIdempotency`.
The [recovery rules](/internals/durability/#5-recovery) explain when an
interrupted tool can run again and when its outcome is recorded as unknown.

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