ExAgent.Continuation (ExAgent v3.0.0)

View Source

Administrative queries and host-authorized decisions for atomic records.

Stability — Stable.

Runtime pause/resume integration is separate. The host authorizes commands and owns templates, policies, credentials and effect dispatch. A Store receipt confirms a data transition.

Every mutation (decide/4, supply_result/4, recover/3, reconcile/5, reconcile_tool/4, reconcile_model/5, retry_effect/4, adopt/4 and acknowledge_history/3) returns the same admin_reply/0. Options are keyword lists with known, unique keys; an unknown, duplicate or missing required key raises ArgumentError before the record is read or the authorizer runs. An invalid reviewer value (decision, arguments, message or result) returns {:error, reason}.

The trusted authorize.(actor, operation, target) must return {:ok, actor_id}; every other return and every exception denies with {:error, :unauthorized}. operation is :approve, :edit, :deny, :cancel, :expire, :supply_result, :recover, :reconcile, :reconcile_tool, :reconcile_model, :retry_effect, :adopt or :acknowledge_history, so a policy can approve without authorizing edits. target is a map with :id, :record_id, :revision, :operation_id, :run_id, :call_id, :tool_name, :definition, :policy, :leaf, :permission_rule, :original_args, :args, :message and :result (nil when they do not apply). :record is the current record for diagnostics only; its fields are not a compatibility contract. Recovery operations also receive the exact data proposal as :payload. The :leaf of an effect comes from its saved node, and :definition and :policy without a leaf qualifier retain their existing scope. The candidate :delegation_path identifies a delegated Frame3 destination on the root record. The bounded string actor ID is the only part of the actor context that is persisted.

Summary

Types

The single return of every administrative mutation.

Exact public continuation reference, optionally including its confirmed attempt.

Delegation edges from the root to the requesting agent, in traversal order.

Versioned configuration of the agent node that owns an effect. The path starts with the workflow step or branch ID, if applicable, followed by delegation tool names in order. A root agent has an empty path. Repeated invocations on the same path have distinct run IDs. A root with saved handoff policies also carries those references.

Journal metadata for one effect.

The retained evidence binding used by acknowledge_history/3.

The result of a prune attempt for one logical ID.

The revision and intent binding used by retry_effect/4.

Operator details and versioned configuration references from one revision.

Status of a run as get/2 and list_runs/2 report it. :executing is a claimed record with an admitted intent or callback whose outcome is unconfirmed; :approved is a ready record whose current revision was written by decide/4 or supply_result/4. A Frame3 guardrail failure with settled effects is :failed. :denied is only read from 2.x records.

Operator metadata for one continuation run.

A host-supplied result for a deferred call. Successful values carry JSON or declared ExAgent.Tool.Content. On resume the result hooks run before any result schema is checked. The other statuses carry JSON-portable content.

A host-owned reference with string keys "id" and "version".

Functions

Explicitly allow later deletion/replacement of an exact terminal run's retained historical uncertainty. Requires the options of recover/3, the :evidence_hash from get/2 and allow_evidence_deletion: true. This is not an assertion that the old external effect was reconciled and does not delete data. Without it, start/prune cannot silently discard evidence retired by a retry.

Authorize a settled agent conversation to start its next turn under a specific catalogue definition. Supply the exact :record_id, :revision, :operation_id, :actor, :authorize and the target :definition reference. Stop the old owner and open a new one using the adopted binding.

Count records in a trusted Store scope or list of scopes by saved definition, policy, model references and status. The result contains the total :open and :closed records in the selected census, the count of :unclassified records whose custom Store supplies a summary without version references, and a list of :groups. Each group counts a record once per distinct reference triple and kind. Workflows include their root and the agent references in saved nodes and step bindings. Workflow roots have a nil model reference.

Persist a reviewer decision without executing IO on behalf of the agent.

Read one continuation from the trusted scoped Store, independently of its former runtime process. The run_details/0 result includes run metadata, effects, retry bindings and historical uncertainty. :definition and :policy are the origin's versioned references. :handoff_policies maps each guarded destination's slash-delimited path to its saved policy reference, including destinations the run has yet to visit.

Read one page of run_summary/0 items in a trusted scoped Store. :updated_at is in UTC milliseconds. :pending counts open approvals and deferred calls.

