This ERC defines IAgentWorkflow: a standard on-chain interface for artificial intelligence (AI) agent task execution. It pursues three goals: a universal execution interface so agents can be developed independently of any application framework and compete across protocols; an on-chain orchestration framework so reliability mechanisms such as Byzantine fault-tolerant (BFT) voting, competitive selection, and commit-reveal are enforceable by contract rather than assumed from off-chain coordination — and deterministic pipelines where every step is pre-declared and auditable; and a full execution evidence chain so trust in results derives from structure — any party can traverse the on-chain AgentTask / AgentReply chain from run() to result() and verify every step independently, without trusting any individual agent.
Motivation
1. A universal execution interface frees agents from application frameworks.
The emerging on-chain AI agent ecosystem has produced complementary standards — agent identity (ERC-8004), agentic commerce (ERC-8183), tool registry (ERC-8257) — each well-scoped to its layer. But every protocol that needs to invoke an agent defines its own invocation format in isolation: ERC-8183 encodes tasks as a free-form description string; ERC-8004 delegates execution entirely to off-chain conventions. Without a shared interface, agent builders must re-implement adapters for each protocol, agents are locked to the frameworks that built them, and competition between agents across protocols is structurally impossible.
2. An on-chain orchestration framework enables reliable distributed execution.
Off-chain agent orchestration frameworks coordinate agents for efficiency, but their results are only as trustworthy as the agents themselves. On-chain, the execution structure can itself be the trust mechanism: when workflow logic lives in a contract, every stage transition is gate-enforced and no agent can bypass or reorder it. Patterns such as commit-reveal, BFT voting, and competitive selection are reliability mechanisms — they only compose correctly when the workflow is enforced by a contract rather than coordinated off-chain. For deterministic pipelines (audit trail, compliance, regulatory evidence), a static finite state machine (FSM) with pre-declared transitions provides the same gate-enforced integrity with full omission detectability.
3. Trust through structure: on-chain evidence chain makes results independently verifiable.
Even when agents are permissionless and unknown, the execution itself can be trusted if every step is anchored on-chain. The bidirectional prevReplyHashes / prevTaskHashes chain means that any party — not just the caller — can traverse from result().finalTaskHash back to run() and verify every transition was gate-approved and every reply was submitted by the claimed replier. Trust in the result does not require trusting any individual agent; it requires only trusting the workflow contract’s gate logic.
This ERC fills the execution primitive in the agent base layer. It defines IAgentWorkflow to:
Provide a universal agent execution interface — agents implement once and run across any conformant protocol, decoupled from application frameworks and free to compete on quality.
Define an on-chain orchestration and coordination framework — the workflow contract is a finite state machine that enforces every stage transition, making distributed reliability patterns (BFT, competitive selection, commit-reveal) structurally sound rather than off-chain assumptions.
Establish a full on-chain execution evidence chain — every task and reply is anchored and linked; results are verifiable by anyone from run() to result() without trusting any individual agent.
Primitive
Blockchain Analogue
ERC
Identity
Address
ERC-8004
Execution
Smart Contract
This ERC
Verify
Consensus
AI Inference Proof Verification
Anchor
On-chain State
TruthAnchor
Settlement
Value Transfer
Agent Escrow & Settlement
Prove
Logs / Audit Trail
Observation Commitment Protocol (OCP) + What You Read Is What You Execute (WYRIWE)
Specification
The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “NOT RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119 and RFC 8174.
Data Envelopes
Four types carry all information between the contract, agents, and external callers.
RunStatus
enumRunStatus{Pending,Success,Failed,NotFound}
Pending — run is active; no result yet
Success — FSM reached a terminal stage with all gates satisfied; finalTaskHash is non-zero
Failed — run aborted; finalTaskHash is bytes32(0)
NotFound — no run exists for the queried identifier
AgentTask — task dispatched by the contract
structAgentTask{uint8stage;// FSM stage (developer-defined enum cast to uint8)
uint256taskSeq;// Per-run monotonic counter; starts at 0
bytes32inputHash;// keccak256(input)
bytesinput;// Input plaintext; MAY be empty if conveyed off-chain
uint256timestamp;// block.timestamp at emission
uint256expiresAt;// Unix timestamp after which this task expires; zero means no expiry
bytes32[]prevReplyHashes;// Replies that triggered this task; empty for the initial task
bytes32workflowRunId;// Run identifier
}
The contract stores one AgentTask per taskHash and MUST compute taskHash as follows (input plaintext is excluded):
The initial task takes its expiresAt from run(). For each task dispatched on a stage transition or retry, the workflow sets expiresAt according to its business rules at dispatch.
prevReplyHashes records which AgentReply submissions triggered this task via gate logic; it is empty for the initial task emitted by run(). When prevReplyHashes is empty, the inner term keccak256(abi.encodePacked(prevReplyHashes)) MUST resolve to keccak256(abi.encodePacked([])) i.e. keccak256("") = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470. Implementations MUST NOT special-case the empty array to bytes32(0). This pins the initial taskHash so two independent implementations cannot diverge at the entry point of the evidence chain.
AgentReply — reply submitted by an agent
structAgentReply{bytes32operationId;// Opaque logical operation identifier; stable across retries
bytes32outputHash;// keccak256(output)
bytesoutput;// Reply output plaintext; MAY be empty
uint256timestamp;// Off-chain execution time (Unix)
addressreplier;// Direct caller address; MUST equal msg.sender when submitted
bytes32[]prevTaskHashes;// Tasks this reply responds to; MUST be non-empty
bytes32workflowRunId;// Run identifier
}
The contract stores one AgentReply per replyHash and MUST compute replyHash as follows:
operationId identifies the logical operation that produced the reply. It MUST be non-zero, opaque, assigned by the logical operation’s originator before the first submission, and carried unchanged by the replier across retries. A uniformly random bytes32 value is RECOMMENDED. An intentional new operation over the same input or output MUST use a new operationId. Because operationId is part of replyHash, distinct logical replies remain distinguishable even when every other hashed field is identical — for example, multiple replies from the same replier to the same tasks, with the same output, submitted within the same one-second timestamp resolution. Implementations MUST NOT derive operationId from reply content: content equality does not imply operation identity.
For idempotency, the contract MUST scope an operationId to the run and replier. The following formula is RECOMMENDED; an equivalent nested mapping is conformant:
The contract MUST also bind the operation to stable reply content. Because a reconstructed retry may carry a later timestamp, the operation digest excludes timestamp:
The first accepted submission binds operationKey immutably to (replyDigest, replyHash). prevTaskHashes records which tasks this reply responds to, completing the bidirectional evidence chain (see Evidence Chain).
IAgentWorkflow — Core Interface
A conformant workflow contract MUST implement the following interface:
pragmasolidity^0.8.0;enumRunStatus{Pending,Success,Failed,NotFound}structAgentTask{uint8stage;uint256taskSeq;bytes32inputHash;bytesinput;// MAY be empty
uint256timestamp;// block.timestamp at emission
uint256expiresAt;bytes32[]prevReplyHashes;// empty for the initial task
bytes32workflowRunId;}structAgentReply{bytes32operationId;// MUST be non-zero and stable across retries
bytes32outputHash;bytesoutput;// MAY be empty
uint256timestamp;// Off-chain execution time (Unix)
addressreplier;// MUST equal msg.sender when submitted
bytes32[]prevTaskHashes;// MUST be non-empty
bytes32workflowRunId;}interfaceIAgentWorkflow{// ── Invocation ───────────────────────────────────────────────────────────
/// @notice Start a new workflow run.
/// @param inputHash keccak256 of the input
/// @param input Input plaintext; MAY be empty if conveyed off-chain
/// @param expiresAt Unix timestamp after which the initial task expires
/// @return workflowRunId Contract-generated unique run identifier
functionrun(bytes32inputHash,bytescalldatainput,uint256expiresAt)externalreturns(bytes32workflowRunId);/// @notice Query the result of a run.
/// @dev For an unknown workflowRunId, result() MUST return (NotFound, bytes32(0), 0) without reverting.
/// @dev For an active run with a timeout policy, it is RECOMMENDED that result() use the current
/// block.timestamp to determine the status returned under that policy. A task deadline
/// has passed when expiresAt is non-zero and block.timestamp > expiresAt.
/// @return status Pending | Success | Failed | NotFound
/// @return finalTaskHash taskHash of the terminal AgentTask; bytes32(0) if not Success
/// @return completedAt block.timestamp at completion; 0 if not Success
functionresult(bytes32workflowRunId)externalviewreturns(RunStatusstatus,bytes32finalTaskHash,uint256completedAt);// ── Query ────────────────────────────────────────────────────────────────
/// @notice Returns the stored AgentTask and its proven status.
/// @dev MUST revert if taskHash is unknown.
/// proven=true iff prevReplyHashes is empty OR all prevReplyHashes are proven.
functiongetAgentTask(bytes32taskHash)externalviewreturns(AgentTaskmemorytask,boolproven);/// @notice Returns the stored AgentReply and its verification status.
/// @dev MUST revert if replyHash is unknown.
/// @dev Until a verifier succeeds, verifier and verificationDigest MUST be
/// address(0) and bytes32(0), including for a proven, proof-exempt reply.
/// On success, verifier MUST identify the verifier contract called.
/// verificationDigest MUST equal the returned digest, or bytes32(0)
/// if the verifier returns no digest.
functiongetAgentReply(bytes32replyHash)externalviewreturns(AgentReplymemoryreply,addressverifier,boolproven,bytes32verificationDigest);/// @notice Resolve a logical reply operation to its canonical replyHash.
/// @return replyHash The first anchored replyHash; bytes32(0) if unknown
functiongetReplyHashByOperation(bytes32workflowRunId,addressreplier,bytes32operationId)externalviewreturns(bytes32replyHash);// ── Agent Callbacks ──────────────────────────────────────────────────────
/// @notice Agent submits a reply to a dispatched task.
/// @param reply See AgentReply; reply.replier MUST equal msg.sender
/// @return replyHash The canonical replyHash for this logical operation
functiononAgentReply(AgentReplycalldatareply)externalreturns(bytes32replyHash);/// @notice Submit proof data for the listed anchored replies.
/// @param replyHashes Each MUST have been anchored by onAgentReply
/// @param proof Proof bytes covering all listed replies; encoding is verifier-specific
functiononAgentProve(bytes32[]calldatareplyHashes,bytescalldataproof)external;// ── Events ───────────────────────────────────────────────────────────────
/// @notice Emitted when a new task is dispatched. Full details via getAgentTask(taskHash).
eventNewAgentTask(bytes32indexedworkflowRunId,uint8indexedstage,bytes32indexedtaskHash);/// @notice Emitted when a reply is anchored, before gate evaluation.
/// A consumer can observe that a reply was submitted and
/// retrieve it via getAgentReply(replyHash), regardless of whether the gate
/// later accepts or silently discards it.
eventAgentReplyAnchored(bytes32indexedworkflowRunId,bytes32indexedreplyHash,addressindexedreplier);/// @notice Emitted when a run reaches a terminal state.
eventWorkflowCompleted(bytes32indexedworkflowRunId,RunStatusstatus,bytes32finalTaskHash,uint256timestamp);}
getReplyHashByOperation MUST use the same (workflowRunId, replier, operationId) scope as onAgentReply. It MUST return the canonical replyHash for an accepted operation and bytes32(0) when no binding exists.
Execution Model
A conformant IAgentWorkflow contract is a finite state machine (FSM). The developer defines:
A stage enum — the complete set of states the workflow can be in. Stages MAY include loops; the set is finite and fixed at deploy time.
Gate logic — conditions for stage transition, evaluated after onAgentReply (async mode) or onAgentProve (sync mode).
Proof policy — which stages require proof, whether proof is sync or async, and which proof verifier to invoke (IProofVerifier or IAgentVerifier from AI Inference Proof Verification). MAY vary per stage.
FSM topology — whether the workflow graph is static (all transitions hardcoded at deploy time) or dynamic (path emerges at runtime from gate logic and replies). See Static vs Dynamic FSM.
The contract drives all stage transitions. Agents react to emitted tasks; they do not control sequencing.
A minimal workflow accepts a reply in a single terminal stage and completes when its proof passes the gate.
Run lifecycle:
run(inputHash, input, expiresAt)
│ generates workflowRunId; emits NewAgentTask(stage=initial)
▼
Agent observes NewAgentTask; calls getAgentTask(taskHash) for details
│ calls onAgentReply(...)
▼
Contract validates operationId and reply; resolves or stores canonical replyHash
│ async: gate evaluates immediately after onAgentReply
│ sync: gate evaluates only after onAgentProve succeeds
│ (gate modes defined in Gate Logic and Stage Transition)
│
├── gate passes → FSM transitions → emit NewAgentTask(next stage)
└── gate fails → retry / abort / silent (implementation-defined)
▼
... stages repeat ...
▼
WorkflowCompleted(workflowRunId, Success | Failed, ...)
Whenever the workflow contract emits NewAgentTask, it MUST record block.timestamp in the emitted task’s timestamp field using its own dispatch logic. Agents MUST NOT be able to set or overwrite this value.
A single stage MAY emit multiple NewAgentTask events in the same block (e.g. parallel dispatch). taskSeq ensures each is uniquely identified.
run() — Run Initiation
For each successful call to run(), the contract MUST generate a deterministic workflowRunId that it has never assigned to another run. A recommended formula is:
where runNonce is a counter the workflow contract maintains for msg.sender and increments once per run. When a proxy calls run(), the counter belongs to the proxy address. The contract MUST initialise the FSM to its initial stage and emit at least one NewAgentTask before returning.
The contract SHOULD verify keccak256(input) == inputHash when input is non-empty. Callers with sensitive inputs SHOULD pass input = "" and deliver plaintext to agents through a confidential channel; inputHash still commits to the content.
onAgentReply — Reply Submission
When an agent calls onAgentReply, the contract MUST enforce the following checks in order:
1. Replier and operation identity
The contract MUST verify reply.replier == msg.sender. This binds the stored struct to the actual submitting address, preventing fronting. The contract MUST reject operationId == bytes32(0).
The contract MUST compute operationKey and replyDigest according to Data Envelopes, then look up the operation before evaluating expiry, current-stage gate eligibility, or any externally visible effect.
If operationKey is already bound:
If the stored replyDigest equals the submitted replyDigest, the call is a logical retry. The contract MUST return the stored canonical replyHash without storing another reply, emitting AgentReplyAnchored, evaluating gate logic, invoking downstream hooks, or applying a second charge or settlement effect. The first accepted reply, including its original timestamp, remains canonical.
If the digests differ, the contract MUST revert and MUST NOT overwrite the existing binding. Reusing an operationId for different output or task context is an operation-ID conflict, not a retry.
This lookup MUST be atomic with first acceptance. Concurrent calls for the same operationKey MUST result in exactly one accepted reply; all matching retries resolve to its canonical replyHash.
2. prevTaskHashes validity for a new operation
For every h in reply.prevTaskHashes, getAgentTask(h) MUST return a valid record with task.workflowRunId == reply.workflowRunId. The contract MUST reject replies referencing unknown or foreign task hashes.
3. Run and task eligibility for a new operation
The run MUST be Pending. Every referenced task MUST still be eligible to receive a new reply under the workflow’s current FSM stage and gate policy. The contract MUST reject a new operation that references a completed, superseded, consumed, or otherwise ineligible task. This check does not apply to a matching retry resolved under step 1 because that retry creates no new reply or state transition.
4. Timestamp and expiry constraints for a new operation
For a referenced task hash h, task[h].timestamp denotes the stored task’s dispatch timestamp. The submitted timestamp MUST satisfy:
max(task[h].timestamp for h in reply.prevTaskHashes) < reply.timestamp ≤ block.timestamp
Agents observe the task dispatch event before submitting a reply. All transactions in a block share its timestamp, so the first opportunity to satisfy the strict lower bound is a later block than the one that emitted the last referenced task. The upper bound prevents future-dated claims. The contract records this timestamp at dispatch.
The contract SHOULD also verify that block.timestamp ≤ task.expiresAt for all tasks in reply.prevTaskHashes (when expiresAt != 0). New replies submitted after a task has expired SHOULD be rejected. A matching retry of an operation accepted before expiry returns its canonical replyHash under step 1.
5. Compute, bind, and store replyHash
After all checks pass, the contract MUST compute replyHash (formula in Data Envelopes). Before emitting events, evaluating gate logic, or calling external contracts, it MUST immutably bind operationKey to (replyDigest, replyHash), store the full AgentReply struct keyed by replyHash, and record block.timestamp as its anchor time. It MUST then emit AgentReplyAnchored(workflowRunId, replyHash, msg.sender) before evaluating the gate.
This event records receipt of every anchored reply, including replies the gate subsequently discards. A consumer can retrieve the full reply via getAgentReply(replyHash).
6. Gate evaluation (async mode)
If the current stage is async, the contract MUST immediately evaluate gate logic and, if it passes, transition the FSM and emit the next NewAgentTask. After completing the applicable steps, the call MUST return replyHash.
onAgentProve — Proof Submission
onAgentProve accepts proof data and a list of anchored reply hashes. An agent or any third party MAY submit the data. The workflow calls the verifier for the reply being checked.
1. Retrieve stored replies
The contract MUST revert if replyHashes is empty or if any entry is unknown.
The contract MUST skip each reply already marked proven, preserving its verification record without invoking the verifier or evaluating the gate for that reply. If all listed replies are already proven, the call MUST succeed without side effects, including after the run has terminated. Otherwise, the terminal-state rules apply to any remaining unproven replies.
For each remaining replyHash, the contract MUST retrieve the stored AgentReply and derive the canonical inputHash from on-chain task data — never from caller-supplied data, preventing hash substitution attacks.
When reply.prevTaskHashes has more than one entry, prevTaskHashes[0] MUST be the primary task (i.e., the task carrying the input to be proven). If multiple tasks carry different inputs, the proof statement covers prevTaskHashes[0].inputHash; implementations that need to bind multiple inputs MUST encode them into a single composite inputHash at task emission time.
Before calling the verifier for a reply, the contract MUST check that every task referenced by its prevTaskHashes is proven. If any is unproven, the call MUST revert. This prerequisite applies in both sync and async modes.
2. Call the proof verifier
Each verifier call checks one reply using its input and output hashes. An implementation can support batch verification as an extension. The batch interface and proof encoding are outside the scope of this ERC.
The developer chooses one of two conformant options; the choice is implementation-defined and MAY vary per stage.
Option A — IAgentVerifier (outer, identity-bound):
Produces a verificationDigest audit anchor. Suitable when proof verification should bind to replier identity.
Pure cryptographic validity; no identity binding. Suitable for zero-knowledge (ZK), trusted execution environment (TEE), or signature-based proofs where the replier address is not part of the proof statement.
boolvalid=IProofVerifier(verifier).verify(inputHash,reply.outputHash,metadata,// deployment-time config: circuit key, enclave hash, etc.
proof);
3. Update proven state and evaluate gate (sync mode)
If verification fails, the contract MUST preserve the proven status, verifier address, and verification digest of each submitted reply. A failed attempt MUST NOT prevent a later proof submission for the same reply.
After a successful verification, the contract MUST mark the replyHash as proven, MUST propagate proven status to downstream tasks (see Evidence Chain), and MUST NOT call the verifier again for the same replyHash. If the proven reply belongs to the current sync stage, the contract MUST then evaluate its gate logic.
Gate Logic and Stage Transition
Gate logic is implementation-defined. This ERC defines when it is evaluated, not what it checks.
Async mode — gate evaluates immediately after onAgentReply:
The silent failure mode is most useful in permissionless workflows: submissions that fail the gate are discarded without disrupting the run; the stage stays open for further submissions. The AgentReplyAnchored event makes silent failures observable — it fires before gate evaluation, so a consumer can see that a reply was submitted even when the gate later discards it. For example, a workflow using a zero-knowledge proof can use a nullifier, a one-time identifier bound by the proof to a private authorization. If the gate evaluates and rejects the reply, the workflow can record the nullifier as spent so the same authorization cannot be reused. The anchoring event records receipt of the reply regardless of that decision. In a static FSM, the gate can still be competitive (multiple replies, one winner), but the transition target is predetermined — the gate selects which reply wins, not which stage is next. Static FSM implementations MAY use revert or explicit-failure modes since the FSM path is not affected by a gate failure; a failed reply simply does not advance the run at the current stage.
Terminal stage. The gate whose pass causes WorkflowCompleted(Success) to be emitted is the final gate; it MUST be sync. When the final sync gate passes, the contract MUST:
Create and store a final AgentTask representing the completion state: stage SHOULD be a terminal sentinel (e.g., type(uint8).max), taskSeq is the next monotonic counter, inputHash = bytes32(0), prevReplyHashes contains all terminal reply hashes that satisfied the gate, both timestamp and expiresAt are set to the completion block’s block.timestamp, and workflowRunId is the current run. The contract computes finalTaskHash via the standard taskHash formula (see Data Envelopes). This final task anchors the completion state in the evidence chain — the chain now uniformly ends with a Task node, consistent with every other stage transition.
Emit WorkflowCompleted(workflowRunId, Success, finalTaskHash, block.timestamp). No NewAgentTask is emitted for the terminal task; the WorkflowCompleted event alone serves as the on-chain anchor.
Persist block.timestamp as completedAt in storage so that result() can return it as a view function.
Reject any subsequent new onAgentReply or onAgentProve for this workflowRunId. A proof submission containing only already-proven replies from the run remains an idempotent retry as defined under Proof Submission. A matching retry of an already accepted operationKey MUST remain resolvable to its canonical replyHash and MUST have no effect.
A run MAY terminate with Failed at any stage by emitting WorkflowCompleted(workflowRunId, Failed, bytes32(0), block.timestamp). The same terminal callback rules, including both idempotent retry cases in step 4, apply after failure.
Evidence Chain
Every operation in a conformant workflow is stored on-chain and linked into a bidirectional chain verifiable by any party without trusting the contract’s internal state.
Structure. The chain alternates between AgentTask and AgentReply nodes:
The chain always ends with a Task node — the final AgentTask created at terminal gate pass. The prevReplyHashes / prevTaskHashes link fields (defined in Data Envelopes) form a tamper-evident record traversable from result().finalTaskHash back to the initial task.
Proven state. A true proven value means that the workflow’s proof policy has been satisfied along the node’s dependency chain. The policy for the stage that produced a reply determines whether that reply requires a proof. An async stage can require a proof even though its gate can advance before the proof arrives.
Node
proven = true when
AgentTask
prevReplyHashes is empty (initial task), or all entries in prevReplyHashes are proven
AgentReply
Every task in prevTaskHashes is proven, and either the stage explicitly exempts the reply from proof or onAgentProve has succeeded for it
The contract MUST apply these rules when storing a task or reply and propagate changes through existing dependants. An exempt reply becomes proven as soon as all its preceding tasks are proven, including when the last such task becomes proven after the reply was stored. This requires no proof submission for the exempt reply. A reply that requires proof remains unproven until its own verification succeeds. Caching the resulting task status makes the sync gate check O(1):
(,boolproven)=getAgentTask(prevTaskHash);require(proven,"upstream chain not fully proven");
Verification paths.
Rely on recorded status: An observer verifying a reply can limit its checks to that reply if it trusts the workflow’s recorded status for its preceding tasks. A task’s proven flag covers its dependency chain under the workflow’s proof policy, including any explicit exemptions.
Independently verify dependencies: From a reply, follow prevTaskHashes to its preceding tasks. From a task, follow prevReplyHashes to the replies that produced it. An observer can stop at a status it trusts or trace every branch back to the initial task, checking the linked records and the evidence required by each stage. For a completed run, traversal starts at result().finalTaskHash.
result().finalTaskHash is the entry point for external verification. A downstream contract MAY check finalTaskHash != bytes32(0) as a sufficient condition that all gates on the execution path were satisfied — provided the workflow contract is correctly implemented.
Static vs Dynamic FSM
This ERC does not mandate a specific FSM topology. The developer chooses whether the workflow is static (all stages and transitions are hardcoded at deploy time) or dynamic (the path emerges at runtime from gate logic and agent replies). Both are conformant; the choice belongs to the use case.
Dynamic FSM. The contract enumerates all possible stages, but the actual execution path is determined at runtime — gate logic selects which reply advances the FSM, and which stage is emitted next may depend on the content of the winning reply. This is the natural shape for permissionless, competitive, or BFT workflows:
Competitive selection (multiple agents bid; gate picks the lowest bid and silently discards the rest).
Commit-reveal rounds (stages are fixed but which agents participate and which commitment wins is unknown until the reveal gate fires).
BFT voting (quorum threshold reached → transition; the set of voters is not known in advance).
The trade-off: a dynamic FSM cannot guarantee omission detectability at the spec level. The path is not pre-declared, so an operator who steers the FSM away from a node it dislikes leaves no NewAgentTask for that node — and from outside, “the FSM didn’t go there” and “the FSM shouldn’t have gone there” are the same observation. Omission detectability in a dynamic FSM requires additional machinery: a pre-committed expected node-graph (declared before execution), an event for every stored reply before gate selection, and timeout or expected-transition semantics, so that a missing dispatched task is a visible gap against a stated expectation.
Static FSM. All stages, transitions, and the complete execution graph are hardcoded in the contract. The operator cannot route around a node — every declared stage MUST be dispatched via NewAgentTask before the next transition can fire. This closes the omission gap at the implementation level: the contract itself is the pre-declared path, and a suppressed step is a contract rule violation, not an unobservable routing choice.
Static FSM is appropriate for:
Auditable workflows where every step must be provably executed (compliance, regulatory evidence, multi-party settlement).
Deterministic pipelines where the topology is known in advance (input sanitization → inference → verification → settlement).
Scenarios where the beneficiary of the claim is not the operator — the static contract guarantees that a third-party skeptic can enumerate every owed step without trusting the operator’s word.
The static FSM still requires liveness consideration: ruling out routing-around a node is not the same as forcing the next transition to be called. Without timeout or expected-transition semantics, “the step was suppressed” and “the workflow has not advanced yet” remain the same observation from outside. Implementations SHOULD declare expected-transition windows or timeout semantics where omission detectability is load-bearing.
Property
Dynamic FSM
Static FSM
Path determined
At runtime (gate logic + replies)
At deploy time (hardcoded)
Omission detectability
Requires additional machinery
Closed at implementation level
Best for
Competitive, BFT, open participation
Audit, compliance, deterministic pipelines
NewAgentTask coverage
Only nodes the gate actually dispatches
Every declared node must be dispatched
Liveness
Same as static
Same as dynamic
Both shapes use the same IAgentWorkflow interface. The ERC standardises the dispatch, anchoring, and verification surface; the FSM topology is an implementation decision.
Rationale
Contract-as-Workflow
A commitment to an off-chain workflow definition alone does not let the contract enforce the workflow. The stage enum identifies valid states, gate logic enforces transitions, and contract storage tracks the replies anchored at each stage. Different workflows can implement the same interface. IAgentVerifier and IProofVerifier handle proof verification. The workflow contract maintains execution state.
FSM Model
A directed acyclic graph (DAG) of replies expresses data dependencies. Without explicit stage information, the contract cannot distinguish a new coordination round from a competing bid or a consensus reveal without reading an off-chain document.
The FSM model adds a stage dimension. Each NewAgentTask carries a stage value that unambiguously identifies the current phase. Agents can determine what is expected of them from the event alone; the contract enforces valid transitions. Patterns like commit-reveal and BFT voting become expressible on-chain without off-chain coordination: the contract emits stage=Commit tasks, agents commit, the gate transitions to stage=Reveal, and no agent needs to infer the phase from context.
Open Task Dispatch
NewAgentTask carries no agentId. This enables permissionless participation: any conformant agent may monitor the event stream and respond to tasks matching its capabilities, supporting competitive selection, BFT voting, and open agent markets. Permissioned workflows restrict participation inside onAgentReply by checking msg.sender; the interface does not change. taskSeq ensures each emitted task is uniquely identified even when multiple tasks are dispatched in the same block and stage.
Evidence Chain Design
The symmetric prevReplyHashes / prevTaskHashes linking design makes the entire execution history verifiable from result().finalTaskHash alone. Rather than trusting the contract’s proven cache, any observer can traverse the alternating task-reply chain back to the initial task and independently verify every anchored hash. The cached proven flag is an optimisation — the O(1) sync gate check — not a source of truth. The incremental propagation rule (a task becomes proven when all its prevReplyHashes are proven) ensures the chain is self-consistent: a proven task implies a proven upstream chain back to run().
Logical Reply Idempotency
Transaction and account nonces prevent replay of the same signed envelope, but they cannot identify two separately signed calls as retries of the same logical operation. operationId supplies that missing caller intent. It is scoped by workflowRunId and replier, so independent agents and runs may safely reuse the same opaque value.
Content hashes cannot replace operationId: submitting the same artifact twice may intentionally request two independent reviews. Conversely, a reconstructed retry may change the off-chain timestamp while preserving the same output and task context. The immutable operationKey → (replyDigest, replyHash) binding therefore preserves the first accepted reply as canonical without collapsing intentional operations that use different IDs.
This mechanism provides transport-level idempotency only. Whether two distinct operations describe the same real-world event is workflow-specific and remains the responsibility of gate or application logic.
Sync and Async Gate Modes
Two gate modes address two fundamentally different verification shapes:
Post-hoc attestation (async): the agent executes, submits a result via onAgentReply, and proof is submitted afterward. The FSM advances before verification completes. Appropriate for most use cases — the proof provides an auditable record; fraud is detectable after the fact.
Pre-action gating (sync): the verifier must approve before the FSM emits the next task. Required when acting on an incorrect or unauthorized input is irreversible (e.g., a task that triggers an on-chain token transfer). The sync-mode WYRIWE stage exemplifies this: the FSM will not emit the inference task until the input sanitization proof passes, so the gateway cannot substitute an unauthorized transform after seeing the input.
Both shapes are expressible through the same interface. The choice belongs to the workflow contract’s proof policy, not to the dispatch interface.
FSM Anchor and OCP Temporal Anchor
The assignment of block.timestamp to AgentTask.timestamp that occurs at NewAgentTask emission and the OCP record() call are complementary, not competing:
FSM anchor is per-task: it records the block timestamp at which a specific task was dispatched. It is written automatically by the workflow contract and cannot be influenced by the caller.
OCP anchor is per-input: it commits the input content to an external log, with an independently checkable timestamp, before execution begins.
They compose naturally: OCP anchors the input before the task is dispatched; the FSM anchor records when the task was emitted. A verifier can check both independently — that the input was committed before the task existed (ocp.timestamp < task.timestamp) and that all subsequent replies carry reply.timestamp > task.timestamp. Neither anchor subsumes the other.
Backwards Compatibility
This ERC introduces new interfaces with no conflicts with existing ERCs. Agent identity, agentic commerce, proof verification, on-chain anchoring, OCP, WYRIWE, and settlement layers integrate as optional dependencies; none require modification.
Reference Implementation
A full reference implementation will be provided in a separate repository and linked here once available.
Call Sequences
In all diagrams, T0, T1, … denote taskHash values from NewAgentTask events; R0, R1, … denote canonical replyHash values returned by the contract in onAgentReply. Each illustrated new reply uses a fresh non-zero operationId unless explicitly labelled as a retry.
Scenario 0 — Single-Stage (Baseline)
The simplest conforming workflow: one task, one reply, one proof.
The input a caller commits to on-chain (inputHash) and the input a model actually processes may differ due to sanitization transforms, template injection, or retrieval-augmented generation (RAG) context assembly. The taskHash and replyHash chains make this gap provable through three composable patterns:
WYRIWE attestation: an agent submits a reply whose outputHash equals the sanitized input hash. The FSM transitions to the inference stage, emitting a NewAgentTask with inputHash = sanitizedHash. All subsequent inference replies reference this task in prevTaskHashes, proving on-chain that inference happened after the WYRIWE attestation and used the attested input.
OCP temporal anchoring: the input commitment is submitted as a reply in a dedicated stage; the FSM only advances after the OCP record() call is confirmed, proving on-chain that the input was anchored before execution began.
Pre-action gate: the input provenance stage is declared sync mode; the verifier must approve before the FSM emits the inference task.
A contract is submitted for audit across three independent dimensions: Gas, Security, and Logic. The workflow hardcodes three stages — Audit → Qualify → Settle — with no way to skip any of them. The Audit stage dispatches all three tasks in parallel; the gate only advances when every dimension has replied.
run(inputHash=H_code, input, expiresAt)
│ emit NewAgentTask(stage=Audit, taskHash=T_gas)
│ emit NewAgentTask(stage=Audit, taskHash=T_sec)
│ emit NewAgentTask(stage=Audit, taskHash=T_logic)
│ // Parallel dispatch: same stage, same block, three agents
├──────────────────┬──────────────────┐
▼ ▼ ▼
onAgentReply(G, [T_gas]) onAgentReply(S, [T_sec]) onAgentReply(L, [T_logic])
replyHash=R_gas replyHash=R_sec replyHash=R_logic
[Gate: all three replies received → FSM transitions to Qualify (hardcoded)]
│ emit NewAgentTask(stage=Qualify, taskHash=T_qual)
│ // getAgentTask(T_qual) → {prevReplyHashes=[R_gas,R_sec,R_logic], ...}
▼
onAgentReply(Q, {prevTaskHashes:[T_qual], outputHash:qualHash, ...})
│ Qualification agent checks auditor credentials and proof validity.
│ contract stores; replyHash=R_qual
│ stage=Qualify is sync → waits for proof
▼
Prove R_gas, R_sec and R_logic so T_qual is proven.
onAgentProve([R_qual], proof) ✓ ← sync gate passes
│ FSM transitions to Settle (hardcoded, terminal)
│ emit NewAgentTask(stage=Settle, taskHash=T_settle)
▼
onAgentReply(Set, {prevTaskHashes:[T_settle], outputHash:settleHash, ...})
│ contract stores; replyHash=R_settle
▼
onAgentProve([R_settle], proof) ✓
│ create & store final AgentTask Tf (prevReplyHashes=[R_settle])
│ emit WorkflowCompleted(Success, finalTaskHash=Tf)
The three-stage graph (Audit → Qualify → Settle) is hardcoded at deploy time. Each audit dimension is pre-declared; the operator cannot skip the security audit by routing the FSM around it — an omitted dimension leaves the gate unsatisfied and the run pending. The parallelism is structural — the three audits are independent — rather than coordinated off-chain. A skeptic can enumerate every owed step from the contract source alone: 3 audit tasks + 1 qualification + 1 settlement = 5 guaranteed dispatch points.
Security Considerations
Input integrity and confidentiality. Checking the hash of the supplied input detects a mismatch with inputHash. Plaintext included in transaction data or an event is public even when the workflow also records its hash.
Gate logic is implementation-defined. This ERC standardises the interface, not the gate logic. A malicious or negligent workflow contract may define gates that always pass or emit WorkflowCompleted(Success) without verification. Before relying on a successful result, an application can review the workflow contract to see which conditions it actually checks. A non-zero finalTaskHash in result() proves gate-level enforcement only if the contract is correctly implemented.
Executor identity is msg.sender.replyHash commits to reply.replier which is validated against msg.sender. No external registry is required by the base protocol. Permissioned implementations can check msg.sender against an allowlist or integrate ERC-8004 inside gate logic.
Task dispatch time. Reply validation uses the recorded dispatch time as a lower bound. If an agent could backdate it, a reply timestamped before dispatch could pass the ordering check.
Replay attacks and logical retries.workflowRunId is contract-generated and unique per run() call. taskHash commits to (stage, taskSeq, inputHash, timestamp, expiresAt, prevReplyHashes, workflowRunId); replyHash commits to (operationId, outputHash, timestamp, replier, prevTaskHashes, workflowRunId). A transaction or account nonce prevents replay of the same signed envelope, while operationId identifies separately signed submissions that represent the same logical reply. Returning the original receipt for a matching retry prevents duplicate events and repeated stage transitions. Rejecting conflicting content under the same operation key protects the original reply.
Repeated submissions of the same record. An agent can submit the same external record under different operationId values. A workflow that accepts each record only once can check a stable identifier for that record in its gate or application logic.
Permissionless spam resistance. In permissionless workflows, any agent may submit replies. In a dynamic FSM, silently discarding a reply that fails the gate keeps the stage open for other agents. In a static FSM, the next stage is predetermined, so implementations can also signal failure explicitly or revert. Sybil resistance and quorum thresholds are the workflow contract’s responsibility.
Timeouts. A read-only query can report a timeout without changing storage or emitting an event. A workflow that allows another task or retry can still be pending after one task expires. Any retry or recorded transition requires a transaction. At dispatch, checking a non-zero deadline against the current block time helps avoid issuing an already expired task.
Reentrancy. Recording an accepted reply before calling downstream hooks prevents a callback from processing the same submission twice. During proof submission, the workflow identifies the replies to verify before calling the external verifier. A reentrancy guard or equivalent protection can prevent a nested call from processing those replies while verification is in progress. The workflow marks the replies as proven only after verification succeeds.
Replies arriving during a stage transition. Two replies for the same stage can arrive in the same block. If the first advances the workflow, the scoped operationId lets the contract recognize a matching retry and return its original replyHash without applying its effects again. A new reply for the closed stage can be rejected or discarded according to workflow policy. Recording the stage transition before dispatching the next task helps prevent late replies from advancing the workflow twice.
Empty reply list. An empty list skips all reply checks and could allow the workflow to advance without verifying any replies.
Proof resubmission. Anyone can submit a proof for an anchored reply. Keeping the reply eligible after a failed attempt lets another caller submit a valid proof later.
Forwarded replies. When a proxy calls onAgentReply on behalf of an agent, the workflow sees the proxy as msg.sender. The proxy supplies its own address as reply.replier, so the recorded reply and the operation’s retry key both identify the proxy. The application determines how the proxy authenticates agents and authorizes submissions on their behalf.
Run identifier reuse. In the counter-based example, resetting a caller’s counter can cause a later run to reuse an earlier identifier. The contract controls updates to the counter. Reading its value does not affect uniqueness.