Skip to content
Blogs

Designing Agentic Workflows That Stay Controllable

· 19 min read

Free-form agents impress in demos and fracture in production. Staff engineers own the state machine—gather, propose, approve, execute, verify, stop—scope tools with real authorization, cap loops and spend, persist transcripts, and recover with dead-letter states instead of invented success.

Autonomy needs a state machine

Free-form agents that invent their own plans are exciting in demos and fragile in production. Prefer an explicit workflow: gather context, propose actions, request approval when needed, execute tools, verify outcomes, and stop. The model fills flexible steps inside that machine; it does not own the machine.

State machines make timeouts, retries, and audits possible. They enforce product promises: an agent cannot refund money, delete data, or message customers unless the workflow reaches an approved state with evidence attached.

Encode states in code reviewers can diff—not only in system prompts. Prompt-only workflows drift when models update, tools multiply, or on-call edits instructions during incidents.

Each transition should declare allowed tools, max duration, and rollback behavior. Illegal transitions fail closed with structured errors the UI can explain without exposing raw model reasoning.

For mobile MVPs, the state machine runs server-side even when chat UI lives in Expo. Clients display proposals; Workers or edge functions decide whether execution is permitted.

Diagram the machine for product and legal review before launch. Ambiguous states become incident magnets when models propose edge-case tool chains that no prompt update can cleanly forbid without breaking happy paths.

Persist the current state id on every user-visible message so reconnecting clients resume safely. Multi-tab users should not fork two competing executions against the same tenant record because each tab ran an independent chat loop without a server lease.

When integrating with Supabase row-level security, the state machine should carry the same JWT claims tools use for authorization—never a service role that bypasses tenant boundaries just because the planner asked nicely.

Tools are capabilities with contracts

Each tool exposes a narrow capability with typed inputs, authorization checks, idempotency keys, and documented side effects. Broad tools that shell out to arbitrary commands or raw SQL invite irreversible mistakes under prompt injection.

Return structured results the workflow validates—success, partial, retryable failure, fatal. Ambiguous tool failures must not become invented successes. If a payment API times out, the agent queries status rather than assuming completion.

| Tool smell | Safer pattern | | --- | --- | | run_sql(query) | named read/write operations | | send_email(to, body) | templated sends with allow-listed domains | | http_fetch(url) | brokered fetch with domain allow list |

Least-privilege credentials per tool beat one super-token the planner can reuse across tenants. Rotate credentials independently when a single integration is compromised.

Version tool schemas alongside API contracts. Breaking changes ride pull requests with eval gates that assert workflow still completes on golden tasks.

Tool routers should log denials with reason codes the model can read on retry—permission denied differs from validation failed differs from downstream outage. Without structured denial, agents hallucinate workarounds that bypass policy.

Contract-test tools the way you contract-test public HTTP APIs: golden inputs, expected error shapes, and regression suites when downstream vendors change field names. Agent evals catch planner mistakes; contract tests catch broken integrations before the planner ever runs.

Separate read tools from write tools at the registry level so kill switches and incident playbooks can disable mutation without removing helpful lookup capabilities users still need during an outage.

Keep humans in the right places

Human approval is not a confession of failure. It is a product control for actions with legal, financial, or reputational impact. Design review interfaces that show proposed action, evidence, and alternatives in seconds—not a raw chain-of-thought dump.

Batch similar approvals when safe: ten identical refund proposals under a threshold might approve once with monitoring, while one large refund still needs individual review.

Over time, promote repeatedly approved patterns into automated paths with telemetry. Controllability improves when the organization learns which decisions are safe to accelerate—document promotion criteria in the runbook.

Mobile approval surfaces should work on poor networks: optimistic UI must not mark actions complete until the server confirms execution after approval.

Escalation queues need SLAs and fallback owners. Agents stuck awaiting human review should degrade gracefully—save draft, notify user, never spin burning tokens overnight.

Measure approval latency as a product metric alongside model latency. If reviewers need five minutes per decision, the workflow is mis-scoped or missing summarization—not an argument to remove humans entirely.

Role-based approval matters in multi-tenant SaaS: the agent should never surface actions a reviewer cannot legally authorize. Bind approval queues to tenant admin roles and log which identity approved each transition for later dispute resolution.

Night-shift on-call should not inherit unbounded approval debt—route low-urgency proposals to business-hours queues with explicit user expectations instead of silent overnight token burn.

Bound loops, steps, and spend

Agents loop when tools fail ambiguously or when the model chases a impossible goal. Cap steps per task, wall-clock time, and model spend per user session. Exceeding limits transitions to a dead-letter state with partial results preserved.

Log loop exits with the last tool error hash so engineers see whether caps hide a broken integration or a genuinely hard task.

Pair caps with kill switches that disable write tools globally during incidents while read-only assistance continues—see your operational playbook for soft degrade versus hard stop defaults.

Cost bounds belong in the same dashboard as availability. An agent that succeeds after fifty retries is not healthy even if the final answer looks fine.