The review inbox of one run: undecided %ApprovalRequest{} items in approval-ID order followed by open %DeferredCall{} items in effect-ID order, all read from one revision because a batch can mix them and the run is ready only when every item is resolved. Each item carries a :call_ref for correlation and a fresh :operation_id. Keep the item server-side and pass it unchanged to decide/4 or supply_result/4, also when retrying after a lost reply. A delegated item also carries the path from the root and the definition of the agent that owns the tool.

Delete eligible terminal records from one bounded page in the trusted namespace. Returns one prune_result/0 per considered record and the next cursor. Active and :uncertain runs are retained. A cancelled run or an expired workflow with only unconfirmed model intents is eligible unless a retry's historical uncertainty is still retained. Stop admissions and writers before using this to remove a namespace, since writes are per record. before is an exclusive UTC-millisecond retention cutoff. Actor is host supplied. Each delete uses an operation ID that is free in the scanned revision. Options are :limit (1–100, default 50) and :after (the previous page's cursor), as in list_runs/2. Resume with the same cutoff and actor. An unknown option or an invalid value raises ArgumentError.

Reconcile one uncertain tool effect using a host-confirmed outcome. The host must obtain the real external result (or prove non-execution); this API performs no external IO and does not roll back or retry the tool. Model recovery requires its explicit model-state/frame evidence and is not inferred from a tool outcome. Options are those of recover/3.

Reconcile an uncertain Model request with host-confirmed effective (post-hook) response and portable model data. Evidence is %{response: response, model_data: data}. In an agent run, optional :accounting supplies already-qualified Usage maps for the exact ancestor IDs. Existing confirmed accounting is never repriced. A Composition or Flow records usage from the response on the request and its ancestors.

Look up a write's outcome through its tool's declared reconciler. An arity-two reconciler can read the result of a stored external deferral, including one left uncertain by cancellation or expiry.

Revoke an expired claim. Unconfirmed effects remain uncertain.

Retry only the exact data transition from a failed runtime checkpoint. Store configuration is supplied separately and never appears in the data-only token. A committed/replayed claim or effect-intent receipt does not authorize dispatch; inspect/recover the current record explicitly before requesting a new resume.

Authorize a new linked attempt using a binding from get/2's :retryable_effects. Supply :operation_id, :actor and :authorize. The binding supplies the record ID and revision. A persisted read reuses the original key without duplicate-risk acceptance. Verify a remote tool's read classification before authorizing it.

Record the result of a deferred call listed by pending/2, without resuming the run. Supply {:succeeded, value} with JSON or declared multimodal ExAgent.Tool.Content, or {:failed | :denied | :not_executed, content} with JSON-portable content. An inadmissible representation returns {:error, {:invalid_result, reason}}.

Types

admin_reply()

@type admin_reply() :: %{
  :status => run_status(),
  :revision => pos_integer() | nil,
  :replayed => boolean(),
  :continuation => map() | nil,
  :pending => non_neg_integer(),
  optional(:record) => map(),
  optional(:receipt) => map()
}

The single return of every administrative mutation.

:revision is the revision the committed transition wrote; a replay reports the original one. :status and :pending (open approvals plus deferrals) describe the current record. :continuation is the reference to resume only when this transition left the current revision :ready or :approved; a replay never points to a later revision. With diagnostics: true the reply also carries the current :record and the Store :receipt.

continuation_reference()

@type continuation_reference() :: %{
  :version => 1,
  :id => String.t(),
  :record_id => String.t(),
  :revision => pos_integer(),
  :run_id => String.t(),
  optional(:attempt_id) => String.t() | nil
}

Exact public continuation reference, optionally including its confirmed attempt.

delegation_path()

(candidate API)
@type delegation_path() :: [
  %{
    parent_run_id: String.t(),
    run_id: String.t(),
    call_ref: String.t(),
    call_id: String.t(),
    tool_name: String.t()
  }
]

Delegation edges from the root to the requesting agent, in traversal order.

effect_leaf()

@type effect_leaf() :: %{
  optional(:handoff_policies) => %{
    required(String.t()) => versioned_reference()
  },
  path: [String.t()],
  definition: versioned_reference(),
  policy: versioned_reference(),
  model_ref: versioned_reference(),
  output_ref: versioned_reference() | nil
}

Versioned configuration of the agent node that owns an effect. The path starts with the workflow step or branch ID, if applicable, followed by delegation tool names in order. A root agent has an empty path. Repeated invocations on the same path have distinct run IDs. A root with saved handoff policies also carries those references.

