# Quickstart: embed zelk in Go

> Write a Go program that runs an agent with zelk.Run, then wire one by hand with zelk.New.

This page builds a small program that asks an agent a question about the
directory it runs in, then shows the same agent wired by hand. It is the
first step of using zelk as a library; the guides under **Embedding guides**
take it on to sessions, storage, approvals and the rest of what a service
needs.

## Set up a module

This page continues from [Get zelk](/start/get/#use-the-go-library): a module
named `hello` that has fetched the library with
`go get github.com/barevoidco/zelk/core@main`. If you haven't done that yet, it is
three commands:

```sh
mkdir hello && cd hello
go mod init example.com/hello
go get github.com/barevoidco/zelk/core@main
```

If you chose [a clone](/start/get/#from-a-clone) instead, your module reaches
the library through a `replace` directive or a workspace, and everything
below works from that module's directory, with one difference for a
workspace: don't run `go mod tidy`. It ignores `go.work`, looks for core on
the network and writes a pseudo-version into `go.mod`, which is the pin the
workspace exists to avoid. `go build` alone is enough there, because it reads
the workspace.

## Write the program

Save this as `main.go`:

```go
// examples/quickstart/main.go
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"os/signal"
	"strings"

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

func main() {
	// Ctrl+C cancels ctx, which interrupts the run.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	err := run(ctx, os.Args[1:], os.Stdout)
	stop()
	if err != nil {
		log.Fatal(err)
	}
}

// run asks zelk the question in args about the current directory and
// writes the answer to out.
func run(ctx context.Context, args []string, out io.Writer) error {
	flags := flag.NewFlagSet("quickstart", flag.ContinueOnError)
	model := flags.String("model", zelk.DefaultModel, "the model to ask")
	if err := flags.Parse(args); err != nil {
		return err
	}
	task := strings.Join(flags.Args(), " ")
	if task == "" {
		return fmt.Errorf("usage: quickstart [-model MODEL] question")
	}

	// Plan mode is read-only: the agent reads and searches the directory
	// but changes nothing.
	res, err := zelk.Run(ctx, task,
		zelk.WithModel(*model),
		zelk.WithPermissionMode(permission.ModePlan))
	if err != nil {
		return err
	}
	fmt.Fprintln(out, res.Text)
	fmt.Fprintf(out, "\n%s in %d turns\n", res.Outcome, res.Turns)
	return nil
}
```

`zelk.Run` is the zero-configuration entry point. It reads
`OPENAI_API_KEY`, or `OPENAI_BASE_URL` for a server that needs no key, and
works in the current directory with the built-in tools: reading, searching,
editing, Bash, web fetches and the skills it finds. The session lives in
memory and ends when `Run` returns.

By default `Run` acts unattended: calling it authorizes zelk to change the
working directory. This program passes
[`WithPermissionMode(permission.ModePlan)`](/reference/go/zelk/#withpermissionmode)
instead, so the agent reads and searches but changes nothing.

Fetch what the program imports and build, in the `hello` directory:

```sh
go mod tidy
go build -o hello .
```

With a workspace, run only the `go build` line ([above](#set-up-a-module)).

## Run it

The program works in the directory it runs in, so run it from the directory
you want to ask about. With a key for an OpenAI-compatible API, run it from
the `hello` directory and ask about the program itself:

```sh
export OPENAI_API_KEY=…
./hello "What does this program do? Answer in two sentences."
```

```text
It sends a question to an agent that works in the current directory and prints
the agent's answer. It then prints how the run ended.
…

success in 3 turns
```

To ask about another project, run the binary there:
`cd ~/src/other && ~/hello/hello "What does this project do?"`.

`-model` picks another model, and `OPENAI_BASE_URL` another server, such as
OpenRouter or a local one: `OPENAI_BASE_URL=http://localhost:11434/v1` for
Ollama. `success` is the run's outcome: the agent reported the question
answered, and zelk checked the report against what the run did.
[Runs and completion](/concepts/runs/) explains the other outcomes.

This program is `examples/quickstart` in the repository, where a test runs
it against a fake model server, so the code on this page builds and works.

## Wire an agent by hand

`Run` reads the environment so that a first program needs nothing else. A
real host passes every dependency itself: the provider, the model, the
permission mode, a workspace and a shell for the file tools and Bash, a
store for sessions that outlive the process. [`zelk.New`](/reference/go/zelk/#new)
takes them as options and fails rather than build an agent that would fail
later.

An agent runs **sessions**; each start of one is an **execution**, which
you wait for or follow as it runs. This example asks for a typed result,
with a scripted provider so it runs offline:

```go
// core/lifecycle_example_test.go
type verdict struct {
	Safe   bool   `json:"safe"`
	Reason string `json:"reason"`
}
p, err := replay.New(provider.Caps{},
	replay.ToolCalls(history.ToolCall{ID: "o", Name: "StructuredOutput", Input: json.RawMessage(`{"safe":true,"reason":"read-only change"}`)}),
	replay.Reported("met", "Reported."))
if err != nil {
	panic(err)
}
ctx := context.Background()
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass))
if err != nil {
	panic(err)
}
defer a.Close(ctx)
s, err := a.Session(ctx, "review-1")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Is this diff safe?")), zelk.WithRunOutputType[verdict](zelk.RunOutput{}))
if err != nil {
	panic(err)
}
out, err := zelk.WaitTyped[verdict](ctx, x)
if err != nil {
	panic(err)
}
fmt.Println(out.Value.Safe, out.Value.Reason)
// Output: true read-only change
```

The sample shows a function body, not the imports. `zelk` is the root package,
`github.com/barevoidco/zelk/core` ([reference](/reference/go/zelk/)). The rest
come from its subpackages, each at `github.com/barevoidco/zelk/core/<name>`:
[`provider`](/reference/go/provider/) and
[`provider/replay`](/reference/go/provider-replay/) for the model,
[`permission`](/reference/go/permission/) for the mode and
[`history`](/reference/go/history/) for the messages the session keeps.

Swap `replay.New` for a real provider, such as
[`openaicompat.New`](/reference/go/provider-openaicompat/#new) or
[`anthropic.New`](/reference/go/provider-anthropic/#new), and the rest stays
as it is.

## Next

- [The Go guides](/go/): every guide, listed by what you want to do
- [Examples](/examples/): an HTTP service, a worker, code review in CI, testing and tracing
- [Wiring an agent](/go/agent/): the provider, the workspace, the shell and the checks `New` makes
- [Zero-config Run](/go/run/): `Run` and typed results
- [Stores, leases and recovery](/go/stores/): sessions that outlive the process
- [Approvals and questions](/go/approvals/): answering a request now, or suspending until later
- [How zelk works](/concepts/overview/): the agent, sessions, executions and the log
- [The `zelk` package](/reference/go/zelk/): every option and type
- [Runs and completion](/concepts/runs/): how a run ends, and what its outcome means
- Prefer a command? [Run zelk from scripts and CI](/start/cli/), or [try the terminal UI](/start/tui/)
