---
title: Control what content leaves the process
description: Decide per destination whether prompts, answers, tool arguments and results are recorded, redact them with ContentConfig.Redact, cap them with MaxBytes, veto content for one agent with weft.Content(false), and keep raw provider bodies to development.
url: https://weftgo.dev/docs/production/content-and-privacy/
type: how-to
sources:
  - 'W11-auditA2-fix, v0.20.2: weft/core/raw.go:133-160 (rawMarked walks Unwrap() log.LoggerProvider, 64 hops); weft/core/layers.go:584-600 (devDetailMarked)'
  - 'weft/otel/options.go:104-123 (DevMode), 169-198 (DevDetail, dev-gated); weft/otel/pipeline.go:241-311, 931-960 (the gate, its WARNs and the DevMode INFO lines); weft/obsdb/request.go:93, 149, 167-168 (the gap and raw_off fixes name otel.DevMode()); weft/CHANGELOG.md:124 (0.19.0: DevMode), 35 (0.20.0: DevDetail)'
  - weft/docs/record-contract.md:936-962 (§5 content policy, weft.content full|stripped|none, what a content-off chain does per kind)
  - weft/docs/adr/0024-observability-data.md:341-354 (content off in the core, on through Install; third parties default off; StripContent the one shaping function)
  - weft/docs/adr/0028-the-request-record.md:595-708 (§12 raw records)
  - weft/core/content.go:7-22 (ContentKind and the eight kinds), 32-45 (Content, spans carry no content), 47-110 (StripContent and its table)
  - 'weft/otel/options.go:19-50 (ContentConfig, MaxBytes: 0 = 32 KiB, negative unlimited, never the transcript; Redact: every kind it sees, panics contained), 52-56 (Content), 142-166 (RawBodies), 307-327 (WithContent, NoContent)'
  - weft/otel/config.go:90-123 (contentDefault Local and Studio on; rawOn; appLogsOn)
  - weft/otel/proc.go:278-324 (redactRaw, ContentRaw, base64 bodies not redacted)
  - weft/otel/slog.go:53-57 (ContentLog)
  - weft/otel/proc.go:503-513, 538-550 (tool_start and pending args redacted, never capped)
  - 'weft/core/observe.go:22-27, 385-387, 518-520 (error text on run and model-call spans), 683, 710, 784 (a failed tool span: error.type only); core/report.go:480 (attempt spans); core/observe.go:1293-1298 and core/request.go:731-734 (transcript, prompt and tools records still ask Enabled)'
  - weft/otel/env.go:17-22, 39-44 (WEFT_STUDIO_URL and the discovery file add a content-on Studio); otel/options.go:263-273 (Langfuse traces only)
  - weft/docs/record-contract.md:948 (none on the session marker)
  - weft/runtime/options.go:289 (WEFT_ENV=dev opens the link)
  - weft/otel/pipeline.go:71-99 (Pipeline.LoggerProvider, LoggerProvider, LoggerProvider.RawBodies), 218-312 (RawBodies and Blocking refused outside WEFT_ENV=dev)
  - weft/AGENTS.md:92 (weft.Content), 133 (weft.StripContent), 610-613 (otel.Content, otel.RawBodies, p.LoggerProvider, weft.raw)
  - weft/CHANGELOG.md:2706 (system prompt and catalog reach content-on destinations), 2967 (ContentPrompt, ContentStop), 3340 (non-JSON args, panicking Redact), 3363-3365 (Redact applies to transcript records), 4197 (steered, pending, nested shaped), 4342 (per-destination content), 4810 (capture resolved at each emission)
  - weft/core/records_test.go:594 (ExampleContent)
  - weft/example_test.go:986 (ExampleStripContent)
  - docs-site/examples/production/main.go (contentPolicy, stripContent), main_test.go TestProduction
  - 'weft v0.20.2: otel/thread.go:13-21 (ContentThread: the kind Redact sees for a thread session record''s content fields), 54-90 (each content string shaped: Redact, MaxBytes); otel/example_thread_test.go:23-71 (ExampleContentThread: Output [agent-7 need a photo]); otel/pipeline.go:86-99 (LoggerProvider.DevDetail, LoggerProvider.RawBodies: the option and the dev gate at Start); weft/docs/record-contract.md:810-817 (the body''s content, stripped content-off)'
---

# Control what content leaves the process