effect_summary()

@type effect_summary() :: %{
  effect_id: String.t(),
  kind: :tool | :model,
  run_id: String.t(),
  leaf: effect_leaf() | nil,
  call_id: String.t() | nil,
  call_ref: String.t() | nil,
  idempotency_key: String.t() | nil,
  tool_name: String.t() | nil,
  effect: ExAgent.Tool.effect() | nil,
  phase: :intent | :raw | :deferred | :final,
  state: :running | :uncertain | :confirmed | :retired,
  status:
    :succeeded
    | :tool_error
    | :validation_error
    | :denied
    | :failed
    | :not_executed
    | :unknown
    | :deferred
    | nil,
  args_source: :model | :reviewer | nil
}

Journal metadata for one effect.

historical_uncertainty()

@type historical_uncertainty() :: %{
  version: 1,
  count: pos_integer(),
  evidence_hash: String.t(),
  retention_acknowledged: boolean()
}

The retained evidence binding used by acknowledge_history/3.

prune_result()

@type prune_result() :: %{id: String.t(), outcome: :deleted | {:error, term()}}

The result of a prune attempt for one logical ID.

retry_binding()

@type retry_binding() :: %{
  version: 1,
  record_id: String.t(),
  revision: pos_integer(),
  run_id: String.t(),
  node_id: String.t(),
  effect_id: String.t(),
  intent_hash: String.t()
}

The revision and intent binding used by retry_effect/4.

run_details()

@type run_details() :: %{
  :id => String.t(),
  :status => run_status(),
  :revision => pos_integer(),
  :updated_at => non_neg_integer(),
  :pending => non_neg_integer(),
  :kind => :agent | :composition | :flow,
  :record_id => String.t(),
  :run_id => String.t(),
  :lease_until => non_neg_integer() | nil,
  :continuation => continuation_reference() | nil,
  :definition => versioned_reference(),
  :policy => versioned_reference(),
  :model_ref => versioned_reference() | nil,
  :adopted_binding => map() | nil,
  :handoff_policies => %{required(String.t()) => versioned_reference()},
  :effects => [effect_summary()],
  :retryable_effects => [retry_binding()],
  :historical_uncertainty => historical_uncertainty() | nil,
  optional(:record) => map(),
  optional(:timeline) => map()
}

Operator details and versioned configuration references from one revision.

run_status()

@type run_status() ::
  :ready
  | :approved
  | :claimed
  | :executing
  | :pending
  | :uncertain
  | :completed
  | :failed
  | :denied
  | :expired
  | :cancelled

Status of a run as get/2 and list_runs/2 report it. :executing is a claimed record with an admitted intent or callback whose outcome is unconfirmed; :approved is a ready record whose current revision was written by decide/4 or supply_result/4. A Frame3 guardrail failure with settled effects is :failed. :denied is only read from 2.x records.

run_summary()

@type run_summary() :: %{
  id: String.t(),
  status: run_status(),
  revision: pos_integer(),
  updated_at: non_neg_integer(),
  pending: non_neg_integer()
}

Operator metadata for one continuation run.

supplied()

@type supplied() ::
  {:succeeded | :failed | :denied | :not_executed, term()} | {:input, map()}

A host-supplied result for a deferred call. Successful values carry JSON or declared ExAgent.Tool.Content. On resume the result hooks run before any result schema is checked. The other statuses carry JSON-portable content.

versioned_reference()

@type versioned_reference() :: %{required(String.t()) => String.t()}

A host-owned reference with string keys "id" and "version".

Functions

acknowledge_history(store, id, opts)

Explicitly allow later deletion/replacement of an exact terminal run's retained historical uncertainty. Requires the options of recover/3, the :evidence_hash from get/2 and allow_evidence_deletion: true. This is not an assertion that the old external effect was reconciled and does not delete data. Without it, start/prune cannot silently discard evidence retired by a retry.

adopt(store, id, catalog, opts)

@spec adopt(ExAgent.Store.scoped(), String.t(), ExAgent.Catalog.t(), keyword()) ::
  {:ok, admin_reply()} | {:error, term()}

Authorize a settled agent conversation to start its next turn under a specific catalogue definition. Supply the exact :record_id, :revision, :operation_id, :actor, :authorize and the target :definition reference. Stop the old owner and open a new one using the adopted binding.

