---
title: 'Observe a run without changing it: Tap, OnRunEnd, OnMessages'
description: Watch every event with weft.Tap, get each run's outcome once with weft.OnRunEnd, persist the transcript as it grows with weft.OnMessages, and read the Debug lines weft.Logger writes.
url: https://weftgo.dev/docs/guides/observers/
type: how-to
sources:
  - weft/core/agent.go:437-451 (Tap), 463-485 (OnRunEnd), 511-524 (Logger), 927-938 (Agent.Logger), 1004-1011 (Agent.TapPanics)
  - weft/core/run.go:551-574 (OnMessages)
  - 'v0.20.2: weft/core/agent.go:1004-1010 (TapPanics counts every call into the TracerProvider or LoggerProvider that panicked; one Warn line per run names the provider); weft/CHANGELOG.md:265 (0.18.0, P9: Tracer and Logger at New, span starts and span calls of invoke_agent, chat, execute_tool and attempt, the records'' Enabled and Emit; a span whose attribute calls panic is still ended; the result and events equal the no-provider run''s)'
  - weft/core/loop.go:867-869 (OnMessages and OnRunEnd run on the loop goroutine)
  - weft/core/observe.go:1274, 1332 (the core emits its records through its LoggerProvider; no otel code uses Tap or OnRunEnd)
  - weft/core/subagent.go:149-159 (AgentFromContext)
  - weft/AGENTS.md:84-88 (block 2 observers), 93 (Logger), 677-679 (rule 3), 701-707 (rule 10)
  - weft/README.md:294-300 (logs)
  - weft/docs/adr/0004-event-ordering.md (a failed run emits nothing after its last event)
  - weft/docs/adr/0006-seams.md (observers are not a seam)
  - weft/example_test.go:172 (ExampleTap), 558 (ExampleTap_async), 892 (ExampleOnRunEnd)
  - weft/core/log_test.go:404 (ExampleLogger)
  - weft/core/onmessages_test.go:251 (ExampleOnMessages)
  - weft/CHANGELOG.md:5046, 5569, 5590, 6166, 6588, 6599
  - docs-site/examples/observers/main.go, main_test.go TestObservers, TestFailureIsInvisibleToTap, TestOnMessagesCannotChangeTranscript
  - weft/core/loop.go:308-329 (a resume rebuilds the partial tool message after the last assistant message with calls, or inserts one before what follows), 431-440 (the completed tool message is reported to OnMessages at step 0)
  - weft/thread/perstep.go:111-117 (a resume's first tool batch is held as the join), 215-231 (the join replaces the partial tool message on the path)
  - 'scratch proof (weft v0.17.0): lookup + gated refund, an OnMessages store appended across the park and the Approve resume held user, assistant, tool[lookup], tool[lookup, refund], assistant; weft.Repair of it answered refund with no result recorded: the call was interrupted (IsError true); res.Messages[len(input):] was the final assistant message alone; with weft.Prompt after the transcript the tool message joined before the new user message'
---

# Observe a run without changing it: Tap, OnRunEnd, OnMessages

weft has four ways to watch a run, none of which can change it. [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) sees every event of every run. [`weft.OnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnRunEnd) is called once per run with the result and the error, failures included. [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) receives the exact messages as they join the transcript. [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) sets the sink for the loop's Debug lines.

A tap that counts tool calls, in `observers/main.go`:

```go title="observers/main.go"
var calls int
agt := weft.New(script(), lookup,
	weft.Tap(func(_ context.Context, ev weft.Event) {
		if _, ok := ev.(weft.ToolStart); ok {
			calls++
		}
	}),
	weft.Tap(func(context.Context, weft.Event) { panic("broken observer") }),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
	return err
}
fmt.Fprintln(w, "tool calls:", calls)
fmt.Fprintln(w, "answer:", res.Text())
fmt.Fprintln(w, "contained tap panics:", agt.TapPanics()) // one per event the broken tap saw
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

Observers observe; behaviour attaches at the two middleware seams, `WrapModel` and `WrapTools`. That is [rule 10](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them): two behavioural seams, one tap, no more.

## How it works

| Observer | Option kind | Called | Sees a failed run |
|---|---|---|---|
| `Tap` | agent `Option` | once per event, every run | its events up to the failure, no end |
| `OnRunEnd` | agent `Option` | once per run, at the end | yes: `err` is the `*RunError` |
| `OnMessages` | `RunOption`, per run | once per batch of transcript messages | the messages that joined before it |
| `Logger` | agent `Option` | one Debug line per phase | yes: the error text |

`Tap`, `OnRunEnd` and `OnMessages` are synchronous, and the run waits for them. A `Tap` runs on the goroutine that emits the event, a tool goroutine included, under the event-ordering lock. `OnMessages` and `OnRunEnd` run on the loop's goroutine. Each receives the run's context, which carries the run's span and its [metadata](https://weftgo.dev/docs/guides/metadata/). A panic in a `Tap`, `OnRunEnd` or `OnMessages` observer is recovered and counted, never breaking the run.

## Tap

`Tap` registers an observer that sees every event of every run, including runs made with `Generate`, which has no stream to range over. Taps run in emission order, the order `Events()` delivers ([rule 3](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)), and several taps run in registration order. The package example is [`ExampleTap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap).

The second tap in the region panics on every event. The run still answers, and [`agt.TapPanics()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.TapPanics) reports `9`: one contained panic per event that tap saw. The counter covers taps, `OnMessages` and `OnRunEnd` observers, and attempt reports whose tracer or logger panicked. Since 0.18.0 it also counts every other call the loop makes into its `TracerProvider` or `LoggerProvider` that panics. That covers `Tracer` and `Logger` at `New`, span starts and attribute calls on the four span kinds, and the records' `Enabled` and `Emit`. Each run names such a provider in one Warn line on the agent's logger. A span whose attribute calls panic is still ended, and the run's result and events equal a run with no provider. A rising count means an observer or a provider is broken.

### Slow observers

A tap runs under the step's event-ordering lock. A slow tap delays every tool event of its step and blocks the tool goroutines that emit them, the same coupling a slow `Events()` consumer has. Do slow work, such as a database write or a network sink, off the tap: hand each event to a queue and drain it on your own goroutine.

```go title="observers/main.go"
events := make(chan weft.Event, 1024)
dropped := 0 // written only inside the tap, read after the run
done := make(chan int)
go func() { // the slow side: a database write, a network sink
	n := 0
	for range events {
		n++
	}
	done <- n
}()
agt := weft.New(script(), lookup,
	weft.Tap(func(_ context.Context, ev weft.Event) {
		select {
		case events <- ev: // never block inside a tap
		default:
			dropped++ // a full queue drops, visibly
		}
	}))
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
close(events)
fmt.Fprintln(w, "events drained:", <-done, "dropped:", dropped)
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

The tap never blocks: when the queue is full it drops the event and counts it. The package example is [`ExampleTap_async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap-Async).

## On run end

A failed run emits no event after its last delivered one ([ADR 0004](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0004-event-ordering.md)), so a tap cannot see a failure. `OnRunEnd` is the outcome signal. The loop calls it exactly once per run, after `RunFinish` is delivered or the `RunError` is built, and before `Generate` returns:

```go title="observers/main.go"
agt := weft.New(wefttest.Script(wefttest.Fail(errors.New("provider down"))),
	weft.OnRunEnd(func(_ context.Context, res *weft.RunResult, err error) {
		var runErr *weft.RunError
		fmt.Fprintf(w, "run ended: id set=%t steps=%d run error=%t\n",
			res.ID != "", res.NumSteps(), errors.As(err, &runErr))
	}),
)
_, err := agt.Generate(ctx, weft.Prompt("hi"))
fmt.Fprintln(w, "Generate returned:", err)
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

```text
run ended: id set=true steps=0 run error=true
Generate returned: weft: run failed at step 0: model stream: provider down
```

On success `err` is nil and `res` is complete. On failure `err` is the `*RunError` and `res` is its partial transcript, the same value `RunError.Result` holds. On cancellation `err` is the `RunError` wrapping the context's error. For a subagent's child run it fires inside the parent's tool call, and `res.ID` names the child. A run that panics, for example in a `PrepareStep` function, never fires it: the loop re-panics, to your caller under `Generate`; under `Stream` the panic crashes the program. The package example is [`ExampleOnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnRunEnd).

