# Sessions and executions

> Start work on a session, wait for its result or follow it live, and steer it while it runs.

An agent runs **sessions**, each a conversation with its own log. Work on a
session runs as an **execution**: it starts with commands, such as a user
message, and ends when the session has nothing left to do.
[How zelk works](/concepts/overview/) explains the model behind this.

## Start and wait

`Agent.Session` opens a session by ID, new or existing.
[`Session.Start`](/reference/go/zelk/#sessionstart) starts an execution with
commands; [`Execution.Wait`](/reference/go/zelk/#executionwait) returns its
result. With `WithRunOutputType`, the run must also deliver a typed value:

```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
```

## Follow it live

[`Execution.Updates`](/reference/go/zelk/#executionupdates) yields every
recorded event in order, from the sequence number you give, with the
model's text streamed between them. A UI renders the deltas as they arrive
and the events as the record:

```go
// core/lifecycle_example_test.go
p, err := replay.New(provider.Caps{}, replay.Reported("met", "Hello there."))
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, "chat-1")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Say hello.")))
if err != nil {
	panic(err)
}
// From event 1: the whole session, then live until the execution ends.
// A run's ID is the sequence number of the event that began it.
for u, err := range x.Updates(ctx, 1, 0) {
	if err != nil {
		panic(err)
	}
	switch {
	case u.Event != nil:
		switch e := u.Event.Payload.(type) {
		case event.RunStarted:
			fmt.Println("run", e.Run, "started")
		case event.RunFinished:
			fmt.Println("run", e.Run, "finished:", e.Outcome)
		}
	case u.Lagged != nil:
		fmt.Println("missed", u.Lagged.Dropped, "deltas")
	}
}
res, err := x.Wait(ctx)
if err != nil {
	panic(err)
}
fmt.Println(res.Text)
// Output:
// run 3 started
// run 3 finished: success
// Hello there.
```

Start from 1 to replay the whole session first; a subscriber that falls
behind is told how many deltas it missed, never which events, since events
are never dropped.

## Cursors and reconnecting

Every event has a sequence number, `Seq`, that is its place in the session's
log. It is the cursor. A client that remembers the `Seq` of the last event it
handled can leave and come back, and ask for the next one: `lastSeq + 1`.
Because the log is the record, it sees each event once, in order, whether the
execution is running, finished or in another process's past. In a
server-sent-events stream, send the `Seq` as the event's `id`; a browser
that reconnects sends it back as `Last-Event-ID`.

Four readers take a cursor. They differ in what they read and when they end:

| Reader | Reads | Ends |
|---|---|---|
| `Session.Events(ctx, from)` | the recorded events | at the end of the log |
| `Execution.Subscribe(ctx, from)` | the recorded events, then each new one of one execution | when that execution has finished |
| `Execution.Updates(ctx, from, buffer)` | `Subscribe`, with the live deltas and `Lagged` markers | when that execution has finished |
| `Session.Follow(ctx, from, buffer)` | the session's events and live deltas, across executions | when `ctx` is done or the agent closes |

`Subscribe` is the finite stream for one run: a response that should end
with the run. It sends events and no deltas:

```go
// core/guide_sessions_example_test.go
p, err := replay.New(provider.Caps{}, replay.Reported("met", "Hello there."))
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, "chat-3")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Say hello.")))
if err != nil {
	panic(err)
}
for ev, err := range x.Subscribe(ctx, 1) {
	if err != nil {
		panic(err)
	}
	if done, ok := ev.Payload.(event.RunFinished); ok {
		fmt.Println("run", done.Run, "finished:", done.Outcome)
	}
}
// Output: run 3 finished: success
```

`Follow` is the stream for a client that stays. It serves the recorded
events from the cursor, follows each execution this agent runs, and between
executions it waits for the next one instead of ending. So a reader that
wants one run reads until the `RunFinished` event it came for and stops, or
cancels its context; `Follow` itself never reports the end of a session. A
client that dropped its connection reconnects with the next sequence number:

```go
// core/guide_sessions_example_test.go
p, err := replay.New(provider.Caps{}, replay.Reported("met", "Hello there."))
if err != nil {
	panic(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
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, "chat-2")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Say hello.")))
if err != nil {
	panic(err)
}
if _, err := x.Wait(ctx); err != nil {
	panic(err)
}

var seen []uint64
// The first connection reads two events, then drops.
for u, err := range s.Follow(ctx, 1, 0) {
	if err != nil {
		panic(err)
	}
	if u.Event != nil {
		seen = append(seen, u.Event.Seq)
	}
	if len(seen) == 2 {
		break
	}
}
// The second asks for what comes after the last event it has.
for u, err := range s.Follow(ctx, seen[len(seen)-1]+1, 0) {
	if err != nil {
		panic(err)
	}
	if u.Event == nil {
		continue
	}
	seen = append(seen, u.Event.Seq)
	if done, ok := u.Event.Payload.(event.RunFinished); ok {
		fmt.Println("run finished:", done.Outcome)
		break
	}
}
for i, seq := range seen {
	if seq != uint64(i+1) {
		panic("an event was skipped or repeated")
	}
}
fmt.Println("events seen once, in order:", len(seen) > 2)
// Output:
// run finished: success
// events seen once, in order: true
```

What `Follow` and `Updates` yield beyond events is live and lossy. The deltas
of a model call aren't in the log and aren't replayed to a client that
reconnects; the recorded event that follows them holds the whole text. The
last event of each read of the log carries `Settled`, which says the log
ended there and the groups of records up to it are whole: a reader that folds
events, such as `transcript.Builder`, flushes there and only there.

`Follow` serves events another process appends only once this agent runs the
session again; until then it waits. A service with several replicas sends a
client back to the one that holds the session's lease.

## Send more while it runs

[`Session.Send`](/reference/go/zelk/#sessionsend) delivers a command to the
session: it joins the execution running, or starts one. A **steer**
(`zelk.Steer(run, text)`) adds text to a run under way; the run can't end
before the model has seen it. `zelk.SendNow` moves the run's commands and
subagents to the background so the steer is read at once:

```go
// core/example_test.go
// A host names the steer it sends, so it can then send it now: the
// run's Bash commands and subagents under way move to the background,
// and the next model call takes the steer.
steer := zelk.Steer(7, "Stop: use the staging database.")
steer.ID = "host/steer/1"
now := zelk.SendNow(7, steer.ID)
fmt.Println(now.Kind, now.BackgroundCalls.SendNow, now.BackgroundCalls.Steers)
// Output:
// background_calls true [host/steer/1]
```

Other commands set the goal, switch the model or mode, compact, rename and
tag; each is a function in [the `zelk` package](/reference/go/zelk/), such
as `SetGoal`, `SetPermissionMode` and `Compact`.

## Stop it

`Execution.Interrupt(reason)` stops a run; its result has the outcome
`interrupted`. Cancelling the context you pass to `Wait` stops waiting, not
the execution. `Agent.Close` ends every execution the agent owns and
releases their leases.

## Next

[Approvals and questions](/go/approvals/) covers what a run needs from a
person.