The :adopt receipt preserves the original snapshot and effect journal. Pending work, unresolved effects and unanswered tool batches refuse adoption. The Store enforces the adopted binding when the next turn starts.

census(store, opts \\ [])

@spec census(ExAgent.Store.scoped() | [ExAgent.Store.scoped()], keyword()) ::
  {:ok,
   %{
     open: non_neg_integer(),
     closed: non_neg_integer(),
     unclassified: non_neg_integer(),
     groups: [
       %{
         kind: :agent | :composition | :flow,
         definition: versioned_reference(),
         policy: versioned_reference(),
         model_ref: versioned_reference() | nil,
         count: pos_integer(),
         statuses: %{required(run_status()) => pos_integer()}
       }
     ]
   }}
  | {:error, term()}

Count records in a trusted Store scope or list of scopes by saved definition, policy, model references and status. The result contains the total :open and :closed records in the selected census, the count of :unclassified records whose custom Store supplies a summary without version references, and a list of :groups. Each group counts a record once per distinct reference triple and kind. Workflows include their root and the agent references in saved nodes and step bindings. Workflow roots have a nil model reference.

Pass include_closed: true to count terminal records too. An adopted conversation counts under its adopted definition. Pass Jobs.Durable.store/1 as a scope to include its committed C7 records. The scan reads journal headers in pages of 1–100 (:page_size, default 50). The bundled Stores include version references in every run header and return {:error, :run_header_missing} for a journal without its header. A nonzero :unclassified count means the groups cover only part of the census. Writes between pages are visible. Stop admitting work to versions being retired and check all relevant scopes.

decide(store, target, decision, opts)

@spec decide(
  ExAgent.Store.scoped(),
  ExAgent.Continuation.ApprovalRequest.t() | String.t(),
  ExAgent.Permissions.decision() | :cancel | :expire,
  keyword()
) :: {:ok, admin_reply()} | {:error, term()}

Persist a reviewer decision without executing IO on behalf of the agent.

With a request from pending/2, the decision is :approve, {:approve, args: map} (an edit), :deny, {:deny, message: text} or :cancel. Options are :actor and :authorize (required), :tool (the ExAgent.Tool the model was offered, required to edit without a catalogue), :catalog and :diagnostics. A catalogue validates the stored definition and tool before a fresh decision and supplies the tool for an edit.

  • An edit must use a tool with the request's name and schema fingerprint ({:error, :tool_mismatch}) and arguments that pass its validation, JSON normalization and the run's max_payload_bytes ({:error, {:invalid_args, errors}}). Arguments equal to the request's are a plain approval. The resumed call executes the edited arguments; the model's tool call in the history is not rewritten. An edit that changes a winning permission rule or reaches a denial returns {:error, {:permission_rule_changed, %{permission_rule: rule}}}. The rule names the edited match or is nil for a default. The request remains pending and its original rule stays bound to its original call.
  • A denial is per call and does not end the run: the resumed call returns :denied with the message (1 to 4096 bytes of UTF-8; by default "The reviewer denied this tool call.") and the model continues. Use :cancel to stop the run.
  • :decisions in the request lists the per-call decisions the stored record accepts; anything else returns {:error, :unsupported_decision}.
  • :cancel stops the run the request belongs to, decided or not; a request whose approval is no longer in the current execution (another run of the same lifetime) returns {:error, :stale_request}.

With a logical ID, the decision is :cancel or :expire and the options are :record_id, :revision, :operation_id, :actor, :authorize (required) and :diagnostics. Cancel can fence a ready, claimed or pending run. It can also close a recovered run with only model requests unconfirmed. Unconfirmed tools, callbacks and external deferrals keep the run :uncertain. A live Server that observes the external cancellation publishes its confirmed status and releases the owned worker. The queue waits while effects still need reconciliation. Expire closes a ready or pending run whose deadline passed. A run that cancel or expire left :uncertain ends :cancelled or :expired once its uncertainty is resolved: it is never offered for resume again.

Cancellation retains the uncertain model intents and their unknown cost. In a conversation it removes the provisional turn. A Composition or Flow can also expire from recovered model-only uncertainty after its deadline. A workflow's resume/3 reads the terminal and its confirmed steps.