## On messages

`OnMessages` is a run option: pass it to `Generate` or `Stream`, not to `New`. The loop calls it whenever messages join the run's transcript: the assistant message a step produced, in its final shape with reasoning signatures, the tool message that follows its calls, and the messages a [steering](https://weftgo.dev/docs/guides/steering/) drain delivered.

```go title="observers/main.go"
var saved []weft.Message // stands in for an append-only store
persist := weft.OnMessages(func(_ context.Context, step int, msgs []weft.Message) {
	for _, m := range msgs {
		b, _ := json.Marshal(m)
		fmt.Fprintf(w, "step %d: save %s (%d bytes)\n", step, m.Role, len(b))
	}
	saved = append(saved, msgs...)
})
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), persist)
if err != nil {
	return err
}
// The prompt is the caller's input: it is in res.Messages, not in a batch.
fmt.Fprintln(w, "saved equals the transcript after the prompt:", reflect.DeepEqual(saved, res.Messages[1:]))
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

```text
step 0: save assistant (116 bytes)
step 0: save tool (143 bytes)
step 1: save assistant (81 bytes)
saved equals the transcript after the prompt: true
```

On an ordinary run the batches concatenate to `res.Messages` after the run's input, so appending each batch to durable storage keeps the exact transcript of a run that crashes mid-way. An [approval resume](https://weftgo.dev/docs/guides/approvals/#resume-an-approval) is the exception: its first batch is the parked step's completed tool message, which belongs right after the parked assistant message, not at the end ([gotcha](#best-practices--gotchas)).

`msgs` is exactly what joined, in transcript order, as a deep copy: keeping or changing it changes nothing the run sees. `step` is the step the messages belong to; a steer's messages name the step whose drain delivered them. Rebuilding messages from events loses signatures and block boundaries; this does not. A subagent's child run does not inherit the observer. The package example is [`ExampleOnMessages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-OnMessages).

