Writing an approval provider (experimental)
Experimental
The approval gate is experimental: tool confirmation, external approvals (approvals:), the provider interface and the on_missing_gate default may change in a minor release.
A provider connects the approval flow to one external system (PagerDuty, Teams, GitHub issues, an internal queue). The worked example is the local_file provider in the quick start. To use the built-in Slack or Jira providers, see External approvals.
Mental model
A provider is a thin translator. The framework owns persistence, schema validation, the allow-list check with its audit trail, config-drift detection and the resume, which runs once per batch. You own four things: create the external artifact, poll it for a decision, update it after the decision, and optionally expand group membership.
BaseExternalApproval marks five methods @final: request_prompt, preflight, poll, mark_resolved and _authorize. They validate schemas, apply timeouts, enforce the allow-list and wrap update_resolved as best effort. abt rejects a provider that overrides one (see Registration).
The method contract
from abt.infra.approvals.external_approval import BaseExternalApproval
class PagerDutyApproval(BaseExternalApproval):
ConfigSchema = PagerDutyConfig
OptionsSchema = PagerDutyOptions
# Required
async def post(self, req, approval_id, *, config, options) -> dict: ...
async def fetch_decision(self, handle, *, config, options): ...
async def update_resolved(self, handle, decision, decided_by, *, config, options) -> None: ...
# Optional, with defaults
async def fetch_authorized_decision(self, handle, *, config, options, is_authorized): ...
async def resolve_groups(self, identity, *, config) -> set[str]: ...
async def resolve_user_identities(self, identity, *, config) -> set[str]: ...
async def own_identities(self, *, config, options) -> set[str]: ...
def own_identities_cache_key(self, *, config, options) -> str: ...
async def validate_request(self, req, approval_id, *, config, options) -> None: ...
def format_decided_by(self, decided_by: str) -> str: ...
post(req, approval_id, *, config, options) -> dict. Called once per approval from ExternalApprovalGate.post_batch. Create the external artifact and return an opaque, JSON-serializable handle (message ts, issue key, path). abt stores it on the row and passes it to fetch_decision and update_resolved. req carries agent_name, tool_name, tool_args and metadata (workflow_name, thread_id). Show tool_args in full: the approver must see what will run. abt.infra.approvals.tool_args has render_tool_args_json (raises ToolArgsTooLargeError above 28,000 characters instead of truncating) and tool_args_hash, the value stored on the row. Raise on hard failures such as bad credentials or an unknown channel: abt marks the row failed, denies the whole batch and resumes it at once, with no retry.
fetch_decision(handle, *, config, options) -> ApprovalPollResult. Called on every abt dispatch that finds a pending row. Return ApprovalPollResult.pending() while no human has acted and ApprovalPollResult.decided(approved, decided_by) once one has. It runs many times, so keep it cheap and free of side effects. decided_by must use the same identifier format as allowed_approvers.users, or every decider fails authorization and the row stays pending forever. The allow-list is enforced by poll, so a provider only reports who decided.
fetch_authorized_decision(handle, *, config, options, is_authorized). Override it when the system can show several candidate decisions at once, such as a comment thread. Skip candidates whose decided_by fails await is_authorized(...) and return the first that passes, so a non-approver's command cannot hide an approver's later one. The default calls fetch_decision. jira-comment and slack (mention_command) override it; for Slack reactions a non-approver's first reaction still keeps the row pending.
update_resolved(handle, decision, decided_by, *, config, options) -> None. Best effort, called once after the row moves from pending to resolved and before the graph resumes. Use it for banners, resolution comments or incident notes. abt logs a failure and continues.
resolve_groups(identity, *, config) -> set[str]. Expand the identity to its groups (usergroups, Okta groups, teams) so allowed_approvers.groups can match. The default returns an empty set. An exception or timeout counts as no match, so the decider is denied.
resolve_user_identities(identity, *, config) -> set[str]. Return other identifiers of the same user (email, username). The raw decided_by is always matched, and the default adds nothing. Implement it when decided_by differs from what operators write in allowed_approvers.users. The Jira providers return the commenter's accountId as decided_by and add the account's email and username here. Failures count as no match.
own_identities(*, config, options) -> set[str]. Return the identifiers your provider acts as (bot user id, service accountId), in the decided_by format. poll rejects a decision from any of them, because the agent can often write through the same account. The default returns an empty set, which gives no protection: abt logs a warning once per process for a provider that returns nothing. poll resolves it before scanning, outside the scan's timeout, and caches the result per process (see own_identities_cache_key). Raise when the lookup fails; poll then skips decisions (a pending result with reason="own_identity_unresolved") until it succeeds, without recording unauthorized attempts. The resume phase reports it and denies on timeout, whatever on_approval_timeout says.
own_identities_cache_key(*, config, options) -> str. The key poll caches own_identities under. The default hashes config only, so options that vary per run (a thread id, an issue summary) do not defeat the cache. Override it to add an option the result depends on.
validate_request(req, approval_id, *, config, options) -> None. Raise when post would fail for a reason you can see without I/O, such as a body over the system's size limit. The gate calls it for every member of a batch before posting any, so one bad member cannot leave its batch-mates' requests open. The default checks nothing.
format_decided_by(decided_by) -> str. Renders a decider for people. The default wraps the id in backticks, and slack returns <@U0123...>. Your own update_resolved can call it for resolution banners. The framework does not call it elsewhere.
Schemas
Declare ConfigSchema and OptionsSchema as frozen pydantic models; both default to an empty model. When abt dispatch builds the gate, it validates the resource's config: against ConfigSchema and the agent's options: against OptionsSchema and passes typed models to your methods. A failed validation is logged at ERROR in logs/abt.log and the gated calls are denied. abt compile does not validate them, so a typo shows up at the first dispatch.
from pydantic import BaseModel, ConfigDict, SecretStr
class PagerDutyConfig(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
api_token: SecretStr # must be SecretStr, see below
service_id: str
class PagerDutyOptions(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
urgency: str = "high"
extra="forbid"turns a typo inabt.yamlinto a dispatch-time error instead of a silent no-op.- Fields named like secrets must be
SecretStr. The registry rejects aConfigSchemafield whose name ends in_token,_key,_secretorpassword(any case) unless its annotation, possibly insideOptionalorAnnotated, isSecretStr. abt hashes and stores the config for drift detection, andSecretStrkeeps the value out of the stored copy.
ConfigSchema is per resource (approvals.resources.<name>.config:): credentials and targeting such as channel, project or service id. OptionsSchema is per agent (approvals.options: in the agent frontmatter): UX settings such as emoji, labels or urgency, with {{ var('...') }} support.
Registration
Decorate the class or declare an entry point. abt validates both the same way when it loads the provider.
from abt.infra.approvals.external_approval import BaseExternalApproval
from abt.infra.approvals.registry import external_approval_for
@external_approval_for("pagerduty")
class PagerDutyApproval(BaseExternalApproval):
...
For a project, put the file in providers/. For a distribution, add an entry point so abt finds the class without an import:
[project.entry-points."abt.external_approvals"]
pagerduty = "my_pkg.approvals:PagerDutyApproval"
A provider in providers/ wins over an entry point with the same type. Two entry points that claim the same type raise DuplicateProviderError.
On load, abt rejects a provider when:
- the class does not subclass
BaseExternalApproval; - a
@finalmethod is overridden; ConfigSchemaorOptionsSchemais not aBaseModelsubclass;post,fetch_decisionorupdate_resolvedis still abstract;- a credential-named field is not a
SecretStr.
abt skips a rejected provider with a warning such as Rejected approval provider 'pagerduty' in <path>/providers/pagerduty.py: <reason>. Its type then does not resolve: abt dispatch logs No external-approval adapter registered for type='pagerduty' and denies the gated calls.
To check that abt finds your provider before you dispatch, resolve it from Python. It returns the class or raises KeyError listing the known types. Leave out providers_dir for a provider installed as a package:
from pathlib import Path
from abt.infra.approvals.registry import require_external_approval
require_external_approval("pagerduty", providers_dir=Path("providers"))
Timeouts
abt wraps every network-facing provider method in asyncio.wait_for, so a stuck provider cannot wedge a dispatch. The limit comes from ABT_APPROVALS_ADAPTER_TIMEOUT_SECONDS (none, 0 or a negative value disables it), else the adapter_timeout_seconds class variable (default 30.0):
class PagerDutyApproval(BaseExternalApproval):
adapter_timeout_seconds = 10.0
| Method | On timeout |
|---|---|
post |
Raises TimeoutError. The gate marks the row failed. |
fetch_decision / fetch_authorized_decision |
Treated as pending. The next poll tries again. |
update_resolved |
Logged and swallowed. |
resolve_groups / resolve_user_identities |
Count as no match, so the decider is denied. |
own_identities |
Decisions are skipped (pending) with a warning until the next poll succeeds. |
Authorization
poll enforces the allow-list before it returns a decision:
- If
decided_byis one ofown_identities, deny. Ifown_identitiesfails, skip every decision (no unauthorized-attempt record). - If
allowed_approvers.usersand.groupsare both empty, deny. - If
usersis set, check{decided_by} ∪ resolve_user_identities(decided_by)against it. A match allows. - If
groupsis set, checkresolve_groups(decided_by)against it. A match allows. This runs even whenusersis also set and did not match. - Otherwise deny.
On a deny, poll calls the on_unauthorized callback, which saves an unauthorized-attempt record, and returns Pending(). A non-approver's reaction or comment is ignored and cannot flip the run to denied.
Testing a provider
Subclass your provider, stub fetch_decision and call poll directly:
# PagerDutyApproval, PagerDutyConfig and PagerDutyOptions are the classes defined above.
from abt.infra.approvals.models import ApprovalPollResult, AuthorizedApprovers
class FakePD(PagerDutyApproval):
async def fetch_decision(self, handle, *, config, options) -> ApprovalPollResult:
return ApprovalPollResult.decided(approved=True, decided_by="U_ALICE")
async def test_poll_authorizes_by_user():
result = await FakePD().poll(
handle={"incident_id": "INC-1"}, approval_id="ap1",
config=PagerDutyConfig(api_token="x", service_id="P1"), options=PagerDutyOptions(),
allowed=AuthorizedApprovers(users=["U_ALICE"], groups=[]),
)
assert result.status == "decided" and result.approved
Also cover pending, both verdicts, an unauthorized decided_by turning into pending, timeouts (adapter_timeout_seconds = 0.01 plus a slow stub) and any group or identity expansion you implement.
Checklist
decided_bymatches theallowed_approversformat.postruns once and raises on failure.fetch_decisionis fast and free of side effects.update_resolvedmay raise (abt logs it), and so may the expansion hooks (abt treats that as no match).- The entry point is declared in
pyproject.toml, or the file sits inproviders/.
Custom approval store
A store implements the ApprovalStore protocol from abt.infra.approvals.store. It must include record_decision(approval_id, decision, decided_by) -> bool, which abt approvals resume uses to record a decision on a row that stays pending until the next dispatch. Without it, dispatch, list and show still work, and resume stops with E_APPROVAL_STORE_UNSUPPORTED. Optional capabilities are separate protocols: UnauthorizedAttemptLog for the audit record and PendingPromptQueue for queued prompts.
Wrap the store in a provider with a static build(project_root, config) -> ApprovalStore method and register it with register_approval_store_provider(name, provider). Registering an existing name raises ValueError. After that, approvals.store.backend: <name> selects it. abt imports only the built-in dynamodb module on demand, so your registration code must run before the store is built.
See also
- External approvals: providers, configuration and operations.
- Extending abt: the shared plugin contract and entry-point groups.
- CLI reference: the
abt approvalsgroup.