Requests read by one pending/2 call can be decided in any order: each binds its record ID, approval ID and payload hash rather than the whole revision, and the write compares the revision it reads. A request whose namespace, approval, tool name or arguments no longer match returns {:error, :stale_request}, another lifetime {:error, :record_mismatch} and an item already decided {:error, :decision_conflict}. A decision after the run's deadline returns {:error, :expired} and one on a run that is not pending {:error, :invalid_transition}. The authorizer's target describes the stored approval and run, never fields copied from the request. Repeat the same request and decision to retry a lost reply: the Store replays the original receipt (replayed: true). A receipt proves the transition committed, not permission for new model or tool effects.

get(store, id, opts \\ [])

@spec get(ExAgent.Store.scoped(), String.t(), keyword()) ::
  {:ok, run_details()} | {:error, term()}

Read one continuation from the trusted scoped Store, independently of its former runtime process. The run_details/0 result includes run metadata, effects, retry bindings and historical uncertainty. :definition and :policy are the origin's versioned references. :handoff_policies maps each guarded destination's slash-delimited path to its saved policy reference, including destinations the run has yet to visit.

:lease_until is the current claim's horizon as a UTC timestamp in milliseconds, or nil without a claim. The Store compares it with its own clock when deciding whether recover/3 can revoke the claim.

:continuation is the exact reference to pass to resume when the record is :ready or :approved. Completed, failed, cancelled and expired workflows also supply this reference for a read through their resume/3. In other states it is nil. Resume checks the saved revision and the host's runtime bindings.

Effects summarize the journal without tool arguments or results. Each carries its owning :leaf when the journal identifies the node and the opaque :call_ref of a tool call. To inspect the stored body, pass diagnostics: true and read :record. The body uses the internal persistence schema. A source configured with :retain_failed_turn can include failed-turn evidence here for authorized capture. Invalid options raise ArgumentError.

The candidate timeline: true option adds an operator projection of the current run from that same revision. It includes the turn's :request_id, qualified aggregate :usage, host :request_count and :tool_calls, and the current :active_time budget, when recorded. The :children identify retained child runs by run ID, parent ID, link name and status. :entries group model attempts, approvals and tools by run and model step. Each entry identifies its kind and run. Model entries include the request ID, model reference and qualified usage, tool entries include their opaque call reference and effect state, and approvals include the tool, call reference, rule, status, actor and decision time when available. Frame3 child entries carry a :delegation_path from the root with a run ID, parent run ID, tool name and opaque call reference per hop. Approvals keep :pending, :approved, :edited or :denied as their status. Child deferrals have kind: :deferred, a :deferral_kind of :external, :timer or :input, and :mcp_input? for a bound MCP form. Their status is :pending, :supplied, :uncertain or :reconciled, or :cancelled or :expired if closed without a reply. Each retained MCP round has its own entry. Timers include :wake_at in UTC milliseconds. Recorded replies include the actor and resolution revision when available. Nil fields mean the journal provides no evidence for that value. :reconciliations list retained reconciliation receipts by revision, with their operation and actor. A receipt linked to a child tool also includes its call reference and delegation path. Older receipts provide run-level evidence. A historical deferral row needs the retained paused outcome or a bound receipt. Steps order entries within a run. The entries carry metadata only. Prompts, arguments, results, form bodies and provider call IDs stay private. The projection defaults to off.

Pass timeline: {:redact, {module, function, extra_args}} to also add :history for the retained root turn. The redactor receives :history for the prompt or accepted answer, :args for a retained tool call's arguments, or :content for a confirmed tool return, then the value and extra arguments. The result is bounded UTF-8 text or nil to omit it. Invalid results and failures never return the input. Guarded answers use only the stored accepted text. Tool content is available on completed turns, excluding withheld and omitted payloads.

A claimed record with an admitted intent or callback whose outcome is unconfirmed reports :executing until the claim releases or recovery takes over. After an observed kill of a heap-capped write, the writer can release a drained claim as :uncertain. A closed run can still show a model intent as :uncertain in :effects. The run itself reports :cancelled or :expired.

list_runs(store, opts \\ [])

@spec list_runs(ExAgent.Store.scoped(), keyword()) ::
  {:ok, ExAgent.Store.page(run_summary())} | {:error, term()}

Read one page of run_summary/0 items in a trusted scoped Store. :updated_at is in UTC milliseconds. :pending counts open approvals and deferred calls.

The :executing filter finds claimed records with an admitted intent or callback whose outcome is unconfirmed. That status can outlive the worker.