Content is message text, tool arguments and results, the system prompt and the tool catalog. weft decides per [destination](https://weftgo.dev/docs/reference/glossary/#destination) whether it leaves the process: [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) and [`otel.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Studio) receive it, every third-party destination receives the records with their content fields emptied. On a content-on destination [`otel.ContentConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentConfig) redacts and caps it; [`weft.Content(false)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) keeps one agent's content out of every destination.

Redact email addresses on the local sink and send a third-party collector shape only, in `production/main.go`:

```go title="production/main.go"
email := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.]+`)
redact := func(kind weft.ContentKind, s string) string {
	return email.ReplaceAllString(s, "[email]") // every content field of every kind
}
p, err := otel.Start(ctx,
	otel.Local(path), // content on: the redactor and the cap apply
	otel.OTLP(collectorURL, otel.NoContent()), // a third party: shape only, no content
	otel.Content(otel.ContentConfig{
		MaxBytes: 16 << 10, // one event field, delta, prompt or catalog body; never the transcript
		Redact:   redact,
	}),
	otel.NoEnv(),
)
```

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

The model still reads the address; the local sink stores `[email]`; the collector stores every event marked `stripped` and no transcript.

## How it works

The core captures content only when some destination asks for it, through the OTel Logs API's `Enabled` question, so a pipeline whose destinations are all content-off makes the core emit no transcript records at all. Each destination's processor chain then clones every record and shapes it on its own: a content-off chain strips it, a content-on chain redacts and caps it. One destination's policy never changes what another receives. Spans carry no message, argument or result content, whatever the policy; the policy governs log record bodies. Two things do ride spans under any policy: the error text of a failed run, model call or attempt (a failed tool call's span carries only its `error.type`), and every `weft.Metadata` pair (such as `weft.session.title` or `weft.page_url`).

Every record says what it holds in its `weft.content` attribute:

| `weft.content` | Meaning |
|---|---|
| `full` | as emitted; a content-on chain may still have redacted or capped it |
| `stripped` | a content-off destination's chain stripped it |
| `none` | the core captured none: no destination wanted content, or the agent has `weft.Content(false)`; also every session marker record, which carries none by nature |

## Per-destination content

The defaults: `otel.Local` and `otel.Studio` are content-on; [`otel.OTLP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#OTLP), [`otel.Exporters`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Exporters), [`otel.Datadog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Datadog) and [`otel.Langfuse`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Langfuse) (traces only, so never any record) are content-off, so content never reaches a third party by accident. Two destination options override the default:

| Option | Effect |
|---|---|
| [`otel.WithContent(cfg...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#WithContent) | content on for this destination, optionally with its own `ContentConfig` |
| [`otel.NoContent()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoContent) | content off: event and delta bodies stripped, transcript records dropped |