## Agent from context

`weft.Option` is sealed, so an observer packaged as `weft.Options(weft.Tap(…), weft.OnRunEnd(…))` never receives the agent it was installed on. [`weft.AgentFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AgentFromContext) returns it: the agent whose run produced the event, or that a tool handler is running for.

```go title="observers/main.go"
who := weft.Tap(func(ctx context.Context, ev weft.Event) {
	if _, ok := ev.(weft.RunStart); ok {
		agt := weft.AgentFromContext(ctx) // the running *Agent; nil outside a run
		agt.Logger().DebugContext(ctx, "observer saw a run")
		fmt.Fprintln(w, "run start by", agt.Name())
	}
})
researcher := weft.New(wefttest.Script(wefttest.Say("notes")), weft.Name("researcher"), who)
lead := weft.New(wefttest.Script(
	wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}),
	wefttest.Say("done"),
), weft.Name("lead"), who, weft.Subagent("research", "Research a topic.", researcher))
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

```text
run start by lead
run start by researcher
outside a run: true
```

For a subagent's child run it is the child. Outside a run, in a manual [`agt.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) or a handler called directly, it is nil, so an observer must not depend on it. The agent is read-only: an `Agent` is immutable after `New`. [`agt.Logger()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Logger) returns the run lines' sink, the `Logger` option's value or `slog.Default`, so an observer can log its own errors where the run's lines go.

## Debug log lines

`weft.Logger(l)` sets the logger the agent's runs report to, at Debug level: one line when a run starts and ends, one per model call, one per tool call.

