# Agent Samples

Copyable Rust patterns and Flue-to-Agent-SDK equivalents covering hooks, conditional tools, model escalation, phase machines, workspaces, channels, schedules, and evals.

Your product's agent is part of your product, written in Rust alongside your
routes and storage bindings. Because the Agent SDK models its authoring surface
on [Flue](https://flueframework.com), every snippet from Flue's guides and
every agent in its `examples/` directory has a compiling, tested Rust
counterpart summarized below.

`ferrite add agent-sdk` installs the SDK without the `samples/` module, and
`ferrite new` templates omit it as well. Copy the code patterns on this page
directly into your own app; the module paths below tell you where each pattern
lives in the reference `samples/` tree.

Two platform differences shape how the samples are written:

- Where Flue reaches for a local shell, these agents use the Ferrite workspace
  file tools (`workspace()`).
- Where Flue registers a model provider in code, these agents pass a model id
  from the AI gateway catalog.

Every sample declares an Anthropic model id (`anthropic/claude-haiku-4-5`,
`anthropic/claude-sonnet-4-6`, and others), so running them unmodified requires
routing model calls through the AI gateway. The reference app's checked-in
manifest calls OpenAI directly, which rejects `anthropic/…` ids. Point
`agents-gateway-url` at the AI gateway (see
[ferrite-agents App](/developers/agents-app/#secrets)) or replace the model ids
with `openai/…` entries before deploying against OpenAI directly.

## Coming from Flue

If you already know Flue, this table maps each concept to its Agent SDK
counterpart:

| Flue | Agent SDK |
| --- | --- |
| `'use agent'; export function Agent() {}` | `pub fn agent() -> Instruction` registered with `Agent::new("agent", agent)` |
| `Agent.agentName`, `Agent.initialData`, `Agent.durability` | `Agent::new(name, f).initial_data(schema).durability(DurabilityConfig { .. })` |
| `useModel(id, { thinkingLevel, compaction })` | `use_model(id)` / `use_model_with(id, UseModelOptions { thinking_level, compaction })` |
| `useTool({ name, description, input, run })` | `use_tool(define_tool(name, description).input(schema).run(\|ctx\| async move { .. }))` |
| `defineTool({ harness: true })`, `harness.prompt`, `harness.sandbox` | `.harness()`, `ctx.harness()?.prompt(text, PromptOptions)`, `ctx.harness()?.sandbox()` |
| `defineTool({ durable: true })`, `step.do(name, fn)` | `.durable()`, `ctx.step()?.do_(name, future)` |
| `useSkill(import SKILL.md)`, `defineSkill({ files })` | `Skill::from_markdown(text, dir)`, `define_skill(SkillDefinition::new(..).file(path, bytes))` |
| `useSubagent({ name, description, agent, model })`, `GeneralSubagent` | `use_subagent(define_subagent(name, description, f).model(..))`, `general_subagent()` |
| `useMcpConnection({ name, url, auth, tools })` | `use_mcp_connection(define_mcp_connection(name, url).auth_resolver(..).only_tools(&[..]))` |
| `useSandbox(local())`, `bash(..)`, `{ cwd }` | `use_sandbox(workspace())`, `use_sandbox_in(workspace(), Some(cwd))` |
| `usePersistentState(name, default)` | `use_persistent_state::<T>(name, default)` returning `(value, setter)` |
| `useInitialData()`, `useDelivery()` | `use_initial_data::<T>()`, `use_delivery()` |
| `useAgentStart`, `useAgentFinish`, `useResponseStart`, `useResponseFinish` | The same names, snake-cased |
| `useDataWriter(name, { schema })` | `use_data_writer(name)` and `writer.write(value)` |
| `useInstruction(text)` | `use_instruction(text)` |
| `dispatch(Agent, { id, initialData, idempotencyKey, message })` | `runtime.dispatch(agent, id, initial_data, message, SubmitOptions { submission_id, .. })` |
| `createAgentRouter(Agent)` mounted in `app.ts` | Every registered agent is served by the faces; `AgentApp::route` mounts channels |
| `app.route('/channels/slack', slack.route())` | `.route("/channels/slack", slack::channel(secret))` |
| `flue run agent.ts --message` | `POST /api/agents/<agent>/instances/<id>/messages` |
| `createFlueClient(url).send/wait/history` | `POST …/messages`, `GET …/events`, or the SSE stream face |
| `setProvider(createProvider(..))` | A model id in the AI gateway's catalog; providers live in the gateway |
| Vitest evals over HTTP | In-process evals over `RuntimeDeps::in_memory` and `ScriptedProvider`, or the thread API against a deployment |

## The guide snippets

`samples/guide/` holds one module per Flue guide page:

| Module | Agents | Shows |
| --- | --- | --- |
| `building_agents.rs` | `guide_triage`, `guide_triage_for`, `guide_assistant` | Minimal agent; reading the instance id in instructions; stable instructions |
| `agent_hooks.rs` | `hooks_triage`, `hooks_support`, `hooks_case_assistant`, `hooks_account_support`, `hooks_stamped`, `hooks_triage_data`, `hooks_order_assistant`, `hooks_support_assistant` | Composing hooks; enabling a tool through persistent state; a phase and a counter; loading data once with `use_agent_start`; response metadata; typed initial data; a data card; a custom hook |
| `tools.rs` | `tools_order_assistant`, `tools_contract_reviewer`, `tools_provisioner`, `tools_release_manager`, `tools_customer_orders` | Basic tool; typed output; a harness tool with a structured result; a durable tool with replayed steps; approval-gated publishing under an HMAC; binding a trusted identifier from the delivery |
| `skills.rs` | `skills_support`, `skills_reviewer` | A skill loaded from `SKILL.md` with a supporting file and the `issue_refund` tool its procedure calls; inline skills |
| `subagents.rs` | `subagents_case_agent`, `subagents_triage`, `subagents_researcher`, `subagents_support` | Basic delegate; a delegate with its own tools sharing the workspace; the general delegate; a shared delegate with a model override |
| `mcp.rs` | `mcp_project_assistant`, `mcp_assistant_for_user`, `mcp_assistant_after_authorization`, `mcp_issue_reader`, `mcp_project_assistant_shared` | A deployment credential; per-user credentials bound to the instance; mounting after authorization; a tool allowlist; a shared connection |
| `models.rs` | `models_triage`, `models_deliberate`, `models_uncompacted`, `models_reviewer` | Declaring a model; thinking level and compaction tuning; compaction disabled; escalating to a stronger model mid-conversation |
| `sandboxes.rs` | `sandboxes_scratch_worker`, `sandboxes_document_reviewer`, `sandboxes_catalog_analyst`, `sandboxes_release_manager`, `sandboxes_support_engineer` | Default workspace; a harness tool staging files; seeding a data set; a working directory; conditional attachment |
| `durability.rs` | `durability_issue_triage` | A retry budget and timeout on the agent registration |
| `schedules.rs` | `schedules_reporter` | An agent driven by a schedule and the signal a fire delivers |

Two patterns show how render-time hooks drive runtime behavior.

Mount a tool conditionally based on durable state. When `escalate` flips
`escalated` to `true`, the SDK re-renders before the next model turn and mounts
`refund_tool()`:

```rust
// Conditional tools: a tool writes persistent state; the next render mounts a second tool because of it.
pub fn support_agent() -> Instruction {
    use_model("anthropic/claude-haiku-4-5");
    let (escalated, set_escalated) = use_persistent_state::<bool>("escalated", false);
    use_tool(define_tool("escalate", "Escalate this conversation when the customer needs a refund.").run(move |_ctx: ToolContext| {
        let set_escalated = set_escalated.clone();
        async move {
            set_escalated.set(true).map_err(tool_err)?;
            Ok("Escalated. The refund tool is now available.")
        }
    }));
    if escalated {
        use_tool(refund_tool());
    }
    "Answer customer support questions clearly and accurately.".into()
}
```

Switch models mid-conversation by computing the model id from persistent state
before the single `use_model` call:

```rust
// Changing models mid-conversation: compute the specifier before the one use_model call.
pub fn reviewer() -> Instruction {
    let (escalated, set_escalated) = use_persistent_state::<bool>("escalated", false);
    use_model(if escalated { "anthropic/claude-opus-5" } else { "anthropic/claude-haiku-4-5" });
    use_tool(define_tool("escalate_review", "Escalate when the change is too complex for a quick pass.").run(move |_ctx: ToolContext| {
        let set_escalated = set_escalated.clone();
        async move {
            set_escalated.set(true).map_err(tool_err)?;
            Ok("Escalated. A stronger model will take over.")
        }
    }));
    "Review the proposed change and leave actionable feedback.".into()
}
```

## hello-world

Flue's `examples/hello-world` maps one agent to each runtime capability. Each
agent exposes a harness tool that exercises that capability and reports the
result when you send it `"Run the demo."`.

| Agent | File | Shows |
| --- | --- | --- |
| `hello` | `hello_world/hello.rs` | A harness prompt with a result schema, structured logging with attributes, and a workspace check |
| `with_request` | `with_request.rs` | The smallest harness prompt |
| `with_tools` | `with_tools.rs` | A safe calculator tool and delegation through `task` |
| `with_thinking` | `with_thinking.rs` | The agent's thinking level and per-prompt overrides |
| `with_image` | `with_image.rs` | An image in both a plain and a structured prompt |
| `with_skill` | `with_skill.rs` | The packaged `greet` skill |
| `with_subagent` | `with_subagent.rs` | A `greeter` delegate |
| `with_abort` | `with_abort.rs` | Timeout, manual, and pre-aborted cancellation, with how long each took to settle |
| `fs_test` | `fs_test.rs` | The model creating and overwriting files, verified by the tool |
| `fs_surface_test` | `fs_surface_test.rs` | The sandbox filesystem API available to a harness tool |
| `compaction_test` | `compaction_test.rs` | A low compaction threshold, a 175 KB article, and recall afterwards |
| `session_test` | `session_test.rs` | A minimal agent for delivery tests |

Two Flue examples have no Ferrite counterpart: `local-env-smoke` (a local
shell's environment allowlist) and `with-registered-provider` (a custom model
provider). Ferrite agents have no local shell, and model providers belong to
the AI gateway.

## imported-skill, support-desk, react-chat

| Agent | File | Shows |
| --- | --- | --- |
| `with_imported_skill` | `imported_skill.rs` | A `SKILL.md` with a `CHECKLIST.txt` supporting file, run from a harness tool |
| `with_custom_workspace` | `imported_skill.rs` | A workspace with a custom working directory (replacing Flue's custom bash) |
| `support_desk` | `support_desk/{machine,tools,support}.rs` | A phase machine built from `use_persistent_state` and `use_instruction`; `guarded()` tools that refuse outside their phase; sentiment-gated retention; every phase mounted on every turn |
| `chat_assistant` | `react_chat/assistant.rs` | Offline echo assistant (scripted in the test, separate from the agent) |
| `chat_demo` | `react_chat/demo.rs` | A background job exposed as a tool with progress logs and a live `jobCard` data part |
| `chat_helper` | `react_chat/helper.rs` | A weather card, a calculator, a `poet` delegate, and `use_response_start` metadata |

`support_desk` builds a phased workflow from public hooks alone. Every phase
stays mounted across turns while guards decide which tools can run:

```rust
pub fn use_machine(name: &str, phases: &[&str], initial: &str) -> Machine {
    let (stored, setter) = use_persistent_state::<String>(name, initial.to_string());
    let phase = if phases.contains(&stored.as_str()) { stored } else { initial.to_string() };
    use_instruction(&format!("You operate a phased workflow: {}. Your current phase is announced by transition tool results.", phases.join(" → ")));
    Machine { phase, setter }
}

/// Wrap a tool so it refuses with the guard's message instead of running when `check()` fails.
pub fn guarded(check: Guard, tool: Tool) -> Tool { … }
```

Its test verifies that the rendered tool list stays constant across all phases
while each guard enforces phase boundaries.

## schedules, evals, channels

| Agent | File | Shows |
| --- | --- | --- |
| `scheduled` | `schedules.rs` | `fire()` dispatches a `schedule` signal into one fixed instance with the fire time as idempotency key; the test verifies two fires share one conversation and a retried fire converges |
| `service_status` | `evals.rs` | `use_response_finish` metadata recording tool calls; the eval asserts the tool ran before the answer |
| `github_assistant` | `channels/github.rs` | The GitHub channel: signed deliveries, one conversation per issue, and a bound comment tool |
| `slack_assistant` | `channels/slack.rs` | The Slack channel: Events API handshake, signed events, one conversation per thread, and a bound reply tool |

See [Agent Channels](/developers/agent-channels/) for the complete channel
pattern.

## Running a sample

Register the agents you copy into your app in an `Agents` registry and pass it
to `AgentApp` so every protocol face can address them:

```rust
impl FerriteApp for AgentsApp {
    async fn run(ctx: AppContext) -> io::Result<()> {
        agent_sdk::app::AgentApp::new(ctx).agents(samples::registry()).serve().await
    }
}
```

Call a sample by name through the Agents API:

```bash
curl -s -X POST "$AGENTS/api/agents/with_tools/instances/demo-1/messages" \
  -H "x-ferrite-agents-authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"message": "Run the demo."}'
```

Address samples by name as shown above. The Thread API, ACP, and A2A route to
the default agent, which is the alphabetically first registered name. In a
registry containing the full sample set above, that default is
`chat_assistant`, regardless of registration order. Set
`AppConfig.default_agent` if you want another default.

To test copied samples locally without a fleet, run `ferrite test` using
`RuntimeDeps::in_memory` and `ScriptedProvider`, or run
`ferrite dev --egress allow` against a live Responses endpoint; see
[Testing an agent](/developers/agent-sdk/#testing-an-agent).