[`otel.Content(cfg)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Content) sets the pipeline-wide `ContentConfig` every content-on destination applies; `WithContent(cfg)` replaces it for one destination. `ContentConfig` has two fields:

| Field | Applies to | Default |
|---|---|---|
| [`MaxBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentConfig.MaxBytes) | one event field or delta body, a prompt record's text, a tools record's body (whole tool entries dropped from the end, so it stays JSON). Never a transcript record (a capped transcript is not replay-grade), nor `tool_start` arguments or a pending call's arguments: those are JSON documents, redacted but never cut | `0` means 32 KiB; negative means no cap |
| [`Redact`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentConfig.Redact) | every content field before the cap ([Redaction](#redaction)) | nil: identity |

A cut sets `weft.content.truncated_bytes` (the bytes removed) on the record. The default 32 KiB cap applies to the catalog too: an MCP server's large catalog arrives truncated on the local sink unless you raise `MaxBytes` there.

What a content-off chain does, per record kind:

| Record | Content-off destination receives |
|---|---|
| `event`, `delta` | the same shape with the content fields emptied ([the table below](#strip-content)), marked `stripped` |
| `messages` (the transcript), `prompt`, `tools`, `raw` | nothing: dropped |
| `request` | kept with `params.stop` emptied and `messages_ref.index` removed (`messages_ref.count` stays); hashes, names and numbers survive; marked `stripped` |
| bridged app log line | body and string attribute values `""`, marked `stripped`, when the destination takes app logs at all ([app logs](https://weftgo.dev/docs/observe/app-logs/#choose-which-destinations-take-the-lines)) |

The environment can add destinations too. `WEFT_STUDIO_URL`, or a running Studio's discovery file when it is unset, adds a Studio destination, content on. An `OTEL_EXPORTER_OTLP_ENDPOINT` destination is content-off unless `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true`. `otel.NoEnv()` turns all of them off; `WEFT_DISCOVERY=off` turns off the discovery file alone ([Environment variables](https://weftgo.dev/docs/reference/env/)).

## What content-on carries

A content-on destination receives, besides events, deltas and the transcript, what each model call was given: the composed system prompt (a `prompt` record) and the tool catalog (a `tools` record), under the same policy. They are redactable (the prompt) and capped (both), and a content-off destination drops them. If a system prompt must not leave the process, redact it with the `prompt` kind or turn content off for that destination. This holds since weft 0.10.0, when ADR 0028 reversed the earlier rule that no record carries the instructions text.

## Content kinds

[`weft.ContentKind`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentKind) names what a content field holds. It is the first argument `Redact` receives, so a redactor can treat tool results differently from user text. The core puts eight kinds into records; `weft/otel` adds one for bridged log lines and one for `weft/thread`'s session records:

| Kind | Value | Holds |
|---|---|---|
| [`weft.ContentText`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentText) | `text` | assistant text and text deltas; in a transcript, the text parts of every role |
| [`weft.ContentReasoning`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentReasoning) | `reasoning` | reasoning text and deltas |
| [`weft.ContentArgs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentArgs) | `args` | tool call arguments and argument deltas |
| [`weft.ContentResult`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentResult) | `result` | tool results |
| [`weft.ContentMessages`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentMessages) | `messages` | whole transcript batches; `weft/otel` redacts them part by part with the four kinds above |
| [`weft.ContentPrompt`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentPrompt) | `prompt` | the composed system text of a prompt record |
| [`weft.ContentStop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentStop) | `stop` | one stop sequence of a request record's params |
| [`weft.ContentRaw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentRaw) | `raw` | one wire body of a raw record ([development only](#raw-provider-bodies)) |
| [`otel.ContentLog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentLog) | `log` | a bridged app log line's message and string attributes |
| [`otel.ContentThread`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentThread) | `thread` | since 0.18.0, each string of a [`thread` record](https://weftgo.dev/docs/reference/record-contract/#thread)'s `content` object: who decided, a deny reason, a resolve's result, a steer's text, a summary |

The core uses the kinds in one place, [`weft.StripContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StripContent)'s table of which field of which event is content.

## Redaction

`Redact func(kind weft.ContentKind, s string) string` sees each content field before the cap. It sees event and delta bodies, and transcript records, part by part with the kinds of the table above. It sees a prompt record's text, each stop sequence and a raw record's text bodies. It sees a bridged log line's message and string attributes. It sees each string of a session record's `content` as `otel.ContentThread`, also capped at `MaxBytes`. A content-off destination strips a session record's `content` whole. The package example [`ExampleContentThread`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-ContentThread) denies a parked call in a `thread` session with `Who` and a reason, and its redactor sees both, `[agent-7 need a photo]`, under that kind. It never sees ids, names, roles, signatures, file parts or hashes, and a tools record is capped, never redacted. Steered user text, the arguments of calls pending approval on `run_finish`, and a subagent's nested events are redacted like the rest.

It changes the record, never what the model sees: the tool result in `res.Messages` still holds the address in the example above.

Redaction fails closed:

- A panic in `Redact` is contained. The event goes out stripped and the transcript record not at all; both count as the destination's dropped records.
- A transcript record that cannot be decoded for redaction is dropped and counted, never exported unredacted. So is a raw record whose body does not survive `Redact`.
- Redacted tool arguments that are no longer JSON are exported as a JSON string.
- A base64 raw body (a binary response) is not text and is not passed to `Redact`.

Before weft 0.8.0, `Redact` did not see transcript records, so a masking redactor left the whole transcript unredacted on the local sink; from 0.8.0 on it applies to them part by part. Capture itself is decided at each emission (the agent's `weft.Content`, else the `Enabled` question), not when the agent is built, so an agent built before `otel.Install` still gets the pipeline's policy.

## The agent veto

`weft.Content(capture bool)` overrides what the destinations ask for, for one agent's runs:

| Option | Records carry content |
|---|---|
| none (the default) | as the logger in force answers `Enabled`: when some destination wants content |
| `weft.Content(false)` | never, even when a destination wants it; records keep their shape and positions, marked `none` |
| `weft.Content(true)` | event bodies always, even with no destination asking (tests); transcript, prompt and tools records are still emitted only when a destination asks for them |

Use `weft.Content(false)` for an agent whose data must never be recorded, whichever destinations an operator configures. The package example [`ExampleContent`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Content) records a run under `Content(false)` and prints its `tool_start` record, whose `args` is `null`.

## Strip content

`weft.StripContent(ev)` returns the event with every content field emptied: what a content-off destination receives. It is the one content-shaping table; `weft/otel` calls it, and you can call it to apply the same rule to events you forward yourself, from a [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) for example:

```go title="production/main.go"
ev := weft.ToolFinish{Seq: 4, CallID: "call_1", Name: "lookup_order",
	Content: "order 1234 has shipped to jane@example.com"}
out := weft.StripContent(ev).(weft.ToolFinish) // what a content-off destination receives
fmt.Fprintf(w, "stripped: name=%s call=%s content=%q\n", out.Name, out.CallID, out.Content)

// This agent's records never carry content, whatever a destination asks for.
payroll := weft.New(script(), weft.Name("payroll-bot"), lookup,
	weft.Content(false),
	weft.TracerProvider(tp), weft.LoggerProvider(lp))
```

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

```text
stripped: name=lookup_order call=call_1 content=""
content(false): succeeded events: 8 transcript batches: 0 the address stored: false
```

| Event | Emptied | Kept |
|---|---|---|
| `text_delta`, `reasoning_delta` | `text` | `run_id` |
| `tool_args_delta` | `args` | `run_id`, `name` |
| `tool_start` | `args` (becomes `null`) | `seq`, `call_id`, `name` |
| `tool_finish` | `content` | `seq`, `call_id`, `name`, `is_error` |
| `steered` | `messages` (becomes `[]`) | `seq`, `step` |
| `run_finish` | each pending call's `args` | usage, steps, pending ids and names, `stopped_by` |
| `run_start`, `step_start`, `step_finish` | nothing: no content | all |
| `nested` | recurses into the child event | the envelope |

A stripped record still attributes and orders: ids, names, counts, positions and usage survive. It is no longer replay-grade, by design. The package example [`ExampleStripContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-StripContent) prints a stripped `tool_finish` as JSON.

## Raw provider bodies

[`otel.RawBodies(true)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#RawBodies) records each model call attempt's HTTP exchange, the request and response a first-party adapter sent and received, as one `weft.raw` record per attempt. It is a development tool and the pipeline enforces that:

- It takes effect only behind the development gate: `WEFT_ENV=dev` when the pipeline starts, or `otel.DevMode()` in code (a `WEFT_ENV` set to anything but `dev` overrules it). Otherwise `Start` logs one WARN naming the cause, `otel: RawBodies ignored: WEFT_ENV is not dev` (under `otel.NoEnv()` without `DevMode`, `… otel.NoEnv reads no WEFT_ENV`), and nothing is recorded. When `WEFT_ENV` overrules `DevMode`, the single WARN is `otel: DevMode ignored: WEFT_ENV=<value>` ([Record provider wire bodies](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only)).
- Raw records go to Local and Studio destinations with content on, never to Datadog, Langfuse, OTLP or `Exporters`, and not to a Local or Studio destination under `NoContent()`.
- Each body is capped at 256 KiB. Credential headers and query values are stripped before emission and named in the record. `Redact` sees the text bodies with the `raw` kind.
- The gate is the pipeline's [`LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LoggerProvider): it embeds the SDK provider ([`LoggerProvider.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LoggerProvider)) and adds the marker [`LoggerProvider.RawBodies`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LoggerProvider.RawBodies) the core asks before it buffers a body: true only with `otel.RawBodies(true)` and the development gate at `Start`. Its twin [`LoggerProvider.DevDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LoggerProvider.DevDetail) reports the development detail level the same way (`otel.DevDetail()` and the gate), which the core asks before it starts a layer span or keeps a repair's original arguments. Pass [`p.LoggerProvider()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.LoggerProvider) to `weft.LoggerProvider`, or rely on `Install`'s global registration: a stock SDK provider has no marker and never records raw bodies. A `LoggerProvider` of your own that wraps the pipeline's (one that filters or adds attributes) must let the core reach the markers in one of three ways: embed the pipeline's `*otel.LoggerProvider`, forward `RawBodies()` and `DevDetail()` to it, or declare `Unwrap() log.LoggerProvider` returning it. The core asks each provider for the markers first and only then unwraps, at most 64 hops. Without one of them both markers are hidden, so `otel.RawBodies(true)` and `otel.DevDetail()` record nothing, and no WARN says so, since the gate passed at `Start`.

[Record provider wire bodies](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only) shows the option in a program.

> **Raw bodies hold everything the provider saw:** A raw record is the whole request and response: prompts, tool results, the full model output. Credential stripping is by header name and pattern. Never set `WEFT_ENV=dev` on a production host, nor ship `otel.DevMode()`: either also lets an explicit `otel.Blocking()` and `otel.DevDetail()` take effect, and `WEFT_ENV=dev` opens the runtime link `runtime.Install` would start.

## Complete example

The Production pages share one example program; `contentPolicy` and `stripContent` are this page's:

```go title="production/main.go"
// Command production runs the examples of the Production pages —
// deploying, content and privacy, retention, limits, storage backends
// and Studio operations:
// go run ./production. Every Studio is a stand-in on a loopback port
// over a fresh SQLite file and the model is scripted with wefttest, so
// it runs offline.
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"os/signal"
	"path/filepath"
	"regexp"
	"strings"
	"syscall"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/obsdb"
	"github.com/weftgo/weft/obsdb/sqlite"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/studio"
	"github.com/weftgo/weft/thread"
	"github.com/weftgo/weft/wefttest"
)

// LookupInput is the lookup tool's argument.
type LookupInput struct {
	OrderID string `json:"order_id" jsonschema:"the order to look up"`
}

// lookup returns a customer's email address: the content the pages keep
// out of the records.
var lookup = weft.Tool("lookup_order", "Look up an order by ID.",
	func(_ context.Context, in LookupInput) (string, error) {
		return "order " + in.OrderID + " has shipped to jane@example.com", 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."),
	)
}

func main() {
	dir, err := os.MkdirTemp("", "weft-production-")
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = os.RemoveAll(dir) }()
	// The shutdown example waits for SIGINT or SIGTERM; here it stops
	// itself after one turn so the program ends.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := run(ctx, os.Stdout, dir); err != nil {
		log.Fatal(err)
	}
	if err := runOperations(ctx, os.Stdout, dir); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context, w io.Writer, dir string) error {
	steps := []struct {
		name string
		fn   func(context.Context, io.Writer, string) error
	}{
		{"content policy", contentPolicy},
		{"strip content", stripContent},
		{"hosted studio", hostedStudio},
		{"retention", retention},
		{"tool limits", toolLimits},
		{"graceful shutdown", gracefulShutdown},
	}
	for _, s := range steps {
		fmt.Fprintln(w, "==", s.name)
		if err := s.fn(ctx, w, dir); err != nil {
			return fmt.Errorf("%s: %w", s.name, err)
		}
	}
	return nil
}

// contentPolicy records one run twice: into the local sink with a
// redactor and a cap, and into a third-party OTLP collector with
// content off.
func contentPolicy(ctx context.Context, w io.Writer, dir string) error {
	collectorURL, collectorDB, stopCollector, err := standInStudio(filepath.Join(dir, "collector.db"))
	if err != nil {
		return err
	}
	defer stopCollector()
	path := filepath.Join(dir, "redacted.db")

	email := regexp.MustCompile(`[\w.+-]+@[\w-]+\.[\w.]+`)
	redact := func(kind weft.ContentKind, s string) string {
		return email.ReplaceAllString(s, "[email]") // every content field of every kind
	}
	p, err := otel.Start(ctx,
		otel.Local(path), // content on: the redactor and the cap apply
		otel.OTLP(collectorURL, otel.NoContent()), // a third party: shape only, no content
		otel.Content(otel.ContentConfig{
			MaxBytes: 16 << 10, // one event field, delta, prompt or catalog body; never the transcript
			Redact:   redact,
		}),
		otel.NoEnv(),
	)
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}

	local, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = local.Close() }()
	stored, err := everything(ctx, local, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "the model saw:", toolResult(res))
	fmt.Fprintln(w, "local sink holds [email]:", strings.Contains(stored, "[email]"),
		"the address:", strings.Contains(stored, "jane@example.com"))

	rec, err := collectorDB.Run(ctx, res.ID)
	if err != nil {
		return err
	}
	page, err := collectorDB.Events(ctx, res.ID, -1, 50)
	if err != nil {
		return err
	}
	stripped := 0
	for _, e := range page.Events {
		if e.Content == "stripped" {
			stripped++
		}
	}
	fmt.Fprintln(w, "collector:", rec.Status, "events:", rec.EventCount, "stripped:", stripped,
		"transcript batches:", rec.MessageCount)
	return nil
}

// stripContent shows the core's content table and the agent-side veto.
func stripContent(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "vetoed.db")
	p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal()) // Local: content on
	if err != nil {
		return err
	}
	tp, lp := p.TracerProvider(), p.LoggerProvider()

	ev := weft.ToolFinish{Seq: 4, CallID: "call_1", Name: "lookup_order",
		Content: "order 1234 has shipped to jane@example.com"}
	out := weft.StripContent(ev).(weft.ToolFinish) // what a content-off destination receives
	fmt.Fprintf(w, "stripped: name=%s call=%s content=%q\n", out.Name, out.CallID, out.Content)

	// This agent's records never carry content, whatever a destination asks for.
	payroll := weft.New(script(), weft.Name("payroll-bot"), lookup,
		weft.Content(false),
		weft.TracerProvider(tp), weft.LoggerProvider(lp))

	res, err := payroll.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}
	db, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()
	rec, err := db.Run(ctx, res.ID)
	if err != nil {
		return err
	}
	stored, err := everything(ctx, db, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "content(false):", rec.Status, "events:", rec.EventCount, "transcript batches:", rec.MessageCount,
		"the address stored:", strings.Contains(stored, "jane@example.com"))
	return nil
}

// hostedStudio is setup C: a Studio behind a Token, its own ingest
// token, one allowed origin and a retention, and an app exporting to it.
func hostedStudio(ctx context.Context, w io.Writer, dir string) error {
	db, err := sqlite.Open(filepath.Join(dir, "hosted.db"))
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()
	apiToken, ingestToken := "api-secret", "ingest-secret" // in production: from your secret store

	srv := studio.New(
		studio.DB(db),                                  // the hosted database (SQLite here; clickhouse.Open in a fleet)
		studio.Token(apiToken),                         // every /api route: Authorization: Bearer <apiToken>
		studio.IngestToken(ingestToken),                // /v1/traces and /v1/logs: Authorization: Bearer <ingestToken>
		studio.AllowOrigins("https://app.example.com"), // the app page that loads the devtools panel
		studio.Retain(30*24*time.Hour),                 // delete runs not running, last seen 30 days ago
	)
	defer func() { _ = srv.Close() }() // stops the sweeper
	mux := http.NewServeMux()
	mux.Handle("/studio/", http.StripPrefix("/studio", srv.Handler()))
	ts := httptest.NewServer(mux)
	defer ts.Close()
	base := ts.URL + "/studio"

	// The app's side: export to the hosted Studio with the ingest token.
	p, err := otel.Start(ctx, otel.Studio(base, ingestToken), otel.NoEnv(), otel.NoGlobal())
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"),
		weft.Metadata(map[string]string{"weft.public_id": "pub_jane"}))
	if err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}

	noToken, _ := get(base+"/api/runs", "")
	withToken, body := get(base+"/api/runs", apiToken)
	fmt.Fprintln(w, "GET /api/runs without a token:", noToken, "with it:", withToken,
		"lists the run:", strings.Contains(body, res.ID))
	_, meta := get(base+"/api/meta", apiToken)
	var m struct {
		Retention string `json:"retention"`
	}
	_ = json.Unmarshal([]byte(meta), &m)
	fmt.Fprintln(w, "retention:", m.Retention)

	// Your backend mints a panel token for one conversation's public id.
	tok, err := mintPanelToken(base, apiToken, "pub_jane")
	if err != nil {
		return err
	}
	own, _ := get(base+"/api/runs?public_id=pub_jane", tok)
	other, _ := get(base+"/api/runs?public_id=pub_other", tok)
	fmt.Fprintln(w, "panel token, its public id:", own, "another:", other)
	return nil
}

// retention keeps runs 30 days and shows what a sweep 30 days later
// deletes, then gives the space back.
func retention(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "retained.db")
	p, err := otel.Start(ctx, otel.Local(path), otel.NoEnv(), otel.NoGlobal())
	if err != nil {
		return err
	}
	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
		return err
	}
	if err := p.Shutdown(ctx); err != nil {
		return err
	}
	db, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()

	srv := studio.New(studio.DB(db), studio.Retain(30*24*time.Hour)) // sweeps at New, then hourly
	defer func() { _ = srv.Close() }()                               // Close stops the sweeper
	page, err := db.Runs(ctx, obsdb.RunQuery{})
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "kept under a 30-day retention:", len(page.Runs), "run") // a fresh run is never swept

	later := time.Now().Add(30*24*time.Hour + time.Minute) // the clock, 30 days on
	n, err := sweepAndVacuum(ctx, db, later, 30*24*time.Hour)
	if err != nil {
		return err
	}
	page, err = db.Runs(ctx, obsdb.RunQuery{})
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "30 days later: swept", n, "runs; left:", len(page.Runs))
	return nil
}

// sweepAndVacuum is one sweep as Retain's sweeper runs it at now, then
// VACUUM: what `weft vacuum --retain` does.
func sweepAndVacuum(ctx context.Context, db obsdb.DB, now time.Time, retain time.Duration) (int, error) {
	cutoff := now.Add(-retain)      // what Retain's sweeper computes each pass
	n, err := db.Sweep(ctx, cutoff) // runs not running, last seen before cutoff, with their children
	if err != nil {
		return n, err
	}
	err = db.Vacuum(ctx) // SQLite: VACUUM; ClickHouse: OPTIMIZE TABLE … FINAL
	return n, err
}

// ReportInput is the report tool's argument.
type ReportInput struct {
	Month string `json:"month" jsonschema:"the month, YYYY-MM"`
}

// toolLimits runs two tools against their limits: a result past its cap
// and a handler past its deadline.
func toolLimits(ctx context.Context, w io.Writer, _ string) error {
	report := weft.Tool("monthly_report", "Export a month's orders as CSV.",
		func(_ context.Context, in ReportInput) (string, error) {
			return strings.Repeat("order,status\n", 5_000), nil // 65,000 bytes
		},
		weft.MaxResultBytes(4<<10), // this tool's results are cut at 4 KiB, with a marker
		weft.Timeout(10*time.Second),
	)
	slow := weft.Tool("carrier_status", "Ask the carrier where a parcel is.",
		func(ctx context.Context, in LookupInput) (string, error) {
			select {
			case <-ctx.Done(): // honour ctx: the deadline cancels it
				return "", ctx.Err()
			case <-time.After(time.Minute):
				return "in transit", nil
			}
		},
		weft.Timeout(50*time.Millisecond), // past it: an error result, the run goes on
	)
	agt := weft.New(model(), report, slow,
		weft.MaxSteps(5), // budget: ErrMaxSteps past 5 model calls
		weft.UsageLimit(weft.Usage{OutputTokens: 20_000}), // budget: ErrUsageLimit past 20,000 output tokens
	)
	res, err := agt.Generate(ctx, weft.Prompt("Report for 2026-09, and where is parcel 1234?"))
	if err != nil {
		return err
	}
	for _, m := range res.Messages {
		for _, part := range m.Content {
			if r, ok := part.(weft.ToolResultPart); ok {
				if r.IsError {
					fmt.Fprintf(w, "%s (error): %s\n", r.Name, r.Content)
					continue
				}
				fmt.Fprintf(w, "%s (%d bytes): …%s\n", r.Name, len(r.Content), tail(r.Content, 28))
			}
		}
	}
	return nil
}

func model() *wefttest.Model {
	return wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{Name: "monthly_report", Args: `{"month":"2026-09"}`},
			wefttest.Call{Name: "carrier_status", Args: `{"order_id":"1234"}`},
		),
		wefttest.Say("The report is partial; the carrier did not answer."),
	)
}

// gracefulShutdown serves one agent over HTTP with a thread session and
// an embedded Studio, then shuts every piece down in order once ctx ends.
func gracefulShutdown(ctx context.Context, w io.Writer, dir string) error {
	path := filepath.Join(dir, "app.db")
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return err
	}
	done := make(chan error, 1)
	go func() { done <- serve(ctx, ln, path) }()

	// One request, then the signal.
	resp, err := http.Post("http://"+ln.Addr().String()+"/chat", "text/plain", strings.NewReader("Where is order 1234?"))
	if err != nil {
		return err
	}
	reply, _ := io.ReadAll(resp.Body)
	_ = resp.Body.Close()
	fmt.Fprintln(w, "reply:", string(reply))
	cancel()
	if err := <-done; err != nil {
		return err
	}

	db, err := sqlite.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = db.Close() }()
	page, err := db.Runs(context.Background(), obsdb.RunQuery{})
	if err != nil {
		return err
	}
	for _, r := range page.Runs {
		fmt.Fprintln(w, "after shutdown the sink holds:", r.Agent, r.Status, "turn", r.Turn)
	}
	return nil
}

// serve runs the app until ctx ends, then shuts down: HTTP first, then
// the session, then Studio, then the recording pipeline.
func serve(ctx context.Context, ln net.Listener, dbPath string) error {
	shutdownRecording := otel.Install(otel.Local(dbPath), otel.NoEnv())
	agt := weft.New(script(), weft.Name("support-bot"), lookup)
	s, err := thread.Create(ctx, thread.Memory(), agt, thread.NoAutoCompact()) // in production: jsonl.Open or sqlite.Open
	if err != nil {
		shutdownRecording()
		return err
	}
	inspector := studio.New(studio.DB(otel.LocalDB()))
	mux := http.NewServeMux()
	mux.Handle("/studio/", http.StripPrefix("/studio", inspector.Handler()))
	mux.HandleFunc("POST /chat", func(rw http.ResponseWriter, r *http.Request) {
		var prompt bytes.Buffer
		_, _ = prompt.ReadFrom(r.Body)
		turn, err := s.Send(r.Context(), weft.User(prompt.String()))
		if err != nil {
			http.Error(rw, err.Error(), http.StatusServiceUnavailable)
			return
		}
		res, err := turn.Wait()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}
		_, _ = io.WriteString(rw, res.Text())
	})
	httpSrv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second}
	go func() { _ = httpSrv.Serve(ln) }()

	<-ctx.Done() // SIGINT or SIGTERM in main
	stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	err = errors.Join(
		httpSrv.Shutdown(stopCtx), // 1. stop taking requests; in-flight handlers finish
		s.Close(stopCtx),          // 2. drain the running turn and the queue, give the writer lease up
		inspector.Close(),         // 3. stop Retain's sweeper and the playground link
	)
	shutdownRecording() // 4. flush every destination (5 s budget), close the local sink last
	return err
}

// standInStudio serves a Studio over a fresh SQLite file on a loopback
// port: its OTLP ingest takes loopback peers without an ingest token.
func standInStudio(path string) (url string, db obsdb.DB, stop func(), err error) {
	db, err = sqlite.Open(path)
	if err != nil {
		return "", nil, nil, err
	}
	srv := studio.New(studio.DB(db))
	ts := httptest.NewServer(srv.Handler())
	return ts.URL, db, func() { ts.Close(); _ = srv.Close(); _ = db.Close() }, nil
}

// everything is every stored body of a run: its events and its
// transcript, joined.
func everything(ctx context.Context, db obsdb.DB, runID string) (string, error) {
	var sb strings.Builder
	page, err := db.Events(ctx, runID, -1, 500)
	if err != nil {
		return "", err
	}
	for _, e := range page.Events {
		b, _ := json.Marshal(e)
		sb.Write(b)
	}
	batches, err := db.Transcript(ctx, runID)
	if err != nil {
		return "", err
	}
	for _, b := range batches {
		sb.Write(b)
	}
	return sb.String(), nil
}

func get(url, token string) (int, string) {
	req, _ := http.NewRequest(http.MethodGet, url, nil)
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return 0, err.Error()
	}
	defer func() { _ = resp.Body.Close() }()
	b, _ := io.ReadAll(resp.Body)
	return resp.StatusCode, string(b)
}

func mintPanelToken(base, apiToken, publicID string) (string, error) {
	body := strings.NewReader(`{"public_id":"` + publicID + `","ttl":"15m"}`)
	req, _ := http.NewRequest(http.MethodPost, base+"/api/panel-tokens", body)
	req.Header.Set("Authorization", "Bearer "+apiToken)
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer func() { _ = resp.Body.Close() }()
	var out struct {
		Token string `json:"token"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return "", err
	}
	if out.Token == "" {
		return "", fmt.Errorf("panel-tokens: %s", resp.Status)
	}
	return out.Token, nil
}

// toolResult is the text of the run's first tool result: what the model
// read, never changed by a destination's redactor.
func toolResult(res *weft.RunResult) string {
	for _, m := range res.Messages {
		for _, part := range m.Content {
			if r, ok := part.(weft.ToolResultPart); ok {
				return r.Content
			}
		}
	}
	return ""
}

func tail(s string, n int) string {
	s = strings.ReplaceAll(s, "\n", `\n`)
	if len(s) <= n {
		return s
	}
	return s[len(s)-n:]
}
```

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

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

```sh
go run ./production
go test ./production
```

```text
== content policy
the model saw: order 1234 has shipped to jane@example.com
local sink holds [email]: true the address: false
collector: succeeded events: 8 stripped: 8 transcript batches: 0
== strip content
stripped: name=lookup_order call=call_1 content=""
content(false): succeeded events: 8 transcript batches: 0 the address stored: false
```

The rest of the output belongs to the other Production pages. `TestProduction` in [`main_test.go`](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/production/main_test.go) pins it: the address never reaches the local sink, and the collector holds only stripped events and no transcript.

## Best practices & gotchas

- **Turn content on for a third party only on purpose.** Every destination but Local and Studio is content-off by default; `WithContent()` is the opt-in. (Source: `otel/config.go:90-99`; ADR 0024 "Content: off by default")
- **Redact on the content-on destinations; strip on the rest.** `Redact` runs only where content is on; a content-off destination never sees content to redact. (Source: `otel/options.go:307-327`)
- **Raise `MaxBytes` on the local sink if you need whole catalogs and long results.** The default 32 KiB cut is marked with `weft.content.truncated_bytes`; the transcript is never cut. (Source: `otel/options.go:23-31`)
- **The model-visible tool-result cap is a different limit.** `weft.MaxResultBytes` (64 KiB) cuts what the model reads; `MaxBytes` cuts only what a destination stores ([Limits](https://weftgo.dev/docs/production/limits/)). (Source: `core/agent.go:22-29`)
- **Spans carry no message content, but they do carry errors and metadata.** A traces-only destination holds structure, timing, usage, the error text of failed runs, model calls and attempts, and every `weft.Metadata` pair; keep secrets out of error strings and metadata. (Source: `core/content.go:40-44`; `core/observe.go:386-387, 519-520, 683, 710, 784`; `core/report.go:480`; AGENTS.md block 3, `weft.Metadata`)

## See also

- [Send records to Studio, Datadog, Langfuse or any OTLP backend](https://weftgo.dev/docs/observe/destinations/)
- [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/)
- [Bridge your app's slog lines into runs](https://weftgo.dev/docs/observe/app-logs/)
- [Secure Studio](https://weftgo.dev/docs/production/security/)
- [Glossary: content policy](https://weftgo.dev/docs/reference/glossary/#content-policy)

Symbols used: [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Studio) · [`otel.OTLP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#OTLP) · [`otel.NoEnv`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoEnv) · [`otel.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Content) · [`otel.ContentConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentConfig) · [`otel.WithContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#WithContent) · [`otel.NoContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoContent) · [`otel.RawBodies`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#RawBodies) · [`otel.ContentLog`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#ContentLog) · [`otel.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LoggerProvider) · [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) · [`weft.ContentKind`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ContentKind) · [`weft.StripContent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StripContent) · [`weft.ToolFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolFinish) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) · [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