```go title="observers/main.go"
scrub := func(_ []string, a slog.Attr) slog.Attr {
	if a.Key == slog.TimeKey || a.Key == "dur" { // not reproducible
		return slog.Attr{}
	}
	return a
}
l := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: scrub}))
agt := weft.New(script(), lookup, weft.Name("support-bot"), weft.Logger(l))
_, err := agt.Generate(ctx, weft.RunID("demo"), weft.Prompt("Where is order 1234?"))
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

```text
level=DEBUG msg="run start" run=demo agent=support-bot provider=wefttest model=script
level=DEBUG msg="model call" run=demo step=0 provider=wefttest model=script reason=tool_calls input_tokens=10 output_tokens=5 tool_calls=1
level=DEBUG msg="tool call" run=demo step=0 call=call_1 tool=lookup_order result_bytes=22
level=DEBUG msg="model call" run=demo step=1 provider=wefttest model=script reason=stop input_tokens=10 output_tokens=5 tool_calls=0
level=DEBUG msg="run finish" run=demo steps=2 input_tokens=20 output_tokens=10 stop=stop
```

The lines carry ids, the model, durations, usage, stop reasons and outcomes; never message text, tool arguments or tool results. The one exception is error text: a failed run, model call or tool call logs the error it returned. The region drops the time and the `dur` attribute only to make the output reproducible.

Without the option the logger is `slog.Default`, which is silent until its handler enables Debug, so weft logs nothing in a program that did not ask. `slog.New(slog.DiscardHandler)` turns the lines off outright. The lines carry the span-carrying context, so a handler that bridges to OpenTelemetry correlates them with the spans. `mw.Log` and `mw.Audit` are separate: middleware you place, at the level you choose. The package example is [`ExampleLogger`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Logger).

## Complete example

`observers/main.go` runs each region against a scripted model that calls `lookup_order` once and then answers:

```go title="observers/main.go"
// Command observers runs the examples of the guide "Observe a run
// without changing it": go run ./observers. Every model is scripted
// with wefttest, so it runs offline; swap in a provider adapter for a
// real one.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"os"
	"reflect"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/wefttest"
)

// lookup is the one tool every example uses.
var lookup = weft.Tool("lookup_order", "Look up an order by ID.",
	func(_ context.Context, in struct {
		OrderID string `json:"order_id" jsonschema:"the order to look up"`
	}) (string, error) {
		return "order " + in.OrderID + " has shipped", nil
	})

// script is a two-step dialogue: one tool call, then an answer.
func script() *wefttest.Model {
	return wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
		wefttest.Say("Order 1234 has shipped."),
	)
}

// tap counts tool calls and shows a panicking tap contained.
func tap(ctx context.Context, w io.Writer) error {
	var calls int
	agt := weft.New(script(), lookup,
		weft.Tap(func(_ context.Context, ev weft.Event) {
			if _, ok := ev.(weft.ToolStart); ok {
				calls++
			}
		}),
		weft.Tap(func(context.Context, weft.Event) { panic("broken observer") }),
	)
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "tool calls:", calls)
	fmt.Fprintln(w, "answer:", res.Text())
	fmt.Fprintln(w, "contained tap panics:", agt.TapPanics()) // one per event the broken tap saw
	return nil
}

// async hands events to a queue and drains it on its own goroutine.
func async(ctx context.Context, w io.Writer) error {
	events := make(chan weft.Event, 1024)
	dropped := 0 // written only inside the tap, read after the run
	done := make(chan int)
	go func() { // the slow side: a database write, a network sink
		n := 0
		for range events {
			n++
		}
		done <- n
	}()
	agt := weft.New(script(), lookup,
		weft.Tap(func(_ context.Context, ev weft.Event) {
			select {
			case events <- ev: // never block inside a tap
			default:
				dropped++ // a full queue drops, visibly
			}
		}))
	_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	close(events)
	fmt.Fprintln(w, "events drained:", <-done, "dropped:", dropped)
	return err
}