Options are :status (one of run_status/0), :limit (1–100, default 50) and :after (the previous page's cursor, or nil). An unknown option or an invalid value raises ArgumentError. The limit bounds candidate rows in the namespace. Even an empty page can have a next cursor after status filtering or skipping standalone snapshots. Pass the opaque cursor to the same Store, namespace and status filter. The page size may change. A mismatched or malformed cursor returns {:error, :invalid_scan}. Writes between pages are visible.

Pages use the header committed with each journal revision. PostgreSQL returns {:error, {:store_migration_required, 4}} if the SQL 4 column or index is missing. A candidate with a missing header returns {:error, :run_header_missing}. Rebuild the headers for existing journals after applying the migration or importing older rows. Use get/3 with diagnostics: true to inspect the journal for one run.

Authorize the operator for the namespace before listing. Use pending/2 for fresh review items on the selected run.

pending(store, id)

The review inbox of one run: undecided %ApprovalRequest{} items in approval-ID order followed by open %DeferredCall{} items in effect-ID order, all read from one revision because a batch can mix them and the run is ready only when every item is resolved. Each item carries a :call_ref for correlation and a fresh :operation_id. Keep the item server-side and pass it unchanged to decide/4 or supply_result/4, also when retrying after a lost reply. A delegated item also carries the path from the root and the definition of the agent that owns the tool.

Returns {:ok, []} for a run with nothing to resolve. A deferred call that a cancellation left unconfirmed is listed while the run is :uncertain.

prune_page(store, before, actor_id, opts \\ [])

@spec prune_page(ExAgent.Store.scoped(), non_neg_integer(), String.t(), keyword()) ::
  {:ok, ExAgent.Store.page(prune_result())} | {:error, term()}

Delete eligible terminal records from one bounded page in the trusted namespace. Returns one prune_result/0 per considered record and the next cursor. Active and :uncertain runs are retained. A cancelled run or an expired workflow with only unconfirmed model intents is eligible unless a retry's historical uncertainty is still retained. Stop admissions and writers before using this to remove a namespace, since writes are per record. before is an exclusive UTC-millisecond retention cutoff. Actor is host supplied. Each delete uses an operation ID that is free in the scanned revision. Options are :limit (1–100, default 50) and :after (the previous page's cursor), as in list_runs/2. Resume with the same cutoff and actor. An unknown option or an invalid value raises ArgumentError.

If queue delivery starts a run when its ID is absent, keep its terminal record through the last possible redelivery or manual retry. To prune earlier, first retire the queue reference durably and drain deliveries already admitted.

reconcile(store, id, effect_id, outcome, opts)

Reconcile one uncertain tool effect using a host-confirmed outcome. The host must obtain the real external result (or prove non-execution); this API performs no external IO and does not roll back or retry the tool. Model recovery requires its explicit model-state/frame evidence and is not inferred from a tool outcome. Options are those of recover/3.

Pass exactly %{"status" => status, "data" => value} with a JSON-portable value and a status of "succeeded", "tool_error", "validation_error", "denied", "failed" or "not_executed". "tool_error" confirms a domain failure the model sees, like a tool's {:tool_error, message}. A supplied success is checked against the result schema bound to a new tool intent. A mismatch is recorded as a confirmed "tool_error". With a tool-output guard the result stays at the raw boundary until resume can check it. The operation receipt binds the normalized proposal, including one rejected by the schema. A retry with the same binding replays the receipt while the effect is retained. A changed proposal under the same operation ID returns {:error, :operation_conflict}. A rejected value is never included in that error or stored as the result. An effect a cancellation left unconfirmed, including an external deferral, is reconciled the same way. Returns an admin_reply/0: :ready once nothing is unconfirmed, :pending while a deferred call of the batch is still open, :cancelled or :expired for a run that cancel or expire closed, and :expired for one past its deadline with nothing left open. Composition and Flow records return {:error, :unsupported_operation}.

reconcile_model(store, id, effect_id, evidence, opts)

@spec reconcile_model(
  ExAgent.Store.scoped(),
  String.t(),
  String.t(),
  map(),
  keyword()
) ::
  {:ok, admin_reply()} | {:error, term()}

