FerriteDocs

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, 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) 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:

FlueAgent SDK
'use agent'; export function Agent() {}pub fn agent() -> Instruction registered with Agent::new("agent", agent)
Agent.agentName, Agent.initialData, Agent.durabilityAgent::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 }), GeneralSubagentuse_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, useResponseFinishThe 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.tsEvery 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 --messagePOST /api/agents/<agent>/instances/<id>/messages
createFlueClient(url).send/wait/historyPOST …/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 HTTPIn-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:

ModuleAgentsShows
building_agents.rsguide_triage, guide_triage_for, guide_assistantMinimal agent; reading the instance id in instructions; stable instructions
agent_hooks.rshooks_triage, hooks_support, hooks_case_assistant, hooks_account_support, hooks_stamped, hooks_triage_data, hooks_order_assistant, hooks_support_assistantComposing 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.rstools_order_assistant, tools_contract_reviewer, tools_provisioner, tools_release_manager, tools_customer_ordersBasic 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.rsskills_support, skills_reviewerA skill loaded from SKILL.md with a supporting file and the issue_refund tool its procedure calls; inline skills
subagents.rssubagents_case_agent, subagents_triage, subagents_researcher, subagents_supportBasic delegate; a delegate with its own tools sharing the workspace; the general delegate; a shared delegate with a model override
mcp.rsmcp_project_assistant, mcp_assistant_for_user, mcp_assistant_after_authorization, mcp_issue_reader, mcp_project_assistant_sharedA deployment credential; per-user credentials bound to the instance; mounting after authorization; a tool allowlist; a shared connection
models.rsmodels_triage, models_deliberate, models_uncompacted, models_reviewerDeclaring a model; thinking level and compaction tuning; compaction disabled; escalating to a stronger model mid-conversation
sandboxes.rssandboxes_scratch_worker, sandboxes_document_reviewer, sandboxes_catalog_analyst, sandboxes_release_manager, sandboxes_support_engineerDefault workspace; a harness tool staging files; seeding a data set; a working directory; conditional attachment
durability.rsdurability_issue_triageA retry budget and timeout on the agent registration
schedules.rsschedules_reporterAn 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():

// 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:

// 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.".

AgentFileShows
hellohello_world/hello.rsA harness prompt with a result schema, structured logging with attributes, and a workspace check
with_requestwith_request.rsThe smallest harness prompt
with_toolswith_tools.rsA safe calculator tool and delegation through task
with_thinkingwith_thinking.rsThe agent’s thinking level and per-prompt overrides
with_imagewith_image.rsAn image in both a plain and a structured prompt
with_skillwith_skill.rsThe packaged greet skill
with_subagentwith_subagent.rsA greeter delegate
with_abortwith_abort.rsTimeout, manual, and pre-aborted cancellation, with how long each took to settle
fs_testfs_test.rsThe model creating and overwriting files, verified by the tool
fs_surface_testfs_surface_test.rsThe sandbox filesystem API available to a harness tool
compaction_testcompaction_test.rsA low compaction threshold, a 175 KB article, and recall afterwards
session_testsession_test.rsA 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

AgentFileShows
with_imported_skillimported_skill.rsA SKILL.md with a CHECKLIST.txt supporting file, run from a harness tool
with_custom_workspaceimported_skill.rsA workspace with a custom working directory (replacing Flue’s custom bash)
support_desksupport_desk/{machine,tools,support}.rsA 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_assistantreact_chat/assistant.rsOffline echo assistant (scripted in the test, separate from the agent)
chat_demoreact_chat/demo.rsA background job exposed as a tool with progress logs and a live jobCard data part
chat_helperreact_chat/helper.rsA 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:

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

AgentFileShows
scheduledschedules.rsfire() 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_statusevals.rsuse_response_finish metadata recording tool calls; the eval asserts the tool ran before the answer
github_assistantchannels/github.rsThe GitHub channel: signed deliveries, one conversation per issue, and a bound comment tool
slack_assistantchannels/slack.rsThe Slack channel: Events API handshake, signed events, one conversation per thread, and a bound reply tool

See 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:

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:

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.

Ferrite counts page views on this site. Privacy · Terms