// runEnd sees a failed run, which no event reports.
func runEnd(ctx context.Context, w io.Writer) error {
	agt := weft.New(wefttest.Script(wefttest.Fail(errors.New("provider down"))),
		weft.OnRunEnd(func(_ context.Context, res *weft.RunResult, err error) {
			var runErr *weft.RunError
			fmt.Fprintf(w, "run ended: id set=%t steps=%d run error=%t\n",
				res.ID != "", res.NumSteps(), errors.As(err, &runErr))
		}),
	)
	_, err := agt.Generate(ctx, weft.Prompt("hi"))
	fmt.Fprintln(w, "Generate returned:", err)
	return nil
}

// messages persists each batch of transcript messages as it joins.
func messages(ctx context.Context, w io.Writer) error {
	agt := weft.New(script(), lookup)
	var saved []weft.Message // stands in for an append-only store
	persist := weft.OnMessages(func(_ context.Context, step int, msgs []weft.Message) {
		for _, m := range msgs {
			b, _ := json.Marshal(m)
			fmt.Fprintf(w, "step %d: save %s (%d bytes)\n", step, m.Role, len(b))
		}
		saved = append(saved, msgs...)
	})
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"), persist)
	if err != nil {
		return err
	}
	// The prompt is the caller's input: it is in res.Messages, not in a batch.
	fmt.Fprintln(w, "saved equals the transcript after the prompt:", reflect.DeepEqual(saved, res.Messages[1:]))
	return nil
}