Reconcile an uncertain Model request with host-confirmed effective (post-hook) response and portable model data. Evidence is %{response: response, model_data: data}. In an agent run, optional :accounting supplies already-qualified Usage maps for the exact ancestor IDs. Existing confirmed accounting is never repriced. A Composition or Flow records usage from the response on the request and its ancestors.

Every tool call in the response must already have a distinct UTF-8 ID of 1 to 512 bytes. Invalid IDs return {:error, :invalid_model_reconciliation} before the record is updated. The response must meet the same JSON portability checks as a new model checkpoint. It must carry :stop or :tool_calls. An incomplete response returns {:error, {:incomplete_response, finish_reason}} before the record is updated. Once an effect retry is authorized, its original effect ID returns {:error, :invalid_model_reconciliation}. Use the active attempt's effect ID when reconciling its response.

In addition to the options of recover/3, pass the trusted target :agent and its :continuation references/model codec (both required). For a child or workflow step use that leaf's agent and its :definition, :policy, :model_ref and :model_codec. Resolve them from the effect's :leaf in get/2, or replace both binding options with the candidate :catalog option to resolve the exact saved leaf. A missing entry returns {:error, {:definition_unavailable, ref}}. For a workflow, first recover the expired claim. The reply stays :uncertain while any other effect is unconfirmed. A closed workflow rejects new reconciliation with :invalid_transition. The authorizer receives a portable proposal after its data checks and before the codec, Model's no-IO resume preflight, and output profile checks. An authorized proposal can still fail validation. The Store receipt confirms the write. No Model request or after-model hook is executed by this operation. When the root agent resumes, the buffered response passes its stream windows and the final value passes its output guard. Either veto closes the turn while preserving the provider outcome and usage.

reconcile_tool(store, id, effect_id, opts)

@spec reconcile_tool(ExAgent.Store.scoped(), String.t(), String.t(), keyword()) ::
  {:ok, admin_reply()} | {:error, term()}

Look up a write's outcome through its tool's declared reconciler. An arity-two reconciler can read the result of a stored external deferral, including one left uncertain by cancellation or expiry.

Supply the options of recover/3 and the bound :tool from the host's current definition. Recover an expired claim first. The authorizer receives the effect and key under :reconcile_tool before the lookup starts. The lookup must be read-only and runs for at most the tool's timeout or five seconds by default. A confirmed outcome or certified non-execution is recorded under the same revision. An unknown result, a timeout or a crashed lookup returns {:error, :execution_uncertain} and leaves the journal unchanged. An invalid return yields {:error, :invalid_reconciliation}. Missing declared lookup support yields {:error, :no_reconciler}.

A committed operation can be replayed with the same binding, operation ID and actor without repeating the lookup while the effect and receipt are retained. Concurrent authorized lookups can run before one wins the CAS. Resume applies the normal tool-result checks. A new write requires its own dispatch.

recover(store, id, opts)

@spec recover(ExAgent.Store.scoped(), String.t(), keyword()) ::
  {:ok, admin_reply()} | {:error, term()}

Revoke an expired claim. Unconfirmed effects remain uncertain.

Supply these required options.

  • :record_id and :revision bind the operation to the lifetime and revision returned by get/2.
  • :operation_id is a caller-chosen UTF-8 string of 1 to 512 bytes that identifies this write within the record. Reuse it with the original options to recover the receipt if the reply is lost. Use a fresh ID for each distinct operation.
  • :actor is the caller identity passed to :authorize.
  • :authorize is an arity-three callback that receives the actor, :recover, and the stored target. Return {:ok, actor_id} to authorize.

Set diagnostics: true to include the record and receipt. The reply reports :uncertain while an intent or callback is unconfirmed, :expired once a deadline has passed with nothing unconfirmed, :pending for an open deferred call before the deadline, and otherwise :ready with a continuation reference.

retry_checkpoint(store, token)

Retry only the exact data transition from a failed runtime checkpoint. Store configuration is supplied separately and never appears in the data-only token. A committed/replayed claim or effect-intent receipt does not authorize dispatch; inspect/recover the current record explicitly before requesting a new resume.

retry_effect(store, id, binding, opts)

@spec retry_effect(ExAgent.Store.scoped(), String.t(), retry_binding(), keyword()) ::
  {:ok, admin_reply()} | {:error, term()}

Authorize a new linked attempt using a binding from get/2's :retryable_effects. Supply :operation_id, :actor and :authorize. The binding supplies the record ID and revision. A persisted read reuses the original key without duplicate-risk acceptance. Verify a remote tool's read classification before authorizing it.

