Running zelk in a service
An HTTP server, a queue worker or a bot is a long-lived process that runs many short conversations. This page is about the decisions that follow: what to build once, what to build per request, who owns each context, and what closes when. Two complete programs put it together: an HTTP service that serves durable sessions and streams their events, and a worker whose agent changes data only with approval and recovers after a crash. Read them beside this page.
The samples below show function bodies, not imports. zelk is the root
package, github.com/barevoidco/zelk/core (reference).
The others come from its subpackages, at github.com/barevoidco/zelk/core/<name>:
provider and
provider/replay (a scripted model, so the
samples run offline), permission,
history, tool,
lease, driver,
env/local and
store/mem.
One agent per process, sessions per request
Section titled “One agent per process, sessions per request”Build the agent when the process starts and share it. It is
safe for concurrent use, and it holds what every session shares: the model
provider, the tools, the store and lease, the MCP connections. A request
gets a session, a handle opened by ID with Agent.Session. Opening one
reads nothing and costs nothing; Start and Send do the work.
Choose session IDs yourself. An ID you derive from your own record, such as
a ticket number, a conversation ID or a job ID, lets a later request, or a
restarted process, find the same session in the store. A session runs one
execution at a time. Session.Send delivers a message to the execution
running or starts one, so two requests for one conversation don’t race: the
second joins the first.
If another process holds a session’s lease, Start and Send fail with a
*lease.HeldError, which wraps lease.ErrHeld and says until when the grant
lasts. Treat it as “busy elsewhere”: a service that runs several replicas
routes a conversation to one, or answers with a retry.
One workspace per agent
Section titled “One workspace per agent”An agent acts in one workspace. WithEnvironment(e, root) fixes the
environment and the root the model sees, and every session records that
root when it starts. An agent with another root can’t take such a session
up: Start fails with driver.ErrIncompatible, before anything changes,
and names both roots.
ctx := context.Background()logs := mem.New()leases, err := lease.NewLocal()if err != nil { panic(err)}// open builds an agent on workspace root, over the shared store.open := func(root string, turns ...replay.Turn) (*zelk.Agent, func()) { e, err := local.New(ctx, root) if err != nil { panic(err) } p, err := replay.New(provider.Caps{}, turns...) if err != nil { panic(err) } a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass), zelk.WithEnvironment(e, root), zelk.WithStore(logs), zelk.WithLease(leases)) if err != nil { panic(err) } return a, func() { // The agent closes first; the environment it was given is ours. if err := a.Close(ctx); err != nil { panic(err) } if err := e.Close(); err != nil { panic(err) } }}tenantA, err := os.MkdirTemp("", "tenant-a-")if err != nil { panic(err)}defer os.RemoveAll(tenantA)tenantB, err := os.MkdirTemp("", "tenant-b-")if err != nil { panic(err)}defer os.RemoveAll(tenantB)
a, closeA := open(tenantA, replay.Reported("met", "Done."))defer closeA()s, err := a.Session(ctx, "job-1")if err != nil { panic(err)}x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Start.")))if err != nil { panic(err)}if _, err := x.Wait(ctx); err != nil { panic(err)}
b, closeB := open(tenantB)defer closeB()s, err = b.Session(ctx, "job-1")if err != nil { panic(err)}_, err = s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Continue.")))fmt.Println("another workspace refused:", errors.Is(err, driver.ErrIncompatible))// Output: another workspace refused: trueSo the workspace is a decision of the host, never of a request. A service
that works for several tenants builds an agent for each tenant’s workspace,
and keeps session IDs from colliding across them, for instance by putting
the tenant in the ID. Don’t build a workspace from request data. The
root check refuses a session reopened in the wrong place, and
sandboxing limits what a command in the right place can
reach. A host that does move a session deliberately opts in with
WithWorkspaceMoves.
Who owns which context
Section titled “Who owns which context”Three contexts are in play, and each owns something different:
- The context you pass to
Startis the execution’s. It runs under it: cancel it, or close the agent, and the execution stops, leaving its unfinished attempts for recovery. A request’s context is the wrong one. When the client disconnects, the work would stop with it. Use a context the service owns, cancelled at shutdown. - The context you pass to
Wait,SubscribeorFollowis a reader’s patience. When it ends, the reader stops waiting; the execution goes on, and anyone can wait for it again. - The context you pass to
zelk.Newserves construction, such as connecting MCP servers. Cancelling it afterwards doesn’t stop the agent;Closedoes.
release := make(chan struct{})started := make(chan struct{})slow, err := tool.Define("Slow", "Takes as long as it takes.", func(ctx context.Context, _ struct{}) (tool.Result, error) { close(started) select { case <-release: return tool.Text("done"), nil case <-ctx.Done(): return tool.Result{}, ctx.Err() }}, tool.WithReadOnly())if err != nil { panic(err)}p, err := replay.New(provider.Caps{}, replay.ToolCalls(history.ToolCall{ID: "s", Name: "Slow", Input: json.RawMessage(`{}`)}), replay.Reported("met", "Finished."))if err != nil { panic(err)}
// The service's context ends when the process shuts down.service, shutdown := context.WithCancel(context.Background())defer shutdown()a, err := zelk.New(service, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeDefault), zelk.WithTools(slow))if err != nil { panic(err)}defer a.Close(service)s, err := a.Session(service, "request-1")if err != nil { panic(err)}
// One request: it starts the run on the service's context and waits// on its own, until the client goes away.request, disconnect := context.WithCancel(service)x, err := s.Start(service, zelk.WithCommands(zelk.UserMessage("Take your time.")))if err != nil { panic(err)}<-starteddisconnect()_, err = x.Wait(request)fmt.Println("request gave up:", errors.Is(err, context.Canceled))
// The run didn't notice. A later request reads its result.close(release)res, err := x.Wait(service)if err != nil { panic(err)}fmt.Println(res.Outcome, res.Text)// Output:// request gave up: true// success Finished.To end a run on purpose and durably, such as when a user presses stop, send
Execution.Interrupt(reason); the session records the interruption and
the run ends as interrupted. Execution.Cancel and cancelling the context
stop the work without a record, which suits shutdown, since the next process
recovers the session from its log. See Stores, leases and
recovery.
Context that is recorded and context that isn’t
Section titled “Context that is recorded and context that isn’t”What you pass in options is recorded in each session when it starts, and a
reopened session keeps what it recorded. WithPromptAppend,
WithPromptContext and WithSessionContext are of that kind: they shape a
new session, and changing them later changes only sessions started after.
The WithPromptAppend text is part of the cached prefix of every request, so
keep it identical across users and machines. WithSessionContext runs once
for a new session, to gather facts such as a repository snapshot.
What differs per run goes in with the run. A zelk.InjectContext command
adds text for the model’s later calls without touching the static prefix, and
the user’s message carries the request itself:
p, err := replay.New(provider.Caps{}, replay.Reported("met", "ready"))if err != nil { panic(err)}a, err := zelk.New(context.Background(), p, zelk.WithPermissionMode(permission.ModeBypass), zelk.WithModel("m"), zelk.WithPromptAppend("Prefer small changes."), zelk.WithPromptContext("Tenant: example"))if err != nil { panic(err)}s, err := a.Session(context.Background(), "prompt-example")if err != nil { panic(err)}x, err := s.Start(context.Background(), zelk.WithCommands(zelk.InjectContext("Workspace revision: 42"), zelk.UserMessage("Start.")))if err != nil { panic(err)}if _, err := x.Wait(context.Background()); err != nil { panic(err)}r := p.Requests()[0]fmt.Println(strings.HasSuffix(r.System, "Prefer small changes."))fmt.Println(strings.Contains(r.History[0].Parts[0].Text, "Tenant: example\n\nWorkspace revision: 42"))if err := a.Close(context.Background()); err != nil { panic(err)}// Output:// true// trueKeep per-user and per-request data out of the options. A tenant name in
WithPromptContext is right for an agent built for that tenant; a user’s
name, today’s date or the state of a repository that changes between
requests belongs in InjectContext.
Change the configuration without a restart
Section titled “Change the configuration without a restart”A new model, a changed rule set, another MCP server: Agent.Reconfigure
prepares a configuration that shares the running work of the agent it was
made from. Nothing changes until Pending.Commit; Pending.Discard throws
the preparation away. Executions running at Commit finish on the
configuration they started with, and executions started afterwards, through
either agent, start on the new one.
ctx := context.Background()first, err := replay.New(provider.Caps{}, replay.Reported("met", "from the first configuration"))if err != nil { panic(err)}a, err := zelk.New(ctx, first, zelk.WithModel("m1"), zelk.WithPermissionMode(permission.ModeBypass))if err != nil { panic(err)}defer a.Close(ctx)run := func(id string) string { s, err := a.Session(ctx, id) if err != nil { panic(err) } x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Report."))) if err != nil { panic(err) } res, err := x.Wait(ctx) if err != nil { panic(err) } return res.Text}
// A configuration that fails the host's own checks is discarded.rejected, err := replay.New(provider.Caps{}, replay.Reported("met", "never used"))if err != nil { panic(err)}pending, err := a.Reconfigure(ctx, rejected, zelk.WithModel("m2"), zelk.WithPermissionMode(permission.ModeBypass))if err != nil { panic(err)}if err := pending.Discard(ctx); err != nil { panic(err)}fmt.Println(run("before"))
// One that passes is committed. The old configuration closes once// nothing runs on it, and retired tells the host it may release what// it built for it, such as the old provider.second, err := replay.New(provider.Caps{}, replay.Reported("met", "from the second configuration"))if err != nil { panic(err)}pending, err = a.Reconfigure(ctx, second, zelk.WithModel("m2"), zelk.WithPermissionMode(permission.ModeBypass))if err != nil { panic(err)}retired := make(chan struct{})if err := pending.Commit(ctx, func() { close(retired) }); err != nil { panic(err)}<-retiredfmt.Println(run("after"))// Output:// from the first configuration// from the second configurationThe options you pass to Reconfigure are the whole new configuration, as
for New: pass WithModel and WithPermissionMode again, and the rest you
want. The store and lease stay the agent’s, and the workspace root must
stay the same, or Reconfigure fails with
ErrIncompatibleReconfiguration. Commit takes a function that is called
once nothing runs on the old configuration any more, after its own MCP
connections and language servers are closed. Release there what you built
only for it, such as the old provider.
Sessions that already exist take the new rules when an execution next
starts on them: a session whose recorded policy differs from the agent’s
current one takes the agent’s, and the rules a user granted in the session
stay. An execution that is already running doesn’t wait for that. Build the
command from the agent the reconfiguration prepared, after Commit, and
send it to the execution:
ctx := context.Background()running, release := make(chan struct{}), make(chan struct{})wait, err := tool.Define("Wait", "Wait for the host.", func(context.Context, struct{}) (tool.Result, error) { close(running) <-release return tool.Text("waited"), nil}, tool.WithReadOnly())if err != nil { panic(err)}greeted := falsegreet, err := tool.Define("Greet", "Say hello.", func(context.Context, struct{}) (tool.Result, error) { greeted = true return tool.Text("hello"), nil}, tool.WithReadOnly())if err != nil { panic(err)}newProvider := func() *replay.Provider { p, err := replay.New(provider.Caps{}, replay.ToolCalls(history.ToolCall{ID: "wait", Name: "Wait", Input: json.RawMessage(`{}`)}), replay.ToolCalls(history.ToolCall{ID: "greet", Name: "Greet", Input: json.RawMessage(`{}`)}), replay.Reported("met", "Done.")) if err != nil { panic(err) } return p}opts := []zelk.Option{zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass), zelk.WithTools(wait, greet)}a, err := zelk.New(ctx, newProvider(), opts...)if err != nil { panic(err)}defer a.Close(ctx)s, err := a.Session(ctx, "s")if err != nil { panic(err)}x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Wait, then greet.")))if err != nil { panic(err)}<-running
// The user forbids Greet while the run is waiting.denying := append(slices.Clone(opts), zelk.WithRules(permission.Rules{Deny: []permission.Rule{permission.MustRule("Greet")}}))pending, err := a.Reconfigure(ctx, newProvider(), denying...)if err != nil { panic(err)}if err := pending.Commit(ctx, nil); err != nil { panic(err)}if _, err := x.Send(pending.Agent().RulesCommand()); err != nil { panic(err)}close(release)if _, err := x.Wait(ctx); err != nil { panic(err)}fmt.Println("Greet ran:", greeted)// Output:// Greet ran: falseRulesCommand reads the rules of the agent you call it on, so one built
from the old agent handle still carries the old rules. It applies once no
tool call is running. An approval that was already asked is decided again
when it is answered: the answer is bound to the action as the user saw it,
which includes the session’s policy revision, so a rules change in between
makes it a different action. It may then be refused or asked about again.
Agent.SetModel builds the command that switches a running session’s model.
Shut down in order
Section titled “Shut down in order”The agent owns its executions; you own what you passed it. So the order is:
- Stop taking requests. Shut the HTTP server down or stop the consumer, so nothing starts new work.
- Decide about runs in flight. Wait for them for a bounded time, or end them. A run that is cut off is not lost: its log says where it stopped, and the next process to open the session recovers it.
- Close the agent, with a fresh bounded context rather than the service
context that was just cancelled.
Agent.Closerefuses new sessions, cancels running executions, waits for them to finish or for its context, closes the MCP connections and language servers the agent started, and releases the leases. It doesn’t close what you gave it. - Close what you injected, in the reverse of the order you built it: the
environment, then the store and lease, then the providers. Do this only
after
Agent.Closehas returned.
ctx := context.Background()root, err := os.MkdirTemp("", "workspace-")if err != nil { panic(err)}defer os.RemoveAll(root)
e, err := local.New(ctx, root)if err != nil { panic(err)}p, err := replay.New(provider.Caps{}, replay.Reported("met", "Done."))if err != nil { panic(err)}a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass), zelk.WithEnvironment(e, root))if err != nil { panic(err)}s, err := a.Session(ctx, "job-2")if err != nil { panic(err)}x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Start.")))if err != nil { panic(err)}if _, err := x.Wait(ctx); err != nil { panic(err)}
// Shutdown: stop taking requests first, then close the agent, then// what it was given.if err := a.Close(ctx); err != nil { panic(err)}if err := e.Close(); err != nil { panic(err)}_, err = a.Session(ctx, "job-3")fmt.Println("closed:", errors.Is(err, zelk.ErrClosed))// Output: closed: trueWhat you injected stays open until Agent.Close has finished: a store, lease,
provider or environment closed earlier is pulled out from under running
executions, which then fail with storage errors instead of stopping cleanly.
The environment matters twice: Close disconnects the MCP servers the agent
connected, and a stdio server runs through the environment you gave it, so
that has to outlive Close as well.
The same holds for an HTTP server: Shutdown drains its handlers first, so
the handlers that use the agent have returned before anything they depend on
closes.
A bounded Close can return its context’s error while tools still run: a
tool that ignores its context holds its execution up, and Close stops
waiting without stopping the tool. The executions are then still using what
you injected, so don’t close it yet. Call Close again, which waits again,
with a longer bound; or, if you can’t wait, leave the injected dependencies
open and exit the process. A run cut off that way is not lost: the next
process recovers it from the log once the lease it held has expired or been
released.
An agent that was reconfigured closes with the agents it was reconfigured from and to: closing any of them closes all.
See it running
Section titled “See it running”The HTTP service and the worker, linked at the top, are the complete programs for this page: run them, then read their code against the sections above.
Providers and models covers the provider you pass to the agent and switching models in a session.