Replay capped sessions in eval to ensure users receive actionable next steps—not silent failure when the step limit hits mid-checkout.

Alert when cap-hit rate spikes for a single tool integration; that pattern usually precedes a broken webhook or auth rotation, not user abuse.

Persist plans and tool transcripts

Store the plan state, tool inputs, tool outputs, approval decisions, and model versions for every task. Support and compliance need reconstructability without downloading entire prompt logs to laptops.

Redact secrets at ingest; never rely on the model to omit API keys in transcripts. Structured storage beats concatenated chat strings for search and retention policies.

Transcripts power post-incident eval: replay the same tool sequence against patched code to verify the fix before re-enabling automation.

Align retention with privacy policy—transcripts are product data subject to deletion requests and locale-specific rules, not informal engineering notebooks.

Expose a support view that maps user-visible status to internal states so agents do not contradict the workflow engine when chatting with customers.

Legal hold and litigation requests may require freezing transcript deletion for specific tenants—design retention hooks early instead of ad hoc database exports during counsel review.

Index transcripts by tenant id, workflow name, and outcome so analytics can answer how often humans override the planner without building a separate shadow logging pipeline engineers forget to maintain.

Recover like software, not like magic

Agents stall, loop, or partially complete work. Provide compensating actions, dead-letter queues, and operator tools to resume, retry idempotent steps, or unwind with explicit user confirmation.

Users should never hear "done" when underlying operations are unresolved—payment pending, message queued, file half-written.

Idempotent tool design makes recovery tractable. Duplicate delivery becomes a no-op instead of a double charge.

Document recovery playbooks per workflow: which states allow automatic retry, which require human operator, which must refund and abort.

Game-day exercises: kill model provider mid-task, saturate tool latency, flip kill switch during approval—measure time to safe steady state.

Compensating transactions should be idempotent and visible in the same task timeline so operators do not run duplicate refunds while unwinding a half-finished agent plan.

Surface recovery status in the product UI with the same vocabulary support uses—users should not need to open a developer console to learn their refund is still pending backend confirmation. Treat ambiguous recovery as a P1 defect until copy and state ids align.

Expo clients and server-side control

React Native clients should not hold long-lived agent loops that call privileged tools with embedded secrets. Stream UI from the device; run the state machine on Workers or Supabase edge with user-scoped JWTs.

Offline queues on mobile enqueue user intent, not autonomous tool plans that execute when connectivity returns unless the server validates each step again.

Deep links into approval screens should carry signed task ids so users cannot approve actions they cannot see in context.

Push notifications for approval must not leak sensitive payload—use neutral copy with in-app detail after unlock.

Static export hosting still routes agent traffic through your API Worker; containment and authz stay centralized regardless of where HTML is served.

Biometric or device-bound sessions on mobile do not replace server-side approval for financial actions—local UI trust is not authorization for shared tenant credentials on the backend.

Operational checklist for controllable agents

Before launch: state diagram reviewed, write tools gated, loop caps configured, transcripts retained, kill switch tested, human approval SLA staffed. Before expanding tools: threat model update, eval tasks cover new side effects, rollback documented.

Weekly: sample transcripts for policy violations, review promotion candidates from approval history, check cap-hit rate for product friction signals.

Controllable agentic systems feel calm—they use models for judgment inside software boundaries you own, audit, and stop.

Link checklist items to on-call runbooks and incident severities so new engineers know which controls are merge-blocking versus nice-to-have documentation.

When eval blocks a workflow change, treat it like a failing unit test—fix or shrink scope before merge, not after customer impact.

Publish a one-page control summary for sales and support: which actions are automated, which require approval, and which are permanently forbidden. Controllability is a positioning claim only when documentation matches runtime behavior under stress.

Frequently asked questions

Is a detailed system prompt enough control?
No. Prompts influence behavior but cannot enforce authorization, cap loops, or guarantee recovery. The state machine in code defines legal transitions, allowed tools, and timeouts. Prompts fill phrasing inside those states—they do not replace them. Treat prompt edits like copy changes, not security controls.
How narrow should tools be?
Narrow enough that each tool maps to one business capability with typed inputs and explicit authz. If a tool can perform arbitrary side effects, split it until reviewers can explain blast radius in one sentence. Generic shells and raw SQL are almost never acceptable in customer-facing agent paths.
Will human approval bottleneck the product?
It bottlenecks irreversible actions—which is the point. Automate low-risk, high-volume patterns only after measured approval history and monitoring, keep humans on financial, legal, and bulk mutations. Design approval UI for seconds-per-decision with evidence attached, not essay reading. Track approval latency like any other SLO so product teams feel friction before customers churn.
What should users see when an agent fails mid-task?
Honest partial status, preserved inputs, and a clear next step—retry, human help, or manual completion path. Never claim success when tools are pending. Recovery copy should match support macros and localized banners so trust does not depend on which channel the user uses.

Sources

Related service

Ship AI features to production: tooling, retrieval, evaluation, safety boundaries, and operable backends.

View hire details


Published on December 9, 2025 by Berktug Berke Ates.