A model effect or an agent write with manual recovery still requires accept_duplicate_risk: true. The key defaults to the one recorded on the original attempt. If it has no key, supply a nonsecret visible-ASCII :idempotency_key of at most 512 bytes. A supplied key must match any key already recorded. A malformed binding, key or acceptance returns {:error, :invalid_effect_retry}.

For a new model retry, pass :agent and its :continuation binding as for reconcile_model/5. Use the trusted definition, policy, model reference and codec for the effect's :leaf from get/2. After authorization, the codec and no-IO model preflight check the captured request with the proposed key. A rejection preserves the uncertain intent for reconciliation. A retry spends a new request. An exhausted persisted request limit on the run or one of its ancestors returns {:error, {:usage_limit_exceeded, :requests, request_count}}, even if WrapUp prepared the lost request. The preflight relies on the host's declared :model_ref for identity. Give each backend and configuration that must be distinguished its own versioned reference and resolve it with the trusted definition and codec. The candidate :catalog option supplies both values from the saved leaf. When supplying a catalogue, omit :agent and :continuation. Replaying a confirmed receipt works without the agent and codec.

Resume needs a new claim and intent acknowledgement before dispatch. The original intent/outcome stays literally uncertain in historical evidence. External deduplication depends on the service. A manual write retry requires a context-aware tool. A write with a declared lookup uses reconcile_tool/4.

Flow also supports this operation for recovered branch model intents. Pass the ready reply's reference to ExAgent.Coordination.Flow.resume/3. It sends the saved request through a new intent, with prior confirmed work restored. Composition and Flow support read tool retries in active leaf batches.

supply_result(store, call, supplied, opts)

@spec supply_result(
  ExAgent.Store.scoped(),
  ExAgent.Continuation.DeferredCall.t(),
  supplied(),
  keyword()
) :: {:ok, admin_reply()} | {:error, term()}

Record the result of a deferred call listed by pending/2, without resuming the run. Supply {:succeeded, value} with JSON or declared multimodal ExAgent.Tool.Content, or {:failed | :denied | :not_executed, content} with JSON-portable content. An inadmissible representation returns {:error, {:invalid_result, reason}}.

The candidate MCP input form accepts {:input, input_responses} with the form responses keyed by the peer's request IDs. A subsequent ExAgent.resume/3 sends a new round of the original tool call. The journal keeps the prior round's confirmed input request. Only the peer can report success or failure for the remote call. A timer rejects this form with {:error, {:invalid_result, :input_not_supported}}. For an MCP input deferral, a supplied {:succeeded, value} or {:failed, content} returns {:error, :mcp_input_required}. To settle locally without sending another round, supply {:denied, content} or {:not_executed, content}.

Options are :actor, :authorize and :tool (required: the tool that deferred, with the same name and schema fingerprint, or {:error, :tool_mismatch}) and :diagnostics. The authorizer receives the operation :supply_result with the result in target.result.

The write is idempotent by the call's :operation_id and bound by record ID and :deferred_hash: another result for a resolved deferral returns {:error, :decision_conflict}. The command depends only on the deferral and the result, so repeating the same item and result replays the original receipt (replayed: true) even after other items of the inbox were decided; once a new run started on the record it returns {:error, :stale_request}, so inspect it with get/2. The Store accepts a timer's result only before :wake_at. At the timestamp a new result returns {:error, :timer_due} while the timer is still open. A pending run past its deadline returns {:error, :expired} (expire it first) and a run with nothing to supply {:error, :invalid_transition}.

A run that :cancel or :expire left :uncertain because an external deferral was open still accepts its result as evidence, and then ends :cancelled or :expired with no :continuation. A result exceeding the tool's saved return slot or the projected checkpoint capacity of a resumable run returns {:error, {:invalid_result, {:retention_limit_exceeded, details}}}. The Store's hard journal limit reports {:error, {:invalid_result, :record_limit}}. Supply a smaller value or a result reference using the same pending call. The projection uses the saved batch before output hooks, other decisions or future model requests can change its size. For a pause without a saved custom writer limit the projection uses the Store limit.

On the first resume, after_tool_call hooks transform the result before its schema is checked. A mismatch finalizes the confirmed result as a bounded :tool_error. The authorizer's target describes the stored deferral. A webhook is one more actor whose signature the host verifies.