// agentFromContext names the agent behind each RunStart, child runs
// included.
func agentFromContext(ctx context.Context, w io.Writer) error {
	who := weft.Tap(func(ctx context.Context, ev weft.Event) {
		if _, ok := ev.(weft.RunStart); ok {
			agt := weft.AgentFromContext(ctx) // the running *Agent; nil outside a run
			agt.Logger().DebugContext(ctx, "observer saw a run")
			fmt.Fprintln(w, "run start by", agt.Name())
		}
	})
	researcher := weft.New(wefttest.Script(wefttest.Say("notes")), weft.Name("researcher"), who)
	lead := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"tariffs"}`}),
		wefttest.Say("done"),
	), weft.Name("lead"), who, weft.Subagent("research", "Research a topic.", researcher))
	_, err := lead.Generate(ctx, weft.Prompt("Brief me."))
	fmt.Fprintln(w, "outside a run:", weft.AgentFromContext(ctx) == nil)
	return err
}

// logger prints the Debug lines one run writes.
func logger(ctx context.Context, w io.Writer) error {
	scrub := func(_ []string, a slog.Attr) slog.Attr {
		if a.Key == slog.TimeKey || a.Key == "dur" { // not reproducible
			return slog.Attr{}
		}
		return a
	}
	l := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: scrub}))
	agt := weft.New(script(), lookup, weft.Name("support-bot"), weft.Logger(l))
	_, err := agt.Generate(ctx, weft.RunID("demo"), weft.Prompt("Where is order 1234?"))
	return err
}

func run(ctx context.Context, w io.Writer) error {
	steps := []struct {
		title string
		fn    func(context.Context, io.Writer) error
	}{
		{"tap", tap},
		{"slow observer", async},
		{"run end", runEnd},
		{"messages", messages},
		{"agent from context", agentFromContext},
		{"logger", logger},
	}
	for _, s := range steps {
		fmt.Fprintf(w, "== %s\n", s.title)
		if err := s.fn(ctx, w); err != nil {
			return fmt.Errorf("%s: %w", s.title, err)
		}
	}
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

[observers/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/observers/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/observers) · run it from `docs-site/examples`:

```sh
go run ./observers
go test ./observers
```

```text
== tap
tool calls: 1
answer: Order 1234 has shipped.
contained tap panics: 9
== slow observer
events drained: 9 dropped: 0
== run end
run ended: id set=true steps=0 run error=true
Generate returned: weft: run failed at step 0: model stream: provider down
== messages
step 0: save assistant (116 bytes)
step 0: save tool (143 bytes)
step 1: save assistant (81 bytes)
saved equals the transcript after the prompt: true
== agent from context
run start by lead
run start by researcher
outside a run: true
== logger
level=DEBUG msg="run start" run=demo agent=support-bot provider=wefttest model=script
level=DEBUG msg="model call" run=demo step=0 provider=wefttest model=script reason=tool_calls input_tokens=10 output_tokens=5 tool_calls=1
level=DEBUG msg="tool call" run=demo step=0 call=call_1 tool=lookup_order result_bytes=22
level=DEBUG msg="model call" run=demo step=1 provider=wefttest model=script reason=stop input_tokens=10 output_tokens=5 tool_calls=0
level=DEBUG msg="run finish" run=demo steps=2 input_tokens=20 output_tokens=10 stop=stop
```

## Best practices & gotchas

- **Never block inside a tap.** A tap runs under the event-ordering lock; a slow one gates the step's tool events. Queue the event and drain elsewhere. (Source: `weft/core/agent.go:437-451`, `ExampleTap_async`)
- **Use `OnRunEnd`, not `Tap`, to record failures.** A failed run has no `RunFinish` and no event after its last one. (Source: ADR 0004, `TestFailureIsInvisibleToTap`)
- **Pass `OnMessages` per run.** It is a `RunOption`; it is not an agent option and child runs do not inherit it. (Source: AGENTS.md:86-87, `weft/core/run.go:551-574`)
- **Replace, do not append, a resume's first tool message.** On a resume, the step-0 batch starts with the completed tool message. If the parked step had a call that already ran, say `lookup` beside a gated `refund`, your store already holds a partial tool message with `lookup`'s result. Appending gives two tool messages for one step, and `weft.Repair` then keeps the partial one and answers `refund` with `no result recorded: the call was interrupted`, so the next model may refund again. Put the resume's tool message right after the parked assistant message, in place of any tool message stored there. `res.Messages[len(input):]` misses it the same way. `weft/thread` handles this for you ([sessions](https://weftgo.dev/docs/sessions/overview/)). (Source: `weft/core/loop.go:308-329, 431-440`, `weft/thread/perstep.go:111-117, 215-231`; scratch test)
- **Watch `TapPanics`.** A panicking observer is contained and counted, so a broken one is otherwise silent. (Source: `weft/core/agent.go:1004-1011`, CHANGELOG 0.2.0)
- **Check `AgentFromContext` for nil.** It is nil outside a run, such as a manual `CallTool`. (Source: `weft/core/subagent.go:149-159`)
- **Do not expect content in `weft.Logger`'s lines.** `weft.Logger` only sets where the loop's own Debug lines go, and those lines carry ids and outcomes, never message text, tool arguments or results; content goes to the [observability pipeline](https://weftgo.dev/docs/observe/recording/) under its content policy. (Source: `weft/core/agent.go:511-524`)

## See also

- [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/): when you need to change a call, not watch it
- [Stream a run's events](https://weftgo.dev/docs/guides/streaming/)
- [Tag runs with metadata](https://weftgo.dev/docs/guides/metadata/)
- [Record runs](https://weftgo.dev/docs/observe/recording/)
- [Event types](https://weftgo.dev/docs/reference/events/)

Symbols used: [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`weft.OnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnRunEnd) · [`weft.OnMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OnMessages) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.AgentFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AgentFromContext) · [`Agent.Logger`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Logger) · [`Agent.TapPanics`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.TapPanics) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.RunError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunError) · [`weft.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunID) · [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Name`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Name) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script) · [`wefttest.Fail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Fail) · [`ExampleTap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap) · [`ExampleTap_async`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Tap-Async) · [`ExampleOnRunEnd`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-OnRunEnd) · [`ExampleOnMessages`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-OnMessages) · [`ExampleLogger`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Logger) · [`weft.Repair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Repair)
