# Documentation for agents URL: https://docs.openagent.id/agents Markdown: https://docs.openagent.id/agents.md Read task-scoped Markdown, source manifests, and the read-only documentation MCP service. Use a specific task page and its package contract before loading the whole corpus. Human pages and machine-readable pages are generated from the same content tree. | Format | Endpoint | Use | | ---------------- | ---------------------------------------------------- | ---------------------------------------------------------- | | Discovery | [/llms.txt](/llms.txt) | Page titles, descriptions, and canonical URLs | | Full corpus | [/llms-full.txt](/llms-full.txt) | Whole-site context when required | | Page Markdown | Append `.md` to a page path | Small, task-scoped context | | Skill | [/skill.md](/skill.md) | Documentation workflow and boundaries | | Page manifest | [/reference/index.json](/reference/index.json) | Machine-readable page discovery | | Package coverage | [/reference/coverage.json](/reference/coverage.json) | Source manifests, versions, entry points, and page mapping | | MCP | `/api/mcp` | Read-only page listing, retrieval and search | ## MCP connection [#mcp-connection] Connect a Streamable HTTP MCP client to `https://docs.openagent.id/api/mcp`. The documentation service provides `list_pages`, `get_page`, and `search`. It only retrieves documentation. It does not generate identity keys, submit transactions, request credentials, or invoke product APIs. ## Use the source boundary [#use-the-source-boundary] * Match SDK language, manifest version, and enabled features. * Treat an unverified registry release as source installation, not a public package promise. * Keep standalone Rust and TypeScript HTTP adapter sessions separate. * Configure identity, credential, and authority providers explicitly. * Never infer cross-language encryption-key restoration from ACT vectors. * Do not include secrets, seeds, sessions, private keys, or bearer credentials in documentation searches. Begin with [verification](/essentials/quickstart), [authentication](/essentials/authentication), or [the library catalog](/reference/packages). # Identity with explicit authority URL: https://docs.openagent.id/ Markdown: https://docs.openagent.id/index.md Build agents with verifiable identity, scoped capabilities, and configured trust. OpenAgentID brings together identity, authentication, delegated capabilities, credential brokering, and verification. Start with the smallest contract your application needs, then connect the providers required for richer workflows. ![The original Keeper and Witness agents illustrate identity and explicit authority.](/images/family/identity.svg) [Verify a capability](/essentials/quickstart) Run a complete verifier with explicit token, trusted key, issuer, audience, and scope inputs. [Choose your SDK](/sdk/overview) Six languages, with actual source versions and implementation-specific boundaries. [Connect a server](/essentials/authentication) Use the right handshake and session format for your chosen implementation. [Build with an agent](/agents) Use task-scoped Markdown, source manifests, and the read-only documentation MCP service. ## Understand the layers [#understand-the-layers] | Layer | Role | | ------------------------- | ------------------------------------------------------------------------------- | | OAS | DID/document primitives, cryptography, lineage, resolution and attestations | | ACT | Canonical signed capability envelope and verification contract | | Arsenal | Tenant-scoped policy, credential storage, capability issuing and proxy requests | | AEGIS | Verification, policy, keys, delegation, authentication and wallet modules | | Unified SDKs | Language-specific convenience APIs that connect the underlying providers | | Adapters and integrations | Transport, identity bridges, tool/skill hooks and deployment examples | Creating a key or parsing a DID does not establish privileged authority. Configure trusted identity, credential, and authority providers explicitly. Alternative anchors require explicit verifier trust policy; an adapter's existence is not blanket acceptance of every anchor. ## Follow the source [#follow-the-source] The [package catalog](/reference/packages) records versions, features and entry points. The [Rust module reference](/reference/rust) and [TypeScript API reference](/reference/typescript) provide signatures, options and source documentation. The audit records source contracts separately from public registry availability and live service deployment. # Delegation URL: https://docs.openagent.id/aegis/delegation Markdown: https://docs.openagent.id/aegis/delegation.md Scope attenuation, proof verification, storage, and revocation propagation. The `aegis-delegate` crate separates proofs, scope rules, session keys, delegation storage, trees, and revocation stores. A delegation may only grant authority supported by its verified parent chain and policy. ## Delegate an action [#delegate-an-action] Verify the parent authority first, restrict the child scope/depth/lifetime, sign the intended delegation proof, and persist it through the configured store. The consuming service must verify the proof and applicable revocation state before authorizing an operation. ## Revoke deliberately [#revoke-deliberately] `RevocationRegistry` exposes `revoke`, `is_revoked`, and `revoke_cascade`. The cascade method accepts IDs to revoke; a local in-memory registry does not make remote caches or separate services immediately consistent. Tree traversal, persistence, propagation and cache invalidation must be configured and exercised by the application. Use `DelegationStore` and `RevocationStore` implementations appropriate to your deployment. In-memory stores are process-local. Test broadened scope, depth exhaustion, expired proof, missing ancestor, and revoked parent behavior. See [delegation module signatures](/reference/rust/aegis-delegate) and [server authority verification](/sdk/server/verification). # FROST threshold signing URL: https://docs.openagent.id/aegis/frost Markdown: https://docs.openagent.id/aegis/frost.md Threshold key and ceremony APIs with explicit version and custody boundaries. FROST enables a threshold quorum to produce an Ed25519 signature. It does not by itself prove personhood, unique humans, or that a group has legitimate authority over an entity. ## Current source versions [#current-source-versions] The OAS workspace declares `frost-ed25519` **3.x**, while the AEGIS workspace declares **2.2**. Serialized share/key-package interoperability across these versions is not established by a shared final-signature algorithm. Pin the actual resolved dependencies and validate migration with the exact libraries and backup material before changing a signing group. Do not discard old shares or assume that generating a new set preserves the same public key or DID. Key refresh, new key generation and authority rotation are different operations and need an explicit ceremony and recovery plan. ## Source APIs [#source-apis] AEGIS keys re-export `generate_shares`, `sign_with_threshold`, and `verify_threshold_signature`. Wallet ceremony utilities live in `aegis-wallet/src/ceremony.rs`. OAS crypto and the shared crypto-WASM crate expose their own threshold primitives. Use the exact signatures and configuration from [AEGIS threshold source](/reference/rust/aegis-keys/threshold), [wallet ceremony source](/reference/rust/aegis-wallet/ceremony), and [the crypto package catalog](/reference/packages). Never reuse signing nonces across signing sessions. Test insufficient quorum, incorrect share, interrupted ceremony and mismatched public-key cases. # AEGIS verification and authority URL: https://docs.openagent.id/aegis/overview Markdown: https://docs.openagent.id/aegis/overview.md Compose verified identity, policy, delegation, custody, and signing infrastructure. AEGIS is a nine-crate Rust workspace with a TypeScript SDK. The high-level Rust package exports `AegisClient`, `AegisStores`, `AegisConfig`, and `StorageBackend`, plus the lower-level crates. | Package area | Guide | | ------------------------------------- | ----------------------------------------------------------- | | Core types and plugin registry | [Source modules](/reference/rust/openagent-aegis-core) | | Identity verification/cache | [Verification pipeline](/aegis/verification-pipeline) | | Policy composition and evaluators | [Policy](/aegis/policies) | | Delegation and revocation | [Delegation](/aegis/delegation) | | Key generation, rotation and recovery | [Key custody](/essentials/key-management) | | Authentication and session stores | [Source authentication modules](/reference/rust/aegis-auth) | | Wallet/signing and threshold ceremony | [Wallet](/aegis/wallet), [FROST](/aegis/frost) | | Postgres store | [Store reference](/reference/rust/aegis-store-pg) | Configure actual resolver, trust, policy, persistence and authority providers before relying on a result. In-memory defaults and source APIs do not prove production persistence or network readiness. The OpenAgent SDK's privileged authority verifier is an explicit integration boundary. Begin at [the verification pipeline](/aegis/verification-pipeline), then inspect [the SDK options and methods](/reference/rust/openagent-aegis-sdk). # AEGIS policy evaluators URL: https://docs.openagent.id/aegis/policies Markdown: https://docs.openagent.id/aegis/policies.md Typed spending, temporal, lineage, contract and composition APIs. `openagent-aegis-policy` exposes five modules. Each evaluator expects the corresponding typed policy and verified operation context. | Module | Input and role | | ------------- | ------------------------------------------------------------- | | `spending` | Transaction information and configured spending rules | | `temporal` | Time policy, current time and optional cooldown | | `lineage` | Lineage requirements and verified identity context | | `contract` | Contract policy and a described contract interaction | | `composition` | Combine policy outcomes under the configured composition rule | ## Apply policy before execution [#apply-policy-before-execution] Build context from authenticated identity and the actual requested operation. Evaluate the relevant policies and require the intended result before signing, issuing a credential or calling a tool. Do not allow the caller to substitute a weaker policy or fabricated spending history. Policy evaluation is separate from persistence of usage and enforcement at the execution boundary. A spending evaluator does not automatically create a reliable transaction ledger. A contract evaluator is not unrestricted execution of arbitrary code. Read [the exact policy types, arguments and results](/reference/rust/openagent-aegis-policy). Exercise deny/no-match, boundary times, missing lineage, over-budget requests and composition behavior using the resolved version you deploy. # Verification pipeline URL: https://docs.openagent.id/aegis/verification-pipeline Markdown: https://docs.openagent.id/aegis/verification-pipeline.md Resolution, proof validation, lineage, liveness, and cache-aware decisions. `VerificationPipeline::new(registry, config)` combines a plugin registry and `VerificationConfig`. `verify(did)` first consults the cache; `verify_force_refresh(did)` invalidates that entry and performs a fresh verification. ## Source pipeline [#source-pipeline] 1. Resolve the OAS document through registered plugins under a timeout. 2. Validate document structure. 3. Verify its Ed25519/JCS document proof. 4. Check revocation status. 5. Verify lineage toward the root using resolved documents. 6. Check human-root liveness. 7. Compute the verified conformance level and retain warnings. 8. Cache and return the result. Configure timeout, maximum depth, cache TTL, resolver trust, revocation and liveness providers explicitly. Cached identity results require appropriate invalidation when authority changes. A basic identity pipeline result is not a substitute for the application's privileged-authority policy. ## Failure handling [#failure-handling] Resolution failures, invalid signatures and timeouts can return `VerificationError`. Other conditions may be reflected in result fields/warnings according to configuration. Inspect the typed result and required policy; do not equate the mere presence of a returned object with permission to execute. See [pipeline signatures and options](/reference/rust/aegis-verify/pipeline), [core types](/reference/rust/openagent-aegis-core), and [conformance](/features/conformance). # Wallet and signing infrastructure URL: https://docs.openagent.id/aegis/wallet Markdown: https://docs.openagent.id/aegis/wallet.md Address encoding, signing pipelines, and chain-specific boundaries. The `aegis-wallet` crate contains `address`, `batch`, `ceremony`, `external`, and `pipeline` modules. Address encoding and transaction signing are separate capabilities. `AddressDeriver::derive_address(chain, public_key_bytes)` takes supplied public-key bytes and returns address metadata. `derivation_path` reports the path convention for a chain; calling the address encoder does not derive a private key from an agent seed or prove that the supplied key is valid for that chain. ## Integration sequence [#integration-sequence] 1. Select the chain and its actual signing-key algorithm. 2. Obtain the public key from the correctly configured key provider. 3. Derive/encode an address and verify it against authoritative chain vectors. 4. Configure the signing pipeline, policies, external signer or threshold ceremony required by the action. 5. Test transaction serialization and broadcast on the intended network separately. The source supports a `Chain` enum and per-chain encoding branches, but source presence is not certification of complete wallet compatibility or live transaction support on every named network. Do not infer Ethereum signing support from an Ed25519 identity alone. Read [address signatures and source documentation](/reference/rust/aegis-wallet/address), [the wallet module index](/reference/rust/aegis-wallet), and [key custody](/essentials/key-management). # HTTP adapter API URL: https://docs.openagent.id/api-reference/http-adapter Markdown: https://docs.openagent.id/api-reference/http-adapter.md Discovery, challenge, proof, and opaque session behavior from the TypeScript adapter. `@openagentid/http` implements the Core Protocol handshake for fetch-standard and Express-style applications. It is a separate package from the standalone Rust server. | Method | Path | Success body | | ------ | ----------------------------------- | --------------------------------------------------------------------------------- | | GET | `/.well-known/openagent` | `auth_endpoint`, `supported_versions`, `server_did`, `required_conformance_level` | | POST | `/.well-known/openagent/auth` | `type`, `nonce`, `timestamp`, `origin`, optional `realm` | | POST | `/.well-known/openagent/auth/prove` | Established identity/session data defined by `IdentityVerified` | ## Proof input [#proof-input] The current source schema requires these nonempty fields: ```json { "signature": "base64url-encoded-signature", "public_key": "base64url-encoded-public-key", "key_type": "ed25519", "nonce": "nonce-from-the-issued-challenge" } ``` The strings above describe encoding and provenance; they are not working credentials. The parser also accepts `secp256k1` as a key-type value. Acceptance by the schema does not certify algorithm support by your supplied verifier. The application must configure and test the algorithm it accepts. ## Handler integration [#handler-integration] * `handleDiscovery(config)` creates the discovery document. * `handleChallenge(config, store)` issues and stores a pending challenge. * `handleProve(config, store, body, verifySignature)` verifies a correlated proof and establishes a session. * `authenticateRequest(request, store)` validates the presented opaque session. * `createOpenAgentHandler(options)` wraps these routes for fetch-standard frameworks. * `createOpenAgentMiddleware(options)` exposes the Express-style adapter. Session defaults are 300 seconds and challenge defaults are 60 seconds in this TypeScript adapter. They differ from the standalone server. Override deliberately; use a shared store when requests can reach multiple replicas. ## Failures and replay [#failures-and-replay] Unknown, consumed, and expired challenge nonces fail. Cryptographic proof verification is provided by `VerifySignatureFn`; never substitute an always-true callback. A malformed proof can fail schema parsing before pending-state handling. Inspect exact validation order and expiry behavior in `src/server.ts` when implementing a custom store. `CoreAuthError` carries an HTTP status. Middleware produces JSON errors, with fallback 400 for invalid challenge requests and 401 for failed proof authentication. Do not treat error text as a stable authorization decision; use the HTTP result and typed implementation contract. Source: `openagent-sdk/adapters/http/typescript/src/{middleware,server,transport,headers,discovery}.ts`. # API and source references URL: https://docs.openagent.id/api-reference/introduction Markdown: https://docs.openagent.id/api-reference/introduction.md Actual HTTP implementations, library entry points, features, and versioned source coverage. The reference has two kinds of contract: * **HTTP routes:** the standalone server, the separate HTTP adapter, and the Arsenal broker. * **Library APIs:** source manifests, feature flags, exported entry points and focused task guides for the six SDKs and supporting packages. Start with the [standalone server](/api-reference/openagent-server), [HTTP adapter](/api-reference/http-adapter), [Arsenal broker](/arsenal/broker), or [package catalog](/reference/packages). The current standalone server has no canonical OpenAPI document in its source tree. Its route table is audited directly from the router and handler definitions. These docs do not fabricate an endpoint specification for DID/key CRUD operations that are not mounted there. For agents, the [coverage manifest](/reference/coverage.json) records checked paths and hashes; [Markdown exports](/agents) provide the same task guides as the human site. A source API is distinct from a hosted service, public package release, or verified production deployment. # Standalone server API URL: https://docs.openagent.id/api-reference/openagent-server Markdown: https://docs.openagent.id/api-reference/openagent-server.md The three routes mounted by the current Rust standalone server. The standalone Rust binary is a minimal authentication service. These routes are derived from `openagents/openagent.id/crates/openagent-standalone/src/main.rs`. They describe source behavior; no public hosted API endpoint is assumed. | Method | Path | Authentication | Result | | ------ | ------------ | --------------------------------------- | ---------------------------------------------------- | | GET | `/healthz` | None | HTTP 200, empty body | | GET | `/livez` | None | JSON with `status` and package `version` | | GET | `/v1/whoami` | OpenAgent middleware and Bearer session | JSON `did`, numeric `trust_tier`, optional `l1fe_id` | ## Inspect your configured server [#inspect-your-configured-server] ```bash curl --fail http://localhost:8080/healthz curl --fail http://localhost:8080/livez ``` These commands require an already-running local instance. They do not deploy a server or generate credentials. ## Protected identity response [#protected-identity-response] ```http GET /v1/whoami HTTP/1.1 Host: localhost:8080 Authorization: Bearer ``` The handler checks a Bearer JWT session. The middleware's detached OpenAgent proof is a different phase; see [authentication](/essentials/authentication). Reuse only sessions issued and trusted by this deployment. ## Configuration [#configuration] | Environment variable | Source default / constraint | | ----------------------- | --------------------------------------------------------- | | `OPENAGENT_SECRET` | Required; at least 32 bytes; session-signing secret | | `OPENAGENT_PORT` | 8080 | | `OPENAGENT_ORIGIN` | `http://localhost:`; configure your intended origin | | `OPENAGENT_SESSION_TTL` | 900 seconds | | `OPENAGENT_NONCE_TTL` | 30 seconds | | `OPENAGENT_DEV_MODE` | false; do not enable for production | Configure TLS, ingress, effective CORS policy, credential custody, and deployment-specific storage at your service boundary. The source router's permissive CORS setup is not a recommendation for every deployment. ## Separate implementations [#separate-implementations] The well-known handshake routes are provided by the [HTTP adapter](/api-reference/http-adapter), not mounted by this binary. DID, lineage, key, and credential operations are library/provider APIs. There are no `/v1/dids`, `/v1/keys`, or delegation-tree routes in the current standalone router. The [source package catalog](/reference/packages) lists the legacy middleware/client crates separately from the unified SDK. # Agent Capability Tokens URL: https://docs.openagent.id/arsenal/act-tokens Markdown: https://docs.openagent.id/arsenal/act-tokens.md The canonical version-1 CBOR envelope and its verification boundary. ACT is a signed capability envelope. The source specification at `act/SPECIFICATION.md` is **version 1, draft status**. The canonical Rust implementation is `agent-capability-token`. It is not wire-compatible with CWT/COSE merely because it uses CBOR. ## Envelope [#envelope] | Field | Type | Contract | | -------- | ---------------- | ------------------------------------------------------ | | `v` | unsigned integer | 1 for this implemented format | | `alg` | text | `Ed25519` | | `claims` | byte string | Exact CBOR-encoded claim bytes | | `sig` | byte string | 64-byte Ed25519 signature over those exact claim bytes | | `kid` | optional text | Signing-key identifier | The encoded token limit is **16,384 bytes**. Check size before decoding. Relay original bytes; re-encoding the claims may change the signed message. ## Claims [#claims] Required claims include `jti`, `sub`, `iss`, `aud`, `iat`, `exp`, `tenant_id`, and `scope`. `aud` accepts a string or array. Temporal values are integer epoch seconds. Optional `nbf` defaults to zero. `cnf` carries proof-of-possession metadata, `delegation` carries onward-delegation restrictions, and `ext` carries issuer-specific values. The presence of `cnf` is not proof of possession: the calling protocol must require and verify the actual possession proof. Issuer-specific budgets, rate limits and revocation distribution are application policy, not automatically enforced by the byte-format parser. ## Verify in order [#verify-in-order] Validate envelope size/shape/version/algorithm and signature shape. Verify the signature over the original claims bytes before trusting claim policy. Then validate the decoded claims against configured time, issuer, audience and required scope. Do not treat an unsupported format version as a signature forgery. Use [the complete quickstart](/essentials/quickstart) or [TypeScript binding recipe](/sdk/typescript). Public keys, issuer, audience and scope requirements must come from trusted service configuration. ## Scope and delegation [#scope-and-delegation] Scopes use `service:resource:action`. Parse and compare them with the canonical scope type; avoid ad hoc substring matching. Delegated tokens must obey their parent scope, depth, delegate and lifetime restrictions. Inspect [the actual claim and delegation types](/reference/rust/agent-capability-token) for optional fields and validation semantics. Token conformance does not certify cross-language encryption-key restoration, a live broker, or privileged authority. See [conformance evidence](/features/conformance) and [broker policy](/arsenal/policies). # Audit events URL: https://docs.openagent.id/arsenal/audit Markdown: https://docs.openagent.id/arsenal/audit.md Hash verification, chain integrity, and explicit durable storage. `AuditEvent` records an event kind, tenant, outcome and contextual metadata. Its builder can attach an agent, session, token, request ID and previous hash. `compute_hash` and `verify_hash` check event integrity; `AuditLog::verify_chain` checks linkage across stored events. ## Record and verify [#record-and-verify] Build an event at the operation boundary, record the correct outcome, link it to the previous event according to your logging implementation, and persist it to a durable sink. Verify individual hashes and the ordered chain during export or incident review. A local `AuditLog` is an in-memory collection. Hash chaining detects modification relative to retained trusted history; it does not by itself provide durable storage, prevent truncation, or publish an immutable blockchain record. Configure retention, append controls and external checkpoints if your threat model requires them. Keep secrets and raw capability/session material out of metadata. Full argument payload capture may contain user data or credentials; choose redaction and payload-hash policy deliberately. See [event and chain API](/reference/rust/arsenal-core/audit). Deployment-specific SIEM export or on-chain archival requires its own integration and verification. # Arsenal broker URL: https://docs.openagent.id/arsenal/broker Markdown: https://docs.openagent.id/arsenal/broker.md Actual router endpoints, credential policy, and deployment trust boundaries. The broker is a separate service from the standalone identity server. Its `BrokerServer::router` mounts the following source routes: | Method | Path | Purpose | | ------ | ----------------------- | -------------------------------- | | POST | `/v1/capabilities` | Capability request | | POST | `/v1/secrets` | Wrapped-secret request | | POST | `/v1/tokens/verify` | Token verification | | POST | `/v1/tokens/revoke` | Token revocation | | POST | `/v1/proxy` | Credential-backed upstream proxy | | POST | `/v1/consent/approve` | Approve consent | | POST | `/v1/consent/deny` | Deny consent | | POST | `/v1/consent/revoke` | Revoke consent | | GET | `/v1/consent` | List consent | | GET | `/health`, `/v1/health` | Health | | GET | `/metrics` | Metrics | ## Configure the broker [#configure-the-broker] Connect tenant policy, identity/public-key resolution, credential storage, wrapping keys, consent/revocation state, audit, and transport security. Production mTLS, destination policy and DNS/address checks must be verified on the deployed ingress and proxy path; a router existing in source is not evidence of secure live configuration. Use typed request and response definitions from the [handler reference](/reference/rust/arsenal-broker/handlers) and [broker modules](/reference/rust/arsenal-broker). Do not send private seed material as an identity lookup or log wrapped-secret payloads. Credential issue/use/refresh/revocation are separate operations. The TypeScript facade's [handle refresh is explicit](/sdk/client/capabilities). Test wrong tenant, missing consent, revoked token, expired capability and denied upstream target. # Human consent URL: https://docs.openagent.id/arsenal/consent Markdown: https://docs.openagent.id/arsenal/consent.md Explicit consent records and broker decision endpoints. Arsenal models consent with `ConsentRecord`, `ConsentPolicy`, `ConsentStatus`, and `ConsentRequest` in `arsenal-core::consent`. The broker mounts approve, deny, revoke and list routes. ## Implement a consent workflow [#implement-a-consent-workflow] Create the consent request from verified tenant/agent context, present the exact operation and constraints to the approving person, authenticate that approval, and persist the resulting signed/validated record through the configured store. Enforce expiry and revocation when the capability is used. `ConsentRecord` provides validity checks and variable/domain coverage checks. `signing_bytes` defines the record material to sign. These are library contracts; a ready-made Slack or email approval delivery channel is not implied by them. ## Denial cases [#denial-cases] Reject missing, expired, revoked, incorrectly scoped or unauthenticated approval. Ensure one tenant cannot approve another tenant's capability. A visible approval button or recorded event is not proof that the broker enforced consent before credential issuance. See [consent types](/reference/rust/arsenal-core/consent), [store interfaces](/reference/rust/arsenal-store/consent_store), and [broker endpoints](/arsenal/broker). # Arsenal credentials URL: https://docs.openagent.id/arsenal/overview Markdown: https://docs.openagent.id/arsenal/overview.md Scoped capabilities, credential storage, policy, and brokered requests. Arsenal separates an agent's authority to invoke a provider from custody of the provider's secret. Its six Rust packages provide core types, cryptography, policy evaluation, storage, broker service and SDK. A separate TypeScript SDK offers language bindings. ## Credential workflow [#credential-workflow] 1. Establish the agent and tenant using configured identity and trust. 2. Request the minimum capability/credential scope required by the operation. 3. Evaluate tenant policy and consent requirements. 4. Issue the appropriate bounded token or credential response. 5. Use the broker proxy with destination policy and transport security. 6. Refresh, release or revoke according to the concrete client contract. The TypeScript `credentialsFor` facade returns a proxy-oriented handle. That facade is distinct from the broker's full API, which also has wrapped-secret delivery. Do not make a blanket claim that every Arsenal mode can never deliver credential material. Read [ACT format](/arsenal/act-tokens), [broker routes](/arsenal/broker), [policy](/arsenal/policies), [consent](/arsenal/consent), and [audit](/arsenal/audit). The [package catalog](/reference/packages) maps all six Rust packages and the TypeScript surface to exact source versions. # Arsenal policy URL: https://docs.openagent.id/arsenal/policies Markdown: https://docs.openagent.id/arsenal/policies.md Tenant-scoped documents, ordered decisions, and default denial. `arsenal-core::policy` defines `PolicyDocument`, `PolicyRule`, `PolicyCondition`, `ConditionOperator`, `PolicyRequest`, and `PolicyDecision`. `arsenal-policy::PolicyEngine` stores documents and evaluates them against a request. ## Configure and evaluate [#configure-and-evaluate] Create a tenant-scoped policy document, add rules with explicit effects and required conditions/scopes, and install it in the engine. Construct `PolicyRequest` from verified application context, not arbitrary client-provided tenant claims. The engine evaluates policies in descending priority and returns the first decision with a matched rule; no match produces a denial. A policy decision alone does not execute or block a request. The broker/application must branch on it before issuing credentials or proxying an upstream action. ## Serialization and limits [#serialization-and-limits] `PolicyDocument` exposes `to_cbor` and `from_cbor`. Use the actual enum and typed condition fields; do not invent a parallel YAML/JSON grammar based on a policy name. Validate depth, size and supported operators using the current source implementation. Read [exact condition variants and document fields](/reference/rust/arsenal-core/policy) and [the engine API](/reference/rust/arsenal-policy). Test no match, conflicting priorities, wrong tenant, missing context and explicit denial. # AEGIS request verification URL: https://docs.openagent.id/features/aegis Markdown: https://docs.openagent.id/features/aegis.md Verification results, cache behavior, policy and explicit authority. AEGIS resolves and verifies OAS identity documents and exposes policy, key, delegation, authentication and wallet modules. Its high-level SDK combines configured stores and providers. `VerificationPipeline::verify` may return an unexpired cached result. It does not unconditionally bypass cache for every revocation check. Use cache policy and `verify_force_refresh` deliberately when the operation requires fresh evidence, and exercise invalidation in the deployed system. Inspect the typed verification result and warnings under your configured policy. Do not equate one numeric conformance/trust field with permission to perform every privileged action. Authenticated identity, permitted scope, tenant access and authority are separate requirements. Read [the pipeline](/aegis/verification-pipeline), [policy evaluators](/aegis/policies), [delegation](/aegis/delegation), and [the nine-crate source reference](/aegis/overview). # Arsenal capability and credentials URL: https://docs.openagent.id/features/arsenal Markdown: https://docs.openagent.id/features/arsenal.md Connect an agent to provider access through explicit policy and custody. Arsenal provides capability tokens, credential storage, policy evaluation and a broker proxy. The supported source modes include proxy-oriented credentials and wrapped-secret delivery; select the mode appropriate to your custody boundary. A route's required scope belongs to server policy. An incoming token must not choose its own authorization requirement. Configure issuer/audience/key trust and tenant identity before evaluating the requested provider access. The unified TypeScript facade adapts an `ArsenalClient` and exposes a `CredentialHandle`. Handle refresh is explicit and returns a new handle. Broker HTTP endpoints and lifetime defaults belong to the actual broker configuration, not a universal SDK-wide timer. See [the credential workflow](/arsenal/overview), [routes](/arsenal/broker), [ACT format](/arsenal/act-tokens), and [handle lifecycle](/sdk/client/capabilities). Payment signals, consent channels or automatic grants require a separately configured integration; they are not implied by installing the facade. # Authentication protocol URL: https://docs.openagent.id/features/auth-protocol Markdown: https://docs.openagent.id/features/auth-protocol.md Canonical challenge proofs with transport-specific discovery and sessions. Authentication proves possession of the signing key associated with a request. The protocol models challenge, proof, session state and errors; transport adapters decide how those messages are carried. ## Implemented source surfaces [#implemented-source-surfaces] * `openagent-auth-protocol`: shared Rust authentication models and helpers. * HTTP TypeScript/Rust adapters: concrete transport implementation. * WebSocket Rust and Weave adapters: separate source packages with their own interfaces. * Legacy Rust server: middleware and JWT sessions used by the standalone binary. ## Proof workflow [#proof-workflow] Obtain a challenge from the intended server, canonicalize its exact signed representation, sign with the corresponding key, and return the proof with its nonce correlation. The server verifies the cryptographic proof and freshness using its configured trust and storage. Replayed or invalid proofs must be denied. Read [the authentication transport table](/essentials/authentication) before selecting headers. The TypeScript HTTP adapter's proactive well-known endpoints and opaque `OpenAgent` sessions are distinct from the standalone server's Bearer JWT handler contract. An authenticated key is not automatically a human root, a delegated broker grant, or privileged authority. Use [verification policy](/sdk/server/verification) for those decisions. Source declarations and exact options are in the [package catalog](/reference/packages). # Conformance URL: https://docs.openagent.id/features/conformance Markdown: https://docs.openagent.id/features/conformance.md Separate wire-format vectors from source coverage and live integration proof. Conformance is specific to a protocol and implementation revision. The source includes canonical ACT vectors, authentication transport vectors, and separate authority/integration cases. Their existence is not proof that every runner passed for a deployed release. ## What to test [#what-to-test] | Area | Required evidence | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | ACT format | Size and envelope limits, algorithm/version handling, signature verification, time, issuer, audience, scopes, delegation attenuation | | Authentication | Exact challenge canonicalization, nonce correlation/replay/expiry, proof encoding, session expiry and transport scheme | | Authority | Configured `PrivilegedAuthorityVerifier`, trusted lineage anchors, revocation/liveness, tenant policy | | SDK integration | Real provider wiring, supported features, negative/error behavior, language-specific key restoration | | Deployment | Actual ingress, replica-aware session state, secrets, runtime bindings and production policy | ## Source locations [#source-locations] * Canonical token crate and specification: `act/agent-capability-token`, `act/SPECIFICATION.md`. * Shared authentication/vector corpus: `openagent-sdk/conformance`. * Per-language verifier tests and vector runners: `openagent-sdk/sdks/`. * Authority draft vectors: `openagent-sdk/conformance/vectors/openagent/lineage-authority.draft.json`. Draft vectors are design material, not a final interoperability certification. Fixed test counts are intentionally omitted: they drift independently of the protocol contract. ## Release evidence [#release-evidence] Record the revision, enabled features, runtime versions, vector corpus digest, command, pass/fail totals, and skipped cases. Keep source inspection, local sample execution, complete SDK tests, hosted smoke checks, and production certification separate. This documentation migration does not itself rerun every backend or cryptographic test suite. # Deployment adapters URL: https://docs.openagent.id/features/deployment-adapters Markdown: https://docs.openagent.id/features/deployment-adapters.md Source examples for Docker, Lambda, Workers, and Vercel with explicit prerequisites. The SDK repository includes four private source examples under `openagent-sdk/deploy`. They illustrate deployment integration; they are not published managed authentication services. | Example | Source entry and build | | ----------------- | ----------------------------------------------------------------------------------- | | Docker | `deploy/docker/server.ts`; tsup targets Node20 | | AWS Lambda | `deploy/aws-lambda/handler.ts`; SAM deployment configuration | | Cloudflare Worker | `deploy/cloudflare-worker`; Wrangler configuration and Worker entry | | Vercel Edge | `deploy/vercel-edge`; separate Next.js application and middleware/route integration | ## Prepare the deployment [#prepare-the-deployment] 1. Resolve the actual SDK artifacts and required cryptographic bindings. 2. Configure identity/verification/credential providers for the application. 3. Select durable session, nonce, revocation and audit storage where those features are used. 4. Keep server-only filesystem and secret operations outside browser/edge bundles. 5. Verify the request path, denial behavior, origin policy and replica behavior on the target runtime. Node filesystem key helpers cannot run in every edge environment. A fetch-standard wrapper does not prove the whole facade and its dependencies work in browsers, Deno, Bun, Workers and Node without adaptation. Use only capabilities supported by your target and test the resolved build. See [middleware](/sdk/server/middleware), [adapter packages](/integrations/adapters), and [source references](/reference/packages). Deploying these documentation sites to Vercel does not deploy any product authentication or broker service. # OAS identity URL: https://docs.openagent.id/features/oas Markdown: https://docs.openagent.id/features/oas.md DIDs, documents, local proofs and explicitly trusted authority. OAS defines identity primitives for the agent ecosystem: identifier parsing, document construction, cryptography, lineage, resolution and attestations. The current Rust workspace has nine packages, all mapped in [the catalog](/reference/packages). A DID such as `did:oas:example:agent:weather-bot` names an entity. It is not a bearer credential and does not grant access. `agent:instance` is a compound kind; use the actual parser. ## Choose the verification level for the action [#choose-the-verification-level-for-the-action] Use local document/cryptographic checks when that is the required contract. For privileged actions, use the typed authority API with the configured anchor/source and verifier trust policy. Required scope, root, finality, freshness and revocation must be evaluated for the operation. Sigil is the default/reference anchor policy in the current SDK. Other registered backends, such as EAS, are only trusted when your verifier explicitly permits them. A document cannot choose the verifier's trust roots. Read [the OAS SDK](/oas/sdk), [entity kinds](/oas/entity-kinds), [lineage](/oas/lineage), and [anchors](/oas/anchors). # The identity stack URL: https://docs.openagent.id/features/overview Markdown: https://docs.openagent.id/features/overview.md Independent protocol layers and the configuration that joins them. OpenAgentID is a family of independently useful libraries. A small facade connects them, but the providers, trust roots, persistence and policy remain explicit application choices. | Need | Start here | | --------------------------- | --------------------------------------------------- | | Identify an entity | [OAS](/oas/overview) | | Verify a capability | [ACT quickstart](/essentials/quickstart) | | Broker credentials | [Arsenal](/arsenal/overview) | | Verify authority and policy | [AEGIS](/aegis/overview) | | Authenticate a peer | [Transport comparison](/essentials/authentication) | | Govern a skill/tool | [Skills policy](/features/skills-governance) | | Integrate with a framework | [MCP and lifecycle hooks](/integrations/frameworks) | | Choose a runtime | [Six language SDKs](/sdk/overview) | ## Compose deliberately [#compose-deliberately] First identify the action and trust boundary. Choose token verification, identity authentication, or privileged authority verification accordingly. Connect the relevant provider, select its storage and configuration, then exercise success and denial paths. Add credential brokering only where the action needs a provider secret. The source includes six SDK languages with different versions and API coverage. [The catalog](/reference/packages) is the version source of truth for this documentation snapshot. No single facade call proves every underlying subsystem has been provisioned or is live. # Skills governance URL: https://docs.openagent.id/features/skills-governance Markdown: https://docs.openagent.id/features/skills-governance.md Use the concrete policy engine for invocations, consent, limits and audit. The dedicated skills-policy packages live under `openagent-sdk/crates/openagent-skills-policy`. They parse policy/skills manifests and evaluate invocation context. The unified SDK's small `SkillsPolicy` interface is a separate adapter boundary; it does not automatically enable every rule in the dedicated engine. ## Policy dimensions [#policy-dimensions] | Rule | Purpose | | -------------------- | ------------------------------------------- | | Allow/deny | Gate a named skill | | Rate limit | Bound invocation frequency | | Argument constraints | Validate invocation arguments | | Time windows | Restrict permitted time periods | | Consent | Require the configured approval | | Audit level | Select none, hash or full payload recording | ## TypeScript engine [#typescript-engine] The source exports `SkillsPolicy`, `InvocationContext`, `Did`, `SkillsManifest`, typed errors, a rate limiter and audit helpers. For example, this creates an explicit policy and records an invocation under it: ```typescript import { Did, InvocationContext, SkillsPolicy } from '@openagentid/skills-policy'; const policy = SkillsPolicy.fromYaml(` version: 1 agent: did:oas:example:agent:docs-bot skills: read-documentation: allow: true audit_level: hash default: allow: false `); const context = new InvocationContext({ agentDid: Did.parse('did:oas:example:agent:docs-bot'), sessionId: 'local-docs-example', arguments: { path: '/essentials/quickstart' }, }); const receipt = policy.recordInvocation('read-documentation', context); ``` Install this package from the source path in [the catalog](/reference/packages). The example configures policy only; it does not authenticate the DID or invoke a remote tool. The application must ensure the policy decision precedes the actual action and that context comes from authenticated state. ## Audit and enforcement [#audit-and-enforcement] A hash chain can verify linkage relative to retained history. It does not make in-memory receipts durable or prove every invocation was recorded. Configure persistence and redaction. Full argument capture may contain sensitive data; choose it deliberately. See [exact TypeScript policy exports](/reference/typescript/openagent-sdk-crates-openagent-skills-policy-typescript), [Rust policy modules](/reference/rust/openagent-skills-policy), and [framework hooks](/integrations/frameworks). # Wallet integration URL: https://docs.openagent.id/features/wallets Markdown: https://docs.openagent.id/features/wallets.md Identity keys and chain-specific signing require explicit integration. OpenAgentID includes wallet and signing-related primitives. A DID is an identifier, not a universal wallet implementation. Address encoding, key derivation, key custody, transaction serialization, policy and network broadcast are distinct operations. The current AEGIS `AddressDeriver` takes supplied public-key bytes and a chain choice. Returning an encoded address does not prove correct secret-key derivation or transaction signing for that chain. Confirm the required algorithm and validate against the chain's test vectors before funding an address. Key rotation or DID revocation does not automatically freeze assets on unrelated blockchains. Migration of funds and external authority must follow the relevant chain and application policy. See [wallet module boundaries](/aegis/wallet), [threshold signing](/aegis/frost), and [custody differences](/essentials/key-management). These docs do not claim a complete live multichain wallet service. # Architecture URL: https://docs.openagent.id/essentials/architecture Markdown: https://docs.openagent.id/essentials/architecture.md How the SDK, protocol, and provider packages compose. ## Application boundary [#application-boundary] Your application owns the requested action and its required scope, tenant, audience and authority policy. It chooses trusted issuer keys and providers, supplies custody/storage, and prevents execution when verification fails. ## SDK boundary [#sdk-boundary] The six SDKs expose language-specific APIs. TypeScript separates `IdentityProvider`, `ArsenalClient`, `VerificationClient`, and privileged authority verification. Rust separates optional Arsenal/AEGIS integration through Cargo features. Other languages have their own verifier, facade and middleware coverage. ## Protocol packages [#protocol-packages] | Family | Main responsibilities | | ---------------------- | --------------------------------------------------------------- | | OAS | DID/document/crypto/lineage/resolution/attestation | | Canonical ACT | Capability byte format and verification | | Arsenal | Credentials, broker, policy, consent and storage | | AEGIS | Verification, keys, auth, delegation, policy and wallet modules | | Core auth and adapters | Challenge/proof/session models and transport bindings | ## Integration boundary [#integration-boundary] MCP and lifecycle hooks connect authorization to tools. OIDC/SCIM bridges connect enterprise identity flows while requiring real identity/key callbacks. Deployment examples show runtime wiring; they do not provision every required backend or secret. ## Source reference [#source-reference] The [64-package catalog](/reference/packages) gives source versions and installation boundaries. [Rust modules](/reference/rust) and [TypeScript exported symbols](/reference/typescript) expose concrete signatures and options. Source availability, registry publication, deployed service availability and production verification are separate evidence. # Authentication URL: https://docs.openagent.id/essentials/authentication Markdown: https://docs.openagent.id/essentials/authentication.md Distinguish standalone Bearer sessions, HTTP adapter sessions, and ACT authorization. OpenAgentID has separate authentication implementations. Select the implementation deployed by your server and use its exact transport contract. Tokens from one implementation are not automatically valid in another. | Surface | Proof/session representation | Source | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | Standalone Rust server | Signature proof uses `Authorization: OpenAgent .` plus nonce metadata; the `/v1/whoami` handler requires `Authorization: Bearer ` | `openagents/openagent.id/crates/openagent-server/src/layer.rs`, standalone `src/main.rs` | | TypeScript HTTP adapter | Proactive discovery → challenge → proof; opaque sessions are validated by a `SessionStore`, with `Authorization: OpenAgent ` | `openagent-sdk/adapters/http/typescript/src/server.ts`, `headers.ts` | | ACT verification | Signed CBOR capability envelope checked against configured issuer, audience, trusted keys, time, and required scopes | Canonical ACT and each SDK verifier | ## Standalone server [#standalone-server] The standalone binary mounts only `/healthz`, `/livez`, and `/v1/whoami`. A successful middleware proof may set session headers, but the identity handler itself reads a Bearer session. Retain the issued session and use the handler's expected scheme on the subsequent request. ```http Authorization: Bearer ``` The angle-bracket value above is notation, not a usable token. This server does not expose DID creation or remote private-key generation endpoints. ## TypeScript HTTP adapter [#typescript-http-adapter] 1. Read `GET /.well-known/openagent` for discovery. 2. Request `POST /.well-known/openagent/auth` for a challenge. 3. Sign the exact canonical challenge bytes with the agent key. 4. Send `POST /.well-known/openagent/auth/prove` with `signature`, `public_key`, `key_type`, and `nonce`. 5. Use the established session for subsequent requests. The server reconstructs the challenge from its pending state. The application supplies `VerifySignatureFn` and a `SessionStore`. The default in-memory store is scoped to one process and does not coordinate replicas. A production deployment needs a shared, correctly expiring store and a verifier tied to the intended key algorithm and trust policy. `createOpenAgentHandler` currently passes its `serverDid` option into the configuration's `origin` field. Inspect this mapping when integrating; do not assume a separate origin/DID option exists. Low-level `createServerConfig` accepts the origin directly. ## Authentication is not authorization [#authentication-is-not-authorization] Proving key possession identifies a caller. It does not grant arbitrary skills, establish human lineage, or authorize privileged operations. Check scope, tenant, audience, policy, revocation, and configured authority at the action boundary. See [the implemented endpoints](/api-reference/openagent-server), [HTTP adapter reference](/api-reference/http-adapter), and [ACT tokens](/arsenal/act-tokens). # Integration practices URL: https://docs.openagent.id/essentials/best-practices Markdown: https://docs.openagent.id/essentials/best-practices.md Small trust boundaries, explicit provider wiring, and useful failure evidence. ## Start with the action [#start-with-the-action] Decide whether the action needs identity, a capability, privileged authority, a provider credential, or several of these. Verify the required contract at the execution boundary rather than assuming another layer already did it. ## Configure trust explicitly [#configure-trust-explicitly] Keep trusted issuer keys, audience, tenant policy, required scopes, resolver/anchor selection and supported algorithms under server control. A token or document is input to verification, not configuration for the verifier. ## Choose custody for the actual runtime [#choose-custody-for-the-actual-runtime] Use appropriate secret storage and protect recovery material. Seed-file helpers store raw material; managed-language objects do not provide a universal zeroization guarantee. Record the exact key-derivation implementation and dependencies before relying on restoration. See [key management](/essentials/key-management). ## Bound delegated access [#bound-delegated-access] Grant the minimum scope/lifetime needed, enforce parent attenuation, and configure revocation propagation and cache invalidation. Rotation schedules and token TTLs depend on the threat model and implementation; these docs do not prescribe a universal timer. ## Preserve failure distinctions [#preserve-failure-distinctions] Distinguish invalid input, unsupported version, failed signature, expired token, wrong audience/scope, missing provider configuration and unavailable authority evidence. All denial paths must keep the action from executing. Sanitize external errors and never log secrets. ## Verify the actual deployment [#verify-the-actual-deployment] Source review, parser/type checks, local examples, conformance runners and live user journeys prove different things. Record the relevant revision, feature flags, dependencies and results. Run negative cases and replica/restart behavior as well as a successful request. # Core concepts URL: https://docs.openagent.id/essentials/core-concepts Markdown: https://docs.openagent.id/essentials/core-concepts.md Identity, proofs, capabilities, sessions and authority are different contracts. ## Identity [#identity] A DID names an entity. An OAS document describes verification methods and related metadata. Parsing the name or retrieving the document does not establish permission to act. ## Proof [#proof] A signature binds bytes to a key under a specific protocol. Challenge proofs, document proofs and ACT signatures have different signed representations. Use the appropriate canonicalization/byte contract instead of reusing a generic signing example. ## Capability [#capability] An ACT expresses an issuer's scoped grant for a subject, audience, tenant and time window. Verification requires configured trusted keys and action-specific policy. Proof-of-possession, revocation distribution and external budgets require the corresponding calling-protocol integration. ## Session [#session] A session represents bounded authenticated state for a particular server implementation. The standalone Rust server uses JWT sessions; the TypeScript HTTP adapter uses opaque stored sessions. They are not interchangeable by renaming a header. ## Lineage and authority [#lineage-and-authority] Local lineage verifies document/proof relationships. Privileged authority needs the verifier's configured trusted source and required scope/freshness/revocation checks. A document cannot appoint its own trusted authority backend. ## Custody and recovery [#custody-and-recovery] Seeds and keypairs are secret material. The actual SDK algorithm/binding determines what can be restored. Cross-language ACT conformance does not mean cross-language encryption-key equivalence. Continue with [authentication](/essentials/authentication), [ACT format](/arsenal/act-tokens), [lineage](/oas/lineage), and [key management](/essentials/key-management). # DID resolution URL: https://docs.openagent.id/essentials/did-resolution Markdown: https://docs.openagent.id/essentials/did-resolution.md Resolve documents through explicit backends, then verify the trust required by your action. DID parsing, document retrieval, cryptographic verification and authority confirmation are separate contracts. A returned document is not automatically permission to execute an action. ## Current resolver library [#current-resolver-library] `oas-resolve` defines an async `Resolver` trait and utility implementations: * `InMemoryResolver` for explicit local/test documents. * `CachingResolver` for time-bounded cached resolution. * `FallbackResolver` for priority-ordered backends. * `AnchoredResolver` for the configured authority-anchor checks. * `ResolutionMetadata` and typed `ResolveError` results. Concrete HTTP, DHT or blockchain backends must implement the resolver contract; the utility crate does not itself prove a globally deployed resolution network. ## Resolve safely [#resolve-safely] Parse with the actual `OasDid` type, select trusted resolver backends, retrieve the document, validate its structure and proofs, and apply the lineage/revocation/authority policy needed by the operation. For `agent:instance`, the kind has two components; a fixed-count string split is not a DID parser. Identifiers need not all be a multibase public key. Cache invalidation and fallback order are application choices. An unavailable required authority backend should produce a denied/unverifiable operation, not an invented positive result. Inspect typed errors to distinguish a malformed DID, unresolved document, signature failure and unavailable authority evidence. See [resolver modules](/reference/rust/oas-resolve), [AEGIS verification](/aegis/verification-pipeline), and [anchor policy](/oas/anchors). # Common questions URL: https://docs.openagent.id/essentials/faq Markdown: https://docs.openagent.id/essentials/faq.md Concrete answers about source availability, identity, authority and interoperability. ## Which SDKs exist? [#which-sdks-exist] TypeScript, Rust, Python, Go, Swift and Kotlin source implementations are present. Their versions, runtime floors and API coverage differ. Use [the SDK table](/sdk/overview) and [package catalog](/reference/packages). Source manifest names are not proof that a given registry/tag is public. ## Does a DID prove a human is behind an agent? [#does-a-did-prove-a-human-is-behind-an-agent] A DID and a valid signature establish a cryptographic relationship under the relevant verification contract. Personhood, organizational legitimacy and privileged authority require additional assurance and verifier-owned policy. A kind named HMR or MHR is not that proof by itself. ## Can verification work offline? [#can-verification-work-offline] Some local document and token checks can run with all required trusted material available locally. Current privileged authority may need fresh anchor/revocation evidence. An unavailable required source must not be converted into authorization success. ## Are keys portable across the six languages? [#are-keys-portable-across-the-six-languages] Do not assume identical encryption keys from the same seed. The implementations use different derivation paths/algorithms and optional bindings. ACT interoperability is a separate contract. Read [key management](/essentials/key-management). ## Does creating an MHR run a threshold ceremony? [#does-creating-an-mhr-run-a-threshold-ceremony] No. The current `create_mhr` convenience helper creates a single keypair and local document. An actual threshold-backed identity requires the configured key-share ceremony and custody workflow. See [MHR](/services/mhr) and [FROST](/aegis/frost). ## Can I use OAS without Arsenal or AEGIS? [#can-i-use-oas-without-arsenal-or-aegis] Yes, direct OAS primitives can create and verify local identity documents. That does not provision a broker or establish the authority required by a separate privileged service. [OAS SDK](/oas/sdk) describes its independent modules. ## Where is the REST API? [#where-is-the-rest-api] The [standalone server](/api-reference/openagent-server) mounts three routes. The [HTTP adapter](/api-reference/http-adapter) implements three different handshake routes. The [Arsenal broker](/arsenal/broker) is a separate service. There is no universal hosted DID/key CRUD service implied by these libraries. ## How should an agent read these docs? [#how-should-an-agent-read-these-docs] Use [the agent guide](/agents), task-scoped `.md` pages, `/llms.txt`, and the read-only docs MCP endpoint. Never send private keys, seeds or sessions to a documentation search. # Glossary URL: https://docs.openagent.id/essentials/glossary Markdown: https://docs.openagent.id/essentials/glossary.md Terms used consistently across developer and agent documentation. | Term | Meaning | | ---------------- | ------------------------------------------------------------------------------- | | ACT | Agent Capability Token: signed CBOR capability envelope | | AEGIS | Verification, policy, key, authentication, delegation and wallet library family | | Anchor | Backend evidence accepted under the verifier's configured authority policy | | Arsenal | Credential, capability, policy, storage and broker library family | | Authority | Permission established under the required trusted verification contract | | Capability | Bounded grant of an action/scope to a subject and audience | | Conformance | Evidence of behavior against a particular protocol/version and vector set | | DID | Decentralized identifier naming an entity | | ENR | Entity-root kind; governance is separately verified | | HMR | Human-root kind; the label alone does not prove personhood | | MHR | Multi-human-root kind; real threshold control requires an actual ceremony | | IdentityProvider | TypeScript interface for creation, resolution, challenge signing and key lookup | | JCS | JSON Canonicalization Scheme used where the protocol signs canonical JSON | | Lineage | Signed identity relationships evaluated by local and authority verifiers | | Nonce | Challenge correlation/freshness value governed by its store and protocol | | OAS | Open Agent Specification and its identity primitives | | Scope | Parsed `service:resource:action` permission expression | | Session | Implementation-specific bounded authenticated state | | Source snapshot | Checked manifests and declaration hashes, not proof of package publication | | Trust policy | Verifier-owned selection of accepted keys, roots, backends and conditions | See [core concepts](/essentials/core-concepts) for how these contracts fit together. # Identity with explicit authority URL: https://docs.openagent.id/essentials/introduction Markdown: https://docs.openagent.id/essentials/introduction.md Build agents with verifiable identity, scoped capabilities, and configured trust. OpenAgentID brings together identity, authentication, delegated capabilities, credential brokering, and verification. Start with the smallest contract your application needs, then connect the providers required for richer workflows. ![The original Keeper and Witness agents illustrate identity and explicit authority.](/images/family/identity.svg) [Verify a capability](/essentials/quickstart) Run a complete verifier with explicit token, trusted key, issuer, audience, and scope inputs. [Choose your SDK](/sdk/overview) Six languages, with actual source versions and implementation-specific boundaries. [Connect a server](/essentials/authentication) Use the right handshake and session format for your chosen implementation. [Build with an agent](/agents) Use task-scoped Markdown, source manifests, and the read-only documentation MCP service. ## Understand the layers [#understand-the-layers] | Layer | Role | | ------------------------- | ------------------------------------------------------------------------------- | | OAS | DID/document primitives, cryptography, lineage, resolution and attestations | | ACT | Canonical signed capability envelope and verification contract | | Arsenal | Tenant-scoped policy, credential storage, capability issuing and proxy requests | | AEGIS | Verification, policy, keys, delegation, authentication and wallet modules | | Unified SDKs | Language-specific convenience APIs that connect the underlying providers | | Adapters and integrations | Transport, identity bridges, tool/skill hooks and deployment examples | Creating a key or parsing a DID does not establish privileged authority. Configure trusted identity, credential, and authority providers explicitly. Alternative anchors require explicit verifier trust policy; an adapter's existence is not blanket acceptance of every anchor. ## Follow the source [#follow-the-source] The [package catalog](/reference/packages) records versions, features and entry points. The [Rust module reference](/reference/rust) and [TypeScript API reference](/reference/typescript) provide signatures, options and source documentation. The audit records source contracts separately from public registry availability and live service deployment. # Key management URL: https://docs.openagent.id/essentials/key-management Markdown: https://docs.openagent.id/essentials/key-management.md Generation, persistence, recovery boundaries, and implementation-specific derivation. Key material, identity documents, and authorization are separate objects. A seed can restore keys only according to the algorithm and binding used by that SDK. It does not restore a broker grant, an issued session, a revocation decision, or an authority anchor. ## Current SDK behavior [#current-sdk-behavior] | Implementation | Encryption-key derivation and boundary | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | TypeScript | Injected `KeyCryptoBinding`. Uses BLAKE3 context `arsenal.agent.encryption_key`. Deterministic X25519 restoration requires `x25519_public_from_secret`; without it the current fallback generates a new encryption keypair. | | Python | Uses BLAKE3 when available; otherwise HKDF-SHA256. Preserve dependency configuration as part of restoration. | | Go | Uses BLAKE2b in the current key implementation. | | Swift | Uses HMAC-SHA256 in the current key implementation. | | Kotlin | Uses SHA-256 in the current key implementation. | | Rust facade | No public `openagent_sdk::keys` module exists in this snapshot. Use the concrete OAS/Arsenal key and identity APIs required by your integration. | **Do not assume the same seed produces the same encryption identity across languages.** Canonical ACT interoperability is a separate contract. Preserve the implementation, algorithm, dependency versions, and derivation parameters with your recovery procedure. ## Seed files are not encrypted vaults [#seed-files-are-not-encrypted-vaults] TypeScript and Python expose seed-file helpers. The file carries raw seed bytes. A requested owner-only file mode does not add encryption, secure deletion, an HSM, or protection against another process with the same account. Rewriting an existing file may retain its existing permissions; provision the file securely and check effective access. Use a managed secret store or an encrypted key store for your deployment's custody requirements. Do not print the seed, place it in a URL, ship it to the browser bundle, or commit it with source. Keep recovery material separate from application logs and documentation exports. ## Python restoration within one implementation [#python-restoration-within-one-implementation] ```python from pathlib import Path from openagent_sdk import generate, save_seed, from_seed_file seed_path = Path("agent.seed") if seed_path.exists(): raise FileExistsError("Choose a new owner-only seed file") original = generate() save_seed(original, str(seed_path)) restored = from_seed_file(str(seed_path)) assert original.verifying_key == restored.verifying_key ``` The assertion checks the signing public key, not all cross-runtime encryption behavior. Confirm the exact `AgentKeys` fields and helper behavior in the [Python source reference](/sdk/python). ## TypeScript binding prerequisites [#typescript-binding-prerequisites] `setKeyCryptoBinding` accepts Ed25519, X25519, and BLAKE3 functions. The current WASM source exports `x25519_generate_keypair` and `x25519_diffie_hellman`, but not `x25519_public_from_secret`. Therefore that direct binding alone does not provide deterministic encryption-key restoration through the TypeScript facade's fallback. Preserve existing encryption keys using your application's custody system until an appropriate complete binding is supplied and tested. The [TypeScript ACT example](/sdk/typescript) only installs the ACT verification binding; it deliberately does not claim complete key-custody initialization. ## Rotation and recovery [#rotation-and-recovery] Rotation, recovery, and authority changes require the relevant OAS/AEGIS protocol and storage integration. Changing a local seed does not itself rotate a published DID, update a lineage proof, revoke old capabilities, or migrate encrypted material. Plan those operations explicitly and verify old and new trust states before retiring a key. Source: `openagent-sdk/sdks/typescript/src/keys.ts`, Python `keys.py`, Go `openagent/keys.go`, Swift `Keys.swift`, Kotlin `Keys.kt`, and Rust `src/lib.rs`. Memory-zeroization guarantees are implementation-specific; these docs do not promise that managed-runtime values never enter swap or remain inaccessible after use. # Verify your first capability URL: https://docs.openagent.id/essentials/quickstart Markdown: https://docs.openagent.id/essentials/quickstart.md A complete local ACT verification example with explicit issuer, audience, scope, and trusted key inputs. Start at a service boundary: verify an Agent Capability Token before allowing an agent to invoke a tool. Verification needs the exact token bytes, the issuer's trusted Ed25519 public key, an expected issuer and audience, and the scope required by your route. ## Install from your source checkout [#install-from-your-source-checkout] These guides describe the source snapshot listed in the [package catalog](/reference/packages). A manifest name or version does not establish public registry availability. Obtain an authorized checkout of `openagent-sdk` and use the local package path. Source access and dependency downloads are prerequisites. ```bash python3 -m venv .venv . .venv/bin/activate python -m pip install ./openagent-sdk/sdks/python ``` ## Verify a token [#verify-a-token] Save this as `verify_act.py`. The token and public key are binary files from your issuer. The key must be exactly 32 bytes; do not use the issuer's private seed or a PEM-encoded key. No secret is created or printed by this example. ```python title="verify_act.py" import argparse from pathlib import Path from openagent_sdk import Verifier, Scope parser = argparse.ArgumentParser() parser.add_argument("token") parser.add_argument("public_key") parser.add_argument("--issuer", required=True) parser.add_argument("--audience", required=True) parser.add_argument("--scope", required=True) args = parser.parse_args() public_key = Path(args.public_key).read_bytes() if len(public_key) != 32: raise ValueError("Expected a raw 32-byte Ed25519 public key") verifier = Verifier( [public_key], args.issuer, args.audience, required_scopes=[Scope.parse(args.scope)], ) claims = verifier.verify(Path(args.token).read_bytes()) print(claims.sub) ``` ```bash python verify_act.py token.cbor issuer-public.bin \ --issuer arsenal:broker:prod-1 \ --audience calendar-service \ --scope tools:calendar:invoke ``` Supply values configured by your issuer and service. A valid token for another audience must fail. Expired, incorrectly signed, or insufficiently scoped input raises an SDK verification error and exits without granting access. Catch those errors at your HTTP boundary and return a denial; never continue into the tool handler after failure. ## What comes after verification [#what-comes-after-verification] * **Identity creation:** configure an `IdentityProvider`, which implements identity creation, resolution, challenge signing, and public-key lookup. A value returned by `keys.generate()` contains key material; it is not an `IdentityProvider`. * **Credentials:** configure an Arsenal client and tenant-scoped broker trust before requesting provider credentials. * **Privileged authority:** configure a `PrivilegedAuthorityVerifier`. An ordinary DID or claimed ancestor does not establish privileged authority. * **Testing:** the separate testing SDK provides explicit fakes. It is not a production identity or credential service. Read the [TypeScript binding guide](/sdk/typescript), [authentication transport comparison](/essentials/authentication), and [key custody limits](/essentials/key-management) before connecting the full facade. ## Source contract [#source-contract] `openagent-sdk/sdks/python/src/openagent_sdk/act.py`, `scope.py`, and `__init__.py` define this verification interface. The example checks verification only; it does not certify a running broker, deployed server, or cross-language key restoration. # Protocol adapters URL: https://docs.openagent.id/integrations/adapters Markdown: https://docs.openagent.id/integrations/adapters.md HTTP, WebSocket, EAS, and Weave adapters connect different contracts. ## Select the transport or anchor you need [#select-the-transport-or-anchor-you-need] | Adapter | Source | Responsibility | | --------------- | ---------------------------------------- | -------------------------------------------------------------- | | HTTP TypeScript | `openagent-sdk/adapters/http/typescript` | Discovery, challenge, proof, sessions and middleware | | HTTP Rust | `openagent-sdk/adapters/http/rust` | Rust HTTP protocol binding | | WebSocket Rust | `openagent-sdk/adapters/websocket/rust` | Message transport binding for the authentication protocol | | Weave Rust | `openagent-sdk/adapters/weave` | Protocol integration with Weave transport/data primitives | | EAS TypeScript | `openagent-sdk/adapters/eas/typescript` | EAS anchor integration, separate from authentication transport | ## Integration workflow [#integration-workflow] 1. Match the peer's protocol and adapter version. 2. Configure the exact origin, identity/key provider, supported algorithm and transport. 3. Implement persistence and nonce/session lifetime appropriate to that transport. 4. Carry verified identity into application policy; do not treat an established channel as unrestricted authority. 5. Test disconnect/reconnect, replay, expiry and peer mismatch at the actual transport boundary. An adapter in source does not imply that a public server has enabled it. HTTP examples cannot be reused as WebSocket frame definitions. EAS is an authority-anchor option only when the verifier's trust policy explicitly accepts the chosen chain/contract and evidence. Each adapter has a dedicated [source package reference](/reference/packages). The [HTTP API guide](/api-reference/http-adapter) documents the concrete TypeScript route contract. # OIDC and SCIM bridges URL: https://docs.openagent.id/integrations/bridges Markdown: https://docs.openagent.id/integrations/bridges.md Connect external identity systems while supplying required production identity hooks. OIDC and SCIM bridge implementations live under `openagent-sdk/bridges`, with separate Rust and TypeScript packages. They connect enterprise identity/provisioning concepts to OpenAgent identity APIs; they do not automatically establish a trusted issuer or production signing authority. ## OIDC integration [#oidc-integration] Start with the provider's issuer, audience, key-discovery, nonce/state, and token-validation contract. Map validated external claims into the intended OAS entity/tenant policy. The TypeScript `mapping.ts` source explicitly defers production identity key creation; supply the real identity/signing hook before using it for authority-bearing identities. ## SCIM integration [#scim-integration] Map provisioning and deprovisioning to the application's tenant/account lifecycle. The TypeScript provisioner contains an identity-generation boundary that must be connected to production keys. Do not treat a created local record or deterministic placeholder as cryptographic proof of identity. ## Integration sequence [#integration-sequence] 1. Pin the bridge and external-provider configuration. 2. Implement the required identity/key callbacks with the correct tenant boundary. 3. Validate inbound assertions before mapping identity fields. 4. Exercise disabled users, revoked access, missing claims, duplicate external IDs, and key rotation. 5. Verify resulting OAS/authority state through the actual configured verifier. See the [library catalog](/reference/packages) for source paths, manifests, and public entry points. Bridge scaffolding and protocol model coverage are not claims of a hosted enterprise provider. # Framework integrations URL: https://docs.openagent.id/integrations/frameworks Markdown: https://docs.openagent.id/integrations/frameworks.md MCP, Claude Agent SDK hooks, and project scaffolding with explicit policy configuration. ## MCP tools [#mcp-tools] `@openagentid/mcp` exports `withOpenAgent`, `withOpenAgentClient`, `buildIdentityMeta`, skills-policy helpers, and typed authentication/authorization errors. Configure an identity verifier, expected tool scopes, and the application's policy hooks. Identity metadata from a client is untrusted until verified. The wrapper operates on the package's `McpServerLike`/`McpClientLike` contract. Match the actual MCP SDK version and handler API you deploy. Test anonymous calls, missing identity, failed verification, denied scope, and denied skills policy. The documentation MCP endpoint is a separate read-only service and is not this runtime authentication integration. ## Claude Agent SDK hooks [#claude-agent-sdk-hooks] `@openagentid/claude-agent` exports `openAgentPlugin`, lifecycle/tool/skill hook functions, capability and skills-policy implementations, and audit-chain utilities. Connect `preToolUse` and skill decisions before execution and `postToolUse` after the result. A recorded audit event does not retroactively prevent an unauthorized tool call. Use the package's plugin/hook types to bridge the exact host SDK version. The package's source interface is the reference; do not assume that any arbitrary object in a host's `plugins` array has equivalent behavior. Configure real identity/capability providers and a durable audit sink where required. ## Scaffold and test tooling [#scaffold-and-test-tooling] `packages/create-openagent` produces project scaffolding. Inspect its templates and generated configuration before treating a project as runnable. The separate testing SDK and conformance runners supply explicit fixtures and tests; they are not production identity providers. All integration package manifests, exported entry points, errors and supported source paths are listed in [the catalog](/reference/packages). Pair them with [skills policy](/features/skills-governance), [ACT verification](/essentials/quickstart), and [authority verification](/sdk/server/verification). # Authority anchors URL: https://docs.openagent.id/oas/anchors Markdown: https://docs.openagent.id/oas/anchors.md Verifier-controlled backend selection and explicit finality/revocation evidence. `oas-resolve::LineageAnchor` is the backend seam for authority evidence. The SDK's anchor-policy module is gated by the `resolve` feature. Documents may name anchor references; the verifier chooses which schemes it trusts. ## Configure the policy [#configure-the-policy] `AnchorPolicy::default()` trusts Sigil. `AnchorPolicy::sigil_then_eas()` prefers Sigil and permits EAS fallback. `AnchorPolicy::trusting` accepts an explicit ordered nonempty scheme list. Register the corresponding backend implementations in `AnchorBackends`. `VerifyWithAnchorRequest` carries the policy, available backends, expected authority-path kind, required scopes and an optional minimum finalized block. These are verifier-controlled values, not privileges supplied by the document itself. ## Confirmation flow [#confirmation-flow] The configured source checks relevant revocation, root-anchor presence, status and finality before confirming authority. An unsupported or missing backend cannot confirm trust. If no trusted backend confirms the required authority, the privileged operation must fail closed. A syntax-valid anchor reference is not inclusion/finality evidence. An adapter in source does not establish a live configured backend or make every foreign chain trusted. Inspect metadata commitments and other requirements of the actual implementation. ## Backends [#backends] Sigil is the reference/default policy. `oas-anchor-eas` and the TypeScript EAS adapter supply a separate implementation seam. Configure chain, contract, endpoint and finality policy and verify the deployment before using it as authority. Read [anchor policy arguments and results](/reference/rust/oas-sdk/anchor_policy), [anchored resolver types](/reference/rust/oas-resolve/anchored), and [EAS source modules](/reference/rust/oas-anchor-eas). Local lineage checks remain [a separate step](/oas/lineage). # Cryptographic primitives URL: https://docs.openagent.id/oas/cryptography Markdown: https://docs.openagent.id/oas/cryptography.md Use the exact protocol representation, key algorithm, and binding. OAS and its supporting crypto crates expose Ed25519 signing, hashing, derivation, canonicalization, encoding and threshold primitives. Their presence does not mean every SDK uses the same key-derivation algorithm or exposes every operation. ## Select the correct contract [#select-the-correct-contract] * OAS document/challenge protocols use their specified canonical JSON representation and proof binding. * ACT signs the original CBOR claim bytes, not a re-encoded JSON or CBOR object. * Encryption-key derivation depends on the exact SDK/binding; [cross-language custody differs](/essentials/key-management). * Threshold shares and signing ceremonies depend on the resolved FROST version and custody configuration. ## Source references [#source-references] [OAS crypto modules](/reference/rust/oas-crypto) describe identity primitives. [Shared crypto-WASM modules](/reference/rust/openagent-crypto-wasm) expose native and feature-gated WASM declarations. The [TypeScript guide](/sdk/typescript) builds and connects the real ACT binding. Use published vectors and meaningful negative tests for the exact primitive/version you deploy. Do not infer broad constant-time, secure-memory or side-channel guarantees from a package name or a managed-runtime wrapper. Review the actual implementation and deployment boundary. # The did:oas identifier URL: https://docs.openagent.id/oas/did-method Markdown: https://docs.openagent.id/oas/did-method.md Use the actual parser for namespaces, kind variants, and identifiers. The typical form is `did:oas:::`. `agent:instance` is a compound kind and uses another colon-separated component. Identifiers need not be public-key multibase strings; source examples also use names such as `alice`. ```rust use oas_did::OasDid; use std::str::FromStr; let did = OasDid::from_str("did:oas:example:agent:weather-bot"); assert!(did.is_ok()); ``` Use `OasDid` and `EntityKind` rather than a fixed-length string split. The parser validates syntax; it does not retrieve a document or authorize an action. ## From identifier to trust [#from-identifier-to-trust] Retrieve the document through your configured resolver, validate its structure and proofs, then evaluate the relevant lineage/authority policy. Creating, updating or deactivating a document requires the concrete provider and storage contract. These operations are not generic `/v1/dids` routes on the standalone server. See [DID parser signatures](/reference/rust/oas-did/did), [kind variants](/oas/entity-kinds), [resolution](/essentials/did-resolution), and [the actual HTTP APIs](/api-reference/introduction). # Entity kinds URL: https://docs.openagent.id/oas/entity-kinds Markdown: https://docs.openagent.id/oas/entity-kinds.md The twelve current kind variants describe entities, not standalone authorization. The current `oas-did/src/kind.rs` enum defines twelve kinds: | Kind | Role | | ---------------- | ----------------------- | | `hmr` | Human root | | `mhr` | Multi-human root | | `enr` | Entity root | | `ao` | Autonomous organization | | `agent` | Agent | | `agent:instance` | Specific agent instance | | `tool` | Callable tool | | `skill` | Declared skill | | `workflow` | Procedure/workflow | | `model` | Model | | `dataset` | Dataset | | `service` | Service | `EntityKind::is_root()` recognizes HMR, MHR and ENR as root kinds in the identifier model. A parser/root-kind classification does not establish a valid governance or authority path. Parent relationships and privileged authority must be evaluated through the lineage and verifier contracts. The `agent:instance` kind occupies two colon-separated kind components; use `OasDid` parsing rather than splitting every DID into a fixed number of segments. See [the kind module](/reference/rust/oas-did/kind), [lineage](/oas/lineage), and [authority anchors](/oas/anchors). # Lineage and authority URL: https://docs.openagent.id/oas/lineage Markdown: https://docs.openagent.id/oas/lineage.md Local proof-chain verification and privileged authority use distinct typed contracts. Lineage binds a child identity to a parent through signed document evidence. A structurally valid chain is not sufficient to establish current privileged authority. ## Source APIs [#source-apis] * `oas_sdk::lineage::derive_child` constructs a child identity from the parent key/document and derivation inputs. * `verify_chain` performs local chain verification. * `verify_privileged_authority` evaluates a typed authority request through `LineageAuthoritySource`. * `oas-lineage` provides proof, verification and document-provider primitives. Use the actual returned types and source signatures rather than inventing language-equivalent APIs. The six unified SDKs do not all expose identical lineage methods. ## Verify the action [#verify-the-action] 1. Resolve the relevant signed documents using trusted providers. 2. Verify parent/child key and proof bindings and chain consistency. 3. Establish the intended root and authority path under verifier-owned policy. 4. Check required scope, finality/freshness and revocation evidence through the configured authority source. 5. Deny privileged actions when the necessary evidence is missing, stale or unavailable. Never recompute a child's secret key from a parent public key. Never authorize from a shape-only structural precheck or unverified embedded key. Personhood and organizational legitimacy remain separate assurance claims. See [lineage signatures and result types](/reference/rust/oas-sdk/lineage), [lower-level chain verification](/reference/rust/oas-lineage), and [anchor policy](/oas/anchors). # Open Agent Specification URL: https://docs.openagent.id/oas/overview Markdown: https://docs.openagent.id/oas/overview.md Nine Rust packages for identity primitives and explicit authority integration. OAS provides DID syntax, document construction, cryptography, lineage, resolution and attestations. The current workspace contains nine packages: | Package | Role | | ----------------- | --------------------------------------------------------------------------- | | `oas-did` | Identifier parsing and the twelve entity-kind variants | | `oas-document` | Document structure, builders, verification methods and conformance metadata | | `oas-crypto` | Identity cryptographic primitives | | `oas-lineage` | Proof, chain verification and document-provider primitives | | `oas-resolve` | Resolver trait, cache/fallback and anchored resolution | | `oas-attestation` | Credential/attestation primitives | | `oas-sdk` | High-level identity, lineage and attestation workflows | | `oas-wasm` | WebAssembly-facing bindings | | `oas-anchor-eas` | EAS authority-anchor adapter | The workspace manifest version is 1.1.1. A consumer may pin a different dependency release; the [source catalog](/reference/packages) records this snapshot independently of registry availability. Start with [the OAS SDK](/oas/sdk), [DID parsing](/oas/did-method), [lineage](/oas/lineage) and [anchor policy](/oas/anchors). Valid local identity is distinct from authorization of a privileged operation. # OAS SDK URL: https://docs.openagent.id/oas/sdk Markdown: https://docs.openagent.id/oas/sdk.md Direct identity, lineage, attestation and resolution APIs. `oas-sdk` wraps the OAS Rust primitives. The current OAS workspace manifest is **1.1.1**; consumers may pin earlier dependencies, so inspect the resolved version for your application. ```toml [dependencies] oas-sdk = { path = "../oas/oas/oas-sdk" } ``` The relative path is from your application's manifest to an authorized source checkout. It is not a registry publication claim. ## Modules [#modules] | Module | Responsibility | | -------------------------- | ------------------------------------------------------------------------------ | | `identity` | `create_hmr`, `create_mhr`, and root creation with a supplied keypair | | `lineage` | Child derivation, local chain verification, and privileged authority contracts | | `attestation` | Credential creation, signing and verification | | `config`, `error` | Configuration and unified errors | | `anchor_policy`, `resolve` | Resolver-related surfaces gated by the `resolve` feature | The SDK re-exports lower-level crypto, DID, document, lineage and attestation crates. Local document/lineage validation is distinct from `verify_privileged_authority` and its configured authority source. See [exact module signatures](/reference/rust/oas-sdk) and [the OAS package catalog](/reference/packages). # Go SDK URL: https://docs.openagent.id/sdk/go Markdown: https://docs.openagent.id/sdk/go.md Local module integration, explicit scope requirements, and net/http middleware. The source module is `github.com/OpenAgentID/openagent-sdk-go`, requiring Go **1.26.4** in its current `go.mod`. Import the `openagent` subpackage. For a local source integration, use a replace directive in your application's module: ```go title="go.mod fragment" replace github.com/OpenAgentID/openagent-sdk-go => ../openagent-sdk/sdks/go ``` Resolve dependencies from your application using its chosen versioning policy. The local replacement is a source-development mechanism, not proof of a remotely published tag. ## Verify with a required scope [#verify-with-a-required-scope] ```go package verification import "github.com/OpenAgentID/openagent-sdk-go/openagent" func VerifyCalendar(token, publicKey []byte, issuer, audience string) (*openagent.ActClaims, error) { verifier, err := openagent.NewVerifier([][]byte{publicKey}, issuer, audience) if err != nil { return nil, err } scope, err := openagent.ParseScope("tools:calendar:invoke") if err != nil { return nil, err } return verifier.RequiringScopes(scope).Verify(token) } ``` The token is binary CBOR and the trusted public key is raw 32-byte Ed25519. Propagate every verification error as denial. `DecodeUnverified` is an inspection helper; use `Verify` for authorization. ## HTTP integration [#http-integration] `RequireAct(verifier, scopes...)` wraps an `http.Handler`. `RequireActFunc` wraps an `http.HandlerFunc`. `ClaimsFromRequest` reads verified claims after the middleware succeeds. Configure issuer/audience/scopes at the route boundary and keep your trusted key set outside user input. ## Key custody [#key-custody] Current Go custody uses BLAKE2b, so do not assume matching encryption keys when importing a seed from another language. See [key management](/essentials/key-management). Source: `openagent-sdk/sdks/go/go.mod`, `openagent/act.go`, `scope.go`, `middleware.go`, and `keys.go`. # Kotlin SDK URL: https://docs.openagent.id/sdk/kotlin Markdown: https://docs.openagent.id/sdk/kotlin.md JVM17 integration with the actual verifier, scope and Ktor APIs. The Kotlin source uses plugin **2.1.0**, JVM toolchain **17**, group `id.openagent`, and version **0.1.0**. Its package namespace is `id.openagent.sdk`. For a local multi-project build, add the source project explicitly rather than assuming a Maven artifact exists: ```kotlin title="settings.gradle.kts" include(":openagent-sdk") project(":openagent-sdk").projectDir = file("../openagent-sdk/sdks/kotlin") ``` ```kotlin title="application build.gradle.kts" dependencies { implementation(project(":openagent-sdk")) } ``` Resolve a compatible Kotlin/Gradle/JVM toolchain and the declared dependencies before compiling. Public Maven availability must be checked for the version you intend to consume. ## Verify with explicit policy [#verify-with-explicit-policy] ```kotlin import id.openagent.sdk.Act import id.openagent.sdk.Scope fun verifyCalendar( token: ByteArray, publicKey: ByteArray, issuer: String, audience: String, ): Act.Claims { val verifier = Act.Verifier( trustedKeys = listOf(publicKey), expectedIssuer = issuer, expectedAudience = audience, requiredScopes = listOf(Scope.parse("tools:calendar:invoke")), ) return verifier.verify(token) } ``` Construction rejects invalid key/configuration input. Verification rejects malformed or unauthorized tokens. Keep exceptions on the denial path. Do not authorize using a decoded envelope before verification. ## Available modules [#available-modules] `Act.kt` provides token verification, `Scope.kt` scope parsing, `Keys.kt` custody, `Ktor.kt` the Ktor integration, `Errors.kt` failures, and `Cbor.kt` the local decoder. The build declares Ktor3 and Bouncy Castle dependencies; this package is JVM-specific in the current source, not a Kotlin Multiplatform artifact. Kotlin encryption-key derivation currently uses SHA-256. Read [the custody limits](/essentials/key-management) before moving seeds from another SDK. Source: `openagent-sdk/sdks/kotlin/build.gradle.kts` and `src/main/kotlin/id/openagent/sdk`. # SDKs URL: https://docs.openagent.id/sdk/overview Markdown: https://docs.openagent.id/sdk/overview.md Six language implementations with explicit source and interoperability boundaries. Choose the runtime you deploy. The six implementations share an ACT wire-format target, but they do not have identical facade coverage, key derivation, dependencies, or deployment support. | Language | Source package | Starting point | | ---------- | ---------------------------------------------------- | --------------------------------------------------------- | | TypeScript | `@openagentid/sdk` 0.1.1; Node >=20 | [WASM-backed verification and providers](/sdk/typescript) | | Rust | `openagent-sdk` 0.1.0; edition 2021 | [Features and component integration](/sdk/rust) | | Python | `openagentid-sdk` 0.1.0; Python >=3.10 | [Complete verifier example](/sdk/python) | | Go | `github.com/OpenAgentID/openagent-sdk-go`; Go 1.26.4 | [Verifier and net/http integration](/sdk/go) | | Swift | `OpenAgentSDK`; Swift tools 6.0 | [Local Swift package integration](/sdk/swift) | | Kotlin | `id.openagent`, version 0.1.0; JVM17 | [Gradle source integration](/sdk/kotlin) | These are source manifest facts, not a registry publication claim. The [package catalog](/reference/packages) records the checked manifests, features, and exported entry points for every scoped package. ## Identity, verification, and authority [#identity-verification-and-authority] ACT verification can be integrated independently of a full identity provider. Identity creation needs the correct provider contract. Broker credentials need tenant policy and a configured broker. Privileged operations need a configured authority verifier. Choose only the capabilities your service needs. ## Interoperability boundaries [#interoperability-boundaries] Run the relevant canonical ACT vectors against the exact implementations and versions you deploy. A set of passing token vectors does not prove encryption-key portability, session-token interchangeability, live anchor availability, or end-to-end authorization across six SDKs. The [conformance guide](/features/conformance) separates those tests. ## Find the right integration [#find-the-right-integration] **TypeScript** Use the Node WASM ACT verifier and explicitly configured provider interfaces. [Binding and SDK guide](/sdk/typescript) . **Rust** Select Cargo features for the exact OAS, Arsenal and AEGIS integration. [Feature and source guide](/sdk/rust) . **Python** Start with a complete CLI verifier and typed errors. [Python guide](/sdk/python) . **Go** Use the verifier and net/http middleware with explicit scope policy. [Go guide](/sdk/go) . **Swift** Integrate the actual Swift 6 package root. [Swift guide](/sdk/swift) . **Kotlin** Use JVM17 and the source Gradle module, with Ktor integration as needed. [Kotlin guide](/sdk/kotlin) . # Python SDK URL: https://docs.openagent.id/sdk/python Markdown: https://docs.openagent.id/sdk/python.md Local installation, ACT verification, optional middleware, and custody behavior. The source distribution is `openagentid-sdk` **0.1.0**, imported as `openagent_sdk`, requiring Python **3.10 or later**. Its core dependencies are `cbor2` and `cryptography`; FastAPI is an optional integration. ```bash python -m pip install ./openagent-sdk/sdks/python # Optional framework dependencies: python -m pip install './openagent-sdk/sdks/python[fastapi]' ``` The [quickstart](/essentials/quickstart) is a complete command-line verification program with binary token/key inputs. `Verifier` accepts trusted public keys, issuer, audience, required `Scope` values, and optional timing policy. `verify()` returns verified `ActClaims` or raises a typed error. `decode_unverified()` is inspection only and must never authorize an action. ## Modules [#modules] | Module | Public responsibilities | | ------------ | ------------------------------------------------------------------------------ | | `act` | Envelope/claims, verification, builder, size/version/algorithm constants | | `scope` | Three-segment scope parsing and matching | | `keys` | Generate/restore seed-derived keys, file/environment helpers | | `agent` | Agent and session facade | | `middleware` | FastAPI dependency and Starlette middleware factory | | `errors` | Configuration, encoding, signature, time, audience, issuer, and scope failures | ## Framework boundary [#framework-boundary] `require_act(verifier, scopes=...)` returns a dependency callable; `require_act_starlette` returns a middleware class. Wire the returned dependency using your framework's actual dependency API and request typing. Inspect and exercise the integration before exposing a route. A verifier object by itself does not attach middleware or deny requests. ## Key restoration [#key-restoration] The Python implementation takes a BLAKE3 branch when that module is importable and an HKDF-SHA256 fallback otherwise. Its BLAKE3 call shape must match the installed binding. Changing optional dependencies can change or break encryption-key derivation. Preserve your tested environment and use [the custody checklist](/essentials/key-management). This is independent of ACT token interoperability. Source: `openagent-sdk/sdks/python/pyproject.toml`, `src/openagent_sdk/__init__.py`, and the modules listed above. See [package references](/reference/packages) for the source manifest and exported declarations. # Rust SDK URL: https://docs.openagent.id/sdk/rust Markdown: https://docs.openagent.id/sdk/rust.md Source installation, actual exports, and optional subsystem features. The `openagent-sdk` Rust facade is **0.1.0**, edition 2021, with a manifest Rust floor of **1.78**. Some transitive components require a newer compiler; use the greatest requirement in your resolved dependency set. ```toml title="Cargo.toml" [dependencies] openagent-sdk = { path = "../openagent-sdk/sdks/rust" } ``` The facade manifest currently refers to sibling OAS, ACT, Arsenal, and AEGIS repositories using Git dependencies. Source access to those repositories is still required by a local path install. Review/pin the resolved revisions for your release; a source manifest version is not evidence of a published facade artifact. ## Choose features deliberately [#choose-features-deliberately] | Feature | Behavior | | --------- | ----------------------------------------------------------------------------------------------------- | | default | Empty feature set; identity, ACT, configuration, builder, errors, and skills modules remain available | | `arsenal` | Credential module and Arsenal client dependencies | | `aegis` | Verification module and AEGIS client dependencies | | `axum` | Optional Axum integration dependency | | `full` | Enables `aegis`, `arsenal`, and `axum` | ## Public facade [#public-facade] The crate re-exports `OpenAgent`, `CreateAgentOptions`, `OpenAgentBuilder`, `OpenAgentConfig`, `BrokerMtlsConfig`, `AgentIdentityRecord`, `ParsedDid`, `AllowListPolicy`, `SkillsPolicy`, `SkillsPolicyHandle`, `OpenAgentError`, and `Result`. Feature-gated exports include credential and verification clients. The `sync::create_agent` helper creates a Tokio runtime for blocking callers. `act` exposes the canonical ACT verification path. Configure the expected issuer, audience, trusted signing keys, and required scopes before accepting a token. See the [ACT contract](/arsenal/act-tokens) and source declarations in the [library catalog](/reference/packages). ## Integration boundaries [#integration-boundaries] Use `OpenAgentBuilder` to attach the concrete broker client, verifier, and skills policy needed by the application. A basic local identity object does not prove authority lineage or provision a live broker. Feature-disabled services must not be assumed available. There is **no** `openagent_sdk::keys` module in this source version. Key and identity custody belong to the concrete OAS/Arsenal APIs you configure. See [key management](/essentials/key-management). Source: `openagent-sdk/sdks/rust/Cargo.toml`, `src/lib.rs`, `src/act.rs`, `src/builder.rs`, and `src/identity.rs`. # Swift SDK URL: https://docs.openagent.id/sdk/swift Markdown: https://docs.openagent.id/sdk/swift.md Swift 6 source integration and explicit ACT verification policy. The source package exposes the `OpenAgentSDK` SwiftPM product and uses Swift tools **6.0**. Platform declarations are macOS14, iOS17, Mac Catalyst17, tvOS17, and watchOS10. Cryptography uses the `swift-crypto` dependency. The verified package root is `openagent-sdk/sdks/swift`, not the monorepo root. From a neighboring application use a local SwiftPM dependency: ```swift title="Package.swift dependency" .package(path: "../openagent-sdk/sdks/swift") ``` Add the `OpenAgentSDK` product to your target dependencies. A remote package URL/tag must point to a repository root with a compatible `Package.swift`; do not assume the monorepo root is that package. ## Verify an ACT [#verify-an-act] ```swift import OpenAgentSDK func verifyCalendar( token: [UInt8], publicKey: [UInt8], issuer: String, audience: String ) throws -> ACT.Claims { let verifier = try ACT.Verifier( trustedKeys: [publicKey], expectedIssuer: issuer, expectedAudience: audience, requiredScopes: [try Scope.parse("tools:calendar:invoke")] ) return try verifier.verify(token) } ``` Use exact binary token bytes and a raw 32-byte key. Construction and verification can throw; a caller must not proceed after an error. The verifier provides clock/leeway controls for tests and replay analysis. ## Other surfaces [#other-surfaces] `Agent` and `Session` provide the identity/authentication facade; `Keys` provides key helpers; `Scope` models required permissions. Those conveniences do not provision a broker or authority verifier for your deployment. Swift encryption-key derivation uses HMAC-SHA256 in the current source. [Cross-language custody is not interchangeable](/essentials/key-management). ACT conformance must be recorded separately for the implementation revision you ship. Source: `openagent-sdk/sdks/swift/Package.swift` and `Sources/OpenAgentSDK/{ACT,Scope,Agent,Keys}.swift`. # TypeScript SDK URL: https://docs.openagent.id/sdk/typescript Markdown: https://docs.openagent.id/sdk/typescript.md ACT verification with a concrete WASM binding and explicit provider configuration. The source package is `@openagentid/sdk` version **0.1.1**, with Node.js **20 or later**. Install from an authorized source checkout until the intended registry/version has been independently confirmed. ```bash npm --prefix openagent-sdk/sdks/typescript install npm --prefix openagent-sdk/sdks/typescript run build npm install ./openagent-sdk/sdks/typescript ``` ## Build the actual ACT binding [#build-the-actual-act-binding] The SDK requires the `act_verify` WASM export. From the crypto crate directory, with Rust, the wasm32 target, and wasm-pack installed: ```bash cd openagent-sdk/crates/openagent-crypto-wasm wasm-pack build --target nodejs --out-dir pkg-node -- \ --no-default-features --features wasm ``` The generated Node package initializes synchronously when required. This source-build recipe does not require a fictional `cryptoWasmInit()` helper. ```typescript title="verify.ts" import { createRequire } from 'node:module'; import { readFile } from 'node:fs/promises'; import { act, setActCryptoBinding } from '@openagentid/sdk'; const require = createRequire(import.meta.url); const cryptoModule = require( './openagent-sdk/crates/openagent-crypto-wasm/pkg-node/openagent_crypto_wasm.js', ); setActCryptoBinding(cryptoModule); const [tokenPath, publicKeyPath, issuer, audience, scope] = process.argv.slice(2); if (!tokenPath || !publicKeyPath || !issuer || !audience || !scope) { throw new Error('Usage: verify.ts TOKEN PUBLIC_KEY ISSUER AUDIENCE SCOPE'); } const claims = await act.verify(new Uint8Array(await readFile(tokenPath))) .issuer(issuer) .forAudience(audience) .requireScope(scope) .trustedKeys([new Uint8Array(await readFile(publicKeyPath))]) .run(); console.log(claims.sub); ``` Place this file in a directory containing your `openagent-sdk` checkout, or adjust the local binding path to the generated file. The verifier requires binary CBOR token bytes and a raw 32-byte Ed25519 public key. Compilation and binding initialization are prerequisites; the docs do not silently replace them with a mock. ## Configure identity separately [#configure-identity-separately] `OpenAgent.configure({ clients })` accepts independently configured identity, credentials, and verification clients. `IdentityProvider` has four methods: ```typescript interface IdentityProvider { createAgentIdentity(input: CreateAgentInput): Promise; resolve(did: Did): Promise; signChallenge(did: Did, challenge: Uint8Array): Promise; publicKey(did: Did): Promise; } ``` These names are exported SDK types. The declaration above explains the contract; implement or adapt a real provider before calling `OpenAgent.createAgent`. `keys.generate()` returns `AgentKeys`, which does not implement these methods. The adapter `toIdentityProvider` checks method presence; it does not certify cryptographic correctness. ## Route protection [#route-protection] `withAct` wraps a fetch-standard handler. `requireActExpress` validates requests before Express-style handlers. Configure issuer, audience, keys, and required scopes for the specific route. Never authorize from decoded but unverified claims. ## Key custody and limitations [#key-custody-and-limitations] ACT setup and key-custody setup are separate. Read [key management](/essentials/key-management) before installing `setKeyCryptoBinding`; the current facade can fall back to newly generated encryption keys when the binding lacks deterministic X25519 public-key derivation. For source versions, subpath exports, modules, and dependency boundaries, use [the package catalog](/reference/packages). Test doubles live in `@openagentid/sdk-testing` and must be chosen explicitly. # Entity roots URL: https://docs.openagent.id/services/enr Markdown: https://docs.openagent.id/services/enr.md Organization-shaped identifiers and explicit governance verification. ENR denotes an entity root in the OAS kind model. An organization-shaped identifier does not by itself prove governance, parent authority, or permission to create descendants. ## Integration workflow [#integration-workflow] Construct the document using the intended key/governance model, bind the relevant authority evidence, persist/publish it through your chosen resolver/anchor, and verify the typed authority path before authorizing descendants or organization actions. `EntityKind::is_root` classifies ENR as a root kind. Parent/governance requirements belong to the lineage and authority contract rather than a static table that treats every ENR as a single fixed parent relationship. Read [entity kinds](/oas/entity-kinds), [document fields](/reference/rust/oas-document), [lineage APIs](/reference/rust/oas-sdk/lineage), and [anchor policy](/oas/anchors). Missing or unverifiable governance must not become a privileged authorization success. # Human roots URL: https://docs.openagent.id/services/hmr Markdown: https://docs.openagent.id/services/hmr.md Create a local HMR document and separately establish trusted authority. An HMR is the human-root kind in OAS. `oas_sdk::identity::create_hmr(namespace, identifier, created)` creates a keypair and a signed local document; the caller is responsible for custody. ## Local creation [#local-creation] ```rust use oas_sdk::identity::create_hmr; fn create_local_root() -> Result { let identity = create_hmr("example", "alice", "2026-09-14T00:00:00Z")?; Ok(identity.document.id) } ``` This example demonstrates document creation, not persistent custody or production root registration. The timestamp is example metadata. A real application must securely retain the generated key and follow its configured document/authority publication workflow. A kind label and valid self-signature do not prove personhood, unique humanity, KYC status, or privileged authority. Those claims require the appropriate external assurance and verifier-owned trust policy. Recovery is a separate keys/ceremony integration; this API does not implement a universal one-attempt-per-day social recovery service. See [identity API](/reference/rust/oas-sdk/identity), [lineage](/oas/lineage), and [anchor policy](/oas/anchors). # Multi-human roots URL: https://docs.openagent.id/services/mhr Markdown: https://docs.openagent.id/services/mhr.md Separate an MHR identifier from an actual threshold signing ceremony. MHR denotes a multi-human-root entity. The current `oas_sdk::identity::create_mhr` helper generates a single Ed25519 keypair and signed L0 document. Calling it does **not** execute a distributed key-generation ceremony or prove control by multiple people. ## Build a threshold-backed root [#build-a-threshold-backed-root] Choose the threshold library/version, coordinate the actual share-generation and signing ceremony, retain participant custody and recovery policy, and publish the document and authority records appropriate to that configuration. Verify that the group's signing key and document verification method agree. The identity, key and ceremony modules are separate. Use [OAS identity signatures](/reference/rust/oas-sdk/identity) and [AEGIS threshold APIs](/reference/rust/aegis-keys/threshold), with the [FROST version/custody guide](/aegis/frost). Threshold signatures prove that the configured key-share quorum participated. They do not independently establish unique humans, organizational legitimacy, or a trusted authority anchor. Apply those policies explicitly. # @openagentid/aegis-sdk API URL: https://docs.openagent.id/reference/typescript/aegis-sdks-typescript Markdown: https://docs.openagent.id/reference/typescript/aegis-sdks-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/aegis-sdks-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## chainCoinType [#chaincointype] BIP-44 coin type for the given chain. ```typescript export declare const chainCoinType: (chain: Chain) => number; ``` Source: `aegis/sdks/typescript/src/core/types.ts:269`. ## derivationStandard [#derivationstandard] Returns the derivation standard name for the given chain. ```typescript export declare const derivationStandard: (chain: Chain) => "BIP-44" | "SLIP-0010"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:294`. ## makePagination [#makepagination] ```typescript export declare const makePagination: (limit: number, offset: number) => Pagination; ``` Source: `aegis/sdks/typescript/src/core/types.ts:355`. ## IdentityType [#identitytype] The type of entity being authenticated. ```typescript // --------------------------------------------------------------------------- // Authentication (§7) // --------------------------------------------------------------------------- /** The type of entity being authenticated. */ export type IdentityType = "human" | "agent" | "organization" | "enterprise" | "delegated"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:16`. ## AegisIdentity [#aegisidentity] Identity information extracted from authentication. ```typescript /** Identity information extracted from authentication. */ export interface AegisIdentity { did: string; identityType: IdentityType; displayName?: string | null; conformanceLevel?: number | null; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:24`. ## AuthContext [#authcontext] The output of successful authentication (AEGIS Spec §7.1). ```typescript /** The output of successful authentication (AEGIS Spec §7.1). */ export interface AuthContext { provider: string; subject: string; did?: string | null; sessionId?: string | null; expiresAt?: string | null; // ISO-8601 UTC claims: Record; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:32`. ## AuthCredential [#authcredential] Discriminated union of credentials accepted by AEGIS auth providers (§7.2). ```typescript /** Discriminated union of credentials accepted by AEGIS auth providers (§7.2). */ export type AuthCredential = { type: "bearer_token"; token: string; } | { type: "session_cookie"; cookie: string; } | { type: "api_key"; key: string; } | { type: "signed_challenge"; did: string; challenge: string; signature: string; timestamp: string; nonce: string; } | { type: "capability_token"; token: string; } | { type: "passkey_assertion"; credentialId: string; authenticatorData: string; clientDataJson: string; signature: string; } | { type: "custom"; provider: string; data: unknown; }; ``` Source: `aegis/sdks/typescript/src/core/types.ts:42`. ## Session [#session] Session token structure (AEGIS Spec §7.4). ```typescript /** Session token structure (AEGIS Spec §7.4). */ export interface Session { sessionId: string; did: string; provider: string; createdAt: string; // ISO-8601 UTC expiresAt: string; // ISO-8601 UTC scope: string[]; deviceBinding?: string | null; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:65`. ## PolicyContext [#policycontext] ```typescript // --------------------------------------------------------------------------- // Policy (§8) // --------------------------------------------------------------------------- export interface PolicyContext { authContext?: AuthContext | null; lineage?: LineageSummary | null; conformanceLevel?: number | null; session?: Session | null; extra: Record; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:79`. ## LineageSummary [#lineagesummary] ```typescript export interface LineageSummary { depth: number; humanRoot: string; verified: boolean; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:87`. ## PolicyRequest [#policyrequest] ```typescript export interface PolicyRequest { principal: string; action: string; resource: string; context: PolicyContext; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:93`. ## ObligationType [#obligationtype] ```typescript export type ObligationType = "log" | "notify" | "approve" | "escrow" | "limit"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:100`. ## Obligation [#obligation] ```typescript export interface Obligation { obligationType: ObligationType; params: Record; deadline?: string | null; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:102`. ## AuditInfo [#auditinfo] ```typescript export interface AuditInfo { auditId: string; timestamp: string; engine: string; policiesEvaluated: string[]; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:108`. ## PolicyDecision [#policydecision] ```typescript export interface PolicyDecision { allowed: boolean; reason?: string | null; obligations: Obligation[]; auditInfo: AuditInfo; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:115`. ## PermissionCheck [#permissioncheck] ```typescript export interface PermissionCheck { principal: string; permission: string; resource?: string | null; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:122`. ## RevocationStatus [#revocationstatus] ```typescript // --------------------------------------------------------------------------- // Verification (§5) // --------------------------------------------------------------------------- export type RevocationStatus = "active" | "revoked" | "suspended" | "expired" | "unknown"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:132`. ## LivenessStatus [#livenessstatus] ```typescript export type LivenessStatus = "active" | "warning" | "stale" | "unknown"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:139`. ## VerificationResult [#verificationresult] ```typescript export interface VerificationResult { did: string; signatureValid: boolean; lineageValid: boolean; lineageDepth: number; humanRoot?: string | null; revocationStatus: RevocationStatus; livenessStatus: LivenessStatus; conformanceLevel: number; warnings: string[]; verifiedAt: string; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:141`. ## VerificationConfig [#verificationconfig] ```typescript export interface VerificationConfig { maxLineageDepth: number; perHopTimeoutSecs: number; totalTimeoutSecs: number; cacheTtlSecs: number; livenessPeriodDays: number; conformanceLevel: number; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:154`. ## DEFAULT\_VERIFICATION\_CONFIG [#default_verification_config] ```typescript export declare const DEFAULT_VERIFICATION_CONFIG: VerificationConfig; ``` Source: `aegis/sdks/typescript/src/core/types.ts:163`. ## ActiveHours [#activehours] ```typescript // --------------------------------------------------------------------------- // Delegation (§9) // --------------------------------------------------------------------------- export interface ActiveHours { startHour: number; endHour: number; timezone: string; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:176`. ## TemporalConstraints [#temporalconstraints] ```typescript export interface TemporalConstraints { validFrom?: string | null; validUntil?: string | null; activeHours?: ActiveHours | null; cooldown?: string | null; // ISO 8601 duration } ``` Source: `aegis/sdks/typescript/src/core/types.ts:182`. ## SpendingLimits [#spendinglimits] ```typescript export interface SpendingLimits { maxAmount?: string | null; dailyVolume?: string | null; assetAllowlist: string[]; recipientAllowlist: string[]; approvalThreshold?: string | null; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:189`. ## DelegationScope [#delegationscope] ```typescript export interface DelegationScope { actions: string[]; resources: string[]; chains: string[]; limits?: SpendingLimits | null; temporal?: TemporalConstraints | null; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:197`. ## DelegationProof [#delegationproof] ```typescript export interface DelegationProof { type: "AegisDelegationProof2025"; verificationMethod: string; created: string; jws: string; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:205`. ## Delegation [#delegation] ```typescript export interface Delegation { id: string; delegator: string; delegate: string; scope: DelegationScope; created: string; expires?: string | null; revocable: boolean; proof: DelegationProof; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:212`. ## SessionKey [#sessionkey] ```typescript export interface SessionKey { sessionKey: string; // multibase-encoded ephemeral verifying key principal: string; scope: DelegationScope; maxTransactions?: number | null; created: string; expires: string; proof: DelegationProof; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:223`. ## WalletType [#wallettype] ```typescript // --------------------------------------------------------------------------- // Wallet (§10) // --------------------------------------------------------------------------- export type WalletType = "eoa" | "smart" | "abstract"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:237`. ## Chain [#chain] ```typescript export type Chain = "ethereum" | "polygon" | "arbitrum" | "optimism" | "base" | "solana" | "bitcoin" | "cosmos" | "osmosis" | "aptos" | "sui" | "starknet"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:239`. ## CHAIN\_VALUES [#chain_values] ```typescript export declare const CHAIN_VALUES: readonly Chain[]; ``` Source: `aegis/sdks/typescript/src/core/types.ts:253`. ## SigningMode [#signingmode] ```typescript export type SigningMode = "direct" | "mpc" | "tee" | "external"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:305`. ## BatchMode [#batchmode] ```typescript export type BatchMode = "all_or_nothing" | "best_effort"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:307`. ## KeyRole [#keyrole] ```typescript // --------------------------------------------------------------------------- // Key Management (§6) // --------------------------------------------------------------------------- export type KeyRole = "identity" | "authentication" | "assertion" | "delegation" | "session" | "recovery" | "chain"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:313`. ## KeyGenerationMode [#keygenerationmode] ```typescript export type KeyGenerationMode = "direct" | "mpc" | "tee" | "hsm"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:322`. ## ThresholdConfig [#thresholdconfig] ```typescript export interface ThresholdConfig { threshold: number; totalShares: number; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:324`. ## GuardianType [#guardiantype] ```typescript export type GuardianType = "identity" | "email" | "phone" | "hardware"; ``` Source: `aegis/sdks/typescript/src/core/types.ts:329`. ## Guardian [#guardian] ```typescript export interface Guardian { guardianType: GuardianType; identifier: string; weight: number; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:331`. ## RecoveryConfig [#recoveryconfig] ```typescript export interface RecoveryConfig { guardians: Guardian[]; threshold: number; timelock: string; // ISO 8601 duration } ``` Source: `aegis/sdks/typescript/src/core/types.ts:337`. ## MAX\_PAGE\_SIZE [#max_page_size] ```typescript export declare const MAX_PAGE_SIZE: 1000; ``` Source: `aegis/sdks/typescript/src/core/types.ts:347`. ## DEFAULT\_PAGE\_SIZE [#default_page_size] ```typescript export declare const DEFAULT_PAGE_SIZE: 100; ``` Source: `aegis/sdks/typescript/src/core/types.ts:348`. ## Pagination [#pagination] ```typescript export interface Pagination { limit: number; offset: number; } ``` Source: `aegis/sdks/typescript/src/core/types.ts:350`. ## DEFAULT\_PAGINATION [#default_pagination] ```typescript export declare const DEFAULT_PAGINATION: Pagination; ``` Source: `aegis/sdks/typescript/src/core/types.ts:362`. ## IdentityTypeSchema [#identitytypeschema] ```typescript export declare const IdentityTypeSchema: z.ZodEnum<{ human: "human"; agent: "agent"; organization: "organization"; enterprise: "enterprise"; delegated: "delegated"; }>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:371`. ## ChainSchema [#chainschema] ```typescript export declare const ChainSchema: z.ZodEnum<{ ethereum: "ethereum"; polygon: "polygon"; arbitrum: "arbitrum"; optimism: "optimism"; base: "base"; solana: "solana"; bitcoin: "bitcoin"; cosmos: "cosmos"; osmosis: "osmosis"; aptos: "aptos"; sui: "sui"; starknet: "starknet"; }>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:379`. ## KeyRoleSchema [#keyroleschema] ```typescript export declare const KeyRoleSchema: z.ZodEnum<{ identity: "identity"; authentication: "authentication"; assertion: "assertion"; delegation: "delegation"; session: "session"; recovery: "recovery"; chain: "chain"; }>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:394`. ## SpendingLimitsSchema [#spendinglimitsschema] ```typescript export declare const SpendingLimitsSchema: z.ZodObject<{ maxAmount: z.ZodOptional>; dailyVolume: z.ZodOptional>; assetAllowlist: z.ZodDefault>; recipientAllowlist: z.ZodDefault>; approvalThreshold: z.ZodOptional>; }, z.core.$strip>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:404`. ## ActiveHoursSchema [#activehoursschema] ```typescript export declare const ActiveHoursSchema: z.ZodObject<{ startHour: z.ZodNumber; endHour: z.ZodNumber; timezone: z.ZodString; }, z.core.$strip>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:412`. ## TemporalConstraintsSchema [#temporalconstraintsschema] ```typescript export declare const TemporalConstraintsSchema: z.ZodObject<{ validFrom: z.ZodOptional>; validUntil: z.ZodOptional>; activeHours: z.ZodOptional>>; cooldown: z.ZodOptional>; }, z.core.$strip>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:418`. ## DelegationScopeSchema [#delegationscopeschema] ```typescript export declare const DelegationScopeSchema: z.ZodObject<{ actions: z.ZodDefault>; resources: z.ZodDefault>; chains: z.ZodDefault>; limits: z.ZodOptional>; dailyVolume: z.ZodOptional>; assetAllowlist: z.ZodDefault>; recipientAllowlist: z.ZodDefault>; approvalThreshold: z.ZodOptional>; }, z.core.$strip>>>; temporal: z.ZodOptional>; validUntil: z.ZodOptional>; activeHours: z.ZodOptional>>; cooldown: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:425`. ## DelegationProofSchema [#delegationproofschema] ```typescript export declare const DelegationProofSchema: z.ZodObject<{ type: z.ZodLiteral<"AegisDelegationProof2025">; verificationMethod: z.ZodString; created: z.ZodString; jws: z.ZodString; }, z.core.$strip>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:433`. ## DelegationSchema [#delegationschema] ```typescript export declare const DelegationSchema: z.ZodObject<{ id: z.ZodString; delegator: z.ZodString; delegate: z.ZodString; scope: z.ZodObject<{ actions: z.ZodDefault>; resources: z.ZodDefault>; chains: z.ZodDefault>; limits: z.ZodOptional>; dailyVolume: z.ZodOptional>; assetAllowlist: z.ZodDefault>; recipientAllowlist: z.ZodDefault>; approvalThreshold: z.ZodOptional>; }, z.core.$strip>>>; temporal: z.ZodOptional>; validUntil: z.ZodOptional>; activeHours: z.ZodOptional>>; cooldown: z.ZodOptional>; }, z.core.$strip>>>; }, z.core.$strip>; created: z.ZodString; expires: z.ZodOptional>; revocable: z.ZodBoolean; proof: z.ZodObject<{ type: z.ZodLiteral<"AegisDelegationProof2025">; verificationMethod: z.ZodString; created: z.ZodString; jws: z.ZodString; }, z.core.$strip>; }, z.core.$strip>; ``` Source: `aegis/sdks/typescript/src/core/types.ts:440`. ## ResolverError [#resolvererror] ```typescript // AEGIS Core — Tagged Errors // // Each AEGIS layer defines its own error variants. We use a discriminated // union of "error tags" rather than throwing untagged Error subclasses, so // callers can pattern-match safely on the `kind` field. export type ResolverError = { kind: "resolver/not_found"; did: string; message: string; } | { kind: "resolver/invalid_format"; reason: string; message: string; } | { kind: "resolver/timeout"; did: string; timeoutMs: number; message: string; } | { kind: "resolver/deactivated"; did: string; message: string; } | { kind: "resolver/network"; did: string; reason: string; message: string; } | { kind: "resolver/creation_not_supported"; message: string; } | { kind: "resolver/update_not_supported"; message: string; } | { kind: "resolver/deactivation_not_supported"; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:7`. ## AuthError [#autherror] ```typescript export type AuthError = { kind: "auth/invalid_credential"; reason: string; message: string; } | { kind: "auth/credential_expired"; expiredAt: string; message: string; } | { kind: "auth/session_revoked"; sessionId: string; message: string; } | { kind: "auth/session_expired"; sessionId: string; message: string; } | { kind: "auth/challenge_invalid"; reason: string; message: string; } | { kind: "auth/provider_unavailable"; provider: string; message: string; } | { kind: "auth/refresh_not_supported"; provider: string; message: string; } | { kind: "auth/revocation_not_supported"; provider: string; message: string; } | { kind: "auth/internal"; reason: string; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:27`. ## PolicyError [#policyerror] ```typescript export type PolicyError = { kind: "policy/evaluation_failed"; reason: string; message: string; } | { kind: "policy/timeout"; timeoutMs: number; message: string; } | { kind: "policy/engine_unavailable"; message: string; } | { kind: "policy/no_engine"; message: string; } | { kind: "policy/config_error"; reason: string; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:42`. ## VerificationError [#verificationerror] ```typescript export type VerificationError = { kind: "verify/resolution_failed"; did: string; reason: string; message: string; } | { kind: "verify/invalid_schema"; did: string; reason: string; message: string; } | { kind: "verify/invalid_signature"; did: string; message: string; } | { kind: "verify/lineage_failed"; did: string; reason: string; message: string; } | { kind: "verify/max_depth_exceeded"; did: string; depth: number; maxDepth: number; message: string; } | { kind: "verify/revoked"; did: string; message: string; } | { kind: "verify/suspended"; did: string; message: string; } | { kind: "verify/human_root_revoked"; humanRoot: string; message: string; } | { kind: "verify/generation_mismatch"; did: string; expected: number; found: number; message: string; } | { kind: "verify/timeout"; did: string; message: string; } | { kind: "verify/consistency_violation"; did: string; reason: string; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:49`. ## KeyError [#keyerror] ```typescript export type KeyError = { kind: "key/generation_failed"; reason: string; message: string; } | { kind: "key/derivation_failed"; reason: string; message: string; } | { kind: "key/rotation_failed"; reason: string; message: string; } | { kind: "key/recovery_failed"; reason: string; message: string; } | { kind: "key/mpc_failed"; reason: string; message: string; } | { kind: "key/not_found"; keyId: string; message: string; } | { kind: "key/storage_error"; reason: string; message: string; } | { kind: "key/signing_failed"; reason: string; message: string; } | { kind: "key/unsupported_type"; keyType: string; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:94`. ## DelegationError [#delegationerror] ```typescript export type DelegationError = { kind: "delegation/invalid_proof"; reason: string; message: string; } | { kind: "delegation/revoked"; delegationId: string; message: string; } | { kind: "delegation/expired"; delegationId: string; message: string; } | { kind: "delegation/max_depth_exceeded"; depth: number; maxDepth: number; message: string; } | { kind: "delegation/scope_amplification"; reason: string; message: string; } | { kind: "delegation/delegator_not_found"; did: string; message: string; } | { kind: "delegation/delegate_not_found"; did: string; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:105`. ## WalletError [#walleterror] ```typescript export type WalletError = { kind: "wallet/authorization_failed"; reason: string; message: string; } | { kind: "wallet/signing_failed"; reason: string; message: string; } | { kind: "wallet/unsupported_chain"; chain: string; message: string; } | { kind: "wallet/derivation_failed"; chain: string; reason: string; message: string; } | { kind: "wallet/policy_denied"; reason: string; message: string; } | { kind: "wallet/obligation_failed"; reason: string; message: string; } | { kind: "wallet/batch_partial_failure"; succeeded: number; total: number; message: string; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:119`. ## AegisError [#aegiserror] ```typescript export type AegisError = ResolverError | AuthError | PolicyError | VerificationError | KeyError | DelegationError | WalletError; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:138`. ## AegisException [#aegisexception] Throwable wrapper around a tagged AegisError. ```typescript export declare class AegisException { error: AegisError; constructor(error: AegisError): AegisException; } ``` Source: `aegis/sdks/typescript/src/core/errors.ts:148`. ## resolverErrors [#resolvererrors] ```typescript export declare const resolverErrors: { notFound: (did: string) => ResolverError; invalidFormat: (reason: string) => ResolverError; timeout: (did: string, timeoutMs: number) => ResolverError; deactivated: (did: string) => ResolverError; network: (did: string, reason: string) => ResolverError; creationNotSupported: () => ResolverError; updateNotSupported: () => ResolverError; deactivationNotSupported: () => ResolverError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:160`. ## authErrors [#autherrors] ```typescript export declare const authErrors: { invalidCredential: (reason: string) => AuthError; credentialExpired: (expiredAt: string) => AuthError; sessionRevoked: (sessionId: string) => AuthError; sessionExpired: (sessionId: string) => AuthError; challengeInvalid: (reason: string) => AuthError; providerUnavailable: (provider: string) => AuthError; refreshNotSupported: (provider: string) => AuthError; revocationNotSupported: (provider: string) => AuthError; internal: (reason: string) => AuthError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:202`. ## policyErrors [#policyerrors] ```typescript export declare const policyErrors: { evaluationFailed: (reason: string) => PolicyError; timeout: (timeoutMs: number) => PolicyError; engineUnavailable: () => PolicyError; noEngine: () => PolicyError; configError: (reason: string) => PolicyError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:250`. ## verificationErrors [#verificationerrors] ```typescript export declare const verificationErrors: { resolutionFailed: (did: string, reason: string) => VerificationError; invalidSchema: (did: string, reason: string) => VerificationError; invalidSignature: (did: string) => VerificationError; lineageFailed: (did: string, reason: string) => VerificationError; maxDepthExceeded: (did: string, depth: number, maxDepth: number) => VerificationError; revoked: (did: string) => VerificationError; suspended: (did: string) => VerificationError; humanRootRevoked: (humanRoot: string) => VerificationError; timeout: (did: string) => VerificationError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:276`. ## keyErrors [#keyerrors] ```typescript export declare const keyErrors: { generationFailed: (reason: string) => KeyError; derivationFailed: (reason: string) => KeyError; rotationFailed: (reason: string) => KeyError; recoveryFailed: (reason: string) => KeyError; mpcFailed: (reason: string) => KeyError; notFound: (keyId: string) => KeyError; storageError: (reason: string) => KeyError; signingFailed: (reason: string) => KeyError; unsupportedKeyType: (keyType: string) => KeyError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:333`. ## delegationErrors [#delegationerrors] ```typescript export declare const delegationErrors: { invalidProof: (reason: string) => DelegationError; revoked: (delegationId: string) => DelegationError; expired: (delegationId: string) => DelegationError; maxDepthExceeded: (depth: number, maxDepth: number) => DelegationError; scopeAmplification: (reason: string) => DelegationError; delegatorNotFound: (did: string) => DelegationError; delegateNotFound: (did: string) => DelegationError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:381`. ## walletErrors [#walleterrors] ```typescript export declare const walletErrors: { authorizationFailed: (reason: string) => WalletError; signingFailed: (reason: string) => WalletError; unsupportedChain: (chain: string) => WalletError; derivationFailed: (chain: string, reason: string) => WalletError; policyDenied: (reason: string) => WalletError; obligationFailed: (reason: string) => WalletError; batchPartialFailure: (succeeded: number, total: number) => WalletError; }; ``` Source: `aegis/sdks/typescript/src/core/errors.ts:420`. ## inferIdentityTypeFromDid [#inferidentitytypefromdid] Infer the IdentityType from a `did:oas:<ns>:<kind>:<id>` string. Returns "agent" if the DID cannot be parsed. ```typescript export declare const inferIdentityTypeFromDid: (did: string) => "human" | "organization" | "enterprise" | "agent"; ``` Source: `aegis/sdks/typescript/src/core/oas.ts:113`. ## LifecycleStatus [#lifecyclestatus] ```typescript // AEGIS Core — OAS Document Interfaces // // AEGIS-TS does not vendor the OAS TypeScript SDK directly. Instead, it // declares the minimal subset of OAS types it needs (DidDocument shape, // LineageSection, VerificationMethod, lifecycle status, etc.) and accepts // any object satisfying these interfaces. Adapters in @oas/document or // custom implementations can supply documents that match. // // Reference: oas/oas/docs/oas/SPECIFICATION.md v1.1.0 export type LifecycleStatus = "active" | "suspended" | "terminated" | "deprecated" | "draft"; ``` Source: `aegis/sdks/typescript/src/core/oas.ts:11`. ## EntityKind [#entitykind] ```typescript export type EntityKind = "hmr" | "mhr" | "enr" | "ao" | "agent" | "agent:instance" | "tool" | "skill" | "workflow" | "model" | "dataset" | "service"; ``` Source: `aegis/sdks/typescript/src/core/oas.ts:18`. ## VerificationMethod [#verificationmethod] Verification method per W3C DID-Core. ```typescript /** Verification method per W3C DID-Core. */ export interface VerificationMethod { id: string; type: string; controller: string; publicKeyMultibase: string; } ``` Source: `aegis/sdks/typescript/src/core/oas.ts:33`. ## LineageSection [#lineagesection] Optional lineage section for non-root entities. ```typescript /** Optional lineage section for non-root entities. */ export interface LineageSection { parent: string; generation: number; humanRootChain: string[]; proof?: AgentLineageProof | null; } ``` Source: `aegis/sdks/typescript/src/core/oas.ts:41`. ## AgentLineageProof [#agentlineageproof] ```typescript export interface AgentLineageProof { type: string; // "AgentLineageProof2025" verificationMethod: string; created: string; jws: string; } ``` Source: `aegis/sdks/typescript/src/core/oas.ts:48`. ## DocumentMetadata [#documentmetadata] ```typescript export interface DocumentMetadata { created: string; updated?: string | null; } ``` Source: `aegis/sdks/typescript/src/core/oas.ts:55`. ## DocumentProof [#documentproof] ```typescript export interface DocumentProof { type: string; // e.g. "Ed25519Signature2020" verificationMethod: string; created: string; jws?: string; proofValue?: string; } ``` Source: `aegis/sdks/typescript/src/core/oas.ts:60`. ## OasDocument [#oasdocument] Minimal OAS Identity Document interface. ```typescript /** Minimal OAS Identity Document interface. */ export interface OasDocument { id: string; oasVersion: string; kind: string; verificationMethod: VerificationMethod[]; authentication?: string[]; assertionMethod?: string[]; delegationMethod?: string[]; metadata: DocumentMetadata; lineage?: LineageSection | null; lifecycleStatus?: LifecycleStatus | null; revoked?: boolean; proof?: DocumentProof | null; // Allow additional fields without complaining. [key: string]: unknown; } ``` Source: `aegis/sdks/typescript/src/core/oas.ts:69`. ## oasDocument [#oasdocument-1] Helpers for inspecting OAS documents without coupling to a specific SDK. ```typescript export declare const oasDocument: { isRoot(doc: OasDocument): boolean; isRevoked(doc: OasDocument): boolean; primaryPublicKeyMultibase(doc: OasDocument): string | null; findVerificationMethod(doc: OasDocument, id: string): VerificationMethod | null; }; ``` Source: `aegis/sdks/typescript/src/core/oas.ts:87`. ## CreateDidParams [#createdidparams] ```typescript // --------------------------------------------------------------------------- // DID Resolver Interface (§4.1) // --------------------------------------------------------------------------- export interface CreateDidParams { entityKind: string; namespace: string; identifier: string; metadata: Record; } ``` Source: `aegis/sdks/typescript/src/core/plugin.ts:30`. ## DidCreationResult [#didcreationresult] ```typescript export interface DidCreationResult { did: string; document: OasDocument; } ``` Source: `aegis/sdks/typescript/src/core/plugin.ts:37`. ## DidResolver [#didresolver] DID Resolver plugin interface (§4.1). Enables AEGIS to resolve any DID method without coupling to a specific resolution mechanism. Each resolver handles one or more DID methods. Implementations MUST resolve within 5 seconds. ```typescript /** * DID Resolver plugin interface (§4.1). * * Enables AEGIS to resolve any DID method without coupling to a specific * resolution mechanism. Each resolver handles one or more DID methods. * * Implementations MUST resolve within 5 seconds. */ export interface DidResolver { resolve(did: string): Promise; handles(did: string): boolean; supportedMethods(): readonly string[]; create?(params: CreateDidParams): Promise; update?(did: string, document: OasDocument): Promise; deactivate?(did: string): Promise; } ``` Source: `aegis/sdks/typescript/src/core/plugin.ts:50`. ## AuthProvider [#authprovider] ```typescript // --------------------------------------------------------------------------- // Auth Provider Interface (§4.2) // --------------------------------------------------------------------------- export interface AuthProvider { validate(credential: AuthCredential): Promise; getIdentity(ctx: AuthContext): Promise; providerName(): string; refresh?(ctx: AuthContext): Promise; revoke?(ctx: AuthContext): Promise; } ``` Source: `aegis/sdks/typescript/src/core/plugin.ts:63`. ## PolicyEngine [#policyengine] ```typescript // --------------------------------------------------------------------------- // Policy Engine Interface (§4.3) // --------------------------------------------------------------------------- export interface PolicyEngine { evaluate(request: PolicyRequest): Promise; checkPermission(check: PermissionCheck): Promise; engineName(): string; getPolicies?(did: string): Promise; } ``` Source: `aegis/sdks/typescript/src/core/plugin.ts:75`. ## PluginRegistry [#pluginregistry] The Plugin Registry manages all loaded plugins and routes requests to the appropriate plugin (AEGIS Spec §4.4). * Multiple DID Resolvers (routed by `handles()` matching) * Multiple Auth Providers (keyed by `providerName()`) * Exactly one Policy Engine Plugin registration order is deterministic. Resolvers are tried in registration order; the first whose `handles()` returns true is used. ```typescript export declare class PluginRegistry { registerResolver(resolver: DidResolver): void; registerAuthProvider(provider: AuthProvider): void; setPolicyEngine(engine: PolicyEngine): void; resolverCount(): number; authProviderCount(): number; hasPolicyEngine(): boolean; getResolverFor(did: string): DidResolver | null; getAuthProvider(name: string): AuthProvider | null; getPolicyEngine(): PolicyEngine | null; resolveDid(did: string): Promise; validateCredential(credential: AuthCredential, providerName?: string | null): Promise; evaluatePolicy(request: PolicyRequest): Promise; checkPermission(check: PermissionCheck): Promise; } ``` Source: `aegis/sdks/typescript/src/core/plugin.ts:97`. ## setCryptoBackend [#setcryptobackend] Inject a custom crypto backend implementation. Call this once at SDK initialization (typically with the `@openagentid/crypto-wasm` exports). ```typescript export declare const setCryptoBackend: (impl: CryptoBackend) => void; ``` Source: `aegis/sdks/typescript/src/core/wasm.ts:106`. ## cryptoBackend [#cryptobackend] Returns the active crypto backend. Throws if none has been registered. In Node.js, the backend can be auto-loaded by `loadDefaultCryptoBackend` which dynamically imports `@openagentid/crypto-wasm`. ```typescript export declare const cryptoBackend: () => CryptoBackend; ``` Source: `aegis/sdks/typescript/src/core/wasm.ts:116`. ## loadDefaultCryptoBackend [#loaddefaultcryptobackend] Attempts to load `@openagentid/crypto-wasm` lazily. Falls back to a stub error backend if the module isn't available — callers should rely on this for one-time setup in tests/examples. ```typescript export declare const loadDefaultCryptoBackend: () => Promise; ``` Source: `aegis/sdks/typescript/src/core/wasm.ts:131`. ## CryptoBackend [#cryptobackend-1] ```typescript // AEGIS Core — WASM Crypto Bridge // // AEGIS-TS delegates all primitive cryptographic operations to a single // audited Rust implementation compiled to WebAssembly via wasm-pack. The // canonical package is `@openagentid/crypto-wasm`. We import its named // exports lazily so that the rest of the SDK works in environments where // the WASM module is loaded asynchronously (Workers, Deno, etc.). // // The contract below is the API surface AEGIS depends on. The actual // `@openagentid/crypto-wasm` package is built in parallel; until it ships, // callers can inject a custom implementation via `setCryptoBackend()`. // // All byte parameters use Uint8Array. All return types are Uint8Array // except for canonicalize which returns Uint8Array (UTF-8 of canonical // JSON) and hash functions which return raw bytes. export interface CryptoBackend { // -- Ed25519 -- ed25519GenerateKeypair(): { signingKey: Uint8Array; verifyingKey: Uint8Array; }; ed25519PublicFromPrivate(signingKey: Uint8Array): Uint8Array; ed25519Sign(signingKey: Uint8Array, message: Uint8Array): Uint8Array; ed25519Verify(verifyingKey: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean; // -- HKDF-SHA256 -- hkdfSha256(ikm: Uint8Array, salt: Uint8Array, info: Uint8Array, length: number): Uint8Array; // -- BLAKE3 -- blake3Hash(input: Uint8Array): Uint8Array; // -- SHA -- sha256(input: Uint8Array): Uint8Array; sha512(input: Uint8Array): Uint8Array; // -- AES-256-GCM -- aes256GcmEncrypt(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array): Uint8Array; aes256GcmDecrypt(key: Uint8Array, nonce: Uint8Array, ciphertext: Uint8Array): Uint8Array; // -- JCS -- jcsCanonicalize(value: unknown): Uint8Array; // -- Multibase base58btc -- multibaseEncode(bytes: Uint8Array): string; multibaseDecode(encoded: string): Uint8Array; // -- Random bytes (CSPRNG) -- randomBytes(length: number): Uint8Array; // -- FROST-Ed25519 (raw protocol primitives) -- frostTrustedKeygen(minSigners: number, maxSigners: number): { keyPackages: FrostKeyPackage[]; publicKeyPackage: Uint8Array; }; frostSignRound1(signingShare: Uint8Array): { nonces: Uint8Array; commitments: Uint8Array; }; frostSignRound2(signingPackage: Uint8Array, nonces: Uint8Array, keyPackage: Uint8Array): Uint8Array; frostBuildSigningPackage(commitments: Map, message: Uint8Array): Uint8Array; frostAggregate(signingPackage: Uint8Array, signatureShares: Map, publicKeyPackage: Uint8Array): Uint8Array; frostVerify(publicKeyPackage: Uint8Array, message: Uint8Array, signature: Uint8Array): boolean; } ``` Source: `aegis/sdks/typescript/src/core/wasm.ts:17`. ## FrostKeyPackage [#frostkeypackage] ```typescript export interface FrostKeyPackage { identifier: number; // 1..max_signers bytes: Uint8Array; } ``` Source: `aegis/sdks/typescript/src/core/wasm.ts:95`. ## base64UrlEncode [#base64urlencode] Encode bytes as URL-safe base64 without padding. ```typescript export declare const base64UrlEncode: (bytes: Uint8Array) => string; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:11`. ## base64UrlDecode [#base64urldecode] Decode a URL-safe base64 string (with or without padding) to bytes. ```typescript export declare const base64UrlDecode: (input: string) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:50`. ## hexEncode [#hexencode] ```typescript export declare const hexEncode: (bytes: Uint8Array) => string; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:97`. ## hexDecode [#hexdecode] ```typescript export declare const hexDecode: (input: string) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:105`. ## utf8Encode [#utf8encode] ```typescript export declare const utf8Encode: (s: string) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:127`. ## utf8Decode [#utf8decode] ```typescript export declare const utf8Decode: (bytes: Uint8Array) => string; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:131`. ## concatBytes [#concatbytes] ```typescript export declare const concatBytes: (...chunks: Uint8Array[]) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:135`. ## u32BeBytes [#u32bebytes] big-endian u32 → 4 bytes ```typescript export declare const u32BeBytes: (n: number) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/core/encoding.ts:148`. ## VerificationPipeline [#verificationpipeline] The AEGIS Verification Pipeline. Performs complete verification of OAS identity documents per AEGIS Specification §5. Results are cached with a configurable TTL (max 300 seconds per spec). ```typescript export declare class VerificationPipeline { constructor(registry: PluginRegistry, config?: VerificationConfig): VerificationPipeline; cache(): VerificationCache; verify(did: string): Promise; verifyForceRefresh(did: string): Promise; } ``` Source: `aegis/sdks/typescript/src/verify/pipeline.ts:49`. ## VerificationCache [#verificationcache] ```typescript export declare class VerificationCache { constructor(ttlSecs: number): VerificationCache; ttl(): number; size(): number; isEmpty(): boolean; get(did: string): VerificationResult | null; insert(did: string, result: VerificationResult): void; invalidate(did: string): void; clear(): void; cleanupExpired(): number; } ``` Source: `aegis/sdks/typescript/src/verify/cache.ts:18`. ## VerificationCacheStore [#verificationcachestore] ```typescript export interface VerificationCacheStore { getCached(did: string): Promise; storeCached(did: string, result: VerificationResult): Promise; invalidate(did: string): Promise; cleanupExpired(): Promise; } ``` Source: `aegis/sdks/typescript/src/verify/store.ts:9`. ## InMemoryVerificationCacheStore [#inmemoryverificationcachestore] ```typescript export declare class InMemoryVerificationCacheStore { constructor(ttlSecs: number): InMemoryVerificationCacheStore; ttlSecs(): number; getCached(did: string): Promise; storeCached(did: string, result: VerificationResult): Promise; invalidate(did: string): Promise; cleanupExpired(): Promise; } ``` Source: `aegis/sdks/typescript/src/verify/store.ts:24`. ## deriveLineageKey [#derivelineagekey] Derive a lineage key from a parent private key using HKDF-SHA256. Algorithm: HKDF-SHA256( IKM = parent\_private\_key (32 bytes), Salt = child\_did\_utf8, Info = "oas-lineage-v1" || generation\_be32, L = 32 ) ```typescript export declare const deriveLineageKey: (parentPrivate: Uint8Array, childDid: string, generation: number) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/keys/derivation.ts:28`. ## derivationPath [#derivationpath] Build a BIP-44 derivation path for a given blockchain chain. Returns the standard `m/44'/coin_type'/account'/0/index` path used for HD key derivation across most chains. ```typescript export declare const derivationPath: (chain: Chain, account: number, index: number) => string; ``` Source: `aegis/sdks/typescript/src/keys/derivation.ts:58`. ## EncryptedKey [#encryptedkey] An encrypted private key blob. Uses AES-256-GCM with a random 96-bit nonce. The ciphertext contains the 32-byte Ed25519 signing key material plus a 16-byte authentication tag. ```typescript export declare class EncryptedKey { ciphertext: Uint8Array; nonce: Uint8Array; encrypt(signingKeyBytes: Uint8Array, encryptionKey: Uint8Array): EncryptedKey; decrypt(encryptionKey: Uint8Array): Uint8Array; fromParts(ciphertext: Uint8Array, nonce: Uint8Array): EncryptedKey; } ``` Source: `aegis/sdks/typescript/src/keys/generation.ts:25`. ## ManagedKey [#managedkey] A managed key with metadata. The private key is stored encrypted; access to the raw signing key requires presenting the encryption key. ```typescript export declare class ManagedKey { keyId: string; role: KeyRole; generationMode: KeyGenerationMode; publicKey: Uint8Array; encryptedPrivate: EncryptedKey; createdAt: string; constructor(params: { keyId: string; role: KeyRole; generationMode: KeyGenerationMode; publicKey: Uint8Array; encryptedPrivate: EncryptedKey; createdAt: string; }): ManagedKey; publicKeyMultibase(): string; decryptPrivate(encryptionKey: Uint8Array): Uint8Array; } ``` Source: `aegis/sdks/typescript/src/keys/generation.ts:100`. ## KeyGenerator [#keygenerator] Key generator supporting multiple generation modes (§6.2). Currently implements `direct` generation via the WASM backend's CSPRNG. MPC, TEE, and HSM modes are stubs that throw an unsupported error. ```typescript export declare class KeyGenerator { generateDirect(role: KeyRole, encryptionKey: Uint8Array): ManagedKey; generateKeyId(): string; } ``` Source: `aegis/sdks/typescript/src/keys/generation.ts:142`. ## isRotationEligible [#isrotationeligible] Convenience function: returns true if the role is eligible for standard rotation. Session and Recovery keys are excluded. ```typescript export declare const isRotationEligible: (role: KeyRole) => boolean; ``` Source: `aegis/sdks/typescript/src/keys/rotation.ts:64`. ## RotationRequest [#rotationrequest] ```typescript export interface RotationRequest { keyId: string; /** Grace period in milliseconds. */ gracePeriodMs: number; } ``` Source: `aegis/sdks/typescript/src/keys/rotation.ts:15`. ## RotationResult [#rotationresult] ```typescript export interface RotationResult { oldKeyId: string; newKey: ManagedKey; /** ISO-8601 timestamp at which the grace period ends. */ gracePeriodEnds: string; } ``` Source: `aegis/sdks/typescript/src/keys/rotation.ts:21`. ## KeyRotation [#keyrotation] ```typescript export declare class KeyRotation { initiate(old: ManagedKey, encryptionKey: Uint8Array): RotationResult; initiateWithGrace(old: ManagedKey, encryptionKey: Uint8Array, gracePeriodMs: number): RotationResult; isGracePeriodExpired(result: RotationResult): boolean; } ``` Source: `aegis/sdks/typescript/src/keys/rotation.ts:28`. ## parseIso8601DurationMs [#parseiso8601durationms] Parse a simplified ISO 8601 duration into milliseconds. Supports `PT{n}S`, `PT{n}M`, `PT{n}H`, and `P{n}D`. Falls back to 24 hours for unrecognized formats. ```typescript export declare const parseIso8601DurationMs: (input: string) => number; ``` Source: `aegis/sdks/typescript/src/keys/recovery.ts:85`. ## GuardianAuthorization [#guardianauthorization] ```typescript export interface GuardianAuthorization { guardian: Guardian; authorizedAt: string; // ISO-8601 UTC signature: string; } ``` Source: `aegis/sdks/typescript/src/keys/recovery.ts:14`. ## RecoveryCeremony [#recoveryceremony] ```typescript export declare class RecoveryCeremony { ceremonyId: string; config: RecoveryConfig; authorizations: GuardianAuthorization[]; initiatedAt: string; timelockUntil: string; constructor(config: RecoveryConfig): RecoveryCeremony; addAuthorization(auth: GuardianAuthorization): void; isThresholdMet(): boolean; isTimelockExpired(): boolean; canExecute(): boolean; accumulatedWeight(): number; authorizationCount(): number; } ``` Source: `aegis/sdks/typescript/src/keys/recovery.ts:20`. ## KeyStore [#keystore] ```typescript export interface KeyStore { store(key: ManagedKey): Promise; load(keyId: string): Promise; delete(keyId: string): Promise; list(role: KeyRole | null, pagination?: Pagination): Promise; } ``` Source: `aegis/sdks/typescript/src/keys/storage.ts:15`. ## InMemoryKeyStore [#inmemorykeystore] ```typescript export declare class InMemoryKeyStore { size(): number; isEmpty(): boolean; store(key: ManagedKey): Promise; load(keyId: string): Promise; delete(keyId: string): Promise; list(role: KeyRole | null, pagination?: Pagination): Promise; } ``` Source: `aegis/sdks/typescript/src/keys/storage.ts:26`. ## generateShares [#generateshares] Generate threshold key shares using FROST trusted dealer. Creates a `t-of-n` setup: any `minSigners` of `maxSigners` participants may cooperate to produce a valid signature. The dealer is trusted to destroy its copy of the master secret after distribution. ```typescript export declare const generateShares: (minSigners: number, maxSigners: number) => ThresholdKeyPackages; ``` Source: `aegis/sdks/typescript/src/keys/threshold.ts:29`. ## signWithThreshold [#signwiththreshold] Run a complete FROST signing round in a single process. In production, each participant would perform round1 and round2 independently. This helper executes the full 2-round protocol locally for testing, validation, and single-process orchestration scenarios. ```typescript export declare const signWithThreshold: (message: Uint8Array, keyPackages: Map, publicKeyPackage: Uint8Array) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/keys/threshold.ts:73`. ## verifyThresholdSignature [#verifythresholdsignature] Verify an aggregated FROST signature against the group public key. ```typescript export declare const verifyThresholdSignature: (message: Uint8Array, signature: Uint8Array, publicKeyPackage: Uint8Array) => boolean; ``` Source: `aegis/sdks/typescript/src/keys/threshold.ts:136`. ## ThresholdKeyPackages [#thresholdkeypackages] Result of FROST trusted-dealer key generation. ```typescript /** Result of FROST trusted-dealer key generation. */ export interface ThresholdKeyPackages { /** Per-participant key packages, indexed by FROST identifier (1..n). */ keyPackages: Map; /** The serialized group public key package. */ publicKeyPackage: Uint8Array; } ``` Source: `aegis/sdks/typescript/src/keys/threshold.ts:15`. ## FrostCeremony [#frostceremony] State of a distributed FROST signing ceremony, suitable for orchestrating the protocol across multiple machines/processes. Each participant calls the methods in order: 1. `addCommitment(id, commitments)` — gather round 1 outputs 2. `buildSigningPackage(message)` — build signing package once all participants have committed 3. `addSignatureShare(id, share)` — gather round 2 outputs 4. `aggregate()` — produce the final aggregated signature The ceremony does NOT hold any participant key material — those remain on the participant's own machine. ```typescript export declare class FrostCeremony { constructor(publicKeyPackage: Uint8Array, threshold: number): FrostCeremony; addCommitment(id: number, commitments: Uint8Array): void; hasEnoughCommitments(): boolean; buildSigningPackage(message: Uint8Array): Uint8Array; addSignatureShare(id: number, share: Uint8Array): void; hasEnoughShares(): boolean; aggregate(): Uint8Array; } ``` Source: `aegis/sdks/typescript/src/keys/threshold.ts:165`. ## generateChallenge [#generatechallenge] Generate a new random challenge. ```typescript export declare const generateChallenge: () => Challenge; ``` Source: `aegis/sdks/typescript/src/auth/challenge.ts:31`. ## buildChallengePayload [#buildchallengepayload] Build the JCS-canonical payload bytes for challenge signing/verification. Canonical form is a JSON object with keys in alphabetical order: \{"challenge":"\","did":"\","nonce":"\","timestamp":"\"} The WASM crypto backend's `jcsCanonicalize` handles RFC 8785 ordering. ```typescript export declare const buildChallengePayload: (challenge: Challenge, did: string) => Uint8Array; ``` Source: `aegis/sdks/typescript/src/auth/challenge.ts:53`. ## Challenge [#challenge] A challenge issued by the verifier to an authenticating entity. ```typescript /** A challenge issued by the verifier to an authenticating entity. */ export interface Challenge { /** 32 cryptographically random bytes. */ challengeBytes: Uint8Array; /** ISO 8601 timestamp of challenge creation. */ timestamp: string; /** Verifier-generated nonce (UUID v7). */ nonce: string; /** Expiry timestamp (creation time + 60 seconds). */ expiresAt: string; } ``` Source: `aegis/sdks/typescript/src/auth/challenge.ts:19`. ## ChallengeVerifier [#challengeverifier] Challenge-response verifier with in-memory nonce tracking. Production deployments should swap the in-memory nonce set for a TTL- backed cache or database via the \{@link NonceStore } abstraction in `auth/store.ts`. ```typescript export declare class ChallengeVerifier { verifyResponse(challenge: Challenge, did: string, signatureB64: string, publicKey: Uint8Array): void; clearNonces(): void; } ``` Source: `aegis/sdks/typescript/src/auth/challenge.ts:71`. ## SessionManagerOptions [#sessionmanageroptions] ```typescript export interface SessionManagerOptions { humanLifetimeMs?: number; agentLifetimeMs?: number; } ``` Source: `aegis/sdks/typescript/src/auth/session.ts:17`. ## SessionManager [#sessionmanager] ```typescript export declare class SessionManager { humanLifetimeMs: number; agentLifetimeMs: number; constructor(opts?: SessionManagerOptions): SessionManager; createSession(params: { did: string; provider: string; scope?: string[]; isAgent: boolean; deviceBinding?: string | null; }): Session; getSession(sessionId: string): Session; revokeSession(sessionId: string): void; isValid(sessionId: string): boolean; cleanupExpired(): number; sessionCount(): number; } ``` Source: `aegis/sdks/typescript/src/auth/session.ts:22`. ## ChallengeResponseProvider [#challengeresponseprovider] Auth provider implementing the AEGIS challenge-response protocol. Validates `signed_challenge` credentials by: 1. Resolving the DID via the registered DID resolver 2. Extracting the primary authentication public key 3. Reconstructing the challenge and verifying the Ed25519 signature ```typescript export declare class ChallengeResponseProvider { constructor(resolver: DidResolver): ChallengeResponseProvider; providerName(): string; verifier(): ChallengeVerifier; validate(credential: AuthCredential): Promise; getIdentity(ctx: AuthContext): Promise; } ``` Source: `aegis/sdks/typescript/src/auth/provider.ts:33`. ## ApiKeyProvider [#apikeyprovider] Simple API key auth provider for service-to-service communication. Maps opaque API keys to DIDs. Suitable for internal services that authenticate via pre-shared keys rather than challenge-response. ```typescript export declare class ApiKeyProvider { constructor(initial?: Record): ApiKeyProvider; providerName(): string; registerKey(key: string, did: string): void; revokeKey(key: string): boolean; validate(credential: AuthCredential): Promise; getIdentity(ctx: AuthContext): Promise; } ``` Source: `aegis/sdks/typescript/src/auth/provider.ts:145`. ## SessionStore [#sessionstore] ```typescript // --------------------------------------------------------------------------- // SessionStore // --------------------------------------------------------------------------- export interface SessionStore { storeSession(session: Session): Promise; getSession(sessionId: string): Promise; deleteSession(sessionId: string): Promise; listByDid(did: string, pagination?: Pagination): Promise; cleanupExpired(): Promise; } ``` Source: `aegis/sdks/typescript/src/auth/store.ts:17`. ## InMemorySessionStore [#inmemorysessionstore] ```typescript export declare class InMemorySessionStore { storeSession(session: Session): Promise; getSession(sessionId: string): Promise; deleteSession(sessionId: string): Promise; listByDid(did: string, pagination?: Pagination): Promise; cleanupExpired(): Promise; } ``` Source: `aegis/sdks/typescript/src/auth/store.ts:25`. ## NonceStore [#noncestore] ```typescript // --------------------------------------------------------------------------- // NonceStore // --------------------------------------------------------------------------- export interface NonceStore { /** Returns true if newly recorded, false if already present (replay). */ recordNonce(nonce: string): Promise; hasNonce(nonce: string): Promise; cleanup(): Promise; } ``` Source: `aegis/sdks/typescript/src/auth/store.ts:65`. ## InMemoryNonceStore [#inmemorynoncestore] ```typescript export declare class InMemoryNonceStore { recordNonce(nonce: string): Promise; hasNonce(nonce: string): Promise; cleanup(): Promise; } ``` Source: `aegis/sdks/typescript/src/auth/store.ts:72`. ## TemporalPolicyEvaluator [#temporalpolicyevaluator] ```typescript export declare class TemporalPolicyEvaluator { evaluate(constraints: TemporalConstraints, now?: Date): PolicyDecision; evaluateWithCooldown(constraints: TemporalConstraints, now: Date, lastOperation: Date | null): PolicyDecision; } ``` Source: `aegis/sdks/typescript/src/policy/temporal.ts:17`. ## parseAmount [#parseamount] Parse a decimal amount string. Throws PolicyError on invalid input. ```typescript export declare const parseAmount: (s: string) => number; ``` Source: `aegis/sdks/typescript/src/policy/spending.ts:128`. ## TransactionInfo [#transactioninfo] ```typescript export interface TransactionInfo { asset: string; amount: string; recipient: string; chain: string; } ``` Source: `aegis/sdks/typescript/src/policy/spending.ts:17`. ## SpendingPolicyEvaluator [#spendingpolicyevaluator] ```typescript export declare class SpendingPolicyEvaluator { evaluate(limits: SpendingLimits, tx: TransactionInfo, dailySpent: string): PolicyDecision; } ``` Source: `aegis/sdks/typescript/src/policy/spending.ts:26`. ## LineagePolicy [#lineagepolicy] ```typescript export interface LineagePolicy { minConformanceLevel?: number | null; maxLineageDepth?: number | null; /** When set, requires `verification.livenessStatus === "active"`. */ requiredHumanRootLiveness?: number | null; requiredAttestations: string[]; bannedHumanRoots: string[]; } ``` Source: `aegis/sdks/typescript/src/policy/lineage.ts:17`. ## LineagePolicyEvaluator [#lineagepolicyevaluator] ```typescript export declare class LineagePolicyEvaluator { evaluate(policy: LineagePolicy, verification: VerificationResult): PolicyDecision; } ``` Source: `aegis/sdks/typescript/src/policy/lineage.ts:26`. ## ContractPolicy [#contractpolicy] ```typescript export interface ContractPolicy { contractAllowlist: string[]; functionAllowlist: string[]; chainAllowlist: string[]; gasLimit?: number | null; } ``` Source: `aegis/sdks/typescript/src/policy/contract.ts:13`. ## ContractInteraction [#contractinteraction] ```typescript export interface ContractInteraction { contractAddress: string; functionName: string; chain: string; gasEstimate?: number | null; } ``` Source: `aegis/sdks/typescript/src/policy/contract.ts:20`. ## ContractPolicyEvaluator [#contractpolicyevaluator] ```typescript export declare class ContractPolicyEvaluator { evaluate(policy: ContractPolicy, interaction: ContractInteraction): PolicyDecision; } ``` Source: `aegis/sdks/typescript/src/policy/contract.ts:27`. ## composeDecisions [#composedecisions] ```typescript export declare const composeDecisions: (decisions: readonly PolicyDecision[]) => PolicyDecision; ``` Source: `aegis/sdks/typescript/src/policy/composition.ts:18`. ## isScopeSubset [#isscopesubset] Returns true if `child` scope is a subset of `parent` scope. Empty fields on `parent` mean "wildcard" — they accept any child value. Limits on `child` must be at least as restrictive as the parent's. ```typescript export declare const isScopeSubset: (child: DelegationScope, parent: DelegationScope) => boolean; ``` Source: `aegis/sdks/typescript/src/delegate/scope.ts:21`. ## intersectScopes [#intersectscopes] Compute the intersection of two scopes. * Empty list = wildcard, take the other side * Otherwise, set intersection * For limits, take the most restrictive value ```typescript export declare const intersectScopes: (a: DelegationScope, b: DelegationScope) => DelegationScope; ``` Source: `aegis/sdks/typescript/src/delegate/scope.ts:95`. ## validateScope [#validatescope] ```typescript export declare const validateScope: (scope: DelegationScope) => void; ``` Source: `aegis/sdks/typescript/src/delegate/scope.ts:186`. ## createDelegationProof [#createdelegationproof] Create a delegation proof by signing the delegation with the delegator's key. Steps per spec §9.7: 1. Construct delegation object (excluding proof field) 2. Canonicalize via JCS (RFC 8785) 3. Sign canonical bytes with delegator's delegation key (Ed25519) ```typescript export declare const createDelegationProof: (params: { delegatorDid: string; delegateDid: string; scope: DelegationScope; expires?: string | null; signingKey: Uint8Array; verificationMethod: string; }) => Delegation; ``` Source: `aegis/sdks/typescript/src/delegate/proof.ts:41`. ## verifyDelegationProof [#verifydelegationproof] Verify a delegation proof against the delegator's public key. Reconstructs the canonical form of the delegation (without the proof), then verifies the Ed25519 signature in the proof's JWS field. ```typescript export declare const verifyDelegationProof: (delegation: Delegation, delegatorPublicKey: Uint8Array) => boolean; ``` Source: `aegis/sdks/typescript/src/delegate/proof.ts:99`. ## DelegationTree [#delegationtree] ```typescript export declare class DelegationTree { maxDepth: number; constructor(maxDepth?: number): DelegationTree; addDelegation(delegation: Delegation): void; getDelegationChain(delegateDid: string): Delegation[]; effectiveScope(delegateDid: string): DelegationScope | null; depth(delegateDid: string): number; revoke(delegationId: string): string[]; } ``` Source: `aegis/sdks/typescript/src/delegate/tree.ts:18`. ## RevocationRegistry [#revocationregistry] ```typescript export declare class RevocationRegistry { revoke(delegationId: string): void; isRevoked(delegationId: string): boolean; revokeCascade(ids: readonly string[]): void; size(): number; } ``` Source: `aegis/sdks/typescript/src/delegate/revocation.ts:8`. ## createSessionKey [#createsessionkey] Create a session key (temporary, scoped, max 24h). Generates a fresh Ed25519 keypair for the session and signs the grant with the principal's identity key. ```typescript export declare const createSessionKey: (params: { principalDid: string; scope: DelegationScope; maxTransactions?: number | null; lifetimeMs: number; principalSigningKey: Uint8Array; verificationMethod: string; }) => CreatedSessionKey; ``` Source: `aegis/sdks/typescript/src/delegate/session_key.ts:43`. ## CreatedSessionKey [#createdsessionkey] ```typescript export interface CreatedSessionKey { sessionKey: SessionKey; /** The ephemeral 32-byte signing key. Caller is responsible for safekeeping. */ ephemeralSigningKey: Uint8Array; ephemeralVerifyingKey: Uint8Array; } ``` Source: `aegis/sdks/typescript/src/delegate/session_key.ts:21`. ## DelegationStore [#delegationstore] ```typescript // --------------------------------------------------------------------------- // DelegationStore // --------------------------------------------------------------------------- export interface DelegationStore { storeDelegation(delegation: Delegation): Promise; getDelegation(id: string): Promise; listByDelegator(delegatorDid: string, pagination?: Pagination): Promise; listByDelegate(delegateDid: string, pagination?: Pagination): Promise; deleteDelegation(id: string): Promise; } ``` Source: `aegis/sdks/typescript/src/delegate/store.ts:17`. ## InMemoryDelegationStore [#inmemorydelegationstore] ```typescript export declare class InMemoryDelegationStore { storeDelegation(delegation: Delegation): Promise; getDelegation(id: string): Promise; listByDelegator(delegatorDid: string, pagination?: Pagination): Promise; listByDelegate(delegateDid: string, pagination?: Pagination): Promise; deleteDelegation(id: string): Promise; } ``` Source: `aegis/sdks/typescript/src/delegate/store.ts:25`. ## RevocationStore [#revocationstore] ```typescript // --------------------------------------------------------------------------- // RevocationStore // --------------------------------------------------------------------------- export interface RevocationStore { revoke(delegationId: string): Promise; isRevoked(delegationId: string): Promise; revokeBatch(ids: readonly string[]): Promise; } ``` Source: `aegis/sdks/typescript/src/delegate/store.ts:65`. ## InMemoryRevocationStore [#inmemoryrevocationstore] ```typescript export declare class InMemoryRevocationStore { revoke(delegationId: string): Promise; isRevoked(delegationId: string): Promise; revokeBatch(ids: readonly string[]): Promise; } ``` Source: `aegis/sdks/typescript/src/delegate/store.ts:71`. ## WalletAddress [#walletaddress] ```typescript export interface WalletAddress { chain: Chain; address: string; derivationPath: string; publicKeyHex: string; } ``` Source: `aegis/sdks/typescript/src/wallet/address.ts:26`. ## AddressDeriver [#addressderiver] ```typescript export declare class AddressDeriver { derivationPath(chain: Chain, account: number, index: number): string; deriveAddress(chain: Chain, publicKeyBytes: Uint8Array): WalletAddress; deriveAll(publicKeyBytes: Uint8Array, chains: readonly Chain[]): WalletAddress[]; } ``` Source: `aegis/sdks/typescript/src/wallet/address.ts:33`. ## verifySignature [#verifysignature] Verify an Ed25519 signature against a message and public key. ```typescript export declare const verifySignature: (publicKey: Uint8Array, message: Uint8Array, signature: Uint8Array) => boolean; ``` Source: `aegis/sdks/typescript/src/wallet/ceremony.ts:81`. ## SigningRequest [#signingrequest] ```typescript export interface SigningRequest { message: Uint8Array; signerDid: string; chain?: Chain | null; } ``` Source: `aegis/sdks/typescript/src/wallet/ceremony.ts:16`. ## SigningResult [#signingresult] ```typescript export interface SigningResult { signature: Uint8Array; publicKey: Uint8Array; mode: SigningMode; } ``` Source: `aegis/sdks/typescript/src/wallet/ceremony.ts:22`. ## SigningBackend [#signingbackend] ```typescript export interface SigningBackend { sign(request: SigningRequest): Promise; publicKey(): Uint8Array; mode(): SigningMode; } ``` Source: `aegis/sdks/typescript/src/wallet/ceremony.ts:28`. ## DirectSigner [#directsigner] Direct signing backend using a single Ed25519 key. The signing key is stored in memory; callers should treat the instance as sensitive material and zeroize when done. ```typescript export declare class DirectSigner { constructor(signingKey: Uint8Array): DirectSigner; sign(request: SigningRequest): Promise; publicKey(): Uint8Array; mode(): SigningMode; } ``` Source: `aegis/sdks/typescript/src/wallet/ceremony.ts:40`. ## makeTransaction [#maketransaction] ```typescript export declare const makeTransaction: (params: { fromDid: string; to: string; chain: string; data: Uint8Array; value?: string | null; }) => Transaction; ``` Source: `aegis/sdks/typescript/src/wallet/pipeline.ts:36`. ## Transaction [#transaction] ```typescript export interface Transaction { txId: string; fromDid: string; to: string; chain: string; data: Uint8Array; value?: string | null; } ``` Source: `aegis/sdks/typescript/src/wallet/pipeline.ts:27`. ## AuthorizedTransaction [#authorizedtransaction] ```typescript export interface AuthorizedTransaction { transaction: Transaction; signature: Uint8Array; fulfilledObligations: string[]; } ``` Source: `aegis/sdks/typescript/src/wallet/pipeline.ts:53`. ## TransactionPipeline [#transactionpipeline] Full transaction authorization pipeline per AEGIS Spec §10.4. Enforces a strict 5-step process; if any step fails the transaction is NOT signed. ```typescript export declare class TransactionPipeline { constructor(signer: SigningBackend): TransactionPipeline; authorizeAndSign(tx: Transaction, auth: AuthContext, policyDecision: PolicyDecision): Promise; } ``` Source: `aegis/sdks/typescript/src/wallet/pipeline.ts:65`. ## StorageBackend [#storagebackend] Storage backend selection. ```typescript /** Storage backend selection. */ export type StorageBackend = { type: "in_memory"; } | { type: "postgres"; url: string; }; ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:11`. ## SessionConfig [#sessionconfig] ```typescript export interface SessionConfig { /** Maximum lifetime for human sessions in seconds (default: 86400 = 24h). */ humanLifetimeSecs: number; /** Maximum lifetime for agent sessions in seconds (default: 3600 = 1h). */ agentLifetimeSecs: number; /** Maximum lifetime for session keys in seconds (default: 86400 = 24h). */ sessionKeyMaxSecs: number; } ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:15`. ## KeyConfig [#keyconfig] ```typescript export interface KeyConfig { encryptionAlgorithm: string; zeroizeOnDrop: boolean; } ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:24`. ## AegisConfig [#aegisconfig] ```typescript export interface AegisConfig { verification: VerificationConfig; sessions: SessionConfig; keys: KeyConfig; storageBackend: StorageBackend; } ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:29`. ## DEFAULT\_SESSION\_CONFIG [#default_session_config] ```typescript export declare const DEFAULT_SESSION_CONFIG: SessionConfig; ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:36`. ## DEFAULT\_KEY\_CONFIG [#default_key_config] ```typescript export declare const DEFAULT_KEY_CONFIG: KeyConfig; ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:42`. ## DEFAULT\_AEGIS\_CONFIG [#default_aegis_config] ```typescript export declare const DEFAULT_AEGIS_CONFIG: AegisConfig; ``` Source: `aegis/sdks/typescript/src/sdk/config.ts:47`. ## defaultAegisStores [#defaultaegisstores] ```typescript export declare const defaultAegisStores: () => AegisStores; ``` Source: `aegis/sdks/typescript/src/sdk/client.ts:81`. ## AegisStores [#aegisstores] Collection of pluggable persistent storage backends used by the client. Defaults to in-memory implementations. Application code may inject Postgres-backed (or any other) implementations via `withStores`. ```typescript /** * Collection of pluggable persistent storage backends used by the client. * * Defaults to in-memory implementations. Application code may inject * Postgres-backed (or any other) implementations via `withStores`. */ export interface AegisStores { sessionStore: SessionStore; nonceStore: NonceStore; delegationStore: DelegationStore; revocationStore: RevocationStore; keyStore: KeyStore; verificationCacheStore: VerificationCacheStore; } ``` Source: `aegis/sdks/typescript/src/sdk/client.ts:72`. ## AegisClient [#aegisclient] Unified AEGIS client. Holds a \[`PluginRegistry`], a verification pipeline, a session manager, a delegation tree, and (optionally) a transaction pipeline. Storage backends are accessible via the `stores` field. ```typescript export declare class AegisClient { registry: PluginRegistry; verifier: VerificationPipeline; sessions: SessionManager; delegations: DelegationTree; config: AegisConfig; stores: AegisStores; constructor(params: { registry: PluginRegistry; config?: AegisConfig; stores?: AegisStores; }): AegisClient; withDefaults(registry: PluginRegistry): AegisClient; withSigner(signer: SigningBackend): this; verifyIdentity(did: string): Promise; verifyIdentityFresh(did: string): Promise; authenticate(credential: AuthCredential, identityType: IdentityType): Promise; getSession(sessionId: string): Session; revokeSession(sessionId: string): void; isSessionValid(sessionId: string): boolean; authorize(request: PolicyRequest): Promise; composePolicyDecisions(decisions: readonly PolicyDecision[]): PolicyDecision; delegate(params: { delegatorDid: string; delegateDid: string; scope: DelegationScope; expires?: string | null; signingKey: Uint8Array; verificationMethod: string; }): Delegation; verifyDelegation(delegation: Delegation, delegatorPublicKey: Uint8Array): boolean; revokeDelegation(delegationId: string): string[]; signTransaction(tx: Transaction, auth: AuthContext, policyDecision: PolicyDecision): Promise; transactions(): TransactionPipeline | null; } ``` Source: `aegis/sdks/typescript/src/sdk/client.ts:99`. # @openagentid/arsenal-sdk API URL: https://docs.openagent.id/reference/typescript/arsenal-sdks-typescript Markdown: https://docs.openagent.id/reference/typescript/arsenal-sdks-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/arsenal-sdks-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## VERSION [#version] ```typescript export declare const VERSION: "0.1.0"; ``` Source: `arsenal/sdks/typescript/src/index.ts:48`. ## isClientError [#isclienterror] Returns true if the error code falls into the 1000..5999 client-error range. ```typescript export declare const isClientError: (code: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:108`. ## isServerError [#isservererror] Returns true if the error code falls into the 6000..6999 server-error range. ```typescript export declare const isServerError: (code: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:113`. ## isProxyError [#isproxyerror] Returns true if the error code falls into the 8000..8999 proxy error range. ```typescript export declare const isProxyError: (code: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:118`. ## isConsentError [#isconsenterror] Returns true if the error code falls into the 9000..9999 consent error range. ```typescript export declare const isConsentError: (code: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:123`. ## isFingerprintError [#isfingerprinterror] Returns true if the error code falls into the 10000..10999 fingerprint range. ```typescript export declare const isFingerprintError: (code: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:128`. ## isPermanentError [#ispermanenterror] Returns true if the error is permanent (retry will not help). ```typescript export declare const isPermanentError: (code: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:133`. ## sanitizeResourceId [#sanitizeresourceid] Strip path-traversal characters and cap length. ```typescript export declare const sanitizeResourceId: (id: string) => string; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:360`. ## sanitizeScope [#sanitizescope] Strip unsafe characters from a scope; keep separators. ```typescript export declare const sanitizeScope: (scope: string) => string; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:371`. ## sanitizeFieldName [#sanitizefieldname] Strip unsafe characters from a field name. ```typescript export declare const sanitizeFieldName: (field: string) => string; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:382`. ## ErrorCode [#errorcode] Error codes for programmatic handling. Numeric values match the Rust crate `arsenal_core::error::ErrorCode` so wire-level cross-language parity holds. ```typescript export declare const ErrorCode: { readonly AuthenticationFailed: 1001; readonly TokenExpired: 1002; readonly TokenSignatureInvalid: 1003; readonly PopVerificationFailed: 1004; readonly IdentityInvalid: 1005; readonly SessionExpired: 1006; readonly InsufficientPermissions: 2001; readonly ScopeExceeded: 2002; readonly PolicyDenied: 2003; readonly DelegationInvalid: 2004; readonly RateLimitExceeded: 2005; readonly BudgetExhausted: 2006; readonly TimeConstraintViolation: 3001; readonly EnvironmentBindingViolation: 3002; readonly NetworkConstraintViolation: 3003; readonly DeviceBindingViolation: 3004; readonly OriginBindingViolation: 3005; readonly SecretNotFound: 4001; readonly SecretVersionNotFound: 4002; readonly SecretRevoked: 4003; readonly SecretRotationInProgress: 4004; readonly SecretUnwrapLimitExceeded: 4005; readonly CryptoOperationFailed: 4006; readonly ValidationFailed: 5001; readonly MalformedRequest: 5002; readonly InvalidTokenFormat: 5003; readonly InvalidScopeFormat: 5004; readonly InvalidConstraint: 5005; readonly InternalError: 6001; readonly StorageError: 6002; readonly ConfigurationError: 6003; readonly CryptoSubsystemError: 6004; readonly AuditError: 6005; readonly SerializationFailed: 6006; readonly TokenRevoked: 7001; readonly AgentDeactivated: 7002; readonly TenantSuspended: 7003; readonly RevocationStatusUnknown: 7004; readonly ProxyDestinationViolation: 8001; readonly ProxyRequestFailed: 8002; readonly ProxyTimeout: 8003; readonly SsrfBlocked: 8004; readonly TemplateVariableNotFound: 8005; readonly TemplateVariableAccessDenied: 8006; readonly InvalidTemplateVariable: 8007; readonly OAuthReauthRequired: 8008; readonly ConsentRequired: 9001; readonly ConsentDenied: 9002; readonly ConsentExpired: 9003; readonly ConsentRevoked: 9004; readonly FingerprintMismatch: 10001; readonly FingerprintStateNotFound: 10002; readonly DctScopeAmplification: 11001; readonly DctDepthExceeded: 11002; }; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:15`. ## ErrorCodeValue [#errorcodevalue] ```typescript export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]; ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:93`. ## ErrorContext [#errorcontext] Additional structured context attached to an ArsenalError. All fields are sanitized — never include raw secrets or internal paths. ```typescript /** * Additional structured context attached to an ArsenalError. All fields are * sanitized — never include raw secrets or internal paths. */ export interface ErrorContext { operation?: string; resource?: string; constraint?: string; timestamp?: string; // ISO 8601 } ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:141`. ## ArsenalError [#arsenalerror] Main error type for ARSENAL operations. Extends the native `Error` class so it interoperates with standard JS error handling while carrying structured code/correlation/context fields. ```typescript export declare class ArsenalError { name: "ArsenalError"; code: number; correlationId: string | undefined; context: ErrorContext | undefined; constructor(code: number, message: string, options?: { correlationId?: string; context?: ErrorContext; cause?: unknown; }): ArsenalError; toString(): string; toJSON(): { code: number; message: string; correlation_id?: string; context?: ErrorContext; }; withCorrelationId(id: string): ArsenalError; withContext(context: ErrorContext): ArsenalError; authenticationFailed(): ArsenalError; tokenExpired(): ArsenalError; tokenSignatureInvalid(): ArsenalError; tokenRevoked(): ArsenalError; scopeExceeded(): ArsenalError; insufficientPermissions(requiredScope: string): ArsenalError; policyDenied(policyId: string): ArsenalError; rateLimitExceeded(retryAfterSecs?: number): ArsenalError; secretNotFound(): ArsenalError; validationFailed(field: string, reason: string): ArsenalError; internal(): ArsenalError; sessionExpired(): ArsenalError; proxyDestinationViolation(domain: string): ArsenalError; ssrfBlocked(): ArsenalError; templateVariableNotFound(variable: string): ArsenalError; invalidTemplateVariable(name: string): ArsenalError; consentRequired(): ArsenalError; consentDenied(): ArsenalError; fingerprintMismatch(): ArsenalError; configurationError(component: string): ArsenalError; cryptoOperationFailed(): ArsenalError; } ``` Source: `arsenal/sdks/typescript/src/core/errors.ts:154`. ## TenantId [#tenantid] Tenant identifier — represents an organization or customer. ```typescript export declare class TenantId { parse(id: string): TenantId; generate(): TenantId; asString(): string; toString(): string; toJSON(): string; equals(other: TenantId): boolean; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:21`. ## PrincipalId [#principalid] Principal identifier — user, service account, or system principal. ```typescript export declare class PrincipalId { parse(id: string): PrincipalId; generate(): PrincipalId; system(): PrincipalId; isSystem(): boolean; asString(): string; toString(): string; toJSON(): string; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:63`. ## AgentId [#agentid] Agent identifier (UUID v4). ```typescript export declare class AgentId { fromUuid(uuid: string): AgentId; generate(): AgentId; asUuid(): string; toString(): string; toJSON(): string; equals(other: AgentId): boolean; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:109`. ## DeviceId [#deviceid] Device identifier for device binding. ```typescript export declare class DeviceId { parse(id: string): DeviceId; asString(): string; toString(): string; toJSON(): string; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:145`. ## KeyFingerprint [#keyfingerprint] Public-key fingerprint — BLAKE3 hash (32 bytes) of a public key. Uses a constant-time compare for equality checks. ```typescript export declare class KeyFingerprint { fromBytes(bytes: Uint8Array): KeyFingerprint; fromPublicKey(publicKey: Uint8Array): Promise; fromHex(hex: string): KeyFingerprint; asBytes(): Uint8Array; toHex(): string; toString(): string; constantTimeEquals(other: KeyFingerprint): boolean; toJSON(): string; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:180`. ## AgentIdentityData [#agentidentitydata] Agent identity — the public cryptographic identity of an agent. Contains only public key material — the private key is never stored. ```typescript /** * Agent identity — the public cryptographic identity of an agent. * * Contains only public key material — the private key is never stored. */ export interface AgentIdentityData { id: AgentId; publicKeyFingerprint: KeyFingerprint; tenantId: TenantId; name: string; createdAt: string; // ISO 8601 expiresAt: string | null; isActive: boolean; tags: readonly string[]; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:249`. ## AgentIdentity [#agentidentity] ```typescript export declare class AgentIdentity { create(tenantId: TenantId, name: string, publicKeyFingerprint: KeyFingerprint): AgentIdentity; id(): AgentId; publicKeyFingerprint(): KeyFingerprint; tenantId(): TenantId; name(): string; isActive(): boolean; tags(): readonly string[]; isValid(now?: Date): boolean; deactivate(): AgentIdentity; withExpiresAt(expiresAt: Date): AgentIdentity; withTag(tag: string): AgentIdentity; toJSON(): { id: string; public_key_fingerprint: string; tenant_id: string; name: string; created_at: string; expires_at: string | null; is_active: boolean; tags: readonly string[]; }; } ``` Source: `arsenal/sdks/typescript/src/core/identity.ts:260`. ## permissionImplies [#permissionimplies] Check if permission `a` implies permission `b`. ```typescript export declare const permissionImplies: (a: PermissionValue, b: PermissionValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/scope.ts:228`. ## parsePermission [#parsepermission] Parse a string into a Permission value. Throws on unknown input. ```typescript export declare const parsePermission: (s: string) => PermissionValue; ``` Source: `arsenal/sdks/typescript/src/core/scope.ts:234`. ## Scope [#scope] A single permission scope. ```typescript export declare class Scope { parse(scope: string): Scope; wildcard(): Scope; readOnly(service: string): Scope; fullAccess(service: string): Scope; service(): string; resource(): string; action(): string; isWildcard(): boolean; implies(other: Scope): boolean; asString(): string; toString(): string; toJSON(): string; equals(other: Scope): boolean; } ``` Source: `arsenal/sdks/typescript/src/core/scope.ts:19`. ## ScopeSet [#scopeset] A set of scopes, maintained as a sorted list for deterministic encoding. ```typescript export declare class ScopeSet { empty(): ScopeSet; single(scope: Scope): ScopeSet; fromStrings(scopes: readonly string[]): ScopeSet; fromScopes(scopes: readonly Scope[]): ScopeSet; add(scope: Scope): ScopeSet; remove(scope: Scope): ScopeSet; contains(scope: Scope): boolean; allows(requested: Scope): boolean; isSupersetOf(other: ScopeSet): boolean; intersection(other: ScopeSet): ScopeSet; union(other: ScopeSet): ScopeSet; length(): number; isEmpty(): boolean; toArray(): readonly Scope[]; toStrings(): readonly string[]; [Symbol.iterator](): Iterator; toJSON(): readonly string[]; } ``` Source: `arsenal/sdks/typescript/src/core/scope.ts:124`. ## Permission [#permission] CRUD permission classification. ```typescript export declare const Permission: { readonly Read: "read"; readonly Create: "create"; readonly Update: "update"; readonly Delete: "delete"; readonly Admin: "admin"; }; ``` Source: `arsenal/sdks/typescript/src/core/scope.ts:217`. ## PermissionValue [#permissionvalue] ```typescript export type PermissionValue = (typeof Permission)[keyof typeof Permission]; ``` Source: `arsenal/sdks/typescript/src/core/scope.ts:225`. ## noConstraints [#noconstraints] Build an empty constraint object (no restrictions). ```typescript export declare const noConstraints: () => Constraints; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:75`. ## withPop [#withpop] Create constraints requiring proof-of-possession. ```typescript export declare const withPop: () => Constraints; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:80`. ## withDevice [#withdevice] Create constraints with a required device binding. ```typescript export declare const withDevice: (base: Constraints, deviceId: string) => Constraints; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:85`. ## withOrigins [#withorigins] Create constraints with an allowed-origins binding. ```typescript export declare const withOrigins: (base: Constraints, origins: readonly string[]) => Constraints; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:95`. ## withTimeWindow [#withtimewindow] Create constraints with a time window. ```typescript export declare const withTimeWindow: (base: Constraints, notBefore: Date, notAfter: Date) => Constraints; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:103`. ## contextNow [#contextnow] Create a fresh ConstraintContext with current\_time=now(). ```typescript export declare const contextNow: () => ConstraintContext; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:118`. ## validateConstraints [#validateconstraints] Validate a set of constraints against a request context. Throws an `ArsenalError` on the first violation. ```typescript export declare const validateConstraints: (constraints: Constraints, ctx: ConstraintContext) => void; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:129`. ## ipInCidrRange [#ipincidrrange] Check if a dotted-quad or IPv6 address falls inside a CIDR range. Supports both IPv4 and IPv6. Invalid CIDR or IP input returns false. ```typescript export declare const ipInCidrRange: (ip: string, cidr: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:317`. ## BindingType [#bindingtype] ```typescript export declare const BindingType: { readonly Required: "required"; readonly Preferred: "preferred"; }; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:12`. ## BindingTypeValue [#bindingtypevalue] ```typescript export type BindingTypeValue = (typeof BindingType)[keyof typeof BindingType]; ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:17`. ## DeviceBinding [#devicebinding] ```typescript export interface DeviceBinding { device_id: string; binding_type: BindingTypeValue; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:19`. ## SessionBinding [#sessionbinding] ```typescript export interface SessionBinding { session_id: string; session_key_hash?: Uint8Array; // 32 bytes when set } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:24`. ## OriginBinding [#originbinding] ```typescript export interface OriginBinding { allowed_origins: ReadonlySet; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:29`. ## NetworkConstraints [#networkconstraints] ```typescript export interface NetworkConstraints { allowed_ips?: ReadonlySet; denied_ips?: ReadonlySet; allowed_cidrs?: readonly string[]; allowed_asns?: ReadonlySet; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:33`. ## TimeConstraints [#timeconstraints] ```typescript export interface TimeConstraints { not_before?: string; // ISO 8601 not_after?: string; // ISO 8601 allowed_hours?: readonly number[]; allowed_days?: readonly number[]; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:40`. ## EnvironmentConstraint [#environmentconstraint] ```typescript export interface EnvironmentConstraint { required_environment?: string; required_tags?: ReadonlySet; forbidden_tags?: ReadonlySet; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:47`. ## Constraints [#constraints] ```typescript export interface Constraints { device_binding?: DeviceBinding; session_binding?: SessionBinding; origin_binding?: OriginBinding; network_constraints?: NetworkConstraints; time_constraints?: TimeConstraints; environment_constraints?: EnvironmentConstraint; require_pop: boolean; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:53`. ## ConstraintContext [#constraintcontext] ```typescript export interface ConstraintContext { current_time: Date; device_id?: string; session_id?: string; session_key_hash?: Uint8Array; origin?: string; client_ip?: string; environment?: string; tags: ReadonlySet; } ``` Source: `arsenal/sdks/typescript/src/core/constraints.ts:63`. ## defaultRateLimits [#defaultratelimits] Default moderate rate limits (same as Rust `RateLimits::default()`). ```typescript export declare const defaultRateLimits: () => RateLimits; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:17`. ## unlimitedRateLimits [#unlimitedratelimits] All unlimited — use with care. ```typescript export declare const unlimitedRateLimits: () => RateLimits; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:29`. ## strictRateLimits [#strictratelimits] Strict lockdown rate limits. ```typescript export declare const strictRateLimits: () => RateLimits; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:34`. ## mergeRateLimits [#mergeratelimits] Merge two limit configs taking the more restrictive (minimum) value. ```typescript export declare const mergeRateLimits: (a: RateLimits, b: RateLimits) => RateLimits; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:46`. ## defaultUsageBudget [#defaultusagebudget] ```typescript export declare const defaultUsageBudget: () => UsageBudget; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:78`. ## unlimitedUsageBudget [#unlimitedusagebudget] ```typescript export declare const unlimitedUsageBudget: () => UsageBudget; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:88`. ## minimalUsageBudget [#minimalusagebudget] ```typescript export declare const minimalUsageBudget: () => UsageBudget; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:92`. ## mergeUsageBudget [#mergeusagebudget] ```typescript export declare const mergeUsageBudget: (a: UsageBudget, b: UsageBudget) => UsageBudget; ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:102`. ## RateLimits [#ratelimits] ```typescript export interface RateLimits { requests_per_second?: number; requests_per_minute?: number; requests_per_hour?: number; max_concurrent?: number; max_request_size?: number; max_response_size?: number; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:7`. ## UsageBudget [#usagebudget] ```typescript export interface UsageBudget { max_requests?: number; max_bytes?: number; max_cost_units?: number; max_secret_unwraps?: number; max_delegation_depth?: number; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:70`. ## UsageStats [#usagestats] Current usage snapshot. ```typescript /** Current usage snapshot. */ export interface UsageStats { request_count: number; bytes_transferred: number; cost_units: number; secret_unwraps: number; elapsed_ms: number; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:126`. ## RemainingBudget [#remainingbudget] Remaining budget (undefined entries are unlimited). ```typescript /** Remaining budget (undefined entries are unlimited). */ export interface RemainingBudget { requests?: number; bytes?: number; cost_units?: number; secret_unwraps?: number; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:135`. ## UsageTracker [#usagetracker] Runtime usage tracker that enforces a budget. Each `record*` call either succeeds or throws an ArsenalError with code `BudgetExhausted` (or `SecretUnwrapLimitExceeded`). ```typescript export declare class UsageTracker { constructor(budget: UsageBudget): UsageTracker; recordRequest(): void; recordBytes(bytes: number): void; recordCost(units: number): void; recordSecretUnwrap(): void; getStats(): UsageStats; remaining(): RemainingBudget; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:148`. ## TokenBucketLimiter [#tokenbucketlimiter] Token-bucket rate limiter. Lock-free single-threaded (JS single-threaded execution model) — refills on each try\_acquire based on elapsed wall clock. ```typescript export declare class TokenBucketLimiter { constructor(maxTokens: number, refillAmount: number, refillIntervalMs: number): TokenBucketLimiter; perSecond(rate: number): TokenBucketLimiter; perMinute(rate: number): TokenBucketLimiter; perHour(rate: number): TokenBucketLimiter; tryAcquire(): void; available(): number; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:236`. ## CompositeRateLimiter [#compositeratelimiter] Composite rate limiter combining multiple time windows + concurrent cap. Use `acquire()` which returns a release function — call it when the request completes (e.g. in a `finally`) to decrement the concurrent counter. If any individual limit rejects, already-consumed slots are rolled back. ```typescript export declare class CompositeRateLimiter { constructor(limits: RateLimits): CompositeRateLimiter; acquire(): () => void; } ``` Source: `arsenal/sdks/typescript/src/core/limits.ts:295`. ## createSecretMetadata [#createsecretmetadata] Create a new secret metadata record. ```typescript export declare const createSecretMetadata: (tenantId: string, name: string, secretType: SecretTypeValue) => SecretMetadata; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:142`. ## latestSecretRef [#latestsecretref] Reference to the latest version. ```typescript export declare const latestSecretRef: (id: string) => SecretRef; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:178`. ## specificSecretRef [#specificsecretref] Reference to a specific version. ```typescript export declare const specificSecretRef: (id: string, version: number) => SecretRef; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:183`. ## SecretId [#secretid] Secret identifier. ```typescript export declare class SecretId { generate(): SecretId; fromString(id: string): SecretId; asString(): string; toString(): string; toJSON(): string; } ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:18`. ## SecretVersion [#secretversion] Secret version number (1-based). ```typescript export declare class SecretVersion { initial(): SecretVersion; fromNumber(n: number): SecretVersion; asNumber(): number; next(): SecretVersion; isInitial(): boolean; toString(): string; toJSON(): number; } ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:52`. ## SecretType [#secrettype] ```typescript export declare const SecretType: { readonly ApiKey: "api_key"; readonly OAuthClientCredentials: "o_auth_client_credentials"; readonly OAuthAccessToken: "o_auth_access_token"; readonly OAuthRefreshToken: "o_auth_refresh_token"; readonly DatabaseCredentials: "database_credentials"; readonly SshKey: "ssh_key"; readonly TlsCertificate: "tls_certificate"; readonly SigningKey: "signing_key"; readonly EncryptionKey: "encryption_key"; readonly Generic: "generic"; }; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:91`. ## SecretTypeValue [#secrettypevalue] ```typescript export type SecretTypeValue = (typeof SecretType)[keyof typeof SecretType]; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:104`. ## SecretVersionState [#secretversionstate] ```typescript export declare const SecretVersionState: { readonly Active: "active"; readonly Previous: "previous"; readonly Disabled: "disabled"; readonly PendingDeletion: "pending_deletion"; }; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:106`. ## SecretVersionStateValue [#secretversionstatevalue] ```typescript export type SecretVersionStateValue = (typeof SecretVersionState)[keyof typeof SecretVersionState]; ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:113`. ## SecretVersionInfo [#secretversioninfo] ```typescript export interface SecretVersionInfo { version: number; created_at: string; created_by?: string; state: SecretVersionStateValue; } ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:116`. ## SecretMetadata [#secretmetadata] ```typescript export interface SecretMetadata { id: string; tenant_id: string; name: string; description?: string; secret_type: SecretTypeValue; current_version: number; versions: readonly SecretVersionInfo[]; created_at: string; updated_at: string; expires_at?: string; last_rotated_at?: string; next_rotation_at?: string; is_active: boolean; labels: Readonly>; service?: string; } ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:123`. ## SecretRef [#secretref] Reference to a secret — used when the value shouldn't be inlined. ```typescript /** Reference to a secret — used when the value shouldn't be inlined. */ export interface SecretRef { id: string; version?: number; } ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:172`. ## SecretValue [#secretvalue] Secret value holder that clears its internal buffer when `zeroize()` is called. JS has no destructors, so callers must explicitly invoke `zeroize()` in a `finally` block after use. ```typescript export declare class SecretValue { fromBytes(bytes: Uint8Array): SecretValue; fromString(s: string): SecretValue; asBytes(): Uint8Array; asString(): string; length(): number; isEmpty(): boolean; zeroize(): void; } ``` Source: `arsenal/sdks/typescript/src/core/secret.ts:192`. ## buildTokenClaims [#buildtokenclaims] Validate and build a fresh set of token claims. ```typescript export declare const buildTokenClaims: (opts: TokenClaimsBuildOptions) => TokenClaims; ``` Source: `arsenal/sdks/typescript/src/core/token.ts:89`. ## SignatureAlgorithm [#signaturealgorithm] ```typescript export declare const SignatureAlgorithm: { readonly Ed25519: "ED25519"; readonly Es256: "ES256"; readonly Es384: "ES384"; }; ``` Source: `arsenal/sdks/typescript/src/core/token.ts:23`. ## SignatureAlgorithmValue [#signaturealgorithmvalue] ```typescript export type SignatureAlgorithmValue = (typeof SignatureAlgorithm)[keyof typeof SignatureAlgorithm]; ``` Source: `arsenal/sdks/typescript/src/core/token.ts:29`. ## TokenSignature [#tokensignature] ```typescript export interface TokenSignature { bytes: Uint8Array; algorithm: SignatureAlgorithmValue; key_id?: string; } ``` Source: `arsenal/sdks/typescript/src/core/token.ts:32`. ## ProofOfPossession [#proofofpossession] ```typescript export interface ProofOfPossession { /** Hex-encoded BLAKE3 public key fingerprint. */ key_fingerprint: string; /** Algorithm label, e.g. "Ed25519". */ alg: string; } ``` Source: `arsenal/sdks/typescript/src/core/token.ts:38`. ## TokenTrace [#tokentrace] ```typescript export interface TokenTrace { issuance_id: string; parent_token_id?: string; policy_id?: string; delegation_depth: number; } ``` Source: `arsenal/sdks/typescript/src/core/token.ts:45`. ## TokenClaims [#tokenclaims] ```typescript export interface TokenClaims { jti: string; // Token ID (UUID v7) sub: string; // Subject (agent ID UUID) iss: string; // Issuer aud: string; // Audience iat: string; // Issued-at ISO timestamp nbf: string; // Not-before ISO timestamp exp: string; // Expiration ISO timestamp tenant_id: string; scope: readonly string[]; constraints?: Constraints; limits?: RateLimits; budget?: UsageBudget; trace?: TokenTrace; cnf?: ProofOfPossession; delegated_variables?: readonly string[]; max_delegation_depth?: number; } ``` Source: `arsenal/sdks/typescript/src/core/token.ts:52`. ## TokenClaimsBuildOptions [#tokenclaimsbuildoptions] Options for building a fresh set of claims. ```typescript /** Options for building a fresh set of claims. */ export interface TokenClaimsBuildOptions { subject: string; issuer: string; audience: string; tenant_id: string; scopes: ScopeSet; ttl_seconds?: number; constraints?: Constraints; limits?: RateLimits; budget?: UsageBudget; parent_token_id?: string; cnf?: ProofOfPossession; delegated_variables?: readonly string[]; max_delegation_depth?: number; } ``` Source: `arsenal/sdks/typescript/src/core/token.ts:72`. ## AgentCapabilityToken [#agentcapabilitytoken] Immutable Agent Capability Token. Wraps a set of claims and an optional signature, and provides validation + CBOR (de)serialization. ```typescript export declare class AgentCapabilityToken { fromClaims(claims: TokenClaims): AgentCapabilityToken; fromClaimsAndSignature(claims: TokenClaims, signature: TokenSignature): AgentCapabilityToken; id(): string; subject(): string; audience(): string; scopes(): ScopeSet; isExpired(now?: Date): boolean; isNotYetValid(now?: Date): boolean; isTimeValid(now?: Date): boolean; remainingTtlMs(now?: Date): number; isSigned(): boolean; validateStructure(now?: Date): void; toCbor(): Uint8Array; claimsToCbor(): Uint8Array; toBase64Url(): string; fromCbor(bytes: Uint8Array): AgentCapabilityToken; fromBase64Url(s: string): AgentCapabilityToken; } ``` Source: `arsenal/sdks/typescript/src/core/token.ts:135`. ## consentStatusAllowsOperation [#consentstatusallowsoperation] ```typescript export declare const consentStatusAllowsOperation: (status: ConsentStatusValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:26`. ## consentRecordIsValid [#consentrecordisvalid] Validity check (not revoked and not expired). ```typescript export declare const consentRecordIsValid: (record: ConsentRecord, now?: Date) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:61`. ## consentRecordCoversVariable [#consentrecordcoversvariable] Returns true if the record covers the given variable name. ```typescript export declare const consentRecordCoversVariable: (record: ConsentRecord, variable: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:67`. ## consentRecordCoversDomain [#consentrecordcoversdomain] Returns true if the record covers the given destination domain (case-insensitive). ```typescript export declare const consentRecordCoversDomain: (record: ConsentRecord, domain: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:75`. ## revokeConsentRecord [#revokeconsentrecord] Return a revoked copy of the consent record. ```typescript export declare const revokeConsentRecord: (record: ConsentRecord, at?: Date) => ConsentRecord; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:84`. ## consentRecordSigningBytes [#consentrecordsigningbytes] Canonical CBOR encoding of the signable subset (excludes signature, revoked, revoked\_at). This is the byte sequence a human root key signs with Ed25519 to produce `record.signature`. ```typescript export declare const consentRecordSigningBytes: (record: ConsentRecord) => Uint8Array; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:96`. ## createConsentRequest [#createconsentrequest] Create a new consent request with validation. ```typescript export declare const createConsentRequest: (opts: { agent_did: string; human_root_did: string; variables: readonly string[]; destination_domains: readonly string[]; scopes: readonly string[]; ttl_seconds?: number; }) => ConsentRequest; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:123`. ## consentRequestIsExpired [#consentrequestisexpired] ```typescript export declare const consentRequestIsExpired: (req: ConsentRequest, now?: Date) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:156`. ## ConsentStatus [#consentstatus] ```typescript export declare const ConsentStatus: { readonly PreApproved: "pre_approved"; readonly Approved: "approved"; readonly Pending: "pending"; readonly Denied: "denied"; readonly Revoked: "revoked"; readonly NotRequired: "not_required"; }; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:15`. ## ConsentStatusValue [#consentstatusvalue] ```typescript export type ConsentStatusValue = (typeof ConsentStatus)[keyof typeof ConsentStatus]; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:24`. ## ConsentPolicy [#consentpolicy] ```typescript export declare const ConsentPolicy: { readonly PerVariable: "per_variable"; readonly PerProvider: "per_provider"; readonly PerAgent: "per_agent"; }; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:34`. ## ConsentPolicyValue [#consentpolicyvalue] ```typescript export type ConsentPolicyValue = (typeof ConsentPolicy)[keyof typeof ConsentPolicy]; ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:40`. ## ConsentRecord [#consentrecord] ```typescript export interface ConsentRecord { consent_id: string; tenant_id: string; agent_did: string; human_root_did: string; variables: readonly string[]; destination_domains: readonly string[]; scopes: readonly string[]; granted_by: string; granted_at: string; expires_at: string; /** Ed25519 signature bytes over the signing payload. */ signature: Uint8Array; revocable: boolean; revoked: boolean; revoked_at?: string; } ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:42`. ## ConsentRequest [#consentrequest] ```typescript export interface ConsentRequest { request_id: string; agent_did: string; human_root_did: string; variables: readonly string[]; destination_domains: readonly string[]; scopes: readonly string[]; created_at: string; expires_at: string; } ``` Source: `arsenal/sdks/typescript/src/core/consent.ts:111`. ## createDestinationBinding [#createdestinationbinding] Create and validate a destination binding. ```typescript export declare const createDestinationBinding: (allowedDomains: readonly string[], opts?: Partial>) => DestinationBinding; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:61`. ## validateDestinationBinding [#validatedestinationbinding] Throws if the binding is malformed. ```typescript export declare const validateDestinationBinding: (binding: DestinationBinding) => void; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:78`. ## isDomainAllowed [#isdomainallowed] Check if a domain is allowed by the binding. ```typescript export declare const isDomainAllowed: (binding: DestinationBinding, domain: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:109`. ## isMethodAllowed [#ismethodallowed] ```typescript export declare const isMethodAllowed: (binding: DestinationBinding, method: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:119`. ## isPortAllowed [#isportallowed] ```typescript export declare const isPortAllowed: (binding: DestinationBinding, port: number) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:124`. ## isPathAllowed [#ispathallowed] ```typescript export declare const isPathAllowed: (binding: DestinationBinding, path: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:129`. ## createTemplateVariable [#createtemplatevariable] Create a template variable, validating the name. ```typescript export declare const createTemplateVariable: (name: string) => TemplateVariable; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:165`. ## validateVariableName [#validatevariablename] ```typescript export declare const validateVariableName: (name: string) => void; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:170`. ## inferVariablePrefix [#infervariableprefix] Infer the credential-type prefix from a variable name. ```typescript export declare const inferVariablePrefix: (name: string) => VariablePrefixValue; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:192`. ## parseTemplateVariables [#parsetemplatevariables] Parse all `{{VARIABLE}}` placeholders from a string. Invalid names inside `{{}}` are silently skipped. Duplicates are deduplicated. ```typescript export declare const parseTemplateVariables: (input: string) => readonly TemplateVariable[]; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:207`. ## validateProxyRequest [#validateproxyrequest] Validate structural fields of a proxy request. ```typescript export declare const validateProxyRequest: (req: ProxyRequest) => void; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:243`. ## effectiveTimeoutMs [#effectivetimeoutms] Resolve the effective timeout, capped to MAX\_TIMEOUT\_MS. ```typescript export declare const effectiveTimeoutMs: (req: ProxyRequest) => number; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:263`. ## extractProxyRequestVariables [#extractproxyrequestvariables] Extract all template variables used anywhere in a proxy request. ```typescript export declare const extractProxyRequestVariables: (req: ProxyRequest) => readonly TemplateVariable[]; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:268`. ## VariablePrefix [#variableprefix] ```typescript export declare const VariablePrefix: { readonly OAuth2: "OAUTH2"; readonly OAuth1: "OAUTH1"; readonly ApiKey: "API_KEY"; readonly Basic: "BASIC"; readonly Bearer: "BEARER"; readonly Cert: "CERT"; readonly Custom: "CUSTOM"; }; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:38`. ## VariablePrefixValue [#variableprefixvalue] ```typescript export type VariablePrefixValue = (typeof VariablePrefix)[keyof typeof VariablePrefix]; ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:48`. ## DestinationBinding [#destinationbinding] Destination binding restricting which endpoints a credential can reach. ```typescript /** Destination binding restricting which endpoints a credential can reach. */ export interface DestinationBinding { allowed_domains: readonly string[]; allowed_paths?: readonly string[]; allowed_methods?: readonly string[]; allowed_ports?: readonly number[]; require_tls: boolean; allow_subdomains: boolean; } ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:51`. ## TemplateVariable [#templatevariable] Parsed template variable reference. ```typescript /** Parsed template variable reference. */ export interface TemplateVariable { name: string; prefix: VariablePrefixValue; } ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:159`. ## ProxyRequest [#proxyrequest] Proxy request envelope sent to the broker. ```typescript /** Proxy request envelope sent to the broker. */ export interface ProxyRequest { method: string; url: string; headers?: Readonly>; body?: Uint8Array; capability_token: string; timeout_ms?: number; } ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:233`. ## ProxyResponse [#proxyresponse] Response from a proxy request. ```typescript /** Response from a proxy request. */ export interface ProxyResponse { status: number; headers: Readonly>; body: Uint8Array; proxy_metadata: ProxyMetadata; } ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:296`. ## ProxyMetadata [#proxymetadata] Metadata about proxy processing (never includes resolved values). ```typescript /** Metadata about proxy processing (never includes resolved values). */ export interface ProxyMetadata { variables_resolved: readonly string[]; destination_verified: boolean; fingerprint_verified: boolean; consent_status: ConsentStatusValue; latency_ms: number; request_id: string; } ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:304`. ## VariableResolutionTable [#variableresolutiontable] In-memory variable → secret-ref table used by the broker. ```typescript export declare class VariableResolutionTable { register(variableName: string, secretRef: { id: string; version?: number; }): void; unregister(variableName: string): boolean; resolve(variableName: string): { id: string; version?: number; } | undefined; variableNames(): readonly string[]; size(): number; isEmpty(): boolean; } ``` Source: `arsenal/sdks/typescript/src/core/proxy.ts:314`. ## createPolicyRule [#createpolicyrule] Create a simple rule. Conditions are added via spread. ```typescript export declare const createPolicyRule: (id: string, effect: PolicyEffectValue, conditions?: readonly PolicyCondition[]) => PolicyRule; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:104`. ## createPolicyDocument [#createpolicydocument] Build a new policy document (no rules yet). ```typescript export declare const createPolicyDocument: (tenantId: string, name: string) => PolicyDocument; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:136`. ## addPolicyRule [#addpolicyrule] Append a rule to a policy, returning a new document. ```typescript export declare const addPolicyRule: (doc: PolicyDocument, rule: PolicyRule) => PolicyDocument; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:160`. ## createPolicyRequest [#createpolicyrequest] Create a new policy request with current timestamp. ```typescript export declare const createPolicyRequest: (agentId: string, tenantId: string, requestedScope: string) => PolicyRequest; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:182`. ## decisionIsAllowed [#decisionisallowed] Returns true if the decision allows the action. ```typescript export declare const decisionIsAllowed: (d: PolicyDecision) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:203`. ## decisionIsDenied [#decisionisdenied] Returns true if the decision denies the action. ```typescript export declare const decisionIsDenied: (d: PolicyDecision) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:208`. ## MAX\_CONDITION\_DEPTH [#max_condition_depth] Maximum recursion depth for nested And/Or/Not conditions. ```typescript export declare const MAX_CONDITION_DEPTH: 16; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:17`. ## PolicyId [#policyid] ```typescript export declare class PolicyId { parse(id: string): PolicyId; generate(): PolicyId; asString(): string; toString(): string; toJSON(): string; } ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:19`. ## PolicyEffect [#policyeffect] ```typescript export declare const PolicyEffect: { readonly Allow: "allow"; readonly Deny: "deny"; }; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:53`. ## PolicyEffectValue [#policyeffectvalue] ```typescript export type PolicyEffectValue = (typeof PolicyEffect)[keyof typeof PolicyEffect]; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:58`. ## ConditionOperator [#conditionoperator] ```typescript export declare const ConditionOperator: { readonly Equals: "equals"; readonly NotEquals: "not_equals"; readonly Contains: "contains"; readonly StartsWith: "starts_with"; readonly EndsWith: "ends_with"; readonly Matches: "matches"; readonly In: "in"; readonly NotIn: "not_in"; }; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:60`. ## ConditionOperatorValue [#conditionoperatorvalue] ```typescript export type ConditionOperatorValue = (typeof ConditionOperator)[keyof typeof ConditionOperator]; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:71`. ## PolicyCondition [#policycondition] ```typescript export type PolicyCondition = { type: "agent_id"; operator: ConditionOperatorValue; value: string; } | { type: "tenant_id"; operator: ConditionOperatorValue; value: string; } | { type: "scope"; operator: ConditionOperatorValue; value: string; } | { type: "environment"; operator: ConditionOperatorValue; value: string; } | { type: "time_of_day"; allowed_hours: readonly number[]; } | { type: "day_of_week"; allowed_days: readonly number[]; } | { type: "ip_address"; allowed_cidrs: readonly string[]; } | { type: "attribute"; key: string; operator: ConditionOperatorValue; value: string; } | { type: "and"; conditions: readonly PolicyCondition[]; } | { type: "or"; conditions: readonly PolicyCondition[]; } | { type: "not"; condition: PolicyCondition; }; ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:74`. ## PolicyRule [#policyrule] ```typescript export interface PolicyRule { id: string; description?: string; effect: PolicyEffectValue; conditions: readonly PolicyCondition[]; scopes?: ScopeSet; constraints?: Constraints; rate_limits?: RateLimits; budget?: UsageBudget; } ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:92`. ## PolicySignature [#policysignature] ```typescript export interface PolicySignature { bytes: Uint8Array; algorithm: string; key_id: string; signed_at: string; } ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:112`. ## PolicyDocument [#policydocument] ```typescript export interface PolicyDocument { id: string; version: number; tenant_id: string; name: string; description?: string; rules: readonly PolicyRule[]; default_effect: PolicyEffectValue; is_active: boolean; priority: number; created_at: string; updated_at: string; signature?: PolicySignature; labels: Readonly>; } ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:119`. ## PolicyRequest [#policyrequest] ```typescript export interface PolicyRequest { agent_id: string; tenant_id: string; requested_scope: string; timestamp: Date; environment?: string; client_ip?: string; attributes: Readonly>; } ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:171`. ## PolicyDecision [#policydecision] ```typescript export interface PolicyDecision { effect: PolicyEffectValue; matched_rule?: string; reason?: string; } ``` Source: `arsenal/sdks/typescript/src/core/policy.ts:196`. ## denyDelegation [#denydelegation] Default: delegation denied. ```typescript export declare const denyDelegation: () => DelegationConstraints; ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:29`. ## allowDelegation [#allowdelegation] Allow up to `depth` levels of delegation to any agent. ```typescript export declare const allowDelegation: (depth: number) => DelegationConstraints; ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:41`. ## canDelegateTo [#candelegateto] Check whether a delegation to the given agent id is permitted. ```typescript export declare const canDelegateTo: (constraints: DelegationConstraints, agentId: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:53`. ## validateDelegationDepth [#validatedelegationdepth] Validate a delegation chain length and scope non-amplification rule. ```typescript export declare const validateDelegationDepth: (depth: number) => void; ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:63`. ## MAX\_DELEGATION\_DEPTH [#max_delegation_depth] Maximum absolute delegation depth allowed anywhere in the system. ```typescript export declare const MAX_DELEGATION_DEPTH: 5; ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:12`. ## MAX\_CHAIN\_LENGTH [#max_chain_length] Maximum number of tokens in a delegation chain. ```typescript export declare const MAX_CHAIN_LENGTH: 10; ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:15`. ## DelegationConstraints [#delegationconstraints] ```typescript export interface DelegationConstraints { allow_delegation: boolean; max_depth: number; delegatable_scopes?: ScopeSet; allowed_delegates: readonly string[]; allow_any_delegate: boolean; /** Minimum TTL reduction (seconds) between parent and child token. */ min_ttl_reduction: number; require_approval: boolean; } ``` Source: `arsenal/sdks/typescript/src/core/delegation.ts:17`. ## sessionStateCanUseTools [#sessionstatecanusetools] ```typescript export declare const sessionStateCanUseTools: (state: SessionStateValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:55`. ## sessionStateCanRequestCapabilities [#sessionstatecanrequestcapabilities] ```typescript export declare const sessionStateCanRequestCapabilities: (state: SessionStateValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:59`. ## sessionStateIsTerminal [#sessionstateisterminal] ```typescript export declare const sessionStateIsTerminal: (state: SessionStateValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:67`. ## sessionStateIsActive [#sessionstateisactive] ```typescript export declare const sessionStateIsActive: (state: SessionStateValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:71`. ## validSessionStateTransitions [#validsessionstatetransitions] Returns the set of valid transitions from a given state. ```typescript export declare const validSessionStateTransitions: (state: SessionStateValue) => readonly SessionStateValue[]; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:76`. ## canTransitionTo [#cantransitionto] ```typescript export declare const canTransitionTo: (from: SessionStateValue, to: SessionStateValue) => boolean; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:107`. ## SessionId [#sessionid] Session identifier (UUID v7 in Rust; UUID v4 is acceptable here). ```typescript export declare class SessionId { generate(): SessionId; fromString(s: string): SessionId; asString(): string; toString(): string; toJSON(): string; } ``` Source: `arsenal/sdks/typescript/src/core/session.ts:10`. ## SessionState [#sessionstate] ```typescript export declare const SessionState: { readonly AgentBootstrapped: "agent_bootstrapped"; readonly SessionStarted: "session_started"; readonly CapabilitiesGranted: "capabilities_granted"; readonly ToolUse: "tool_use"; readonly Renewal: "renewal"; readonly Escalation: "escalation"; readonly SessionEnded: "session_ended"; }; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:43`. ## SessionStateValue [#sessionstatevalue] ```typescript export type SessionStateValue = (typeof SessionState)[keyof typeof SessionState]; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:53`. ## SessionEndReason [#sessionendreason] ```typescript export declare const SessionEndReason: { readonly Completed: "completed"; readonly Logout: "logout"; readonly Timeout: "timeout"; readonly TokenExpired: "token_expired"; readonly Revoked: "revoked"; readonly SecurityViolation: "security_violation"; readonly PolicyViolation: "policy_violation"; readonly SystemShutdown: "system_shutdown"; }; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:114`. ## SessionEndReasonValue [#sessionendreasonvalue] ```typescript export type SessionEndReasonValue = (typeof SessionEndReason)[keyof typeof SessionEndReason] | { error: string; }; ``` Source: `arsenal/sdks/typescript/src/core/session.ts:125`. ## createAuditEvent [#createauditevent] Create a new audit event. ```typescript export declare const createAuditEvent: (opts: { kind: AuditEventKindValue; tenant_id: string; severity?: AuditSeverityValue; outcome?: AuditOutcomeValue; description?: string; metadata?: Record; agent_id?: string; session_id?: string; token_id?: string; client_ip?: string; user_agent?: string; request_id?: string; }) => AuditEvent; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:88`. ## hashAuditEvent [#hashauditevent] Compute a BLAKE3 hash of an audit event. The hash is used for chain linkage and tamper detection. The result is a 32-byte `Uint8Array`. ```typescript export declare const hashAuditEvent: (event: AuditEvent) => Promise; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:125`. ## AuditSeverity [#auditseverity] ```typescript export declare const AuditSeverity: { readonly Info: "info"; readonly Warning: "warning"; readonly Error: "error"; readonly Critical: "critical"; }; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:11`. ## AuditSeverityValue [#auditseverityvalue] ```typescript export type AuditSeverityValue = (typeof AuditSeverity)[keyof typeof AuditSeverity]; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:18`. ## AuditOutcome [#auditoutcome] ```typescript export declare const AuditOutcome: { readonly Success: "success"; readonly Failure: "failure"; readonly Partial: "partial"; readonly Pending: "pending"; }; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:20`. ## AuditOutcomeValue [#auditoutcomevalue] ```typescript export type AuditOutcomeValue = (typeof AuditOutcome)[keyof typeof AuditOutcome]; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:27`. ## AuditEventKind [#auditeventkind] Kind of audit event. ```typescript export declare const AuditEventKind: { readonly AgentAuthenticated: "agent_authenticated"; readonly AuthenticationFailed: "authentication_failed"; readonly SessionStarted: "session_started"; readonly SessionEnded: "session_ended"; readonly CapabilityRequested: "capability_requested"; readonly CapabilityGranted: "capability_granted"; readonly CapabilityDenied: "capability_denied"; readonly TokenRevoked: "token_revoked"; readonly SecretRead: "secret_read"; readonly SecretRotated: "secret_rotated"; readonly ProxyRequest: "proxy_request"; readonly ProxyDenied: "proxy_denied"; readonly ConsentRequested: "consent_requested"; readonly ConsentApproved: "consent_approved"; readonly ConsentDenied: "consent_denied"; readonly ConsentRevoked: "consent_revoked"; readonly PolicyEvaluated: "policy_evaluated"; readonly PolicyViolation: "policy_violation"; readonly ConfigChanged: "config_changed"; readonly KeyRotated: "key_rotated"; }; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:30`. ## AuditEventKindValue [#auditeventkindvalue] ```typescript export type AuditEventKindValue = (typeof AuditEventKind)[keyof typeof AuditEventKind]; ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:66`. ## AuditEvent [#auditevent] ```typescript export interface AuditEvent { id: string; timestamp: string; kind: AuditEventKindValue; severity: AuditSeverityValue; tenant_id: string; agent_id?: string; session_id?: string; token_id?: string; outcome: AuditOutcomeValue; description: string; metadata: Readonly>; client_ip?: string; user_agent?: string; request_id?: string; previous_hash?: Uint8Array; event_hash?: Uint8Array; } ``` Source: `arsenal/sdks/typescript/src/core/audit.ts:68`. ## base64Encode [#base64encode] Encode bytes to base64 (standard alphabet, no padding). ```typescript export declare const base64Encode: (bytes: Uint8Array) => string; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:11`. ## base64UrlEncode [#base64urlencode] Encode bytes to base64url (URL-safe alphabet, no padding). ```typescript export declare const base64UrlEncode: (bytes: Uint8Array) => string; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:16`. ## base64Decode [#base64decode] Decode a base64 string (standard or URL alphabet, with or without padding). ```typescript export declare const base64Decode: (s: string) => Uint8Array; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:21`. ## base64UrlDecode [#base64urldecode] Decode a base64url string. Same as `base64Decode` for convenience. ```typescript export declare const base64UrlDecode: (s: string) => Uint8Array; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:26`. ## hexEncode [#hexencode] Encode bytes as lowercase hex. ```typescript export declare const hexEncode: (bytes: Uint8Array) => string; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:114`. ## hexDecode [#hexdecode] Decode a hex string into bytes. Throws on invalid input. ```typescript export declare const hexDecode: (s: string) => Uint8Array; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:123`. ## zeroize [#zeroize] Zeroize a `Uint8Array` in place. Use in `finally` blocks for secret buffers. ```typescript export declare const zeroize: (bytes: Uint8Array) => void; ``` Source: `arsenal/sdks/typescript/src/core/codec.ts:135`. ## encodeCbor [#encodecbor] Encode a value to deterministic CBOR bytes. ```typescript export declare const encodeCbor: (value: unknown) => Uint8Array; ``` Source: `arsenal/sdks/typescript/src/core/cbor.ts:94`. ## decodeCbor [#decodecbor] Decode a CBOR byte string into a plain JS value. ```typescript export declare const decodeCbor: (bytes: Uint8Array) => unknown; ``` Source: `arsenal/sdks/typescript/src/core/cbor.ts:236`. ## evaluatePolicy [#evaluatepolicy] Evaluate a single policy against a request. Returns the first matching rule's decision or the policy's default effect. ```typescript export declare const evaluatePolicy: (policy: PolicyDocument, request: PolicyRequest) => PolicyDecision; ``` Source: `arsenal/sdks/typescript/src/policy/engine.ts:80`. ## compareOperator [#compareoperator] Compare two strings using a condition operator. ```typescript export declare const compareOperator: (operator: ConditionOperatorValue, actual: string, expected: string) => boolean; ``` Source: `arsenal/sdks/typescript/src/policy/engine.ts:152`. ## policyAllows [#policyallows] Convenience alias: true if the policy decision allows the request. ```typescript export declare const policyAllows: (decision: PolicyDecision) => boolean; ``` Source: `arsenal/sdks/typescript/src/policy/engine.ts:197`. ## denyWith [#denywith] Build a deny decision with a reason string. ```typescript export declare const denyWith: (reason: string) => PolicyDecision; ``` Source: `arsenal/sdks/typescript/src/policy/engine.ts:202`. ## PolicyEngine [#policyengine] A policy engine evaluates multiple policies in priority order. Policies are added via `addPolicy` and removed via `removePolicy`. On each `evaluate(request)` call, policies are sorted by descending priority and the first matching rule's decision is returned. When no rule matches, the default effect of the first policy (ordered by priority) is used, and if there are no policies the engine returns `Deny`. ```typescript export declare class PolicyEngine { addPolicy(policy: PolicyDocument): void; removePolicy(policyId: string): PolicyDocument | undefined; getPolicy(policyId: string): PolicyDocument | undefined; policyIds(): readonly string[]; size(): number; evaluate(request: PolicyRequest): PolicyDecision; } ``` Source: `arsenal/sdks/typescript/src/policy/engine.ts:34`. ## BrokerClientOptions [#brokerclientoptions] Configuration for the broker client. ```typescript /** Configuration for the broker client. */ export interface BrokerClientOptions { /** Base URL of the broker (e.g. `https://broker.example.com`). */ baseUrl: string; /** Per-request timeout in milliseconds. Default: 30_000. */ timeoutMs?: number; /** Extra headers applied to every outbound request. */ defaultHeaders?: Record; /** Custom `fetch` implementation (defaults to `globalThis.fetch`). */ fetch?: typeof globalThis.fetch; } ``` Source: `arsenal/sdks/typescript/src/broker/client.ts:43`. ## BrokerClient [#brokerclient] Broker HTTP client. All methods throw `ArsenalError` on failure. Response bodies are validated with Zod schemas at the boundary. ```typescript export declare class BrokerClient { constructor(opts: BrokerClientOptions): BrokerClient; health(): Promise; requestCapability(payload: CapabilityRequestPayload): Promise; requestSecret(payload: SecretRequestPayload): Promise; revokeToken(tokenId: string, reason?: string): Promise; verifyToken(token: string): Promise; proxyRequest(req: ProxyRequest, opts?: { fingerprintHex?: string; }): Promise; approveConsent(payload: ConsentApprovalPayload): Promise; denyConsent(payload: ConsentDenialPayload): Promise; revokeConsent(payload: ConsentRevocationPayload): Promise; listConsents(agentDid: string): Promise; decodeCapabilityToken(response: CapabilityResponsePayload): AgentCapabilityToken; } ``` Source: `arsenal/sdks/typescript/src/broker/client.ts:62`. ## ConstraintsPayloadSchema [#constraintspayloadschema] ```typescript export declare const ConstraintsPayloadSchema: z.ZodObject<{ require_pop: z.ZodBoolean; allowed_origins: z.ZodOptional>; device_id: z.ZodOptional; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:12`. ## ConstraintsPayload [#constraintspayload] ```typescript export type ConstraintsPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:20`. ## CapabilityRequestPayloadSchema [#capabilityrequestpayloadschema] ```typescript export declare const CapabilityRequestPayloadSchema: z.ZodObject<{ scopes: z.ZodArray; ttl_seconds: z.ZodOptional; audience: z.ZodString; constraints: z.ZodOptional>; device_id: z.ZodOptional; }, z.core.$strict>>; pop_key_fingerprint: z.ZodOptional; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:22`. ## CapabilityRequestPayload [#capabilityrequestpayload] ```typescript export type CapabilityRequestPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:32`. ## CapabilityResponsePayloadSchema [#capabilityresponsepayloadschema] ```typescript export declare const CapabilityResponsePayloadSchema: z.ZodObject<{ token_id: z.ZodString; token: z.ZodString; expires_at: z.ZodString; granted_scopes: z.ZodArray; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:34`. ## CapabilityResponsePayload [#capabilityresponsepayload] ```typescript export type CapabilityResponsePayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:43`. ## SecretRequestPayloadSchema [#secretrequestpayloadschema] ```typescript export declare const SecretRequestPayloadSchema: z.ZodObject<{ secret_id: z.ZodString; version: z.ZodOptional; capability_token: z.ZodString; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:47`. ## SecretRequestPayload [#secretrequestpayload] ```typescript export type SecretRequestPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:55`. ## SecretResponsePayloadSchema [#secretresponsepayloadschema] ```typescript export declare const SecretResponsePayloadSchema: z.ZodObject<{ secret_id: z.ZodString; version: z.ZodNumber; wrapped_value: z.ZodString; wrap_key_id: z.ZodString; ephemeral_public_key: z.ZodString; expires_at: z.ZodString; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:57`. ## SecretResponsePayload [#secretresponsepayload] ```typescript export type SecretResponsePayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:68`. ## RevokeTokenPayloadSchema [#revoketokenpayloadschema] ```typescript export declare const RevokeTokenPayloadSchema: z.ZodObject<{ token_id: z.ZodString; reason: z.ZodOptional; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:72`. ## RevokeTokenPayload [#revoketokenpayload] ```typescript export type RevokeTokenPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:79`. ## RevokeTokenResponseSchema [#revoketokenresponseschema] ```typescript export declare const RevokeTokenResponseSchema: z.ZodObject<{ success: z.ZodBoolean; message: z.ZodString; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:81`. ## RevokeTokenResponse [#revoketokenresponse] ```typescript export type RevokeTokenResponse = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:88`. ## VerifyTokenPayloadSchema [#verifytokenpayloadschema] ```typescript export declare const VerifyTokenPayloadSchema: z.ZodObject<{ token: z.ZodString; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:90`. ## VerifyTokenPayload [#verifytokenpayload] ```typescript export type VerifyTokenPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:96`. ## VerifyTokenResponseSchema [#verifytokenresponseschema] ```typescript export declare const VerifyTokenResponseSchema: z.ZodObject<{ valid: z.ZodBoolean; token_id: z.ZodOptional; subject: z.ZodOptional; audience: z.ZodOptional; expires_at: z.ZodOptional; scopes: z.ZodOptional>; error: z.ZodOptional; }, z.core.$loose>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:98`. ## VerifyTokenResponse [#verifytokenresponse] ```typescript export type VerifyTokenResponse = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:110`. ## ProxyRequestPayloadSchema [#proxyrequestpayloadschema] ```typescript export declare const ProxyRequestPayloadSchema: z.ZodObject<{ method: z.ZodString; url: z.ZodString; headers: z.ZodOptional>; body: z.ZodOptional; capability_token: z.ZodString; timeout_ms: z.ZodOptional; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:114`. ## ProxyRequestPayload [#proxyrequestpayload] ```typescript export type ProxyRequestPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:125`. ## ProxyMetadataPayloadSchema [#proxymetadatapayloadschema] ```typescript export declare const ProxyMetadataPayloadSchema: z.ZodObject<{ variables_resolved: z.ZodArray; destination_verified: z.ZodBoolean; fingerprint_verified: z.ZodBoolean; consent_status: z.ZodString; latency_ms: z.ZodNumber; request_id: z.ZodOptional; }, z.core.$loose>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:127`. ## ProxyMetadataPayload [#proxymetadatapayload] ```typescript export type ProxyMetadataPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:138`. ## ProxyResponsePayloadSchema [#proxyresponsepayloadschema] ```typescript export declare const ProxyResponsePayloadSchema: z.ZodObject<{ status: z.ZodNumber; headers: z.ZodRecord; body: z.ZodString; proxy_metadata: z.ZodObject<{ variables_resolved: z.ZodArray; destination_verified: z.ZodBoolean; fingerprint_verified: z.ZodBoolean; consent_status: z.ZodString; latency_ms: z.ZodNumber; request_id: z.ZodOptional; }, z.core.$loose>; }, z.core.$loose>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:140`. ## ProxyResponsePayload [#proxyresponsepayload] ```typescript export type ProxyResponsePayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:149`. ## ConsentApprovalPayloadSchema [#consentapprovalpayloadschema] ```typescript export declare const ConsentApprovalPayloadSchema: z.ZodObject<{ agent_did: z.ZodString; human_root_did: z.ZodString; variables: z.ZodArray; destination_domains: z.ZodArray; scopes: z.ZodArray; granted_by: z.ZodString; expires_in_seconds: z.ZodOptional; signature: z.ZodString; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:153`. ## ConsentApprovalPayload [#consentapprovalpayload] ```typescript export type ConsentApprovalPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:166`. ## ConsentRecordPayloadSchema [#consentrecordpayloadschema] ```typescript export declare const ConsentRecordPayloadSchema: z.ZodObject<{ consent_id: z.ZodString; agent_did: z.ZodString; human_root_did: z.ZodOptional; variables: z.ZodArray; destination_domains: z.ZodOptional>; scopes: z.ZodOptional>; granted_by: z.ZodOptional; granted_at: z.ZodString; expires_at: z.ZodString; revoked: z.ZodOptional; }, z.core.$loose>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:168`. ## ConsentRecordPayload [#consentrecordpayload] ```typescript export type ConsentRecordPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:183`. ## ConsentDenialPayloadSchema [#consentdenialpayloadschema] ```typescript export declare const ConsentDenialPayloadSchema: z.ZodObject<{ agent_did: z.ZodString; human_root_did: z.ZodString; variables: z.ZodArray; destination_domains: z.ZodArray; scopes: z.ZodArray; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:185`. ## ConsentDenialPayload [#consentdenialpayload] ```typescript export type ConsentDenialPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:195`. ## ConsentRevocationPayloadSchema [#consentrevocationpayloadschema] ```typescript export declare const ConsentRevocationPayloadSchema: z.ZodObject<{ consent_id: z.ZodString; }, z.core.$strict>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:197`. ## ConsentRevocationPayload [#consentrevocationpayload] ```typescript export type ConsentRevocationPayload = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:203`. ## HealthResponseSchema [#healthresponseschema] ```typescript export declare const HealthResponseSchema: z.ZodObject<{ status: z.ZodString; version: z.ZodString; registered_agents: z.ZodOptional; revoked_tokens: z.ZodOptional; }, z.core.$loose>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:207`. ## HealthResponse [#healthresponse] ```typescript export type HealthResponse = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:216`. ## ApiErrorResponseSchema [#apierrorresponseschema] ```typescript export declare const ApiErrorResponseSchema: z.ZodObject<{ code: z.ZodNumber; message: z.ZodString; correlation_id: z.ZodOptional; retry_after: z.ZodOptional; }, z.core.$loose>; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:218`. ## ApiErrorResponse [#apierrorresponse] ```typescript export type ApiErrorResponse = z.infer; ``` Source: `arsenal/sdks/typescript/src/broker/wire.ts:227`. ## ArsenalClientConfig [#arsenalclientconfig] Configuration for the Arsenal client. ```typescript /** Configuration for the Arsenal client. */ export interface ArsenalClientConfig { /** Agent identity (public key fingerprint + metadata). */ identity: AgentIdentity; /** Broker client options. Required for any server-backed operation. */ broker?: BrokerClientOptions; /** Session configuration. Default: 24-hour session, 30s renewal threshold. */ sessionConfig?: SessionConfig; /** Auto-renew capability tokens when they are close to expiry. Default: true. */ autoRenew?: boolean; /** Token issuer label. Default: "arsenal". */ issuer?: string; /** Default audience (service) for broker-issued tokens. Default: "default". */ defaultAudience?: string; } ``` Source: `arsenal/sdks/typescript/src/sdk/client.ts:33`. ## ArsenalClient [#arsenalclient] High-level ARSENAL client. Combines session management, capability requests, proxy calls, and consent operations. Construct with `ArsenalClient.create({...})` and then: 1. `await client.startSession()` 2. `await client.requestCapabilityForScopes([...], 300)` 3. `await client.proxyHttp({...})` or other proxy calls 4. `await client.endSession()` when done ```typescript export declare class ArsenalClient { create(opts: ArsenalClientConfig): ArsenalClient; identity(): AgentIdentity; broker(): BrokerClient | undefined; startSession(): Promise; endSession(): Promise; revokeSession(): Promise; hasActiveSession(): boolean; sessionStats(): SessionStats; currentToken(): AgentCapabilityToken | undefined; requestCapability(request: CapabilityRequest): Promise; requestCapabilityForScopes(scopes: readonly string[], ttlSeconds: number): Promise; renewCurrentCapability(): Promise; proxyHttp(request: ProxyRequest): Promise; callToolSimple(_toolId: string, _method: string, params: unknown, opts?: { scopes?: readonly string[]; ttlSeconds?: number; }): Promise; approveConsent(payload: ConsentApprovalPayload): Promise; denyConsent(payload: ConsentDenialPayload): Promise; revokeConsent(payload: ConsentRevocationPayload): Promise; listConsents(): Promise; requestSecret(secretId: string, capabilityToken: string, version?: number): Promise; verifyToken(tokenBase64: string): Promise<{ valid: boolean; subject?: string; audience?: string; scopes?: string[]; }>; revokeToken(tokenId: string, reason?: string): Promise; } ``` Source: `arsenal/sdks/typescript/src/sdk/client.ts:58`. ## CapabilityRequest [#capabilityrequest] Builder for capability requests. ```typescript export declare class CapabilityRequest { create(): CapabilityRequest; scope(scope: string): CapabilityRequest; scopes(scopes: readonly string[]): CapabilityRequest; ttlSeconds(ttl: number): CapabilityRequest; audience(audience: string): CapabilityRequest; constraints(constraints: Constraints): CapabilityRequest; getScopes(): ScopeSet; getTtl(): number; getAudience(): string; getConstraints(): Constraints | undefined; } ``` Source: `arsenal/sdks/typescript/src/sdk/capability.ts:12`. ## CapabilityHandle [#capabilityhandle] Handle wrapping an issued capability token. Provides convenient inspection methods — the token itself is immutable. ```typescript export declare class CapabilityHandle { constructor(token: AgentCapabilityToken): CapabilityHandle; tokenId(): string; audience(): string; scopes(): ScopeSet; isExpired(now?: Date): boolean; remainingTtlMs(now?: Date): number; encode(): string; } ``` Source: `arsenal/sdks/typescript/src/sdk/capability.ts:93`. ## defaultSessionConfig [#defaultsessionconfig] ```typescript export declare const defaultSessionConfig: () => SessionConfig; ``` Source: `arsenal/sdks/typescript/src/sdk/session.ts:27`. ## SessionConfig [#sessionconfig] Configuration for session lifecycle. ```typescript /** Configuration for session lifecycle. */ export interface SessionConfig { /** Session TTL in seconds. Default: 24 hours. */ sessionTtlSeconds: number; /** * Renew tokens when their remaining lifetime drops below this many * seconds. Default: 30. */ renewalThresholdSeconds: number; } ``` Source: `arsenal/sdks/typescript/src/sdk/session.ts:17`. ## SessionStats [#sessionstats] Aggregate session statistics. ```typescript /** Aggregate session statistics. */ export interface SessionStats { state: SessionStateValue; created_at: string | null; last_activity_at: string | null; has_active_token: boolean; } ``` Source: `arsenal/sdks/typescript/src/sdk/session.ts:35`. ## SessionManager [#sessionmanager] In-memory session manager. Not thread-safe in the shared-memory sense, but JavaScript is single-threaded so method calls cannot interleave. ```typescript export declare class SessionManager { constructor(config?: SessionConfig): SessionManager; startSession(): Promise; sessionIdOrThrow(): SessionId; hasActiveSession(): boolean; stats(): SessionStats; setCurrentToken(token: AgentCapabilityToken): void; currentToken(): AgentCapabilityToken | undefined; recordActivity(): void; needsTokenRenewal(now?: Date): boolean; endSession(): Promise; revokeSession(): Promise; } ``` Source: `arsenal/sdks/typescript/src/sdk/session.ts:46`. # TypeScript API reference URL: https://docs.openagent.id/reference/typescript Markdown: https://docs.openagent.id/reference/typescript.md Exported interfaces and signatures from the actual package entry points. * [@openagentid/aegis-sdk](/reference/typescript/aegis-sdks-typescript) — 176 exported symbols * [@openagentid/arsenal-sdk](/reference/typescript/arsenal-sdks-typescript) — 222 exported symbols * [@openagentid/anchor-eas](/reference/typescript/openagent-sdk-adapters-eas-typescript) — 10 exported symbols * [@openagentid/http](/reference/typescript/openagent-sdk-adapters-http-typescript) — 50 exported symbols * [@openagentid/oidc](/reference/typescript/openagent-sdk-bridges-oidc-typescript) — 41 exported symbols * [@openagentid/scim](/reference/typescript/openagent-sdk-bridges-scim-typescript) — 61 exported symbols * [@openagentid/skills-policy](/reference/typescript/openagent-sdk-crates-openagent-skills-policy-typescript) — 26 exported symbols * [@openagentid/claude-agent](/reference/typescript/openagent-sdk-integrations-claude-agent-sdk-typescript) — 57 exported symbols * [@openagentid/mcp](/reference/typescript/openagent-sdk-integrations-mcp-typescript) — 36 exported symbols * [create-openagent](/reference/typescript/openagent-sdk-packages-create-openagent) — 0 exported symbols * [@openagentid/sdk-testing](/reference/typescript/openagent-sdk-sdks-testing) — 4 exported symbols * [@openagentid/sdk](/reference/typescript/openagent-sdk-sdks-typescript) — 68 exported symbols * [@openagentid/client](/reference/typescript/openagents-openagent-id-clients-typescript) — 24 exported symbols [Download the structured API reference](/reference/typescript-source.json). # @openagentid/anchor-eas API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-adapters-eas-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-adapters-eas-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-adapters-eas-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## didRecipient [#didrecipient] Derive the deterministic recipient address for a subject DID. ```typescript export declare const didRecipient: (did: string) => string; ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:57`. ## encodeAnchorData [#encodeanchordata] ABI-encode the anchor data (same layout as the Rust adapter). ```typescript export declare const encodeAnchorData: (data: AnchorData) => Uint8Array; ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:75`. ## SCHEMA\_STRING [#schema_string] The OAS lineage-root attestation schema registered on EAS. ```typescript export declare const SCHEMA_STRING: "string did,string kind,string status,string metadataCommitment,uint64 anchoredAtBlock"; ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:30`. ## AnchorData [#anchordata] The attestation's decoded data fields. ```typescript /** The attestation's decoded data fields. */ export interface AnchorData { did: string; kind: string; status: string; metadataCommitment: string; anchoredAtBlock: bigint; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:34`. ## AnchorRecord [#anchorrecord] The anchor record an anchor backend reports for a root. ```typescript /** The anchor record an anchor backend reports for a root. */ export interface AnchorRecord { did: string; status: string; anchoredAtBlock: number; metadataCommitment: string; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:43`. ## RevocationStatus [#revocationstatus] The revocation status of a subject. ```typescript /** The revocation status of a subject. */ export interface RevocationStatus { revoked: boolean; reasonCommitment?: string; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:51`. ## EasResolverConfig [#easresolverconfig] Configuration for the resolver. ```typescript /** Configuration for the resolver. */ export interface EasResolverConfig { /** The OAS lineage schema UID on this chain. */ schemaUid: string; /** EAS GraphQL endpoint. */ graphqlUrl: string; /** Chain JSON-RPC endpoint (for eth_blockNumber). */ rpcUrl: string; /** Confirmations subtracted from the head to define "finalized". Default: 64. */ confirmationDepth?: number; /** Injected fetch (tests and non-Node runtimes). Default: globalThis.fetch. */ fetch?: typeof fetch; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:92`. ## EasAnchorResolver [#easanchorresolver] The EAS resolver: reads lineage authority from attestations. ```typescript export declare class EasAnchorResolver { constructor(config: EasResolverConfig): EasAnchorResolver; checkRevocation(did: string): Promise; getRoot(did: string, kind: "hmr" | "mhr" | "enr"): Promise; currentFinalizedBlock(): Promise; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:112`. ## EasPublisherConfig [#easpublisherconfig] Signer shape the publisher needs: a viem-compatible account plus provider. ```typescript /** Signer shape the publisher needs: a viem-compatible account plus provider. */ export interface EasPublisherConfig { /** The OAS lineage schema UID on this chain. */ schemaUid: string; /** The EAS contract address on this chain. */ easContractAddress: string; /** A viem-compatible signer (any object the EAS SDK accepts). */ signer: unknown; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:210`. ## EasAnchorPublisher [#easanchorpublisher] The EAS publisher: writes anchors as attestations via the maintained SDK. ```typescript export declare class EasAnchorPublisher { constructor(config: EasPublisherConfig): EasAnchorPublisher; publishAnchor(data: AnchorData): Promise; revoke(uid: string): Promise; } ``` Source: `openagent-sdk/adapters/eas/typescript/src/index.ts:220`. # @openagentid/http API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-adapters-http-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-adapters-http-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-adapters-http-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## OPENAGENT\_AUTH\_SCHEME [#openagent_auth_scheme] The canonical authorization scheme for OpenAgent-authenticated requests. ```typescript export declare const OPENAGENT_AUTH_SCHEME: "OpenAgent"; ``` Source: `openagent-sdk/adapters/http/typescript/src/headers.ts:6`. ## HEADER\_OPENAGENT\_DID [#header_openagent_did] Header carrying the authenticated agent's DID. ```typescript export declare const HEADER_OPENAGENT_DID: "x-openagent-did"; ``` Source: `openagent-sdk/adapters/http/typescript/src/headers.ts:9`. ## HEADER\_OPENAGENT\_SESSION [#header_openagent_session] Header carrying the session token (alternative to Authorization). ```typescript export declare const HEADER_OPENAGENT_SESSION: "x-openagent-session"; ``` Source: `openagent-sdk/adapters/http/typescript/src/headers.ts:12`. ## CONTENT\_TYPE\_JSON [#content_type_json] Content-Type for all Core Protocol JSON payloads. ```typescript export declare const CONTENT_TYPE_JSON: "application/json"; ``` Source: `openagent-sdk/adapters/http/typescript/src/headers.ts:15`. ## extractOpenAgentToken [#extractopenagenttoken] Extract the session token from an `Authorization: OpenAgent <token>` header. Returns `undefined` if the header is missing, malformed, or uses a different scheme. ```typescript export declare const extractOpenAgentToken: (authorization: string) => string | undefined; ``` Source: `openagent-sdk/adapters/http/typescript/src/headers.ts:22`. ## buildOpenAgentHeader [#buildopenagentheader] Build an `Authorization: OpenAgent <token>` header value. ```typescript export declare const buildOpenAgentHeader: (token: string) => string; ``` Source: `openagent-sdk/adapters/http/typescript/src/headers.ts:31`. ## HttpTransport [#httptransport] HTTP transport carrying the identity flow over REST. ```typescript export declare class HttpTransport { constructor(config?: HttpTransportConfig): HttpTransport; fetchChallenge(endpoint: string): Promise; prove(endpoint: string, proof: IdentityProof): Promise; } ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:129`. ## TransportError [#transporterror] Transport error with HTTP context. ```typescript export declare class TransportError { statusCode: number | undefined; responseBody: string | undefined; constructor(message: string, statusCode?: number, responseBody?: string): TransportError; } ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:107`. ## CHALLENGE\_TYPE [#challenge_type] The literal `type` value of an identity challenge (Section 15.2). ```typescript export declare const CHALLENGE_TYPE: "openagent-challenge-v1"; ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:13`. ## canonicalChallengeBytes [#canonicalchallengebytes] The JCS-canonical (RFC 8785) UTF-8 bytes of a challenge object. Scoped to the challenge shape: a flat object whose values are strings (or absent). JCS for that shape is lexicographic key order, no whitespace, and JSON string escaping — which is exactly what this produces. Do not reuse for nested or numeric payloads; pull in a full JCS implementation there. ```typescript export declare const canonicalChallengeBytes: (challenge: IdentityChallenge) => Uint8Array; ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:91`. ## identityChallengeSchema [#identitychallengeschema] Zod schema for challenge validation (agents MUST validate before signing). ```typescript export declare const identityChallengeSchema: z.ZodObject<{ type: z.ZodLiteral<"openagent-challenge-v1">; nonce: z.ZodString; timestamp: z.ZodString; origin: z.ZodString; realm: z.ZodOptional; }, z.core.$strict>; ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:56`. ## identityVerifiedSchema [#identityverifiedschema] Zod schema for the verified session message. ```typescript export declare const identityVerifiedSchema: z.ZodObject<{ did: z.ZodString; trust_tier: z.ZodEnum<{ anonymous: "anonymous"; identified: "identified"; sovereign: "sovereign"; }>; session_token: z.ZodString; session_expires: z.ZodString; capabilities: z.ZodOptional>; }, z.core.$strip>; ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:75`. ## IdentityChallenge [#identitychallenge] Server → Agent: a cryptographic challenge (Section 15.2). ```typescript /** Server → Agent: a cryptographic challenge (Section 15.2). */ export interface IdentityChallenge { type: string; /** 64-character lowercase hex string (32 CSPRNG bytes). */ nonce: string; /** ISO 8601 UTC, Z suffix, seconds precision. */ timestamp: string; /** `scheme://host[:port]`. */ origin: string; /** Optional protection-space identifier. */ realm?: string; } ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:16`. ## IdentityProof [#identityproof] Agent → Server: the cryptographic proof of identity (Section 15.3). ```typescript /** Agent → Server: the cryptographic proof of identity (Section 15.3). */ export interface IdentityProof { /** Base64url (no padding) signature over the JCS-canonical challenge bytes. */ signature: string; /** Base64url (no padding) raw public key. */ public_key: string; key_type: KeyType; /** The nonce from the challenge, echoed. */ nonce: string; } ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:32`. ## IdentityVerified [#identityverified] Server → Agent: identity confirmed; session issued (Section 15.4). ```typescript /** Server → Agent: identity confirmed; session issued (Section 15.4). */ export interface IdentityVerified { did: string; trust_tier: TrustTier; session_token: string; /** ISO 8601 UTC timestamp of session expiry. */ session_expires: string; capabilities?: string[]; } ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:46`. ## KeyType [#keytype] Signature scheme for a proof (Section 15.3). ```typescript /** Signature scheme for a proof (Section 15.3). */ export type KeyType = 'ed25519' | 'secp256k1'; ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:29`. ## TrustTier [#trusttier] The resolution tier the server assigns (Section 15.4). ```typescript /** The resolution tier the server assigns (Section 15.4). */ export type TrustTier = 'anonymous' | 'identified' | 'sovereign'; ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:43`. ## HttpTransportConfig [#httptransportconfig] Configuration for the HTTP transport. ```typescript /** Configuration for the HTTP transport. */ export interface HttpTransportConfig { /** Request timeout in milliseconds. Default: 30000. */ timeoutMs?: number; /** Custom headers to include in all requests. */ headers?: Record; } ``` Source: `openagent-sdk/adapters/http/typescript/src/transport.ts:121`. ## ConformanceLevel [#conformancelevel] Conformance level enum values. ```typescript /** Conformance level enum values. */ export type ConformanceLevel = 'L0' | 'L1' | 'L2'; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:13`. ## DiscoveryDocument [#discoverydocument] Discovery document returned by the server. ```typescript /** Discovery document returned by the server. */ export interface DiscoveryDocument { auth_endpoint: string; supported_versions: number[]; server_did: string; required_conformance_level: ConformanceLevel; } ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:16`. ## discoveryDocumentSchema [#discoverydocumentschema] Zod schema for DiscoveryDocument. ```typescript export declare const discoveryDocumentSchema: z.ZodObject<{ auth_endpoint: z.ZodString; supported_versions: z.ZodArray; server_did: z.ZodString; required_conformance_level: z.ZodEnum<{ L0: "L0"; L1: "L1"; L2: "L2"; }>; }, z.core.$strip>; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:24`. ## WELL\_KNOWN\_PATH [#well_known_path] Default well-known path. ```typescript export declare const WELL_KNOWN_PATH: "/.well-known/openagent"; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:32`. ## AUTH\_ENDPOINT\_PATH [#auth_endpoint_path] Default auth endpoint path. ```typescript export declare const AUTH_ENDPOINT_PATH: "/.well-known/openagent/auth"; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:35`. ## PROVE\_ENDPOINT\_PATH [#prove_endpoint_path] Default prove endpoint path. ```typescript export declare const PROVE_ENDPOINT_PATH: "/.well-known/openagent/auth/prove"; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:38`. ## fetchDiscovery [#fetchdiscovery] Fetch the discovery document from a server. ```typescript export declare const fetchDiscovery: (baseUrl: string, timeoutMs?: number) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:46`. ## resolveAuthEndpoint [#resolveauthendpoint] Resolve the full auth endpoint URL from a base URL and discovery document. ```typescript export declare const resolveAuthEndpoint: (baseUrl: string, doc: DiscoveryDocument) => string; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:78`. ## resolveProveEndpoint [#resolveproveendpoint] Resolve the prove endpoint URL (auth endpoint + `/prove`). ```typescript export declare const resolveProveEndpoint: (baseUrl: string, doc: DiscoveryDocument) => string; ``` Source: `openagent-sdk/adapters/http/typescript/src/discovery.ts:85`. ## DEFAULT\_SESSION\_TTL\_SECS [#default_session_ttl_secs] Default session TTL in seconds. ```typescript export declare const DEFAULT_SESSION_TTL_SECS: 300; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:29`. ## DEFAULT\_CHALLENGE\_TTL\_SECS [#default_challenge_ttl_secs] Default challenge TTL in seconds (Section 7: default 30s, max 300s). ```typescript export declare const DEFAULT_CHALLENGE_TTL_SECS: 60; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:32`. ## ServerConfig [#serverconfig] Server configuration for the HTTP endpoints. ```typescript /** Server configuration for the HTTP endpoints. */ export interface ServerConfig { /** The server's origin per RFC 6454 (`scheme://host[:port]`). Bound into every challenge. */ origin: string; /** Optional protection-space identifier. */ realm?: string; /** The trust tier assigned to verified agents. Default: anonymous. */ trustTier?: TrustTier; /** Session TTL in seconds. */ sessionTtlSecs?: number; /** Challenge TTL in seconds. */ challengeTtlSecs?: number; /** Conformance level advertised in discovery. */ requiredConformance?: ConformanceLevel; } ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:35`. ## SessionState [#sessionstate] Session states. ```typescript /** Session states. */ export type SessionState = 'awaiting_proof' | 'established' | 'closed'; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:63`. ## StoredSession [#storedsession] A stored session. ```typescript /** A stored session. */ export interface StoredSession { id: string; state: SessionState; initiatorDid: string; responderDid: string; nonce: string; /** The exact challenge timestamp (spec format); needed to reconstruct the signed payload. */ challengeTimestamp: string; createdAt: number; expiresAt: number; capabilities: string[]; } ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:66`. ## SessionStore [#sessionstore] Session store interface. ```typescript /** Session store interface. */ export interface SessionStore { put(session: StoredSession): Promise; get(sessionId: string): Promise; remove(sessionId: string): Promise; } ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:80`. ## VerifySignatureFn [#verifysignaturefn] Signature verifier function. The caller provides this (crypto-wasm, libsodium, noble-ed25519, a KMS call) since Ed25519 verification is not in every runtime's Web Crypto. ```typescript /** * Signature verifier function. The caller provides this (crypto-wasm, * libsodium, noble-ed25519, a KMS call) since Ed25519 verification is not in * every runtime's Web Crypto. */ export type VerifySignatureFn = (params: { publicKeyBase64Url: string; payload: Uint8Array; signatureBase64Url: string; }) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:187`. ## AuthResult [#authresult] Result of authenticating an incoming request. ```typescript /** Result of authenticating an incoming request. */ export interface AuthResult { authenticated: boolean; peerDid?: string; sessionToken?: string; error?: string; } ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:276`. ## InMemorySessionStore [#inmemorysessionstore] In-memory session store for development and testing. ```typescript export declare class InMemorySessionStore { put(session: StoredSession): Promise; get(sessionId: string): Promise; remove(sessionId: string): Promise; } ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:87`. ## CoreAuthError [#coreautherror] Error returned by server handlers, carrying the HTTP status to render. ```typescript export declare class CoreAuthError { statusCode: number; constructor(message: string, statusCode: number): CoreAuthError; } ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:104`. ## createServerConfig [#createserverconfig] Create a server config with sensible defaults. ```typescript export declare const createServerConfig: (origin: string, overrides?: Partial) => Required> & ServerConfig; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:51`. ## handleDiscovery [#handlediscovery] Handle `GET /.well-known/openagent` - returns the discovery document. ```typescript export declare const handleDiscovery: (config: ServerConfig & { requiredConformance?: ConformanceLevel; }) => DiscoveryDocument; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:134`. ## handleChallenge [#handlechallenge] Handle the challenge step - issue an IdentityChallenge. Records a pending session keyed by the nonce: the proof carries exactly that correlation, and single-use-ness is enforced by removal. ```typescript export declare const handleChallenge: (config: ServerConfig & { requiredConformance?: ConformanceLevel; }, store: SessionStore) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:149`. ## handleProve [#handleprove] Handle the prove step - verify an IdentityProof and issue a session. Verification is normative-ordered: pending challenge first (present, unexpired), then shape checks (nonce echo), then the signature over the JCS-canonical challenge bytes. The nonce is consumed on success *and* on failure - a failed answer must not be retryable, or a verifier becomes an oracle. ```typescript export declare const handleProve: (config: ServerConfig & { requiredConformance?: ConformanceLevel; }, store: SessionStore, body: unknown, verifySignature: VerifySignatureFn) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:202`. ## authenticateRequest [#authenticaterequest] Authenticate an incoming request by checking the session token. ```typescript export declare const authenticateRequest: (request: Request, store: SessionStore) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/server.ts:284`. ## MiddlewareOptions [#middlewareoptions] Options for creating OAAP middleware. ```typescript /** Options for creating OAAP middleware. */ export interface MiddlewareOptions { /** Server DID. */ serverDid: string; /** Session store (default: in-memory). */ store?: SessionStore; /** Required conformance level (default: L2). */ requiredConformance?: 'L0' | 'L1' | 'L2'; /** Session TTL in seconds (default: 300). */ sessionTtlSecs?: number; /** Challenge TTL in seconds (default: 60). */ challengeTtlSecs?: number; /** Signature verification function. */ verifySignature: VerifySignatureFn; /** Paths to exclude from authentication (well-known paths are always excluded). */ excludePaths?: string[]; } ``` Source: `openagent-sdk/adapters/http/typescript/src/middleware.ts:21`. ## createOpenAgentHandler [#createopenagenthandler] Create a generic OAAP middleware using the standard fetch Request/Response API. Returns a function that: * Handles OAAP well-known endpoints * Validates authenticated requests * Returns `undefined` for well-known routes (caller should send the JSON response) Works with Hono, Cloudflare Workers, Deno, Bun, and any fetch-based framework. ```typescript export declare const createOpenAgentHandler: (options: MiddlewareOptions) => { config: ServerConfig; store: SessionStore; handle: (request: Request) => Promise; }; ``` Source: `openagent-sdk/adapters/http/typescript/src/middleware.ts:55`. ## createOpenAgentMiddleware [#createopenagentmiddleware] Create Express-compatible middleware. Usage: ```ts app.use(createOpenAgentMiddleware({ serverDid: 'did:oas:l1fe:service:api', verifySignature: async (did, payload, sig) => { ... }, })); ``` ```typescript export declare const createOpenAgentMiddleware: (options: MiddlewareOptions) => (req: { url?: string; method?: string; headers: Record; path?: string; }, res: { status: (code: number) => { json: (body: unknown) => void; end: () => void; }; }, next: () => void) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/middleware.ts:155`. ## ClientConfig [#clientconfig] Client configuration. ```typescript /** Client configuration. */ export interface ClientConfig { /** * The agent's DID. Reported to the server for audit and, where the * deployment resolves DIDs, for trust-tier assignment. The agent proves * possession of the key - lineage evaluation is the server's job. */ did: string; /** The signature scheme the `sign` function implements. */ keyType?: KeyType; /** Request timeout in milliseconds. Default: 30000. */ timeoutMs?: number; } ``` Source: `openagent-sdk/adapters/http/typescript/src/client.ts:18`. ## SignFn [#signfn] Function that signs a payload and returns a base64url (no padding) encoded signature. The caller provides this — it may use ```typescript /** * Function that signs a payload and returns a base64url (no padding) * encoded signature. * * The caller provides this — it may use @openagentid/crypto-wasm, Web Crypto, * or any Ed25519 implementation. */ export type SignFn = (payload: Uint8Array) => Promise; ``` Source: `openagent-sdk/adapters/http/typescript/src/client.ts:38`. ## HttpAuthClient [#httpauthclient] HTTP client that performs the Core Protocol identity flow. Usage: ```ts const client = new HttpAuthClient({ config: { did: 'did:oas:l1fe:agent:my-bot' }, sign: async (payload) => base64url(ed25519Sign(privateKey, payload)), publicKey: async () => base64url(ed25519PublicKey(privateKey)), }); const session = await client.authenticate('https://api.example.com'); const resp = await session.get('/api/tools'); ``` ```typescript export declare class HttpAuthClient { constructor(params: { config: ClientConfig; sign: SignFn; publicKey: () => Promise; transport?: HttpTransport; }): HttpAuthClient; authenticate(baseUrl: string): Promise; } ``` Source: `openagent-sdk/adapters/http/typescript/src/client.ts:54`. ## AuthenticatedSession [#authenticatedsession] An authenticated HTTP session obtained after a successful Core Protocol identity flow. ```typescript export declare class AuthenticatedSession { constructor(params: { baseUrl: string; sessionId: string; peerDid: string; sessionToken: string; expiresAt: number; }): AuthenticatedSession; isExpired(): boolean; getSessionId(): string; getPeerDid(): string; getBaseUrl(): string; fetch(path: string, init?: RequestInit): Promise; get(path: string): Promise; post(path: string, body: unknown): Promise; put(path: string, body: unknown): Promise; delete(path: string): Promise; } ``` Source: `openagent-sdk/adapters/http/typescript/src/session.ts:12`. ## VERSION [#version] SDK version — kept in sync with `package.json`. ```typescript export declare const VERSION: "0.1.1"; ``` Source: `openagent-sdk/adapters/http/typescript/src/index.ts:86`. # @openagentid/oidc API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-bridges-oidc-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-bridges-oidc-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-bridges-oidc-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## OidcBridge [#oidcbridge] The OIDC bridge -- maps between human OIDC tokens and OAS agent identities. ```typescript export declare class OidcBridge { constructor(input: OidcConfig | SingleProviderInput): OidcBridge; getConfig(): Readonly; deriveAgentFromJwt(token: string, agentName: string): Promise; actToJwt(claims: ActJwtClaims, signingKey: jose.KeyLike | Uint8Array, algorithm: string, kid?: string): Promise; wrapActAsJwt(opts: { agentDid: string; bridgeIssuer: string; audience?: string; scopes: readonly string[]; lineageDepth: number; parentHmr: string; actB64: string; signingKey: jose.KeyLike | Uint8Array; algorithm: string; kid?: string; }): Promise; exchangeToken(humanJwt: string, requestedScopes: readonly string[], signingKey?: jose.KeyLike | Uint8Array, algorithm?: string, bridgeIssuer?: string): Promise; executeExchange(request: TokenExchangeRequest, signingKey: jose.KeyLike | Uint8Array | undefined, algorithm: string, bridgeIssuer: string): Promise; validateJwt(token: string): Promise; refreshAllJwks(): Promise; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/bridge.ts:67`. ## ProviderConfig [#providerconfig] ```typescript export type ProviderConfig = z.infer; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:26`. ## OidcConfig [#oidcconfig] ```typescript export type OidcConfig = z.infer; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:42`. ## SingleProviderInput [#singleproviderinput] Shorthand input for single-provider setup. ```typescript /** Shorthand input for single-provider setup. */ export interface SingleProviderInput { /** Provider name. */ name?: string; /** OIDC issuer URL. */ issuer: string; /** Expected audience. */ audience?: string; /** JWKS URL override. */ jwksUrl?: string; /** HMR claim name. */ hmrClaim?: string; /** Scope mapping. */ scopeMapping?: Record; /** OAS namespace. */ namespace?: string; /** JWT TTL seconds. */ jwtTtlSeconds?: number; /** HTTP timeout ms. */ httpTimeoutMs?: number; /** Custom fetch. */ fetch?: typeof globalThis.fetch; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:45`. ## providerConfigSchema [#providerconfigschema] Configuration for a single OIDC provider. ```typescript export declare const providerConfigSchema: z.ZodObject<{ name: z.ZodString; issuer: z.ZodString; audience: z.ZodOptional; jwksUrl: z.ZodOptional; hmrClaim: z.ZodDefault; scopeMapping: z.ZodDefault>>; }, z.core.$strip>; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:11`. ## oidcConfigSchema [#oidcconfigschema] Top-level OIDC bridge configuration. ```typescript export declare const oidcConfigSchema: z.ZodObject<{ providers: z.ZodArray; jwksUrl: z.ZodOptional; hmrClaim: z.ZodDefault; scopeMapping: z.ZodDefault>>; }, z.core.$strip>>; namespace: z.ZodDefault; jwtTtlSeconds: z.ZodDefault; httpTimeoutMs: z.ZodDefault; fetch: z.ZodOptional>; }, z.core.$strip>; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:29`. ## singleProviderConfig [#singleproviderconfig] Build an OidcConfig from a single-provider shorthand input. ```typescript export declare const singleProviderConfig: (input: SingleProviderInput) => OidcConfig; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:69`. ## findProvider [#findprovider] Find the provider config whose issuer matches the given string. ```typescript export declare const findProvider: (config: OidcConfig, issuer: string) => ProviderConfig | undefined; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:89`. ## resolveFetch [#resolvefetch] Resolve the fetch implementation from config or globalThis. ```typescript export declare const resolveFetch: (config: OidcConfig) => typeof globalThis.fetch; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/config.ts:97`. ## DiscoveryDocument [#discoverydocument] ```typescript export type DiscoveryDocument = z.infer; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/discovery.ts:23`. ## DiscoveryClient [#discoveryclient] OIDC discovery client with per-issuer caching. ```typescript export declare class DiscoveryClient { constructor(fetchImpl: typeof globalThis.fetch, timeoutMs?: number, cacheTtlMs?: number): DiscoveryClient; discover(issuer: string): Promise; invalidate(issuer: string): void; invalidateAll(): void; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/discovery.ts:40`. ## discoveryDocumentSchema [#discoverydocumentschema] Subset of the OpenID Connect Discovery document we need. ```typescript export declare const discoveryDocumentSchema: z.ZodObject<{ issuer: z.ZodString; authorization_endpoint: z.ZodDefault; token_endpoint: z.ZodDefault; jwks_uri: z.ZodString; response_types_supported: z.ZodDefault>; subject_types_supported: z.ZodDefault>; id_token_signing_alg_values_supported: z.ZodDefault>; scopes_supported: z.ZodDefault>; token_exchange_endpoint: z.ZodOptional; }, z.core.$strip>; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/discovery.ts:11`. ## wellKnownUrl [#wellknownurl] Build the `.well-known/openid-configuration` URL from an issuer. ```typescript export declare const wellKnownUrl: (issuer: string) => string; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/discovery.ts:31`. ## OidcBridgeError [#oidcbridgeerror] Base error class for all OIDC bridge errors. ```typescript export declare class OidcBridgeError { code: OidcErrorCode; constructor(code: OidcErrorCode, message: string): OidcBridgeError; config(message: string): OidcBridgeError; discovery(message: string): OidcBridgeError; jwks(message: string): OidcBridgeError; jwtValidation(message: string): OidcBridgeError; unknownIssuer(issuer: string): OidcBridgeError; mapping(message: string): OidcBridgeError; exchange(message: string): OidcBridgeError; signing(message: string): OidcBridgeError; transport(message: string): OidcBridgeError; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/errors.ts:18`. ## OidcErrorCode [#oidcerrorcode] Error codes for OIDC bridge errors. ```typescript /** * Error types for the OIDC bridge. */ /** Error codes for OIDC bridge errors. */ export type OidcErrorCode = 'DISCOVERY_ERROR' | 'JWKS_ERROR' | 'JWT_VALIDATION_ERROR' | 'UNKNOWN_ISSUER' | 'MAPPING_ERROR' | 'EXCHANGE_ERROR' | 'SIGNING_ERROR' | 'CONFIG_ERROR' | 'TRANSPORT_ERROR'; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/errors.ts:6`. ## TokenExchangeRequest [#tokenexchangerequest] ```typescript export type TokenExchangeRequest = z.infer; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:41`. ## TokenExchangeResponse [#tokenexchangeresponse] Token exchange response (RFC 8693 Section 2.2). ```typescript /** Token exchange response (RFC 8693 Section 2.2). */ export interface TokenExchangeResponse { readonly accessToken: string; readonly issuedTokenType: string; readonly tokenType: 'Bearer'; readonly expiresIn: number; readonly scope?: string; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:44`. ## TokenExchangeError [#tokenexchangeerror] RFC 8693 error response. ```typescript /** RFC 8693 error response. */ export interface TokenExchangeError { readonly error: string; readonly errorDescription?: string; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:53`. ## tokenExchangeRequestSchema [#tokenexchangerequestschema] Token exchange request (RFC 8693 Section 2.1). ```typescript export declare const tokenExchangeRequestSchema: z.ZodObject<{ grantType: z.ZodLiteral<"urn:ietf:params:oauth:grant-type:token-exchange">; subjectToken: z.ZodString; subjectTokenType: z.ZodEnum<{ "urn:ietf:params:oauth:token-type:jwt": "urn:ietf:params:oauth:token-type:jwt"; "urn:ietf:params:oauth:token-type:access_token": "urn:ietf:params:oauth:token-type:access_token"; }>; requestedTokenType: z.ZodOptional>; scope: z.ZodOptional; audience: z.ZodOptional; resource: z.ZodOptional; actorToken: z.ZodOptional; actorTokenType: z.ZodOptional; }, z.core.$strip>; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:29`. ## GRANT\_TYPE\_TOKEN\_EXCHANGE [#grant_type_token_exchange] Standard grant type for RFC 8693 Token Exchange. ```typescript export declare const GRANT_TYPE_TOKEN_EXCHANGE: "urn:ietf:params:oauth:grant-type:token-exchange"; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:12`. ## TOKEN\_TYPE\_JWT [#token_type_jwt] Standard token type for JWT subject tokens. ```typescript export declare const TOKEN_TYPE_JWT: "urn:ietf:params:oauth:token-type:jwt"; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:16`. ## TOKEN\_TYPE\_ACT [#token_type_act] Custom token type for OpenAgent ACTs. ```typescript export declare const TOKEN_TYPE_ACT: "urn:openagent:token-type:act"; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:19`. ## TOKEN\_TYPE\_ACCESS [#token_type_access] Standard token type for access tokens. ```typescript export declare const TOKEN_TYPE_ACCESS: "urn:ietf:params:oauth:token-type:access_token"; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:22`. ## createJwtToActRequest [#createjwttoactrequest] Create a token exchange request for JWT -> ACT exchange. ```typescript export declare const createJwtToActRequest: (subjectToken: string, scopes?: readonly string[]) => TokenExchangeRequest; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:59`. ## validateExchangeRequest [#validateexchangerequest] Validate a token exchange request. ```typescript export declare const validateExchangeRequest: (request: TokenExchangeRequest) => void; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:73`. ## parseScopes [#parsescopes] Parse scopes from a space-delimited string. ```typescript export declare const parseScopes: (scope: string | undefined) => string[]; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:83`. ## successResponse [#successresponse] Build a successful token exchange response. ```typescript export declare const successResponse: (accessToken: string, issuedTokenType: string, expiresIn: number, scope?: string) => TokenExchangeResponse; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:89`. ## exchangeErrors [#exchangeerrors] Create standard OAuth2 error responses. ```typescript export declare const exchangeErrors: { readonly invalidRequest: (desc: string) => TokenExchangeError; readonly invalidGrant: (desc: string) => TokenExchangeError; readonly unsupportedTokenType: (desc: string) => TokenExchangeError; readonly invalidTarget: (desc: string) => TokenExchangeError; }; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/exchange.ts:105`. ## JwksClient [#jwksclient] JWKS client with per-URI caching and rotation-aware refresh. ```typescript export declare class JwksClient { constructor(fetchImpl: typeof globalThis.fetch, timeoutMs?: number, cacheTtlMs?: number): JwksClient; fetchJwks(jwksUri: string): Promise; refresh(jwksUri: string): Promise; selectKey(jwks: jose.JSONWebKeySet, kid: string | undefined, alg: string | undefined): jose.JWK; invalidate(jwksUri: string): void; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwks.ts:17`. ## ValidatedClaims [#validatedclaims] Claims extracted from a validated human JWT. ```typescript /** Claims extracted from a validated human JWT. */ export interface ValidatedClaims { /** Issuer (`iss` claim). */ readonly issuer: string; /** Subject (`sub` claim). */ readonly subject: string; /** Audience (`aud` claim). */ readonly audience: readonly string[]; /** Expiration (epoch seconds). */ readonly exp: number; /** Issued-at (epoch seconds). */ readonly iat: number; /** The claim value that maps to the HMR. */ readonly hmrValue: string; /** OIDC scopes extracted from the token. */ readonly scopes: readonly string[]; /** All original claims. */ readonly rawClaims: Readonly>; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:12`. ## ActJwtClaims [#actjwtclaims] Claims for an outbound JWT wrapping an Arsenal ACT (Flow 2). ```typescript /** Claims for an outbound JWT wrapping an Arsenal ACT (Flow 2). */ export interface ActJwtClaims { /** Subject: the agent's DID. */ readonly sub: string; /** Issuer: the bridge's own issuer identifier. */ readonly iss: string; /** Audience. */ readonly aud?: string; /** Expiration (epoch seconds). */ readonly exp: number; /** Issued-at (epoch seconds). */ readonly iat: number; /** JWT ID. */ readonly jti: string; /** Arsenal scope strings. */ readonly scope: string; /** Lineage depth (hops from HMR root). */ readonly lineage_depth: number; /** Parent HMR DID. */ readonly parent_hmr: string; /** Serialized ACT (base64url). */ readonly act: string; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:32`. ## decodeJwtHeader [#decodejwtheader] Decode the JWT header without verification (to get kid/alg). ```typescript export declare const decodeJwtHeader: (token: string) => { kid?: string; alg?: string; }; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:56`. ## extractUnverifiedIssuer [#extractunverifiedissuer] Extract the unverified `iss` claim from a JWT. ```typescript export declare const extractUnverifiedIssuer: (token: string) => string; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:62`. ## validateJwt [#validatejwt] Validate and decode a JWT using the given JWK. Performs standard OIDC validation: issuer, audience, expiry, signature. ```typescript export declare const validateJwt: (token: string, jwk: jose.JWK, provider: ProviderConfig) => Promise; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:75`. ## buildActClaims [#buildactclaims] Build ACT JWT claims. ```typescript export declare const buildActClaims: (opts: { agentDid: string; bridgeIssuer: string; audience?: string; scopes: readonly string[]; lineageDepth: number; parentHmr: string; actB64: string; ttlSeconds: number; }) => ActJwtClaims; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:128`. ## signActJwt [#signactjwt] Sign a JWT wrapping an Arsenal ACT for OAuth2-only services. ```typescript export declare const signActJwt: (claims: ActJwtClaims, signingKey: jose.KeyLike | Uint8Array, algorithm: string, kid?: string) => Promise; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/jwt.ts:154`. ## DerivedAgent [#derivedagent] Result of deriving an agent DID from a human JWT. ```typescript /** Result of deriving an agent DID from a human JWT. */ export interface DerivedAgent { /** Agent DID (did:oas::agent:). */ readonly agentDid: string; /** Agent keypair (Ed25519 public + private key bytes). */ readonly agentKeypair: { readonly publicKey: Uint8Array; readonly privateKey: Uint8Array; }; /** Lineage proof (JSON structure). */ readonly lineageProof: Record | null; /** Parent HMR DID. */ readonly parentHmrDid: string; /** Lineage depth (0 for HMR, 1 for direct child). */ readonly lineageDepth: number; } ``` Source: `openagent-sdk/bridges/oidc/typescript/src/mapping.ts:12`. ## deriveAgentFromClaims [#deriveagentfromclaims] Derive an agent DID from validated OIDC claims. This is the core of Flow 1: Human JWT -> Agent DID. In a production deployment, this would use the OAS SDK's `create_hmr` and `derive_child` functions (available via the WASM crypto module). Here we produce the correct DID format and structure, with placeholder keypairs that would be replaced by the real OAS SDK integration. ```typescript export declare const deriveAgentFromClaims: (namespace: string, claims: ValidatedClaims, agentName: string) => DerivedAgent; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/mapping.ts:52`. ## hmrIdentifierFromClaims [#hmridentifierfromclaims] Deterministic identifier for an HMR derived from an OIDC subject. Uses issuer + subject to produce a stable, collision-resistant identifier that doesn't leak PII. ```typescript export declare const hmrIdentifierFromClaims: (issuer: string, hmrValue: string) => string; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/mapping.ts:34`. ## mapScopes [#mapscopes] Map OIDC scopes/roles to Arsenal capability scopes. Unmapped scopes are passed through as-is. ```typescript export declare const mapScopes: (oidcScopes: readonly string[], scopeMapping: Readonly>) => string[]; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/mapping.ts:101`. ## VERSION [#version] SDK version. ```typescript export declare const VERSION: "0.1.1"; ``` Source: `openagent-sdk/bridges/oidc/typescript/src/index.ts:98`. # @openagentid/scim API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-bridges-scim-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-bridges-scim-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-bridges-scim-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## createScimRouter [#createscimrouter] Create a SCIM 2.0 router with the given configuration. ```typescript export declare const createScimRouter: (routerConfig?: ScimRouterConfig) => ScimRouter; ``` Source: `openagent-sdk/bridges/scim/typescript/src/server.ts:52`. ## ScimRouter [#scimrouter] ```typescript export interface ScimRouter { /** Handle a WHATWG Request and return a WHATWG Response. */ handle(request: Request): Promise; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/server.ts:44`. ## ScimRouterConfig [#scimrouterconfig] ```typescript // ── Router configuration ────────────────────────────────────────────────── export interface ScimRouterConfig extends ScimBridgeConfig { /** Custom agent store. Defaults to in-memory. */ readonly store?: AgentStore; /** Audit event sink. */ readonly auditSink?: AuditSink; /** DID revocation hook (production: OAS SDK). */ readonly revokeDidDocument?: DidRevoker; /** Delegation cascade revocation hook (production: AEGIS SDK). */ readonly cascadeRevokeDelegations?: DelegationCascadeRevoker; /** Arsenal session invalidation hook (production: Arsenal SDK). */ readonly invalidateArsenalSessions?: ArsenalSessionInvalidator; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/server.ts:31`. ## ScimBridgeConfig [#scimbridgeconfig] Configuration for the SCIM provisioning bridge. ```typescript /** Configuration for the SCIM provisioning bridge. */ export interface ScimBridgeConfig { /** * OAS namespace for generated DIDs. Defaults to `l1fe`. */ readonly namespace?: string; /** * Bearer token(s) that SCIM clients must present. * When undefined, authentication is disabled (dev only). */ readonly bearerTokens?: readonly string[]; /** * Base URL for SCIM resource `meta.location` fields. * Example: `https://scim.example.com/scim/v2` */ readonly baseUrl?: string; /** Maximum page size for list responses. Default: 100. */ readonly maxPageSize?: number; /** Structured logger. */ readonly logger?: Logger; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/config.ts:25`. ## ResolvedScimConfig [#resolvedscimconfig] ```typescript export interface ResolvedScimConfig { readonly namespace: string; readonly bearerTokens: readonly string[]; readonly baseUrl: string; readonly maxPageSize: number; readonly logger: Logger; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/config.ts:59`. ## Logger [#logger] Logger interface matching the OpenAgent SDK convention. ```typescript /** Logger interface matching the OpenAgent SDK convention. */ export interface Logger { debug(msg: string, fields?: Record): void; info(msg: string, fields?: Record): void; warn(msg: string, fields?: Record): void; error(msg: string, fields?: Record): void; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/config.ts:10`. ## resolveScimConfig [#resolvescimconfig] ```typescript export declare const resolveScimConfig: (config?: ScimBridgeConfig) => ResolvedScimConfig; ``` Source: `openagent-sdk/bridges/scim/typescript/src/config.ts:67`. ## silentLogger [#silentlogger] ```typescript export declare const silentLogger: Logger; ``` Source: `openagent-sdk/bridges/scim/typescript/src/config.ts:17`. ## SCIM\_USER\_SCHEMA [#scim_user_schema] SCIM core User schema URN. ```typescript export declare const SCIM_USER_SCHEMA: "urn:ietf:params:scim:schemas:core:2.0:User"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:9`. ## OPENAGENT\_AGENT\_SCHEMA [#openagent_agent_schema] OpenAgent agent extension schema URN. ```typescript export declare const OPENAGENT_AGENT_SCHEMA: "urn:openagent:scim:1.0:Agent"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:12`. ## SCIM\_LIST\_RESPONSE\_SCHEMA [#scim_list_response_schema] SCIM List Response schema URN. ```typescript export declare const SCIM_LIST_RESPONSE_SCHEMA: "urn:ietf:params:scim:api:messages:2.0:ListResponse"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:15`. ## SCIM\_ERROR\_SCHEMA [#scim_error_schema] SCIM Error schema URN. ```typescript export declare const SCIM_ERROR_SCHEMA: "urn:ietf:params:scim:api:messages:2.0:Error"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:18`. ## SCIM\_PATCH\_OP\_SCHEMA [#scim_patch_op_schema] SCIM Patch Operation schema URN. ```typescript export declare const SCIM_PATCH_OP_SCHEMA: "urn:ietf:params:scim:api:messages:2.0:PatchOp"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:21`. ## SCIM\_SPC\_SCHEMA [#scim_spc_schema] SCIM ServiceProviderConfig schema URN. ```typescript export declare const SCIM_SPC_SCHEMA: "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:24`. ## SCIM\_SCHEMA\_SCHEMA [#scim_schema_schema] SCIM Schema schema URN. ```typescript export declare const SCIM_SCHEMA_SCHEMA: "urn:ietf:params:scim:schemas:core:2.0:Schema"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:27`. ## SCIM\_RESOURCE\_TYPE\_SCHEMA [#scim_resource_type_schema] SCIM ResourceType schema URN. ```typescript export declare const SCIM_RESOURCE_TYPE_SCHEMA: "urn:ietf:params:scim:schemas:core:2.0:ResourceType"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:30`. ## ConformanceLevel [#conformancelevel] Conformance levels for OpenAgent agents. ```typescript /** Conformance levels for OpenAgent agents. */ export type ConformanceLevel = 'L0' | 'L1' | 'L2'; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:33`. ## AgentExtension [#agentextension] The OpenAgent agent extension attribute group. ```typescript /** The OpenAgent agent extension attribute group. */ export interface AgentExtension { readonly parentDid: string; readonly conformanceLevel: ConformanceLevel; readonly scopes: readonly string[]; readonly lineageDepth: number; readonly createdVia: string; readonly keypairFingerprint: string; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:36`. ## ScimAgentResource [#scimagentresource] Full SCIM User resource with agent extension. ```typescript /** Full SCIM User resource with agent extension. */ export interface ScimAgentResource { readonly schemas: readonly string[]; readonly id: string; readonly externalId?: string; readonly userName: string; readonly displayName: string; readonly active: boolean; readonly meta: ScimMeta; readonly [OPENAGENT_AGENT_SCHEMA]: AgentExtension; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:46`. ## ScimMeta [#scimmeta] SCIM resource metadata. ```typescript /** SCIM resource metadata. */ export interface ScimMeta { readonly resourceType: string; readonly created: string; readonly lastModified: string; readonly location: string; readonly version: string; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:58`. ## ScimListResponse [#scimlistresponse] SCIM List Response envelope. ```typescript /** SCIM List Response envelope. */ export interface ScimListResponse { readonly schemas: readonly string[]; readonly totalResults: number; readonly startIndex: number; readonly itemsPerPage: number; readonly Resources: readonly T[]; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:67`. ## ScimErrorResponse [#scimerrorresponse] SCIM Error response. ```typescript /** SCIM Error response. */ export interface ScimErrorResponse { readonly schemas: readonly string[]; readonly status: string; readonly scimType?: string; readonly detail: string; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:76`. ## buildServiceProviderConfig [#buildserviceproviderconfig] Service Provider Configuration response. ```typescript export declare const buildServiceProviderConfig: (baseUrl: string) => Record; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:84`. ## buildSchemas [#buildschemas] Schema discovery response for the User + Agent extension. ```typescript export declare const buildSchemas: () => readonly Record[]; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:111`. ## buildResourceTypes [#buildresourcetypes] Resource type discovery for User (Agent). ```typescript export declare const buildResourceTypes: (baseUrl: string) => readonly Record[]; ``` Source: `openagent-sdk/bridges/scim/typescript/src/schemas.ts:144`. ## AgentRecord [#agentrecord] The canonical internal representation of a provisioned agent. ```typescript // ── Internal agent record ───────────────────────────────────────────────── /** The canonical internal representation of a provisioned agent. */ export interface AgentRecord { readonly did: string; readonly userName: string; readonly displayName: string; readonly active: boolean; readonly parentDid: string; readonly conformanceLevel: ConformanceLevel; readonly scopes: readonly string[]; readonly lineageDepth: number; readonly createdVia: string; readonly keypairFingerprint: string; readonly createdAt: string; readonly updatedAt: string; readonly version: string; readonly externalId?: string; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:22`. ## CreateAgentFromScimInput [#createagentfromsciminput] ```typescript export type CreateAgentFromScimInput = z.infer; ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:65`. ## ReplaceAgentFromScimInput [#replaceagentfromsciminput] ```typescript export type ReplaceAgentFromScimInput = z.infer; ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:68`. ## agentToScimResource [#agenttoscimresource] Convert an internal AgentRecord into a SCIM User resource. ```typescript export declare const agentToScimResource: (agent: AgentRecord, baseUrl: string) => ScimAgentResource; ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:73`. ## parseCreateInput [#parsecreateinput] Parse and validate a SCIM create request body into typed input. ```typescript export declare const parseCreateInput: (body: unknown) => CreateAgentFromScimInput; ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:107`. ## parseReplaceInput [#parsereplaceinput] Parse and validate a SCIM replace (PUT) request body into typed input. ```typescript export declare const parseReplaceInput: (body: unknown) => ReplaceAgentFromScimInput; ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:112`. ## createAgentFromScimSchema [#createagentfromscimschema] ```typescript export declare const createAgentFromScimSchema: z.ZodObject<{ schemas: z.ZodArray; externalId: z.ZodOptional; userName: z.ZodString; displayName: z.ZodOptional; active: z.ZodDefault; "urn:openagent:scim:1.0:Agent": z.ZodObject<{ parentDid: z.ZodString; conformanceLevel: z.ZodDefault>; scopes: z.ZodArray; lineageDepth: z.ZodOptional; createdVia: z.ZodOptional; keypairFingerprint: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>; ``` Source: `openagent-sdk/bridges/scim/typescript/src/resources.ts:53`. ## ParsedFilter [#parsedfilter] ```typescript export type ParsedFilter = AttributeFilter | LogicalFilter; ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:34`. ## AttributeFilter [#attributefilter] A single attribute filter expression. ```typescript /** A single attribute filter expression. */ export interface AttributeFilter { readonly type: 'attribute'; readonly attribute: string; readonly op: FilterOp; readonly value: string | boolean | number | null; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:21`. ## LogicalFilter [#logicalfilter] Logical combination of filters. ```typescript /** Logical combination of filters. */ export interface LogicalFilter { readonly type: 'and' | 'or'; readonly filters: readonly ParsedFilter[]; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:29`. ## FilterOp [#filterop] Supported comparison operators. ```typescript /** Supported comparison operators. */ export type FilterOp = 'eq' | 'ne' | 'co' | 'sw' | 'ew' | 'pr' | 'gt' | 'ge' | 'lt' | 'le'; ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:18`. ## parseFilter [#parsefilter] Parse a SCIM filter string into a structured filter tree. Returns `undefined` for empty/missing filters (match all). Throws on malformed filters. ```typescript export declare const parseFilter: (filterStr: string | undefined | null) => ParsedFilter | undefined; ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:109`. ## matchesFilter [#matchesfilter] Evaluate a parsed filter against an agent record. Returns true if the record matches. ```typescript export declare const matchesFilter: (record: AgentRecord, filter: ParsedFilter | undefined) => boolean; ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:206`. ## ScimFilterError [#scimfiltererror] ```typescript export declare class ScimFilterError { constructor(message: string): ScimFilterError; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/filtering.ts:278`. ## PaginationParams [#paginationparams] Parsed pagination parameters from a SCIM request. ```typescript /** Parsed pagination parameters from a SCIM request. */ export interface PaginationParams { /** 1-based start index. */ readonly startIndex: number; /** Number of results to return. */ readonly count: number; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/pagination.ts:11`. ## parsePagination [#parsepagination] Extract pagination parameters from a SCIM request URL search params. Returns immutable params — never mutates the input. ```typescript export declare const parsePagination: (searchParams: URLSearchParams, maxPageSize: number) => PaginationParams; ``` Source: `openagent-sdk/bridges/scim/typescript/src/pagination.ts:23`. ## paginateResults [#paginateresults] Apply pagination to an array of items and return a SCIM ListResponse. Items are expected to be pre-filtered and pre-sorted. This function slices the array according to 1-based SCIM indexing. ```typescript export declare const paginateResults: (items: readonly T[], params: PaginationParams) => ScimListResponse; ``` Source: `openagent-sdk/bridges/scim/typescript/src/pagination.ts:43`. ## PatchOperation [#patchoperation] A single SCIM PATCH operation. ```typescript /** A single SCIM PATCH operation. */ export interface PatchOperation { readonly op: 'add' | 'replace' | 'remove'; readonly path?: string; readonly value?: unknown; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/operations.ts:13`. ## PatchRequest [#patchrequest] SCIM PatchOp request body. ```typescript /** SCIM PatchOp request body. */ export interface PatchRequest { readonly schemas: readonly string[]; readonly Operations: readonly PatchOperation[]; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/operations.ts:20`. ## parsePatchRequest [#parsepatchrequest] Parse and validate a SCIM PATCH request body. ```typescript export declare const parsePatchRequest: (body: unknown) => PatchRequest; ``` Source: `openagent-sdk/bridges/scim/typescript/src/operations.ts:40`. ## applyPatchOperations [#applypatchoperations] Apply a set of SCIM PATCH operations to an agent record. Returns a new record with all operations applied. The original is never mutated. Throws on invalid paths or unsupported operations. ```typescript export declare const applyPatchOperations: (record: AgentRecord, operations: readonly PatchOperation[]) => AgentRecord; ``` Source: `openagent-sdk/bridges/scim/typescript/src/operations.ts:50`. ## ScimPatchError [#scimpatcherror] ```typescript export declare class ScimPatchError { constructor(message: string): ScimPatchError; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/operations.ts:170`. ## AgentProvisioner [#agentprovisioner] ```typescript export declare class AgentProvisioner { constructor(config: ProvisionerConfig): AgentProvisioner; createAgent(params: CreateAgentParams): Promise; replaceAgent(did: string, params: CreateAgentParams): Promise; updateAgent(did: string, record: AgentRecord): Promise; deprovisionAgent(did: string): Promise; findByDid(did: string): Promise; findByUserName(userName: string): Promise; listAgents(): Promise; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:83`. ## ProvisionerConfig [#provisionerconfig] ```typescript // ── Provisioner configuration ───────────────────────────────────────────── export interface ProvisionerConfig { readonly store: AgentStore; readonly namespace: string; readonly logger: Logger; readonly auditSink?: AuditSink; readonly revokeDidDocument?: DidRevoker; readonly cascadeRevokeDelegations?: DelegationCascadeRevoker; readonly invalidateArsenalSessions?: ArsenalSessionInvalidator; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:60`. ## CreateAgentParams [#createagentparams] ```typescript // ── Create ──────────────────────────────────────────────────────────────── export interface CreateAgentParams { readonly userName: string; readonly displayName?: string; readonly parentDid: string; readonly conformanceLevel: ConformanceLevel; readonly scopes: readonly string[]; readonly externalId?: string; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:72`. ## AuditEvent [#auditevent] Audit event emitted during agent lifecycle operations. ```typescript // ── Event types ─────────────────────────────────────────────────────────── /** Audit event emitted during agent lifecycle operations. */ export interface AuditEvent { readonly type: 'agent.created' | 'agent.updated' | 'agent.deprovisioned'; readonly did: string; readonly timestamp: string; readonly details: Record; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:20`. ## AuditSink [#auditsink] Callback invoked for each lifecycle audit event. ```typescript /** Callback invoked for each lifecycle audit event. */ export type AuditSink = (event: AuditEvent) => void | Promise; ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:28`. ## DidRevoker [#didrevoker] Hook invoked during deprovisioning to revoke the agent's DID document. Production: wires to OAS SDK's `revokeIdentity`. Default: no-op (logs a warning). ```typescript // ── Deprovisioning hooks ────────────────────────────────────────────────── /** * Hook invoked during deprovisioning to revoke the agent's DID document. * * Production: wires to OAS SDK's `revokeIdentity`. * Default: no-op (logs a warning). */ export type DidRevoker = (did: string) => Promise; ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:38`. ## DelegationCascadeRevoker [#delegationcascaderevoker] Hook invoked during deprovisioning to cascade-revoke all delegation proofs issued by (or to) the deprovisioned agent. Production: wires to AEGIS SDK's delegation tree walker. Default: no-op (logs a warning). ```typescript /** * Hook invoked during deprovisioning to cascade-revoke all delegation * proofs issued by (or to) the deprovisioned agent. * * Production: wires to AEGIS SDK's delegation tree walker. * Default: no-op (logs a warning). */ export type DelegationCascadeRevoker = (did: string) => Promise; ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:47`. ## ArsenalSessionInvalidator [#arsenalsessioninvalidator] Hook invoked during deprovisioning to invalidate all active Arsenal sessions for the deprovisioned agent. Production: wires to Arsenal SDK's session invalidation. Default: no-op (logs a warning). ```typescript /** * Hook invoked during deprovisioning to invalidate all active Arsenal * sessions for the deprovisioned agent. * * Production: wires to Arsenal SDK's session invalidation. * Default: no-op (logs a warning). */ export type ArsenalSessionInvalidator = (did: string) => Promise; ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:56`. ## ProvisionerError [#provisionererror] ```typescript export declare class ProvisionerError { code: ProvisionerErrorCode; constructor(message: string, code: ProvisionerErrorCode): ProvisionerError; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/provisioner.ts:341`. ## AgentStore [#agentstore] Storage interface for agent records. All methods return new objects — implementations must never return mutable references to internal state. ```typescript /** * Storage interface for agent records. * * All methods return new objects — implementations must never return * mutable references to internal state. */ export interface AgentStore { /** List all agent records. Returns an immutable snapshot. */ list(): Promise; /** Find agent by DID. Returns undefined if not found. */ findByDid(did: string): Promise; /** Find agent by userName. Returns undefined if not found. */ findByUserName(userName: string): Promise; /** Find agent by externalId. Returns undefined if not found. */ findByExternalId(externalId: string): Promise; /** Insert a new agent record. Throws if DID already exists. */ create(record: AgentRecord): Promise; /** Replace an agent record. Throws if DID does not exist. */ update(did: string, record: AgentRecord): Promise; /** Delete an agent record. Throws if DID does not exist. */ delete(did: string): Promise; /** Return the count of all active agents. */ countActive(): Promise; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/store.ts:17`. ## InMemoryAgentStore [#inmemoryagentstore] In-memory store for testing and development. ```typescript export declare class InMemoryAgentStore { list(): Promise; findByDid(did: string): Promise; findByUserName(userName: string): Promise; findByExternalId(externalId: string): Promise; create(record: AgentRecord): Promise; update(did: string, record: AgentRecord): Promise; delete(did: string): Promise; countActive(): Promise; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/store.ts:44`. ## StoreError [#storeerror] ```typescript export declare class StoreError { code: StoreErrorCode; constructor(message: string, code: StoreErrorCode): StoreError; } ``` Source: `openagent-sdk/bridges/scim/typescript/src/store.ts:106`. ## StoreErrorCode [#storeerrorcode] ```typescript export type StoreErrorCode = 'NOT_FOUND' | 'CONFLICT' | 'INTERNAL'; ``` Source: `openagent-sdk/bridges/scim/typescript/src/store.ts:104`. ## VERSION [#version] Package version. ```typescript export declare const VERSION: "0.1.1"; ``` Source: `openagent-sdk/bridges/scim/typescript/src/index.ts:120`. # @openagentid/skills-policy API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-crates-openagent-skills-policy-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-crates-openagent-skills-policy-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-crates-openagent-skills-policy-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## AuditChain [#auditchain] ```typescript export declare class AuditChain { length(): number; isEmpty(): boolean; head(): string; get(sequence: number): Receipt | undefined; all(): readonly Receipt[]; verify(): boolean; append(skill: string, agent: string, session: string, invokedAt: Date, level: AuditLevel, args: unknown): Receipt; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/audit.ts:34`. ## Receipt [#receipt] ```typescript export interface Receipt { sequence: number; skill: string; agent: string; session: string; invokedAt: string; auditLevel: AuditLevel; argumentsHash: string; arguments?: unknown; previousHash: string; receiptHash: string; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/audit.ts:21`. ## HASH\_LEN [#hash_len] ```typescript export declare const HASH_LEN: 32; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/audit.ts:17`. ## Did [#did] ```typescript export declare class Did { parse(input: string): Did; toString(): string; equals(other: Did): boolean; asString(): string; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/did.ts:13`. ## InvocationContext [#invocationcontext] Context describing a single attempted skill invocation. Immutable; builder-style helpers return new instances. ```typescript export declare class InvocationContext { agentDid: Did; sessionId: string; arguments: unknown; invokedAt: Date; consentGranted: boolean; constructor(init: InvocationContextInit): InvocationContext; withConsent(): InvocationContext; withInvokedAt(invokedAt: Date): InvocationContext; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/engine.ts:52`. ## SkillsPolicy [#skillspolicy] ```typescript export declare class SkillsPolicy { fromYaml(yaml: string): SkillsPolicy; fromFile(path: string): Promise; agent(): Did; hasRule(skill: string): boolean; auditChain(): AuditChain; resetRateLimit(skill: string): void; canInvoke(skill: string, ctx: InvocationContext): void; recordInvocation(skill: string, ctx: InvocationContext): Receipt; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/engine.ts:88`. ## ArgumentConstraintError [#argumentconstrainterror] ```typescript export declare class ArgumentConstraintError { name: "ArgumentConstraintError"; skill: string; details: string; constructor(skill: string, details: string): ArgumentConstraintError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:63`. ## ConsentRequiredError [#consentrequirederror] ```typescript export declare class ConsentRequiredError { name: "ConsentRequiredError"; skill: string; constructor(skill: string): ConsentRequiredError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:87`. ## InvalidPolicyError [#invalidpolicyerror] ```typescript export declare class InvalidPolicyError { name: "InvalidPolicyError"; constructor(message: string): InvalidPolicyError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:17`. ## InvalidSkillsMarkdownError [#invalidskillsmarkdownerror] ```typescript export declare class InvalidSkillsMarkdownError { name: "InvalidSkillsMarkdownError"; constructor(message: string): InvalidSkillsMarkdownError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:25`. ## NotAllowedError [#notallowederror] ```typescript export declare class NotAllowedError { name: "NotAllowedError"; skill: string; reason: string; constructor(skill: string, reason: string): NotAllowedError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:33`. ## OutsideTimeWindowError [#outsidetimewindowerror] ```typescript export declare class OutsideTimeWindowError { name: "OutsideTimeWindowError"; skill: string; constructor(skill: string): OutsideTimeWindowError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:75`. ## RateLimitExceededError [#ratelimitexceedederror] ```typescript export declare class RateLimitExceededError { name: "RateLimitExceededError"; skill: string; used: number; max: number; windowSecs: number; constructor(skill: string, used: number, max: number, windowSecs: number): RateLimitExceededError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:45`. ## SkillsPolicyError [#skillspolicyerror] Typed error hierarchy for the skills policy engine. Each failing dimension has its own subclass so callers can pattern-match with `instanceof` rather than parsing error messages. ```typescript export declare class SkillsPolicyError { name: string; constructor(message: string): SkillsPolicyError; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/errors.ts:8`. ## RateLimiter [#ratelimiter] ```typescript export declare class RateLimiter { checkAndRecord(skill: string, limit: RateLimit, nowSecs: number): RateLimitDecision; reset(skill: string): void; snapshot(): Array<[string, number]>; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/rate.ts:16`. ## RateLimitDecision [#ratelimitdecision] ```typescript export type RateLimitDecision = { kind: "allowed"; } | { kind: "denied"; used: number; }; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/rate.ts:12`. ## AuditLevel [#auditlevel] ```typescript export type AuditLevel = z.infer; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:15`. ## CURRENT\_VERSION [#current_version] ```typescript export declare const CURRENT_VERSION: 1; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:11`. ## DefaultRule [#defaultrule] ```typescript export type DefaultRule = z.infer; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:50`. ## MAX\_SKILL\_RULES [#max_skill_rules] ```typescript export declare const MAX_SKILL_RULES: 256; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:12`. ## RateLimit [#ratelimit] ```typescript export type RateLimit = z.infer; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:21`. ## SkillRule [#skillrule] ```typescript export type SkillRule = z.infer; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:42`. ## SkillsPolicyDoc [#skillspolicydoc] ```typescript export type SkillsPolicyDoc = z.infer; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:69`. ## TimeWindow [#timewindow] ```typescript export type TimeWindow = z.infer; ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/schema.ts:28`. ## SkillEntry [#skillentry] ```typescript export interface SkillEntry { readonly name: string; readonly description: string; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/skillsMd.ts:14`. ## SkillsManifest [#skillsmanifest] ```typescript export declare class SkillsManifest { skills: readonly SkillEntry[]; fromMarkdown(input: string): SkillsManifest; fromFile(path: string): Promise; length(): number; isEmpty(): boolean; get(name: string): SkillEntry | undefined; names(): string[]; } ``` Source: `openagent-sdk/crates/openagent-skills-policy/typescript/src/skillsMd.ts:19`. # @openagentid/claude-agent API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-integrations-claude-agent-sdk-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-integrations-claude-agent-sdk-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-integrations-claude-agent-sdk-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## openAgentPlugin [#openagentplugin] Build a Claude Agent SDK plugin that wires OpenAgent identity, capability control, and tamper-evident audit logging into the agent lifecycle. ```typescript export declare const openAgentPlugin: (opts: OpenAgentPluginOptions) => OpenAgentPlugin; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/plugin.ts:135`. ## OpenAgentPlugin [#openagentplugin-1] Shape returned by \{@link openAgentPlugin}. ```typescript /** Shape returned by {@link openAgentPlugin}. */ export interface OpenAgentPlugin { /** Stable plugin identifier. */ readonly name: '@openagentid/claude-agent'; /** Plugin schema version. */ readonly version: string; /** Bound hook handlers — wired to the Claude Agent SDK lifecycle. */ readonly hooks: PluginHooks; /** * Inspect the in-memory audit buffer (only populated when `audit: true` * with the default sink). Returns an empty array otherwise. */ inspectAudit(): readonly import('./types.js').AuditRecord[]; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/plugin.ts:86`. ## OpenAgentPluginOptions [#openagentpluginoptions] Configuration accepted by \{@link openAgentPlugin}. ```typescript /** Configuration accepted by {@link openAgentPlugin}. */ export interface OpenAgentPluginOptions { /** Verified OpenAgent identity to attach to the session. Required. */ agent: OpenAgentIdentity; /** Capability checker — Arsenal-backed in production. Required. */ capabilities: CapabilityChecker; /** Skills policy. Defaults to {@link DenyUnlessScopedSkillsPolicy}. */ skillsPolicy?: SkillsPolicy; /** * Audit configuration: * - `false` → no audit (records are dropped) * - `true` → in-memory + stdout console sink * - {@link AuditSink} → custom sink */ audit?: boolean | AuditSink; /** * Sign every outbound message with the agent's Ed25519 key. Defaults * to `false` because most agent flows don't need it. */ signMessages?: boolean; /** * Behaviour on a denied tool / skill: * - `'throw'` (default) — throws {@link ToolDeniedError} or {@link SkillDeniedError} * - `'block'` — returns a blocking decision object the SDK can interpret */ denyMode?: 'throw' | 'block'; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/plugin.ts:58`. ## PluginHooks [#pluginhooks] Bound hook handlers. Each method receives the SDK's hook input plus the SDK-managed context object and returns a plain JS object the SDK can route. The shapes below are the documented Claude Agent SDK hook signatures; if Anthropic adds a new lifecycle stage we add a new method here without breaking existing wiring. ```typescript /** * Bound hook handlers. Each method receives the SDK's hook input plus the * SDK-managed context object and returns a plain JS object the SDK can * route. The shapes below are the documented Claude Agent SDK hook * signatures; if Anthropic adds a new lifecycle stage we add a new method * here without breaking existing wiring. */ export interface PluginHooks { onSessionStart(input: SessionStartInput): Promise<{ allow: true; }>; preToolUse(input: ToolUseInput): Promise; postToolUse(input: PostToolUseInput): Promise<{ ok: true; }>; onMessage(input: MessageInput): Promise<{ allow: true; signature?: string; }>; onSkillInvoke(input: SkillInvokeInput): Promise; onSessionEnd(): Promise<{ ok: true; }>; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/plugin.ts:107`. ## HookDecision [#hookdecision] Decision object returned by gating hooks (preToolUse, onSkillInvoke). ```typescript /** Decision object returned by gating hooks (preToolUse, onSkillInvoke). */ export interface HookDecision { allow: boolean; reason?: string; /** * Hash of the canonicalised tool input (preToolUse only) — thread it into * the matching postToolUse call so the audit chain links preflight to * completion. */ inputHash?: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/plugin.ts:117`. ## AuditChain [#auditchain] Builds and signs (hash-chains) audit records. The chain is owned by a single session — callers should construct one chain per session. ```typescript export declare class AuditChain { constructor(opts: { sessionId: string; agentDid: string; sink: AuditSink; }): AuditChain; append(input: { kind: AuditKind; name?: string; outcome: AuditRecord["outcome"]; inputHash?: string; outputHash?: string; context?: Record; }): Promise; head(): string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:26`. ## ConsoleAuditSink [#consoleauditsink] Audit sink that writes structured JSON to stdout — handy for dev. ```typescript export declare class ConsoleAuditSink { append(record: AuditRecord): void; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:119`. ## FanOutAuditSink [#fanoutauditsink] Compose multiple sinks (records are dispatched to all in order). ```typescript export declare class FanOutAuditSink { constructor(sinks: readonly AuditSink[]): FanOutAuditSink; append(record: AuditRecord): Promise; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:127`. ## GENESIS\_PREV\_HASH [#genesis_prev_hash] Sentinel for the head of the chain. ```typescript export declare const GENESIS_PREV_HASH: string; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:20`. ## InMemoryAuditSink [#inmemoryauditsink] In-memory audit sink (handy for tests + dry runs). ```typescript export declare class InMemoryAuditSink { records: AuditRecord[]; append(record: AuditRecord): void; clear(): void; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:105`. ## hashRecord [#hashrecord] Compute the hash of a record (excludes the hash field itself). ```typescript export declare const hashRecord: (record: AuditRecord) => string; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:80`. ## verifyChain [#verifychain] Verify that a previously emitted chain has not been tampered with. ```typescript export declare const verifyChain: (records: readonly AuditRecord[]) => { valid: boolean; brokenAt?: number; }; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/audit.ts:88`. ## AllowListSkillsPolicy [#allowlistskillspolicy] Allow-listed skills policy: only the named skills are permitted, and the agent must additionally hold the right scope. ```typescript export declare class AllowListSkillsPolicy { constructor(allowedSkills: Iterable, inner?: SkillsPolicy): AllowListSkillsPolicy; evaluate(skillName: string, ctx: SkillEvaluationContext): Promise; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:106`. ## CompositeSkillsPolicy [#compositeskillspolicy] Compose multiple policies — a skill is allowed only if every policy allows it. Useful for stacking allow-list + scope + custom policies. ```typescript export declare class CompositeSkillsPolicy { constructor(policies: readonly SkillsPolicy[]): CompositeSkillsPolicy; evaluate(skillName: string, ctx: SkillEvaluationContext): Promise; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:130`. ## DenyUnlessScopedSkillsPolicy [#denyunlessscopedskillspolicy] Deny-unless-scoped skills policy. For a skill named `foo`, requires the agent to hold `skills:invoke:foo` (or a wildcard that subsumes it). This is the default policy when the caller passes `audit: true` without supplying their own. ```typescript export declare class DenyUnlessScopedSkillsPolicy { evaluate(skillName: string, ctx: SkillEvaluationContext): Promise; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:81`. ## SKILL\_SCOPE\_PREFIX [#skill_scope_prefix] Scope grammar for skill invocations. ```typescript export declare const SKILL_SCOPE_PREFIX: "skills:invoke:"; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:24`. ## StaticCapabilityChecker [#staticcapabilitychecker] Capability checker backed by a fixed allowlist. Supports literal scopes and one wildcard form: `prefix:*` matches anything starting with `prefix:`. Example: `tools:invoke:*` allows every tool, `skills:invoke:web.*` allows every skill whose name starts with `web.`. ```typescript export declare class StaticCapabilityChecker { constructor(scopes: Iterable): StaticCapabilityChecker; check(scope: string): ScopeDecision; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:46`. ## TOOL\_SCOPE\_PREFIX [#tool_scope_prefix] Scope grammar for tool invocations. ```typescript export declare const TOOL_SCOPE_PREFIX: "tools:invoke:"; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:27`. ## skillScope [#skillscope] Build the canonical scope string for a skill name. ```typescript export declare const skillScope: (name: string) => string; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:30`. ## toolScope [#toolscope] Build the canonical scope string for a tool name. ```typescript export declare const toolScope: (name: string) => string; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/policy.ts:35`. ## onMessage [#onmessage] Sign an outbound message with the agent's Ed25519 key (if signing is enabled) and append an audit record. ```typescript export declare const onMessage: (input: MessageInput, ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:226`. ## onSessionEnd [#onsessionend] Emit a closing record at session end. ```typescript export declare const onSessionEnd: (ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:320`. ## onSessionStart [#onsessionstart] Initialise the per-session hook context and emit the opening audit record. Call this once when the Claude Agent SDK fires the session start hook. ```typescript export declare const onSessionStart: (input: SessionStartInput, ctx: Omit & { sink: AuditSink; }) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:57`. ## onSkillInvoke [#onskillinvoke] Consult the OpenAgent skills policy before a SKILLS.md skill runs. The Claude Agent SDK loads skills from SKILLS.md files; we hook the invocation point and refuse anything the policy denies. Default policy is `DenyUnlessScopedSkillsPolicy`. ```typescript export declare const onSkillInvoke: (input: SkillInvokeInput, ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:278`. ## onSkillInvokeOrThrow [#onskillinvokeorthrow] Throw-on-deny variant of \{@link onSkillInvoke}. ```typescript export declare const onSkillInvokeOrThrow: (input: SkillInvokeInput, ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:308`. ## postToolUse [#posttooluse] Emit a post-tool-use audit record with input + output hashes. The record's hash chain prevents post-hoc tampering: a verifier can replay \{@link import ('./audit.js').verifyChain} over an exported chain to detect any modification. ```typescript export declare const postToolUse: (input: PostToolUseInput, ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:190`. ## preToolUse [#pretooluse] Verify a tool call against Arsenal scopes and emit a preflight audit record. Returns `{ allow: false }` rather than throwing so the caller can decide whether to short-circuit the SDK or surface an error to the model. The plugin's hook adapter throws \{@link ToolDeniedError} when the SDK requires an exception-based deny. ```typescript export declare const preToolUse: (input: ToolUseInput, ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:117`. ## preToolUseOrThrow [#pretooluseorthrow] Throw-on-deny variant of \{@link preToolUse}. ```typescript export declare const preToolUseOrThrow: (input: ToolUseInput, ctx: HookContext) => Promise; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:159`. ## HookContext [#hookcontext] Per-session state that the hooks share. Constructed once when the session starts and disposed when it ends. ```typescript /** * Per-session state that the hooks share. Constructed once when the * session starts and disposed when it ends. */ export interface HookContext { readonly identity: OpenAgentIdentity; readonly capabilities: CapabilityChecker; readonly skillsPolicy: SkillsPolicy; readonly chain: AuditChain; readonly signMessages: boolean; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:31`. ## MessageInput [#messageinput] Input shape for \{@link onMessage}. ```typescript /** Input shape for {@link onMessage}. */ export interface MessageInput { /** Plain-text or already-serialised message body. */ body: string | Uint8Array; /** Direction of the message — used for the audit context only. */ direction: 'in' | 'out'; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:207`. ## OnMessageResult [#onmessageresult] Result of \{@link onMessage}. ```typescript /** Result of {@link onMessage}. */ export interface OnMessageResult { /** Hex-encoded Ed25519 signature, when message signing is enabled. */ signature?: string; /** Audit record emitted for this message. */ record: AuditRecord; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:215`. ## PostToolUseInput [#posttooluseinput] Input shape for \{@link postToolUse}. ```typescript /** Input shape for {@link postToolUse}. */ export interface PostToolUseInput { toolName: string; /** Tool result (any shape). */ result: unknown; /** Was the underlying call successful? */ ok: boolean; /** Optional error description if the call failed. */ error?: string; /** Hash of the original input — typically threaded from preToolUse. */ inputHash?: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:171`. ## PreToolUseResult [#pretooluseresult] Result of a pre-tool-use evaluation. ```typescript /** Result of a pre-tool-use evaluation. */ export interface PreToolUseResult { /** Whether the tool call may proceed. */ allow: boolean; /** Reason on deny. */ reason?: string; /** The audit record emitted (preflight). */ record: AuditRecord; /** Hash of the canonicalised input — reused by post hook. */ inputHash: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:97`. ## SessionStartInput [#sessionstartinput] Input shape for \{@link onSessionStart}. ```typescript /** Input shape for {@link onSessionStart}. */ export interface SessionStartInput { sessionId: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:40`. ## SessionStartResult [#sessionstartresult] Result of \{@link onSessionStart}. ```typescript /** Result of {@link onSessionStart}. */ export interface SessionStartResult { /** The audit record emitted for the session start. */ record: AuditRecord; /** The hook context to be threaded through subsequent hooks. */ context: HookContext; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:45`. ## SkillInvokeInput [#skillinvokeinput] Input shape for \{@link onSkillInvoke}. ```typescript /** Input shape for {@link onSkillInvoke}. */ export interface SkillInvokeInput { skillName: string; args?: unknown; metadata?: Record; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:259`. ## SkillInvokeResult [#skillinvokeresult] Result of \{@link onSkillInvoke}. ```typescript /** Result of {@link onSkillInvoke}. */ export interface SkillInvokeResult { decision: SkillDecision; record: AuditRecord; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:266`. ## ToolUseInput [#tooluseinput] Input shape for \{@link preToolUse}. ```typescript /** Input shape for {@link preToolUse}. */ export interface ToolUseInput { /** Tool name as advertised by the Claude Agent SDK. */ toolName: string; /** The arguments the agent intends to pass to the tool. */ args: unknown; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hooks.ts:89`. ## ConfigError [#configerror] Configuration was invalid at plugin construction time. ```typescript export declare class ConfigError { constructor(message: string, context?: Record): ConfigError; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/errors.ts:79`. ## PluginError [#pluginerror] Base error for the plugin. ```typescript export declare class PluginError { code: PluginErrorCodeValue; context: Record; cause: unknown; constructor(message: string, code: PluginErrorCodeValue, options?: { context?: Record; cause?: unknown; }): PluginError; toJSON(): Record; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/errors.ts:22`. ## PluginErrorCode [#pluginerrorcode] Stable, machine-readable error codes. ```typescript export declare const PluginErrorCode: { readonly CONFIG_INVALID: "openagent/claude-agent/config-invalid"; readonly IDENTITY_MISSING: "openagent/claude-agent/identity-missing"; readonly TOOL_DENIED: "openagent/claude-agent/tool-denied"; readonly SKILL_DENIED: "openagent/claude-agent/skill-denied"; readonly AUDIT_FAILED: "openagent/claude-agent/audit-failed"; readonly HOOK_INTERNAL: "openagent/claude-agent/hook-internal"; readonly SIGN_FAILED: "openagent/claude-agent/sign-failed"; }; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/errors.ts:9`. ## PluginErrorCodeValue [#pluginerrorcodevalue] ```typescript export type PluginErrorCodeValue = (typeof PluginErrorCode)[keyof typeof PluginErrorCode]; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/errors.ts:19`. ## SkillDeniedError [#skilldeniederror] A skill invocation was rejected by the skills policy. ```typescript export declare class SkillDeniedError { skill: string; constructor(skill: string, reason?: string, context?: Record): SkillDeniedError; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/errors.ts:65`. ## ToolDeniedError [#tooldeniederror] A tool call was rejected because the agent lacks the required scope. ```typescript export declare class ToolDeniedError { tool: string; constructor(tool: string, reason?: string, context?: Record): ToolDeniedError; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/errors.ts:51`. ## AuditKind [#auditkind] Categories of audit events. ```typescript /** Categories of audit events. */ export type AuditKind = 'session.start' | 'session.stop' | 'tool.preflight' | 'tool.complete' | 'skill.preflight' | 'skill.complete' | 'message.signed' | 'policy.deny'; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:89`. ## AuditRecord [#auditrecord] A single tamper-evident audit record. ```typescript /** A single tamper-evident audit record. */ export interface AuditRecord { /** Monotonic sequence number within a session. */ seq: number; /** ISO-8601 timestamp the record was emitted. */ timestamp: string; /** Session id this record belongs to. */ sessionId: string; /** Agent DID that performed the action. */ agentDid: string; /** What kind of event this is. */ kind: AuditKind; /** Tool or skill name (when applicable). */ name?: string; /** Allow / deny outcome. */ outcome: 'allow' | 'deny' | 'ok' | 'error'; /** Hash of the request payload (BLAKE3 hex, lowercase). */ inputHash?: string; /** Hash of the response payload (BLAKE3 hex, lowercase). */ outputHash?: string; /** Hash chain pointer to the previous record. */ prevHash: string; /** This record's hash. */ hash: string; /** Free-form context (matched scope, error message, etc.). */ context?: Record; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:61`. ## AuditSink [#auditsink] Audit sink — receives one record per tool / skill invocation. ```typescript /** Audit sink — receives one record per tool / skill invocation. */ export interface AuditSink { /** Append an audit record. MUST be best-effort and non-throwing. */ append(record: AuditRecord): Promise | void; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:55`. ## CapabilityChecker [#capabilitychecker] Anything implementing this can authorise tool / skill invocations. ```typescript /** Anything implementing this can authorise tool / skill invocations. */ export interface CapabilityChecker { /** * Check whether the agent currently holds the requested scope. * * Implementations should be deterministic and side-effect free — * Arsenal-backed checkers may cache, but MUST NOT mutate. */ check(scope: string): Promise | ScopeDecision; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:44`. ## OpenAgentIdentity [#openagentidentity] A verified OpenAgent identity, anchored on a `did:oas:*` string. ```typescript /** * Shared types for the OpenAgent x Claude Agent SDK plugin. * * These mirror the public surface of `@openagentid/sdk` but are duplicated * here so the plugin can run in environments where the SDK is not yet * resolved (e.g., bun's optional peer dep handling, dev installs). * * When `@openagentid/sdk` is present, the runtime objects passed by the * caller are structurally compatible with the interfaces below. */ /** A verified OpenAgent identity, anchored on a `did:oas:*` string. */ export interface OpenAgentIdentity { /** Decentralised identifier, e.g. `did:oas:test:agent:refactor-bot`. */ did: string; /** Entity kind: `hmr`, `mhr`, `agent`, `tool`, `skill`, etc. */ kind: string; /** Optional human-readable display name (not authoritative). */ displayName?: string; /** Public Ed25519 verification key, hex-encoded (32 bytes). */ publicKey: string; /** * Sign a payload with the agent's Ed25519 secret key. * * The signing key MUST live behind this function — it is never * exposed to plugin code directly. */ sign(payload: Uint8Array): Promise | Uint8Array; /** Optional lineage chain (HMR -> ... -> this agent). */ lineage?: readonly string[]; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:13`. ## ScopeDecision [#scopedecision] Result of a credential / scope check. ```typescript /** Result of a credential / scope check. */ export interface ScopeDecision { /** Whether the request is allowed. */ allowed: boolean; /** Matched scope string (e.g. `tools:invoke:bash`), if any. */ matchedScope?: string; /** Human-readable reason for denial. */ reason?: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:34`. ## SkillDecision [#skilldecision] Result of a skills policy evaluation. ```typescript /** Result of a skills policy evaluation. */ export interface SkillDecision { /** Allow / deny. */ allowed: boolean; /** Reason on deny. */ reason?: string; /** The scope that authorised the call. */ matchedScope?: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:131`. ## SkillEvaluationContext [#skillevaluationcontext] Context passed to a skills policy evaluation. ```typescript /** Context passed to a skills policy evaluation. */ export interface SkillEvaluationContext { /** The agent's verified identity. */ identity: OpenAgentIdentity; /** Capability checker (Arsenal-backed) for scope lookups. */ capabilities: CapabilityChecker; /** Optional metadata about the call site. */ metadata?: Record; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:121`. ## SkillsManifestEntry [#skillsmanifestentry] SKILLS.md entry as parsed from a manifest. ```typescript /** SKILLS.md entry as parsed from a manifest. */ export interface SkillsManifestEntry { /** Stable skill identifier (e.g. `web.search`). */ name: string; /** Human description. */ description?: string; /** Required scope to invoke. Defaults to `skills:invoke:`. */ requiredScope?: string; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:100`. ## SkillsPolicy [#skillspolicy] Skills policy: decides whether a SKILLS.md skill may be invoked. ```typescript /** Skills policy: decides whether a SKILLS.md skill may be invoked. */ export interface SkillsPolicy { /** * Check whether the named skill may be invoked by the current agent. * * Default behaviour for any concrete implementation: deny unless the * agent holds `skills:invoke:`. */ evaluate(skillName: string, ctx: SkillEvaluationContext): Promise | SkillDecision; } ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/types.ts:110`. ## canonicalJson [#canonicaljson] Stable JSON stringify (sorted keys) for deterministic hashing. ```typescript export declare const canonicalJson: (value: unknown) => string; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hash.ts:63`. ## getHashAlgo [#gethashalgo] Resolve which hash algorithm to use, attempting to load `blake3` once. Subsequent calls are cached. ```typescript export declare const getHashAlgo: () => HashAlgo; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hash.ts:25`. ## hashHex [#hashhex] Hash a string or byte buffer and return lowercase hex. ```typescript export declare const hashHex: (data: string | Uint8Array) => string; ``` Source: `openagent-sdk/integrations/claude-agent-sdk/typescript/src/hash.ts:50`. # @openagentid/mcp API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-integrations-mcp-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-integrations-mcp-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-integrations-mcp-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## withOpenAgent [#withopenagent] Wrap an MCP server so every tool call is authenticated against an OpenAgent identity. ```typescript export declare const withOpenAgent: (server: T, config: OpenAgentMcpConfig) => T; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/server.ts:92`. ## ANONYMOUS\_IDENTITY [#anonymous_identity] ```typescript export declare const ANONYMOUS_IDENTITY: VerifiedIdentity; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/server.ts:418`. ## McpServerLike [#mcpserverlike] Minimal McpServer surface used by the middleware. We avoid importing concrete types from `@modelcontextprotocol/sdk` because peer-dep versions vary across host applications and the SDK's own type exports are subject to change. The shape below is the intersection of every `1.x` McpServer release. ```typescript /** * Minimal McpServer surface used by the middleware. We avoid importing * concrete types from `@modelcontextprotocol/sdk` because peer-dep * versions vary across host applications and the SDK's own type exports * are subject to change. The shape below is the intersection of every * `1.x` McpServer release. */ export interface McpServerLike { tool(...args: unknown[]): unknown; registerTool(...args: unknown[]): unknown; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/server.ts:58`. ## withOpenAgentClient [#withopenagentclient] Wrap an MCP client so every outbound `callTool` carries an OpenAgent identity envelope. ```typescript export declare const withOpenAgentClient: (client: T, config: OpenAgentClientConfig) => T; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/client.ts:70`. ## buildIdentityMeta [#buildidentitymeta] Helper for tests and tools that want to construct the identity envelope manually without going through a full Agent. Returns a `_meta` object that can be merged into a CallToolRequest's params. ```typescript export declare const buildIdentityMeta: (identity: { did: string; proof: string; nonce?: string; context?: Record; }) => Record; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/client.ts:184`. ## McpClientLike [#mcpclientlike] Minimal MCP client surface used by the interceptor. Like the server adapter, we describe just the methods we need to keep peer-dep compatibility broad. ```typescript /** * Minimal MCP client surface used by the interceptor. Like the server * adapter, we describe just the methods we need to keep peer-dep * compatibility broad. */ export interface McpClientLike { callTool(params: { name: string; arguments?: Record; _meta?: Record; }, ...rest: unknown[]): Promise; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/client.ts:30`. ## OpenAgentClientConfig [#openagentclientconfig] ```typescript export interface OpenAgentClientConfig { /** The agent doing the calling — used to sign each request. */ agent: Agent; /** * Optional audience DID. When set, it is passed to * {@link Agent.signRequest} so the proof can be bound to a specific * server. Most production deployments should set this. */ audience?: string; /** * Optional hook fired before every outbound call. Use it for client- * side metrics or to mutate the params (e.g., add tracing headers). * Returning a value replaces the params. */ beforeCall?: (params: { name: string; arguments?: Record; _meta?: Record; }) => Promise<{ name: string; arguments?: Record; _meta?: Record; } | void> | { name: string; arguments?: Record; _meta?: Record; } | void; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/client.ts:41`. ## OpenAgentMcpError [#openagentmcperror] Base class for all middleware errors. Subclasses set a default \{@link OpenAgentMcpError.code} that maps to a JSON-RPC error code. ```typescript export declare class OpenAgentMcpError { code: McpErrorCodeValue; data: Record; constructor(message: string, code: McpErrorCodeValue, data?: Record): OpenAgentMcpError; toJsonRpcError(): { code: McpErrorCodeValue; message: string; data?: Record; }; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:37`. ## MissingIdentityError [#missingidentityerror] Caller did not present an OpenAgent identity envelope. ```typescript export declare class MissingIdentityError { constructor(toolName: string): MissingIdentityError; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:71`. ## IdentityVerificationError [#identityverificationerror] Identity envelope was present but the verifier rejected it. ```typescript export declare class IdentityVerificationError { constructor(toolName: string, cause: unknown): IdentityVerificationError; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:83`. ## AuthorizationDeniedError [#authorizationdeniederror] Caller's verified identity does not hold the required scopes. ```typescript export declare class AuthorizationDeniedError { constructor(toolName: string, requiredScopes: ReadonlyArray, heldScopes: ReadonlyArray): AuthorizationDeniedError; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:95`. ## SkillsPolicyDeniedError [#skillspolicydeniederror] Skills policy hook returned `allow: false`. ```typescript export declare class SkillsPolicyDeniedError { constructor(toolName: string, reason: string | undefined): SkillsPolicyDeniedError; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:115`. ## McpErrorCode [#mcperrorcode] Standard JSON-RPC + MCP error codes used by the middleware. ```typescript export declare const McpErrorCode: { readonly InvalidRequest: -32600; readonly MethodNotFound: -32601; readonly InvalidParams: -32602; readonly InternalError: -32603; readonly ServerError: -32000; readonly AuthenticationFailed: -32001; readonly AuthorizationDenied: -32002; readonly SkillsPolicyDenied: -32003; }; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:11`. ## McpErrorCodeValue [#mcperrorcodevalue] ```typescript export type McpErrorCodeValue = (typeof McpErrorCode)[keyof typeof McpErrorCode]; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/errors.ts:30`. ## createSkillsPolicy [#createskillspolicy] Build a \{@link SkillsPolicyHook} from a store and matching options. The returned hook always allows tools that are not skill-like; it only consults the store when \{@link CreateSkillsPolicyOptions.isSkillTool} returns true. ```typescript export declare const createSkillsPolicy: (options: CreateSkillsPolicyOptions) => SkillsPolicyHook; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:100`. ## combineSkillsPolicies [#combineskillspolicies] Compose two skills policy hooks. The combined hook denies if either underlying hook denies; allow decisions from `first` are forwarded to `second`. ```typescript export declare const combineSkillsPolicies: (first: SkillsPolicyHook, second: SkillsPolicyHook) => SkillsPolicyHook; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:175`. ## InMemorySkillsPolicyStore [#inmemoryskillspolicystore] Trivial in-memory store useful in tests and as a starting point for production stores. ```typescript export declare class InMemorySkillsPolicyStore { constructor(rules?: ReadonlyArray): InMemorySkillsPolicyStore; lookup(skillName: string): SkillsRule | null; withRule(rule: SkillsRule): InMemorySkillsPolicyStore; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:53`. ## DEFAULT\_SKILL\_TOOL\_NAMES [#default_skill_tool_names] Tool name prefixes that the middleware treats as skill-like by default. Host applications can override the matcher entirely via \{@link createSkillsPolicy}. ```typescript export declare const DEFAULT_SKILL_TOOL_NAMES: readonly string[]; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:20`. ## SkillsRule [#skillsrule] A single rule describing whether a `(skillName, did)` pair is allowed. `null` for `dids` means "any verified caller". An empty array means "no caller". ```typescript /** * A single rule describing whether a `(skillName, did)` pair is allowed. * `null` for `dids` means "any verified caller". An empty array means * "no caller". */ export interface SkillsRule { skillName: string; /** DIDs allowed to invoke this skill, or `null` for any. */ dids: ReadonlyArray | null; /** Optional reason emitted when the rule denies a call. */ reason?: string; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:33`. ## SkillsPolicyStore [#skillspolicystore] Policy store interface — implementations may be in-memory, file-backed by `SKILLS.md`, or fetched from a remote service. ```typescript /** * Policy store interface — implementations may be in-memory, file-backed * by `SKILLS.md`, or fetched from a remote service. */ export interface SkillsPolicyStore { lookup(skillName: string): Promise | SkillsRule | null; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:45`. ## CreateSkillsPolicyOptions [#createskillspolicyoptions] ```typescript export interface CreateSkillsPolicyOptions { /** The store backing skill lookups. */ store: SkillsPolicyStore; /** * Returns true when a tool call should be checked against the skills * policy. Defaults to matching the tool name against * {@link DEFAULT_SKILL_TOOL_NAMES}. */ isSkillTool?: (toolName: string) => boolean; /** * Extracts the skill name from the tool's arguments. Defaults to * reading `args.skill` or `args.skillName`. */ extractSkillName?: (args: unknown) => string | null; /** * Default decision when no rule matches. Defaults to `{ allow: true }` * to keep non-skill tools unaffected. */ defaultDecision?: SkillsPolicyDecision; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/skills.ts:72`. ## Agent [#agent] Minimal Agent surface — only the parts of the OpenAgent SDK Agent that the MCP middleware actually needs. ```typescript /** * Minimal Agent surface — only the parts of the OpenAgent SDK Agent that * the MCP middleware actually needs. */ export interface Agent { did: Did; verifier: IdentityVerifier; /** * Sign an outbound MCP call so the receiving server can verify the * caller. Returns the identity envelope to attach as `_meta.openagent`. */ signRequest(toolName: string, audience?: Did): Promise; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:77`. ## AuditedResultMeta [#auditedresultmeta] Result envelope returned by an authenticated tool call. The `auditId` is pushed into `_meta.openagent.audit_id` on the response, so callers can correlate logs end-to-end. ```typescript /** * Result envelope returned by an authenticated tool call. The `auditId` is * pushed into `_meta.openagent.audit_id` on the response, so callers can * correlate logs end-to-end. */ export interface AuditedResultMeta { audit_id: string; verified_did: Did; scopes: ReadonlyArray; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:95`. ## Did [#did] A decentralized identifier following the `did:oas:*` method or any other DID method understood by the configured verifier. ```typescript /** * Public types for @openagentid/mcp. * * These interfaces describe the contract the middleware expects from an * OpenAgent {@link Agent} instance and the surrounding configuration. They are * defined locally so the package can be installed without `@openagentid/sdk` in * tests, in CI, and in environments where the host application brings its own * verifier implementation. * * The real `@openagentid/sdk` exports types that are structurally compatible * with these — there is no runtime dependency. */ /** * A decentralized identifier following the `did:oas:*` method or any other * DID method understood by the configured verifier. */ export type Did = string; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:18`. ## ErrorHook [#errorhook] Hook fired when the tool body or any earlier middleware step throws. The middleware re-throws the error after running this hook so MCP clients still observe the original failure mode. ```typescript /** * Hook fired when the tool body or any earlier middleware step throws. * The middleware re-throws the error after running this hook so MCP * clients still observe the original failure mode. */ export type ErrorHook = (input: { toolName: string; args: unknown; identity: VerifiedIdentity | null; error: unknown; }) => Promise | void; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:151`. ## IdentityVerifier [#identityverifier] The verifier interface — implemented by `@openagentid/sdk` (production) and by the in-memory test agent shipped here. Implementations MUST be deterministic for a given input and MUST NOT mutate the request identity object. ```typescript /** * The verifier interface — implemented by `@openagentid/sdk` (production) and * by the in-memory test agent shipped here. * * Implementations MUST be deterministic for a given input and MUST NOT * mutate the request identity object. */ export interface IdentityVerifier { verify(identity: OpenAgentRequestIdentity, requiredScopes: ReadonlyArray): Promise; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:66`. ## OpenAgentMcpConfig [#openagentmcpconfig] Configuration for \{@link withOpenAgent }. ```typescript /** * Configuration for {@link withOpenAgent}. */ export interface OpenAgentMcpConfig { /** The agent that owns this MCP server (used for outbound signing). */ agent: Agent; /** * Per-tool required scope set. Defaults to * `(toolName) => [`mcp:${toolName}:invoke`]`. */ requireScopes?: ScopeDeriver; /** * If true (default), tool calls without an `_meta.openagent.identity` * envelope are rejected. Set to false to opt-in to permissive mode for * local development — the middleware will still run hooks but skip * verification. */ requireIdentity?: boolean; /** Optional skills policy hook. */ skillsPolicy?: SkillsPolicyHook; /** Optional pre-call hook. */ preCall?: PreCallHook; /** Optional post-call hook for audit/log emission. */ postCall?: PostCallHook; /** Optional error hook. */ onError?: ErrorHook; /** * Override the default `mcp::invoke` scope format. Receives the * tool name and returns the canonical scope string. */ scopeFormat?: (toolName: string) => string; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:161`. ## OpenAgentRequestIdentity [#openagentrequestidentity] The four pieces of metadata an MCP request carries about the calling agent. Populated by the \{@link createClientInterceptor } on the call site and consumed by the server middleware. ```typescript /** * The four pieces of metadata an MCP request carries about the calling * agent. Populated by the {@link createClientInterceptor} on the call site * and consumed by the server middleware. */ export interface OpenAgentRequestIdentity { /** Caller's DID — typically `did:oas:...`. */ did: Did; /** * A signed challenge response or capability token (Arsenal ACT) the * server can verify offline. Format is opaque to the middleware. */ proof: string; /** * Optional bearer-style nonce. Servers may require it for replay * protection. Verifiers MUST treat the value as untrusted until * verification succeeds. */ nonce?: string; /** * Free-form context the verifier may use (issuer DID, audience, scopes * the caller claims). Always validated against the verifier's policy. */ context?: Record; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:25`. ## PostCallHook [#postcallhook] Hook fired after a tool body executes successfully. Use it for audit logging, metrics, and trace propagation. Throwing from this hook does NOT roll back the tool call. ```typescript /** * Hook fired after a tool body executes successfully. Use it for audit * logging, metrics, and trace propagation. Throwing from this hook does * NOT roll back the tool call. */ export type PostCallHook = (input: { toolName: string; args: unknown; identity: VerifiedIdentity; durationMs: number; result: unknown; }) => Promise | void; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:138`. ## PreCallHook [#precallhook] Hook fired before a tool body executes — after the identity has been verified and the skills policy has approved the call. ```typescript /** * Hook fired before a tool body executes — after the identity has been * verified and the skills policy has approved the call. */ export type PreCallHook = (input: { toolName: string; args: unknown; identity: VerifiedIdentity; }) => Promise | void; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:127`. ## ScopeDeriver [#scopederiver] Per-tool scope deriver. ```typescript /** Per-tool scope deriver. */ export type ScopeDeriver = (toolName: string, args: unknown) => ReadonlyArray; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:102`. ## SkillsPolicyDecision [#skillspolicydecision] ```typescript export interface SkillsPolicyDecision { allow: boolean; reason?: string; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:118`. ## SkillsPolicyHook [#skillspolicyhook] Hook signature for the skills policy. The hook receives the tool name, the arguments, and the verified identity, and decides whether the call should be allowed. ```typescript /** * Hook signature for the skills policy. The hook receives the tool name, * the arguments, and the verified identity, and decides whether the call * should be allowed. */ export type SkillsPolicyHook = (input: { toolName: string; args: unknown; identity: VerifiedIdentity; }) => Promise | SkillsPolicyDecision; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:112`. ## VerifiedIdentity [#verifiedidentity] The result of running the auth pipeline against an incoming MCP request. Available to post-call hooks and audit log emitters. ```typescript /** * The result of running the auth pipeline against an incoming MCP request. * Available to post-call hooks and audit log emitters. */ export interface VerifiedIdentity { did: Did; scopes: ReadonlyArray; /** Audit identifier echoed back to the caller in result `_meta`. */ auditId: string; /** Verifier-issued claims about the caller. */ claims: Readonly>; } ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:50`. ## defaultRequireScopes [#defaultrequirescopes] Default scope deriver used when \{@link OpenAgentMcpConfig.requireScopes} is not supplied. ```typescript export declare const defaultRequireScopes: (toolName: string) => ReadonlyArray; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:202`. ## defaultScopeFormat [#defaultscopeformat] Default scope format used when \{@link OpenAgentMcpConfig.scopeFormat} is not supplied. ```typescript export declare const defaultScopeFormat: (toolName: string) => string; ``` Source: `openagent-sdk/integrations/mcp/typescript/src/types.ts:195`. # create-openagent API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-packages-create-openagent Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-packages-create-openagent.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-packages-create-openagent). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. # @openagentid/sdk-testing API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-sdks-testing Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-sdks-testing.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-sdks-testing). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## stubArsenalClient [#stubarsenalclient] In-memory Arsenal client for tests. Echoes a deterministic proxy URL per provider without minting any credential. ```typescript export declare const stubArsenalClient: () => ArsenalClient; ``` Source: `openagent-sdk/sdks/testing/src/index.ts:115`. ## createTestingConfig [#createtestingconfig] An \{@link OpenAgentConfig } with all three in-memory backends wired in. The production SDK requires real protocol clients and fails closed when one is missing; tests opt into the fakes explicitly through this helper. ```typescript export declare const createTestingConfig: (overrides?: Partial) => OpenAgentConfig; ``` Source: `openagent-sdk/sdks/testing/src/index.ts:218`. ## StubIdentityProvider [#stubidentityprovider] In-memory identity provider for tests. Generates deterministic-looking DIDs and public keys. NOT cryptographically sound for production - `signChallenge` returns a tagged base64 blob, not an Ed25519 signature. ```typescript export declare class StubIdentityProvider { constructor(namespace?: string): StubIdentityProvider; createAgentIdentity(input: CreateAgentInput): Promise; resolve(did: Did): Promise; signChallenge(did: Did, challenge: Uint8Array): Promise; publicKey(did: Did): Promise; } ``` Source: `openagent-sdk/sdks/testing/src/index.ts:51`. ## StubVerificationClient [#stubverificationclient] In-memory verification client for tests. Accepts any request carrying `Authorization: OpenAgent stub:<did>` or `Authorization: Bearer stub:<did>` and returns a synthetic \{@link AuthContext }. NOT a real verifier: any well-formed stub token passes. ```typescript export declare class StubVerificationClient { verifyRequest(req: Request, options?: VerifyRequestOptions): Promise; issueChallenge(): Promise<{ challenge: Uint8Array; challengeId: string; }>; verifyChallengeResponse(params: { challengeId: string; agentDid: Did; signatureBase64: string; }): Promise; } ``` Source: `openagent-sdk/sdks/testing/src/index.ts:138`. # @openagentid/sdk API URL: https://docs.openagent.id/reference/typescript/openagent-sdk-sdks-typescript Markdown: https://docs.openagent.id/reference/typescript/openagent-sdk-sdks-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagent-sdk-sdks-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## OpenAgent [#openagent] `OpenAgent` — the public namespace. All calls delegate to a singleton runtime created lazily on first use. Most apps never need more than this. ```typescript export declare const OpenAgent: { readonly configure: (config?: OpenAgentConfig) => OpenAgentRuntime; readonly runtime: () => OpenAgentRuntime; readonly createAgent: (input: CreateAgentInput) => Promise; readonly loadAgent: (did: Did, skills?: readonly SkillId[]) => Promise; readonly authenticate: (req: Request, options?: VerifyRequestOptions) => Promise; }; ``` Source: `openagent-sdk/sdks/typescript/src/agent.ts:221`. ## OpenAgentRuntime [#openagentruntime] Global, lazily-initialized OpenAgent runtime. The default instance is populated by \{@link OpenAgent.configure}. Callers who need multiple runtimes in one process can instantiate `OpenAgentRuntime` directly. ```typescript export declare class OpenAgentRuntime { constructor(config?: OpenAgentConfig): OpenAgentRuntime; config(): Readonly; identity(): IdentityProvider; arsenal(): ArsenalClient; verification(): VerificationClient; createAgent(input: CreateAgentInput): Promise; loadAgent(did: Did, skills?: readonly SkillId[]): Promise; authenticate(req: Request, options?: VerifyRequestOptions): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/agent.ts:121`. ## OpenAgentInstance [#openagentinstance] A live, fully-authenticated agent handle. ```typescript /** A live, fully-authenticated agent handle. */ export interface OpenAgentInstance { /** The agent's DID. */ readonly did: Did; /** The raw OAS identity document. */ readonly document: IdentityDocument; /** Skills policy bound to this agent. */ skillsPolicy(): SkillsPolicy; /** Replace the agent's skills policy (immutable — returns a new instance). */ withSkillsPolicy(policy: SkillsPolicy): OpenAgentInstance; /** Fetch a credential handle for `provider`. */ credentialsFor(provider: string, scopes?: readonly string[]): Promise; /** Underlying identity provider (escape hatch). */ identity(): IdentityProvider; } ``` Source: `openagent-sdk/sdks/typescript/src/agent.ts:99`. ## OpenAgentConfig [#openagentconfig] Global SDK configuration. All fields are optional; sensible defaults are applied by \{@link OpenAgent.configure }. The SDK works with zero configuration for local development and test environments. ```typescript /** * Global SDK configuration. * * All fields are optional; sensible defaults are applied by * {@link OpenAgent.configure}. The SDK works with zero configuration for * local development and test environments. */ export interface OpenAgentConfig { /** Override the default namespace (`l1fe`). */ namespace?: string; /** * Transport endpoints. If omitted, the SDK assumes it is running in-process * with the underlying libraries (useful for tests) or that the wrapped * SDKs will read their own env vars. */ endpoints?: { oasResolver?: string; arsenalBroker?: string; aegisVerifier?: string; }; /** * Inject a custom `fetch`. Defaults to globalThis.fetch (native on Node 20+, * Bun, Deno, browsers, Workers). */ fetch?: typeof fetch; /** Optional structured logger. */ logger?: Logger; /** Override the abort timeout (ms) for HTTP calls. Default: 30000. */ requestTimeoutMs?: number; /** * Pre-constructed subsystem clients (advanced). When provided, the SDK * uses them directly instead of constructing its own. */ clients?: OpenAgentClients; } ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:98`. ## OpenAgentClients [#openagentclients] Forward-declared clients for the three wrapped subsystems. Concrete interfaces live in the per-module files so that this config file does not depend on internal implementation details. ```typescript /** * Forward-declared clients for the three wrapped subsystems. * * Concrete interfaces live in the per-module files so that this config file * does not depend on internal implementation details. */ export interface OpenAgentClients { readonly identity?: unknown; readonly credentials?: unknown; readonly verification?: unknown; } ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:85`. ## ResolvedOpenAgentConfig [#resolvedopenagentconfig] Resolved configuration with all defaults applied. ```typescript /** Resolved configuration with all defaults applied. */ export interface ResolvedOpenAgentConfig { namespace: string; endpoints: { oasResolver?: string; arsenalBroker?: string; aegisVerifier?: string; }; fetch: typeof fetch; logger: Logger; requestTimeoutMs: number; clients: OpenAgentClients; } ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:128`. ## CreateAgentInput [#createagentinput] ```typescript export type CreateAgentInput = z.infer; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:61`. ## Logger [#logger] Logger interface — structured, dependency-free. ```typescript /** Logger interface — structured, dependency-free. */ export interface Logger { debug(msg: string, fields?: Record): void; info(msg: string, fields?: Record): void; warn(msg: string, fields?: Record): void; error(msg: string, fields?: Record): void; } ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:64`. ## resolveConfig [#resolveconfig] Merge user config with defaults. Pure function — does not mutate input. ```typescript export declare const resolveConfig: (config?: OpenAgentConfig) => ResolvedOpenAgentConfig; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:145`. ## silentLogger [#silentlogger] No-op logger used by default. ```typescript export declare const silentLogger: Logger; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:72`. ## createAgentInputSchema [#createagentinputschema] Parameters accepted by \{@link OpenAgent.createAgent }. ```typescript export declare const createAgentInputSchema: z.ZodObject<{ parent: z.ZodString; name: z.ZodString; scopes: z.ZodArray; namespace: z.ZodOptional; skills: z.ZodOptional>; metadata: z.ZodOptional>; }, z.core.$strict>; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:40`. ## didSchema [#didschema] ```typescript export declare const didSchema: z.ZodString; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:20`. ## scopeSchema [#scopeschema] A parsed OAS scope string such as `openai:chat:completions`. ```typescript export declare const scopeSchema: z.ZodString; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:23`. ## providerSchema [#providerschema] Provider identifier (e.g. `openai`, `github`, `stripe`). ```typescript export declare const providerSchema: z.ZodString; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:32`. ## DEFAULT\_NAMESPACE [#default_namespace] ```typescript export declare const DEFAULT_NAMESPACE: "l1fe"; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:141`. ## DEFAULT\_REQUEST\_TIMEOUT\_MS [#default_request_timeout_ms] ```typescript export declare const DEFAULT_REQUEST_TIMEOUT_MS: 30000; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:142`. ## DID\_REGEX [#did_regex] DID regex for `did:oas:<namespace>:<kind>:<identifier>`. Mirrors the OAS v1.1.0 specification. We keep it deliberately permissive here — strict validation belongs in the OAS SDK itself. ```typescript export declare const DID_REGEX: RegExp; ``` Source: `openagent-sdk/sdks/typescript/src/config.ts:17`. ## Did [#did] Fully qualified `did:oas` identifier. ```typescript /** Fully qualified `did:oas` identifier. */ export type Did = string; ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:19`. ## IdentityDocument [#identitydocument] OAS identity document fragment — minimum fields needed by the SDK. ```typescript /** OAS identity document fragment — minimum fields needed by the SDK. */ export interface IdentityDocument { /** Canonical DID. */ did: Did; /** Parent DID (lineage). */ parent: Did; /** Multibase-encoded Ed25519 public key. */ publicKeyMultibase: string; /** Entity kind — `agent`, `tool`, etc. */ kind: string; /** Granted scopes. */ scopes: readonly string[]; /** ISO-8601 creation timestamp. */ createdAt: string; /** Opaque metadata. */ metadata?: Record; } ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:22`. ## IdentityProvider [#identityprovider] The OAS identity facade. Concrete providers come from `@openagentid/oas-sdk` (production) or from \{@link StubIdentityProvider } (test / offline dev). ```typescript /** * The OAS identity facade. Concrete providers come from `@openagentid/oas-sdk` * (production) or from {@link StubIdentityProvider} (test / offline dev). */ export interface IdentityProvider { /** Create a new OAS identity descended from `input.parent`. */ createAgentIdentity(input: CreateAgentInput): Promise; /** Resolve an existing DID to its identity document. */ resolve(did: Did): Promise; /** Sign a challenge (e.g. from AEGIS) with the agent's private key. */ signChallenge(did: Did, challenge: Uint8Array): Promise; /** Return the public key for a DID (multibase). */ publicKey(did: Did): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:57`. ## SignedAssertion [#signedassertion] Signed credential returned by the identity provider. ```typescript /** Signed credential returned by the identity provider. */ export interface SignedAssertion { /** JWS / JWT / OAS assertion envelope (base64url). */ token: string; /** Raw signature bytes (base64). */ signature: string; /** DID of the signer. */ signer: Did; /** Unix timestamp when the assertion was minted. */ issuedAt: number; /** Unix timestamp after which the assertion is invalid. */ expiresAt: number; } ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:40`. ## parseIdentityDocument [#parseidentitydocument] Validate an untrusted identity document. Throws \{@link IdentityError} on failure. ```typescript export declare const parseIdentityDocument: (raw: unknown) => IdentityDocument; ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:85`. ## toIdentityProvider [#toidentityprovider] Narrow any unknown value into an \{@link IdentityProvider}, or throw. This is the integration point where `@openagentid/oas-sdk`'s client is adapted into our interface. When that SDK is finalized, replace the duck-typing below with a direct import. ```typescript export declare const toIdentityProvider: (client: unknown) => IdentityProvider; ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:107`. ## identityDocumentSchema [#identitydocumentschema] Runtime-validated identity document schema. ```typescript export declare const identityDocumentSchema: z.ZodObject<{ did: z.ZodString; parent: z.ZodString; publicKeyMultibase: z.ZodString; kind: z.ZodString; scopes: z.ZodReadonly>; createdAt: z.ZodString; metadata: z.ZodOptional>; }, z.core.$strict>; ``` Source: `openagent-sdk/sdks/typescript/src/identity.ts:72`. ## ArsenalClient [#arsenalclient] Arsenal broker client facade. The real client lives in `@openagentid/arsenal-sdk` and is injected by the application; see `INTEGRATION_NOTES.md`. ```typescript /** * Arsenal broker client facade. The real client lives in `@openagentid/arsenal-sdk` * and is injected by the application; see `INTEGRATION_NOTES.md`. */ export interface ArsenalClient { /** Request a scoped credential for `provider` on behalf of `agentDid`. */ requestCredential(params: { agentDid: Did; provider: string; scopes?: readonly string[]; }): Promise; /** Optionally release / revoke a previously issued credential. */ release?(credentialProxyUrl: string): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/credentials.ts:50`. ## CredentialHandle [#credentialhandle] A live, fetch-ready credential bound to an agent DID + provider. The fetch method is a drop-in replacement for `globalThis.fetch`. The underlying credential is refreshed lazily when the caller invokes `refresh()` — auto-rotation stays out of the per-request hot path. ```typescript /** * A live, fetch-ready credential bound to an agent DID + provider. * * The fetch method is a drop-in replacement for `globalThis.fetch`. The * underlying credential is refreshed lazily when the caller invokes * `refresh()` — auto-rotation stays out of the per-request hot path. */ export interface CredentialHandle { readonly provider: string; readonly agentDid: Did; readonly expiresAt: number; /** * Drop-in replacement for the global `fetch`. The `X-Arsenal-Target` * header is set to the original URL and the request is routed through * the Arsenal credential proxy. * * Streaming responses (SSE, chunked JSON, transfer-encoding: chunked) * are fully supported because the return value is a standard `Response`. */ fetch: typeof fetch; /** Mint a fresh credential and return a new handle. */ refresh(): Promise; /** Release the credential (best-effort; safe to call multiple times). */ release(): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/credentials.ts:69`. ## IssuedCredential [#issuedcredential] A short-lived credential minted by the Arsenal broker. ```typescript /** A short-lived credential minted by the Arsenal broker. */ export interface IssuedCredential { /** Provider identifier this credential targets. */ provider: string; /** * Credential material location. Arsenal's broker returns pre-signed proxy * URLs rather than raw secrets; raw tokens never leave the broker. */ proxyUrl: string; /** Unix timestamp after which the credential is invalid. */ expiresAt: number; /** Optional ceiling on how many requests this credential can issue. */ remainingCalls?: number; /** Arbitrary metadata (tenant, project, region). */ metadata?: Record; } ``` Source: `openagent-sdk/sdks/typescript/src/credentials.ts:30`. ## createCredentialHandle [#createcredentialhandle] Create a \{@link CredentialHandle} backed by an Arsenal client. ```typescript export declare const createCredentialHandle: (params: CreateCredentialHandleParams) => Promise; ``` Source: `openagent-sdk/sdks/typescript/src/credentials.ts:102`. ## AuthContext [#authcontext] A resolved, authenticated caller identity. ```typescript /** A resolved, authenticated caller identity. */ export interface AuthContext { /** The calling agent's DID. */ readonly did: Did; /** The root HMR/MHR this agent chains to. */ readonly root: Did; /** Delegation chain from `root` → `did`. Ordered, length ≥ 1. */ readonly lineage: readonly Did[]; /** OAS + Sigil authority proof required for privileged access. */ readonly lineageAuthority?: LineageAuthorityContext; /** Scopes granted to this caller for this request. */ readonly scopes: readonly string[]; /** Unix timestamp when the underlying assertion expires. */ readonly expiresAt: number; /** Raw bearer the caller presented, for audit logging. */ readonly presentedToken?: string; /** Arbitrary claims passed through from AEGIS. */ readonly claims?: Readonly>; } ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:42`. ## LineageAuthorityContext [#lineageauthoritycontext] Sigil-backed lineage authority attached by an OAS verifier. ```typescript /** Sigil-backed lineage authority attached by an OAS verifier. */ export interface LineageAuthorityContext { /** DID whose privileged authority was verified. */ readonly subject: Did; /** Backend/source identifier, normally `sigil_gal`. */ readonly source: string; /** Finalized root DID for the verified path. */ readonly root: Did; /** Reconstructed finalized path, ordered root to caller. */ readonly path: readonly Did[]; /** Sigil block height at which this authority was finalized. */ readonly finalizedBlock: number; /** Authority path kind, e.g. `human_to_agent`. */ readonly pathKind: string; /** Scopes proven by this lineage path. */ readonly scopes: readonly string[]; /** Generation/depth from root to subject. */ readonly generation: number; /** Accepted root kind for this authority path. */ readonly rootKind?: string; /** Optional org lineage root commitment for org-scoped authority. */ readonly orgRootCommitment?: string; /** Optional expiry timestamp for the authority edge/path. */ readonly expiresAt?: string; } ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:16`. ## PrivilegedAuthorityVerifier [#privilegedauthorityverifier] Runtime hook that turns an authenticated context into OAS/Sigil authority. ```typescript /** Runtime hook that turns an authenticated context into OAS/Sigil authority. */ export interface PrivilegedAuthorityVerifier { verify(ctx: AuthContext, options: VerifyRequestOptions): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:96`. ## VerificationClient [#verificationclient] AEGIS verifier facade. Concrete implementation lives in `@openagentid/aegis-sdk`. The OpenAgent SDK never decodes assertions itself — it delegates to AEGIS for all verification, lineage walking, and policy evaluation. ```typescript /** * AEGIS verifier facade. Concrete implementation lives in `@openagentid/aegis-sdk`. * * The OpenAgent SDK never decodes assertions itself — it delegates to * AEGIS for all verification, lineage walking, and policy evaluation. */ export interface VerificationClient { verifyRequest(req: Request, options?: VerifyRequestOptions): Promise; /** Issue a short-lived challenge for challenge-response auth. */ issueChallenge(): Promise<{ challenge: Uint8Array; challengeId: string; }>; /** Verify a challenge response (typically from a worker/CLI flow). */ verifyChallengeResponse(params: { challengeId: string; agentDid: Did; signatureBase64: string; }): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:81`. ## VerifyRequestOptions [#verifyrequestoptions] Options for \{@link VerificationClient.verifyRequest}. ```typescript /** Options for {@link VerificationClient.verifyRequest}. */ export interface VerifyRequestOptions { /** Require the caller to hold all of these scopes; otherwise throw. */ requiredScopes?: readonly string[]; /** Require the caller's lineage to include (or equal) this DID. */ requiredAncestor?: Did; /** Require a Sigil-backed OAS lineage authority result. */ requirePrivilegedAuthority?: boolean; /** Required authority path kind when privileged authority is required. */ requiredAuthorityPath?: string; /** Extra clock skew tolerance (seconds). Default: 60. */ clockSkewSeconds?: number; } ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:62`. ## PrivilegedAuthorityVerificationClient [#privilegedauthorityverificationclient] Wraps any verifier and requires OAS/Sigil authority for privileged requests. ```typescript export declare class PrivilegedAuthorityVerificationClient { constructor(inner: VerificationClient, authorityVerifier: PrivilegedAuthorityVerifier): PrivilegedAuthorityVerificationClient; verifyRequest(req: Request, options?: VerifyRequestOptions): Promise; issueChallenge(): Promise<{ challenge: Uint8Array; challengeId: string; }>; verifyChallengeResponse(params: { challengeId: string; agentDid: Did; signatureBase64: string; }): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:168`. ## extractBearerToken [#extractbearertoken] Extract the bearer token from a `Request` without trusting it. Checks, in order: `Authorization: OpenAgent ...`, `Authorization: Bearer ...`, `X-OpenAgent-Token`, and an `oa_token` query parameter. Returns `null` if absent. ```typescript export declare const extractBearerToken: (req: Request) => string | null; ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:107`. ## assertScopes [#assertscopes] Assert that `ctx` holds every scope in `required`. ```typescript export declare const assertScopes: (ctx: AuthContext, required: readonly string[]) => void; ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:126`. ## assertAncestor [#assertancestor] Assert that `ctx.lineage` contains `ancestor`. ```typescript export declare const assertAncestor: (ctx: AuthContext, ancestor: Did) => void; ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:138`. ## toVerificationClient [#toverificationclient] Narrow any unknown value into a \{@link VerificationClient}, or throw. Duck-typed for forward compatibility with `@openagentid/aegis-sdk`. ```typescript export declare const toVerificationClient: (client: unknown) => VerificationClient; ``` Source: `openagent-sdk/sdks/typescript/src/verification.ts:151`. ## SkillId [#skillid] A skill identifier such as `frontend-design` or `sql-query`. ```typescript /** A skill identifier such as `frontend-design` or `sql-query`. */ export type SkillId = string; ``` Source: `openagent-sdk/sdks/typescript/src/skills.ts:17`. ## SkillsPolicy [#skillspolicy] The minimum contract the OpenAgent SDK expects from a skills policy. ```typescript /** The minimum contract the OpenAgent SDK expects from a skills policy. */ export interface SkillsPolicy { /** Return true if the agent may invoke `skill`. */ canInvoke(skill: SkillId): boolean; /** Throw a {@link SkillDeniedError} if `skill` is not allowed. */ assertCanInvoke(skill: SkillId): void; /** List all skills the agent is currently permitted to invoke. */ listAllowed(): readonly SkillId[]; /** Produce a new policy with an additional skill. */ grant(skill: SkillId): SkillsPolicy; /** Produce a new policy without `skill`. */ revoke(skill: SkillId): SkillsPolicy; } ``` Source: `openagent-sdk/sdks/typescript/src/skills.ts:20`. ## InMemorySkillsPolicy [#inmemoryskillspolicy] In-memory, immutable skills policy. Every mutation returns a new instance. Supports two match modes: * Exact: `frontend-design` matches only `frontend-design` * Wildcard suffix: `frontend-*` matches `frontend-design`, `frontend-test`, ... ```typescript export declare class InMemorySkillsPolicy { constructor(skills?: readonly SkillId[]): InMemorySkillsPolicy; canInvoke(skill: SkillId): boolean; assertCanInvoke(skill: SkillId): void; listAllowed(): readonly SkillId[]; grant(skill: SkillId): SkillsPolicy; revoke(skill: SkillId): SkillsPolicy; } ``` Source: `openagent-sdk/sdks/typescript/src/skills.ts:44`. ## denyAllSkills [#denyallskills] Empty policy that denies everything. ```typescript export declare const denyAllSkills: SkillsPolicy; ``` Source: `openagent-sdk/sdks/typescript/src/skills.ts:87`. ## allowAllSkills [#allowallskills] Policy that allows any skill (dangerous — use only in tests). ```typescript export declare const allowAllSkills: SkillsPolicy; ``` Source: `openagent-sdk/sdks/typescript/src/skills.ts:90`. ## act [#act] The ACT namespace. ```typescript export declare const act: { readonly verify: (token: Uint8Array) => ActVerifierBuilder; readonly setCryptoBinding: (binding: ActVerifyBinding) => void; }; ``` Source: `openagent-sdk/sdks/typescript/src/act.ts:215`. ## ActVerifierBuilder [#actverifierbuilder] Fluent ACT verifier, built by \{@link act.verify}. ```typescript export declare class ActVerifierBuilder { constructor(token: Uint8Array): ActVerifierBuilder; issuer(iss: string): this; forAudience(audience: string): this; requireScope(scope: string): this; requireScopes(scopes: string[]): this; trustedKeys(keys: Uint8Array[]): this; withLeeway(seconds: number): this; atTime(unixSeconds: number): this; run(): Promise; } ``` Source: `openagent-sdk/sdks/typescript/src/act.ts:108`. ## setActCryptoBinding [#setactcryptobinding] Inject the crypto-wasm binding. Called by consumers at startup (and by tests with a mock). The binding is the `@openagentid/crypto-wasm` module's nodejs or bundler build, already instantiated. ```typescript export declare const setActCryptoBinding: (binding: ActVerifyBinding) => void; ``` Source: `openagent-sdk/sdks/typescript/src/act.ts:92`. ## ActClaims [#actclaims] The claims of a verified ACT, as returned by the canonical verifier. ```typescript /** The claims of a verified ACT, as returned by the canonical verifier. */ export interface ActClaims { /** Token identifier. */ jti: string; /** Subject: the OAS DID of the agent the token was issued to. */ sub: string; /** Issuer: the broker instance that minted the token. */ iss: string; /** Audiences this token is valid for. */ aud: string[]; /** Issued-at, seconds since the Unix epoch. */ iat: number; /** Not-before, seconds since the Unix epoch. */ nbf: number; /** Expiry, seconds since the Unix epoch. */ exp: number; /** Tenant this token is scoped to. */ tenant_id: string; /** Granted scopes (`service:resource:action`). */ scope: string[]; /** Proof-of-possession binding, when present. */ cnf?: { key_fingerprint: string; alg: string; }; /** Onward delegation constraints, when present. */ delegation?: { allow_delegation: boolean; max_depth: number; }; /** Issuer-defined extension claims (opaque to the format). */ ext?: Record; } ``` Source: `openagent-sdk/sdks/typescript/src/act.ts:29`. ## ActVerifyOptions [#actverifyoptions] Options accepted by the fluent verifier. ```typescript /** Options accepted by the fluent verifier. */ export interface ActVerifyOptions { /** The trusted issuer string (required — see {@link ActVerifierBuilder.issuer}). */ issuer?: string; /** The audience this verifier answers for (required). */ audience?: string; /** Scopes the token must grant. Wildcards in the grant expand; literal in the request. */ scopes?: string[]; /** Raw 32-byte Ed25519 trusted public keys (required). */ trustedKeys?: Uint8Array[]; /** Symmetric clock-skew allowance in seconds. Default: 0. */ leewaySeconds?: number; /** Pinned verification time (tests and decision replay). Default: system clock. */ nowUnixSeconds?: number; } ``` Source: `openagent-sdk/sdks/typescript/src/act.ts:57`. ## withAct [#withact] Fetch-standard middleware factory. Returns a handler that takes `(request, claims)`. A request whose token is missing, malformed, forged, expired, wrong-audience, or under-scoped gets a 401 with the reason — the handler never runs, and unauthenticated claims never reach the application. ```typescript export declare const withAct: (config: RequireActConfig, handler: (req: Request, claims: ActClaims) => Promise | Response) => (req: Request) => Promise; ``` Source: `openagent-sdk/sdks/typescript/src/middleware.ts:88`. ## requireActExpress [#requireactexpress] Express-compatible middleware factory. On success, the verified claims land on `req.actClaims`; on failure the request is rejected with a 401 and never reaches the route. ```typescript export declare const requireActExpress: (config: RequireActConfig) => (req: { headers: Record; actClaims?: ActClaims; }, res: { status: (code: number) => { json: (body: unknown) => unknown; }; }, next: () => void) => Promise; ``` Source: `openagent-sdk/sdks/typescript/src/middleware.ts:126`. ## RequireActConfig [#requireactconfig] Policy for the middleware: the verifier bindings plus optional scopes. ```typescript /** Policy for the middleware: the verifier bindings plus optional scopes. */ export interface RequireActConfig { /** The trusted issuer string. */ issuer: string; /** The audience this service answers for. */ audience: string; /** Scopes every request must carry. Default: none. */ scopes?: string[]; /** Trusted Ed25519 public keys (raw 32 bytes each). */ trustedKeys: Uint8Array[]; /** Clock-skew allowance in seconds. Default: 0. */ leewaySeconds?: number; /** * Extract the ACT envelope bytes from the request. Default: base64url of * the `Authorization: Bearer ` header value. */ extractToken?: (req: Request) => Uint8Array | undefined; /** * Render the 401 response. Default: JSON `{ error }` with a * `WWW-Authenticate: OpenAgent` hint. */ onUnauthorized?: (req: Request, reason: string) => Response; } ``` Source: `openagent-sdk/sdks/typescript/src/middleware.ts:20`. ## keys [#keys] The key-custody namespace. ```typescript export declare const keys: { readonly generate: () => Promise; readonly fromSeed: (seed: Uint8Array) => AgentKeys; readonly fromSeedHex: (hex: string) => AgentKeys; readonly fromEnv: (envVar: string) => AgentKeys; readonly saveSeed: (keys: AgentKeys, path: string) => Promise; readonly fromSeedFile: (path: string) => Promise; readonly seedToHex: (bytes: Uint8Array) => string; readonly setCryptoBinding: (binding: KeyCryptoBinding) => void; }; ``` Source: `openagent-sdk/sdks/typescript/src/keys.ts:123`. ## setKeyCryptoBinding [#setkeycryptobinding] Inject the crypto-wasm binding (same one as \{@link setActCryptoBinding }). ```typescript export declare const setKeyCryptoBinding: (binding: KeyCryptoBinding) => void; ``` Source: `openagent-sdk/sdks/typescript/src/keys.ts:36`. ## AgentKeys [#agentkeys] An agent's key material, derived from one seed. ```typescript /** An agent's key material, derived from one seed. */ export interface AgentKeys { /** The 32-byte seed — the only thing that must be persisted. */ readonly seed: Uint8Array; /** Ed25519 signing (private) key. */ readonly signingKey: Uint8Array; /** Ed25519 verifying (public) key — the agent's identity fingerprint. */ readonly verifyingKey: Uint8Array; /** X25519 encryption secret key (derived from the seed). */ readonly encryptionSecretKey: Uint8Array; /** X25519 encryption public key (derived). */ readonly encryptionPublicKey: Uint8Array; } ``` Source: `openagent-sdk/sdks/typescript/src/keys.ts:55`. ## KeyCryptoBinding [#keycryptobinding] The crypto-wasm binding shape key custody consumes. ```typescript /** The crypto-wasm binding shape key custody consumes. */ export interface KeyCryptoBinding { ed25519_generate_keypair(): { signing_key: Uint8Array; verifying_key: Uint8Array; }; ed25519_public_from_private(signingKey: Uint8Array): Uint8Array; x25519_generate_keypair(): { secret_key: Uint8Array; public_key: Uint8Array; }; x25519_public_from_secret?(secretKey: Uint8Array): Uint8Array; blake3_derive_key(context: string, keyMaterial: Uint8Array): Uint8Array; } ``` Source: `openagent-sdk/sdks/typescript/src/keys.ts:25`. ## OpenAgentError [#openagenterror] Root of the OpenAgent SDK error hierarchy. ```ts try { await OpenAgent.createAgent({ ... }); } catch (err) { if (err instanceof OpenAgentError) { console.error(err.code, err.message); } } ``` ```typescript export declare class OpenAgentError { code: ErrorCodeValue; cause: unknown; context: Record; constructor(message: string, details: ErrorDetails): OpenAgentError; toJSON(): Record; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:74`. ## ConfigError [#configerror] Configuration or usage violation (invalid input, missing dependency). ```typescript export declare class ConfigError { constructor(message: string, context?: Record): ConfigError; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:101`. ## InputValidationError [#inputvalidationerror] Runtime input validation failure (Zod, boundary checks). ```typescript export declare class InputValidationError { constructor(message: string, cause?: unknown, context?: Record): InputValidationError; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:110`. ## IdentityError [#identityerror] OAS identity subsystem failure. ```typescript export declare class IdentityError { constructor(message: string, details: ErrorDetails): IdentityError; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:119`. ## CredentialError [#credentialerror] Arsenal credentials subsystem failure. ```typescript export declare class CredentialError { constructor(message: string, details: ErrorDetails): CredentialError; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:128`. ## VerificationError [#verificationerror] AEGIS verification subsystem failure. ```typescript export declare class VerificationError { constructor(message: string, details: ErrorDetails): VerificationError; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:137`. ## SkillDeniedError [#skilldeniederror] Skills policy denial. ```typescript export declare class SkillDeniedError { skill: string; constructor(skill: string, reason?: string, context?: Record): SkillDeniedError; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:146`. ## ErrorCode [#errorcode] Stable machine-readable error codes. These are part of the SDK's public contract and MUST stay in sync with the Rust reference implementation. ```typescript export declare const ErrorCode: { readonly INVALID_CONFIG: "openagent/invalid-config"; readonly INVALID_INPUT: "openagent/invalid-input"; readonly NOT_INITIALIZED: "openagent/not-initialized"; readonly IDENTITY_CREATE_FAILED: "openagent/identity/create-failed"; readonly IDENTITY_RESOLVE_FAILED: "openagent/identity/resolve-failed"; readonly IDENTITY_SIGNATURE_INVALID: "openagent/identity/signature-invalid"; readonly IDENTITY_LINEAGE_INVALID: "openagent/identity/lineage-invalid"; readonly CREDENTIAL_FETCH_FAILED: "openagent/credentials/fetch-failed"; readonly CREDENTIAL_SCOPE_DENIED: "openagent/credentials/scope-denied"; readonly CREDENTIAL_PROVIDER_UNKNOWN: "openagent/credentials/provider-unknown"; readonly CREDENTIAL_EXPIRED: "openagent/credentials/expired"; readonly VERIFICATION_FAILED: "openagent/verification/failed"; readonly AUTH_REQUIRED: "openagent/verification/auth-required"; readonly AUTH_CHALLENGE_INVALID: "openagent/verification/challenge-invalid"; readonly SKILL_DENIED: "openagent/skills/denied"; readonly SKILL_UNKNOWN: "openagent/skills/unknown"; readonly NETWORK_ERROR: "openagent/network-error"; readonly SERIALIZATION_ERROR: "openagent/serialization-error"; readonly UNKNOWN: "openagent/unknown"; }; ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:16`. ## ErrorCodeValue [#errorcodevalue] ```typescript export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]; ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:49`. ## ErrorDetails [#errordetails] Structured error metadata attached to every \{@link OpenAgentError}. ```typescript /** Structured error metadata attached to every {@link OpenAgentError}. */ export interface ErrorDetails { /** Stable machine-readable code. */ code: ErrorCodeValue; /** Optional cause (native Error, SDK error, or anything). */ cause?: unknown; /** Arbitrary structured context for logging. */ context?: Record; } ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:52`. ## wrapError [#wraperror] Wraps any non-OpenAgentError into the SDK hierarchy without losing the cause. ```typescript export declare const wrapError: (err: unknown, fallbackMessage: string) => OpenAgentError; ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:161`. ## getErrorMessage [#geterrormessage] Narrow an unknown caught value to a human-readable message. ```typescript export declare const getErrorMessage: (err: unknown) => string; ``` Source: `openagent-sdk/sdks/typescript/src/errors.ts:168`. ## VERSION [#version] SDK version — kept in sync with `package.json`. ```typescript export declare const VERSION: "0.1.1"; ``` Source: `openagent-sdk/sdks/typescript/src/index.ts:127`. # @openagentid/client API URL: https://docs.openagent.id/reference/typescript/openagents-openagent-id-clients-typescript Markdown: https://docs.openagent.id/reference/typescript/openagents-openagent-id-clients-typescript.md Exported TypeScript types, signatures and source documentation. [Package manifest, subpaths, and integration guide](/reference/packages/openagents-openagent-id-clients-typescript). This reference resolves exported symbols from the package entry point with the TypeScript parser/type checker. It includes declarations and inferred types, not implementation bodies. External dependencies unavailable to the extraction environment can remain unresolved; this is source documentation, not proof that all packages typecheck or are published. ## OpenAgentClient [#openagentclient] Client for the OpenAgent Core challenge-response protocol. The client owns an Ed25519 \{@link KeyPair} and a per-origin session cache. On each \{@link OpenAgentClient.fetch} call: 1. If a non-expired cached session token exists for the request origin, it is sent as `Authorization: Bearer <token>`. If that returns 401, the cache is cleared and the client falls through to a challenge. 2. Otherwise the client sends the request unauthenticated. If the server replies 401 with a `WWW-Authenticate: OpenAgent` header, the client decodes the challenge, freshness-checks the timestamp and origin, JCS-canonicalizes it (RFC 8785), signs the canonical bytes with Ed25519, and re-sends the request with the proof in the `Authorization` header. 3. The new session token from `X-OpenAgent-Session` is cached for subsequent calls. ```typescript export declare class OpenAgentClient { constructor(keyPair: KeyPair, options?: OpenAgentClientOptions): OpenAgentClient; getKeyPair(): KeyPair; getCachedSession(origin: string): string | undefined; clearSession(): void; fetch(url: string, options?: FetchOptions): Promise; logout(): void; } ``` Source: `openagents/openagent.id/clients/typescript/src/client.ts:72`. ## OpenAgentClientOptions [#openagentclientoptions] Optional configuration for the \{@link OpenAgentClient}. ```typescript /** * Optional configuration for the {@link OpenAgentClient}. */ export interface OpenAgentClientOptions { /** * Custom `fetch` implementation. Defaults to `globalThis.fetch`. * Useful for tests, polyfills, or wiring through a proxy. */ fetch?: typeof fetch; /** * Optional clock used for session expiry checks. Defaults to * `() => new Date()`. Allows tests to inject a fake clock. */ now?: () => Date; /** * Maximum acceptable age of a server-issued challenge before we refuse * to sign it. Defaults to 60 seconds (matches the server's default * 30-second nonce TTL with margin). */ maxChallengeAgeMs?: number; } ``` Source: `openagents/openagent.id/clients/typescript/src/client.ts:33`. ## KeyPair [#keypair] An Ed25519 signing key. Holds 32 raw secret bytes plus the lazily-derived public key. Instances are immutable. Callers SHOULD NOT log or serialize the secret key — use \{@link KeyPair.publicKeyBytes} for the safe public half. ```typescript export declare class KeyPair { fromSecretBytes(secretKey: Uint8Array): KeyPair; fromSecretBase64Url(secretBase64Url: string): KeyPair; generate(): KeyPair; publicKeyBytes(): Uint8Array; publicKeyBase64Url(): string; toDidKey(): string; sign(message: Uint8Array): Uint8Array; exportSecretBytes(): Uint8Array; exportSecretBase64Url(): string; } ``` Source: `openagents/openagent.id/clients/typescript/src/keypair.ts:31`. ## encodeDidKey [#encodedidkey] Encodes an Ed25519 public key as a `did:key` URI per the W3C `did:key` method specification. Multicodec prefix for Ed25519 public keys: 0xed 0x01 (varint of 0xed). Multibase prefix: `z` for base58btc. ```typescript export declare const encodeDidKey: (publicKey: Uint8Array) => string; ``` Source: `openagents/openagent.id/clients/typescript/src/keypair.ts:161`. ## CHALLENGE\_TYPE [#challenge_type] ```typescript export declare const CHALLENGE_TYPE: "openagent-challenge-v1"; ``` Source: `openagents/openagent.id/clients/typescript/src/challenge.ts:10`. ## parseWwwAuthenticate [#parsewwwauthenticate] Parses an OpenAgent challenge from a `WWW-Authenticate` header value. ```typescript export declare const parseWwwAuthenticate: (headerValue: string) => Challenge; ``` Source: `openagents/openagent.id/clients/typescript/src/challenge.ts:42`. ## validateChallenge [#validatechallenge] Validates a parsed JSON object against the \{@link Challenge} schema and returns it as a typed value. ```typescript export declare const validateChallenge: (value: unknown) => Challenge; ``` Source: `openagents/openagent.id/clients/typescript/src/challenge.ts:92`. ## canonicalizeChallenge [#canonicalizechallenge] JCS-canonicalizes a challenge per RFC 8785 and returns the UTF-8 bytes. The result MUST byte-equal what the openagent-server produces from `serde_jcs::to_string` over the same logical object. ```typescript export declare const canonicalizeChallenge: (challenge: Challenge) => Uint8Array; ``` Source: `openagents/openagent.id/clients/typescript/src/challenge.ts:148`. ## isChallengeFresh [#ischallengefresh] Optional sanity check on the challenge timestamp. Returns `true` if the timestamp parses as a date and is within `maxAgeMs` of `now`. Implementations SHOULD reject stale challenges before signing them (per spec §3.3 step 3). ```typescript export declare const isChallengeFresh: (challenge: Challenge, options?: { now?: Date; maxAgeMs?: number; }) => boolean; ``` Source: `openagents/openagent.id/clients/typescript/src/challenge.ts:177`. ## Challenge [#challenge] A challenge issued by an OpenAgent server, decoded from the `WWW-Authenticate: OpenAgent challenge="<base64url>"` header. Per OPENAGENT-CORE-SPEC.md §4: * `type` MUST equal `"openagent-challenge-v1"` * `nonce` MUST be a 64-character hex string (32 random bytes) * `timestamp` MUST be RFC 3339 / ISO 8601 UTC * `origin` MUST be the server origin in `scheme://host[:port]` form * `realm` is optional ```typescript /** * A challenge issued by an OpenAgent server, decoded from the * `WWW-Authenticate: OpenAgent challenge=""` header. * * Per OPENAGENT-CORE-SPEC.md §4: * - `type` MUST equal `"openagent-challenge-v1"` * - `nonce` MUST be a 64-character hex string (32 random bytes) * - `timestamp` MUST be RFC 3339 / ISO 8601 UTC * - `origin` MUST be the server origin in `scheme://host[:port]` form * - `realm` is optional */ export interface Challenge { type: string; nonce: string; timestamp: string; origin: string; realm?: string; } ``` Source: `openagents/openagent.id/clients/typescript/src/challenge.ts:23`. ## OpenAgentClientError [#openagentclienterror] Base class for all OpenAgent client errors. All thrown errors from `OpenAgentClient` are instances of this class — callers may rely on `instanceof OpenAgentClientError` for control flow. ```typescript export declare class OpenAgentClientError { code: string; constructor(code: string, message: string, options?: ErrorOptions): OpenAgentClientError; } ``` Source: `openagents/openagent.id/clients/typescript/src/errors.ts:11`. ## InvalidUrlError [#invalidurlerror] The URL passed to \{@link OpenAgentClient.fetch } could not be parsed. ```typescript export declare class InvalidUrlError { constructor(url: string): InvalidUrlError; } ``` Source: `openagents/openagent.id/clients/typescript/src/errors.ts:24`. ## NoChallengeHeaderError [#nochallengeheadererror] The server returned 401 but no `WWW-Authenticate` header was present. This indicates a server bug or a non-OpenAgent server returning 401. ```typescript export declare class NoChallengeHeaderError { constructor(): NoChallengeHeaderError; } ``` Source: `openagents/openagent.id/clients/typescript/src/errors.ts:36`. ## MalformedChallengeError [#malformedchallengeerror] The `WWW-Authenticate` header was present but could not be parsed as an OpenAgent challenge. ```typescript export declare class MalformedChallengeError { constructor(reason: string): MalformedChallengeError; } ``` Source: `openagents/openagent.id/clients/typescript/src/errors.ts:50`. ## NetworkError [#networkerror] Network error during the underlying `fetch` call. The original error is exposed as `cause` for inspection. ```typescript export declare class NetworkError { constructor(cause: unknown): NetworkError; } ``` Source: `openagents/openagent.id/clients/typescript/src/errors.ts:61`. ## InvalidKeyError [#invalidkeyerror] The signing key is invalid (must be 32 raw bytes for Ed25519). ```typescript export declare class InvalidKeyError { constructor(reason: string): InvalidKeyError; } ``` Source: `openagents/openagent.id/clients/typescript/src/errors.ts:73`. ## bodyAsString [#bodyasstring] Helper: parses the response body as a UTF-8 string. ```typescript export declare const bodyAsString: (response: AuthenticatedResponse) => string; ``` Source: `openagents/openagent.id/clients/typescript/src/types.ts:71`. ## bodyAsJson [#bodyasjson] Helper: parses the response body as JSON. Throws on parse failure. ```typescript export declare const bodyAsJson: (response: AuthenticatedResponse) => T; ``` Source: `openagents/openagent.id/clients/typescript/src/types.ts:78`. ## AuthenticatedResponse [#authenticatedresponse] Result of an authenticated request through \{@link OpenAgentClient.fetch }. Mirrors `AuthenticatedResponse` in the Rust client. Includes both the raw HTTP response (`status`, `headers`, `bodyBytes`) and the OpenAgent principal headers (`did`, `trustTier`, `sessionToken`) extracted from the server's response. ```typescript // Public types returned by the OpenAgent client API. /** * Result of an authenticated request through {@link OpenAgentClient.fetch}. * * Mirrors `AuthenticatedResponse` in the Rust client. Includes both the * raw HTTP response (`status`, `headers`, `bodyBytes`) and the OpenAgent * principal headers (`did`, `trustTier`, `sessionToken`) extracted from * the server's response. */ export interface AuthenticatedResponse { /** HTTP status code. */ status: number; /** All response headers. */ headers: Headers; /** Raw response body bytes. */ bodyBytes: Uint8Array; /** * The agent's resolved DID, if the server returned `X-OpenAgent-DID`. * Always present after a successful challenge-response round. */ did?: string; /** * Numeric trust tier (0-4), if the server returned * `X-OpenAgent-Trust-Tier` and it parses as a number. */ trustTier?: number; /** * Session JWT issued by the server in the `X-OpenAgent-Session` header, * if present. The client caches this internally and reuses it on * subsequent requests until 401. */ sessionToken?: string; /** * Session expiration timestamp from `X-OpenAgent-Session-Expires`, if * present. ISO 8601. */ sessionExpires?: string; /** * Legacy lineage response metadata retained only for migration and audit. * It cannot satisfy an authorization predicate. */ legacyLineageEvidence?: InformationalLineageEvidence; } ``` Source: `openagents/openagent.id/clients/typescript/src/types.ts:11`. ## FetchOptions [#fetchoptions] Options for \{@link OpenAgentClient.fetch }. ```typescript /** * Options for {@link OpenAgentClient.fetch}. */ export interface FetchOptions { /** HTTP method. Defaults to `"GET"`, or `"POST"` if a body is given. */ method?: string; /** * Request body. Strings are sent as `text/plain`, objects are * JSON-encoded with `application/json`, Uint8Array goes through as-is. */ body?: string | Uint8Array | Record; /** Extra headers to include on the request. */ headers?: Record; /** * If true, do NOT consume the cached session token even if one exists * for this origin. Forces a fresh challenge-response round. * * Use sparingly — only for debugging or after a logout. */ forceChallenge?: boolean; /** * Optional `AbortSignal` for cancellation, propagated to the underlying * fetch calls. */ signal?: AbortSignal; } ``` Source: `openagents/openagent.id/clients/typescript/src/types.ts:86`. ## InformationalLineageEvidence [#informationallineageevidence] Explicitly informational wrapper for a legacy response header. ```typescript /** Explicitly informational wrapper for a legacy response header. */ export interface InformationalLineageEvidence { readonly status: "informational"; readonly profile: "agent-lineage-proof-2025"; readonly evidence: LegacyLineageEvidence; } ``` Source: `openagents/openagent.id/clients/typescript/src/types.ts:62`. ## LegacyLineageEvidence [#legacylineageevidence] Legacy wire fields. None of these fields confer authority. ```typescript /** Legacy wire fields. None of these fields confer authority. */ export interface LegacyLineageEvidence { subject: string; root: string; path_kind: string; source: string; path: string[]; finalized_block: number; scopes: string[]; generation: number; root_kind?: string; org_root_commitment?: string; expires_at?: string; } ``` Source: `openagents/openagent.id/clients/typescript/src/types.ts:47`. ## base64url [#base64url] ```typescript export declare const base64url: typeof import("openagents/openagent.id/clients/typescript/src/base64url"); ``` Source: `openagents/openagent.id/clients/typescript/src/base64url.ts:6`. ## hex [#hex] ```typescript export declare const hex: typeof import("openagents/openagent.id/clients/typescript/src/hex"); ``` Source: `openagents/openagent.id/clients/typescript/src/hex.ts:3`. # Rust module reference URL: https://docs.openagent.id/reference/rust Markdown: https://docs.openagent.id/reference/rust.md Signatures and source documentation for the OpenAgentID Rust package family. This source reference follows declared modules; it is not a compiler-resolved root-import list. Feature attributes and source paths are retained. * [agent-capability-token](/reference/rust/agent-capability-token) — 5 modules * [aegis-auth](/reference/rust/aegis-auth) — 5 modules * [aegis-delegate](/reference/rust/aegis-delegate) — 8 modules * [aegis-keys](/reference/rust/aegis-keys) — 7 modules * [aegis-store-pg](/reference/rust/aegis-store-pg) — 7 modules * [aegis-verify](/reference/rust/aegis-verify) — 4 modules * [aegis-wallet](/reference/rust/aegis-wallet) — 6 modules * [openagent-aegis-core](/reference/rust/openagent-aegis-core) — 4 modules * [openagent-aegis-policy](/reference/rust/openagent-aegis-policy) — 6 modules * [openagent-aegis-sdk](/reference/rust/openagent-aegis-sdk) — 3 modules * [arsenal-broker](/reference/rust/arsenal-broker) — 14 modules * [arsenal-core](/reference/rust/arsenal-core) — 16 modules * [arsenal-crypto](/reference/rust/arsenal-crypto) — 9 modules * [arsenal-policy](/reference/rust/arsenal-policy) — 1 modules * [arsenal-sdk](/reference/rust/arsenal-sdk) — 8 modules * [arsenal-store](/reference/rust/arsenal-store) — 9 modules * [oas-anchor-eas](/reference/rust/oas-anchor-eas) — 4 modules * [oas-attestation](/reference/rust/oas-attestation) — 14 modules * [oas-crypto](/reference/rust/oas-crypto) — 9 modules * [oas-did](/reference/rust/oas-did) — 6 modules * [oas-document](/reference/rust/oas-document) — 21 modules * [oas-lineage](/reference/rust/oas-lineage) — 6 modules * [oas-resolve](/reference/rust/oas-resolve) — 8 modules * [oas-sdk](/reference/rust/oas-sdk) — 7 modules * [oas-wasm](/reference/rust/oas-wasm) — 5 modules * [openagent-http](/reference/rust/openagent-http) — 8 modules * [openagent-weave](/reference/rust/openagent-weave) — 8 modules * [openagent-ws](/reference/rust/openagent-ws) — 7 modules * [openagent-oidc](/reference/rust/openagent-oidc) — 9 modules * [openagent-scim](/reference/rust/openagent-scim) — 3 modules * [conformance-runner](/reference/rust/conformance-runner) — 3 modules * [openagent-auth-protocol](/reference/rust/openagent-auth-protocol) — 7 modules * [openagent-crypto-wasm](/reference/rust/openagent-crypto-wasm) — 14 modules * [openagent-skills-policy](/reference/rust/openagent-skills-policy) — 8 modules * [openagent-claude-agent](/reference/rust/openagent-claude-agent) — 8 modules * [openagent-mcp](/reference/rust/openagent-mcp) — 7 modules * [openagent-sdk](/reference/rust/openagent-sdk) — 10 modules * [openagent-capability](/reference/rust/openagent-capability) — 1 modules * [openagent-client](/reference/rust/openagent-client) — 2 modules * [openagent-server](/reference/rust/openagent-server) — 10 modules * [openagent-standalone](/reference/rust/openagent-standalone) — 0 modules [Download the structured module reference](/reference/rust-source.json). # Credential handles URL: https://docs.openagent.id/sdk/client/capabilities Markdown: https://docs.openagent.id/sdk/client/capabilities.md Request, use, refresh, and release broker-backed credentials explicitly. TypeScript `agent.credentialsFor(provider)` uses the configured `ArsenalClient` to request an `IssuedCredential` and returns a `CredentialHandle`. The provider, agent identity, scopes, broker policy, and tenant trust must already be configured. ## Handle lifecycle [#handle-lifecycle] | API | Behavior | | ----------------------------------- | ------------------------------------------------------------------------------- | | `provider`, `agentDid`, `expiresAt` | Read-only metadata for the issued handle | | `fetch(input, init)` | Route the intended target through the issued proxy URL using `X-Arsenal-Target` | | `refresh()` | Request a fresh credential and return a **new handle** | | `release()` | Mark the handle released and invoke the optional broker release callback | Refresh is explicit in this implementation. The per-request path does not silently mint a new token on expiry. Keep and use the handle returned by `refresh()`. A released handle rejects use; errors from minting, proxying, or releasing must be handled. ## Broker boundary [#broker-boundary] `ArsenalClient.requestCredential` accepts `agentDid`, `provider`, and optional scopes. It returns the proxy URL, expiration and optional remaining-call metadata. A TypeScript adapter must map that interface to the actual broker contract; method-shape compatibility alone does not establish secure deployment. Keep issuer credentials in the configured custody/broker system. Do not accept an arbitrary proxy URL or target from an untrusted agent without the intended broker policy and destination validation. Source: `openagent-sdk/sdks/typescript/src/credentials.ts`. See [Arsenal broker routes](/arsenal/broker) and [ACTs](/arsenal/act-tokens). # Client handshake URL: https://docs.openagent.id/sdk/client/handshake Markdown: https://docs.openagent.id/sdk/client/handshake.md The actual TypeScript HTTP client state sequence and its required signing callbacks. `HttpAuthClient` from `@openagentid/http` performs discovery, challenge retrieval, proof submission, and session construction. Its constructor takes `config`, `sign`, `publicKey`, and an optional transport. | Input | Required behavior | | ------------------ | ------------------------------------------------------------------------- | | `config.did` | Agent identifier used by the client | | `config.keyType` | Signing algorithm label; defaults to `ed25519` | | `config.timeoutMs` | Request timeout; transport default is 30,000 milliseconds | | `sign(payload)` | Return a base64url signature without padding for the exact supplied bytes | | `publicKey()` | Return the raw public key encoded as base64url without padding | ## Sequence [#sequence] 1. Fetch discovery from the requested server. 2. Resolve auth/prove endpoints. If discovery fails, the current client falls back to the well-known paths. 3. Fetch and validate an `openagent-challenge-v1` challenge. 4. Call `canonicalChallengeBytes` and sign those exact bytes. 5. Submit the signature, key, key type, and echoed nonce. 6. Construct `AuthenticatedSession` using the returned token and expiration. Use the intended server origin over TLS and review discovered endpoint resolution for your trust boundary. Do not sign an arbitrary payload supplied by a tool or unrelated origin. Challenge signing is not a generic remote-signing service. The `sign` and `publicKey` callbacks must refer to the same keypair. Fake callbacks belong only in explicit tests. Handle transport and verification failure by ending authentication; do not fabricate a session. This flow targets the [TypeScript HTTP adapter](/api-reference/http-adapter). The standalone Rust server uses a different protected-handler/session contract. Source: `openagent-sdk/adapters/http/typescript/src/client.ts`, `transport.ts`, and `discovery.ts`. # Client integration URL: https://docs.openagent.id/sdk/client/overview Markdown: https://docs.openagent.id/sdk/client/overview.md Choose the SDK facade, explicit HTTP handshake client, or legacy client package. OpenAgentID has several client layers. Choose by the server contract you integrate with. | Client | Responsibility | | ----------------------------------------------- | ------------------------------------------------------------------------------------- | | Unified language SDK | ACT verification and language-specific identity/credential conveniences | | TypeScript `@openagentid/http` | Discovery, canonical challenge signing, proof submission, and opaque-session requests | | Rust HTTP/WebSocket adapters | Protocol transport implementations with their own source types | | Legacy `openagent-client` and TypeScript client | Earlier client/server compatibility surface, documented separately in the catalog | A client does not create a trusted parent lineage, provision a broker, or configure server policy by itself. For TypeScript identity operations, inject a real `IdentityProvider`. For credentials, inject an `ArsenalClient`. For privileged verification, configure the authority source/verifier required by that deployment. Start with the [HTTP handshake](/sdk/client/handshake), [credential lifecycle](/sdk/client/capabilities), and [session formats](/sdk/client/sessions). All packages and versions are mapped in [the catalog](/reference/packages). # Sessions URL: https://docs.openagent.id/sdk/client/sessions Markdown: https://docs.openagent.id/sdk/client/sessions.md State, expiry, token schemes, and storage differ by authentication adapter. A session records successful authentication for a bounded period. Use the session contract belonging to the actual server implementation; sessions are not a universal token format across OpenAgentID libraries. ## Standalone Rust server [#standalone-rust-server] The legacy standalone server issues signed JWT sessions and its `/v1/whoami` handler accepts `Authorization: Bearer `. Session validation uses the server's configured signing secret and time policy. The default session TTL is 900 seconds in that binary. ## TypeScript HTTP adapter [#typescript-http-adapter] The HTTP adapter creates opaque random session strings and resolves them through a `SessionStore`. These are not JWTs and are not derived from an ECDH shared secret. `Authorization: OpenAgent ` carries this adapter's session. Its default TTL is 300 seconds. `InMemorySessionStore` is process-local. A serverless or replicated service needs consistent shared state, expiration, and replay behavior. Restarting a process loses its in-memory sessions. ## Session handling [#session-handling] 1. Use the deployment's discovery/handshake contract. 2. Keep the returned session private and transmit it over TLS. 3. Preserve the expected header scheme and issuer/server binding. 4. Handle expiry by performing the implementation's supported reauthentication flow. 5. Apply action-level scopes, tenant checks, and authority policy after authentication. Do not exchange a session for an ACT by renaming its header. ACTs are signed capability envelopes and carry a different verification/authorization contract. Source: `openagents/openagent.id/crates/openagent-server/src/session.rs`, `openagent-sdk/adapters/http/typescript/src/server.ts`, `session.ts`, and `headers.ts`. # Middleware URL: https://docs.openagent.id/sdk/server/middleware Markdown: https://docs.openagent.id/sdk/server/middleware.md ACT route wrappers and handshake middleware have different inputs and outputs. ## ACT verification [#act-verification] TypeScript `withAct(config, handler)` wraps a fetch-standard handler. `requireActExpress(config)` exposes an Express-style middleware. Both come from `@openagentid/sdk`; configure the ACT crypto binding first. Required trust values include issuer, audience and trusted public keys. Add the scopes required by the route. Go provides `RequireAct` and `RequireActFunc` for `net/http`. Python provides dependency/middleware factories in `openagent_sdk.middleware`. Kotlin's `Ktor.kt` provides the Ktor integration. Use each language's real request/context types rather than assuming one universal context object. ## HTTP handshake [#http-handshake] TypeScript `createOpenAgentHandler` from `@openagentid/http` accepts a signature verifier, session store and server options. Its `handle(request)` returns either a `Response` for a handled/failed request or an authentication result for the application to process. The application must branch on the return value before executing protected handlers. The Express-style adapter has its own request/response conversion. Fetch-standard compatibility is not a guarantee that every framework adapter accepts identical options. ## Legacy Rust layer [#legacy-rust-layer] `OpenAgentLayer` lives in `openagent-server`. Read the standalone route and session contract before combining it with a new router. Source presence does not establish that gRPC, Hono-specific exports or a custom extractor exists under the unified package. See [package references](/reference/packages) for exact entry points and [the TypeScript guide](/sdk/typescript) for binding prerequisites. # Server integration URL: https://docs.openagent.id/sdk/server/overview Markdown: https://docs.openagent.id/sdk/server/overview.md Compose authentication and authorization from real middleware and provider contracts. Choose a server surface before wiring routes. The [standalone Rust binary](/api-reference/openagent-server) exposes health and authenticated identity. The [TypeScript HTTP adapter](/api-reference/http-adapter) exposes well-known handshake routes. ACT middleware verifies capability envelopes at application routes. There is no `@openagentid/sdk/server` or `@openagentid/sdk/server/hono` export in the current unified SDK manifest. Import actual middleware from the package that implements the needed contract: * `@openagentid/sdk`: `withAct` and `requireActExpress` for ACT route verification. * `@openagentid/http`: `createOpenAgentHandler` and `createOpenAgentMiddleware` for challenge/session authentication. * `openagent-server`: the legacy Rust Tower layer used by the standalone binary. ## Integration sequence [#integration-sequence] 1. Configure server origin, trusted keys, issuer/audience, and session storage. 2. Select the matching handshake and session format. 3. Authenticate the caller before attaching verified context. 4. Enforce route scope and tenant policy at the action boundary. 5. Invoke configured authority verification for privileged operations. 6. Record meaningful denial/error outcomes without logging credentials. AEGIS is an explicit verifier integration. Do not assume every HTTP authentication handler automatically executes the entire AEGIS pipeline. See [middleware](/sdk/server/middleware), [verification](/sdk/server/verification), and [policy](/sdk/server/policies). # Server policies URL: https://docs.openagent.id/sdk/server/policies Markdown: https://docs.openagent.id/sdk/server/policies.md Bind scopes, tenant trust, delegation, and skills policy to the operation being protected. Define policy at the action boundary. Scope requirements come from your application, not the incoming token. Trust the configured issuer keys and expected audience, then compare verified grants against the required operation. ## Layers [#layers] * ACT verifies signed capability claims and required scope. * Arsenal evaluates credential/proxy requests against tenant policy and consent. * AEGIS provides composition, spending, temporal, lineage and contract evaluators. * Skills governance gates specific declared tool/skill invocations. An authenticated request can still be denied by policy. A permitted skill does not imply permission to use every credential or mutate every tenant. Delegation must preserve scope and depth restrictions rather than expanding the parent's authority. Exercise missing policy, nonmatching policy, expired capability, wrong audience, revoked authority, and missing consent. Record denials distinctly from configuration failures. See [Arsenal policy](/arsenal/policies), [AEGIS policy](/aegis/policies), and [skills governance](/features/skills-governance). # Server verification URL: https://docs.openagent.id/sdk/server/verification Markdown: https://docs.openagent.id/sdk/server/verification.md Keep capability verification, key-possession authentication, and privileged authority separate. ACT verification answers whether a capability envelope is valid for the configured issuer, audience, time and scope. Challenge-response answers whether the caller possesses the key used for a proof. Authority verification answers whether an operation is authorized through a trusted lineage/anchor path. The TypeScript SDK exposes `VerificationClient` and `PrivilegedAuthorityVerifier`. `PrivilegedAuthorityVerificationClient` composes configured request and authority verification. Configure the correct provider; passing a DID or a claimed ancestor is not enough. AEGIS exposes `VerificationPipeline` and store/cache interfaces. Select the resolver, revocation/liveness behavior and trust policy needed by your deployment. Cache lifetime and invalidation matter when authority changes. A middleware name does not prove this entire sequence runs. Verify the actual call path from the protected route to the configured authority verifier, including failure propagation. See [AEGIS verification](/aegis/verification-pipeline) and [conformance](/features/conformance). # agent-capability-token (Rust) URL: https://docs.openagent.id/reference/packages/act-agent-capability-token Markdown: https://docs.openagent.id/reference/packages/act-agent-capability-token.md Canonical wire format for the Agent Capability Token (ACT) required by ANVIL section 5. ## Purpose [#purpose] Canonical wire format for the Agent Capability Token (ACT) required by ANVIL section 5. [Read the canonical act guide](/arsenal/act-tokens). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `agent-capability-token` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `act/agent-capability-token/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `ed7fd1fef0c11c2748a6f223cd99f9ef873c6ff17af1c31608defd489654ce23`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "sign": [] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `act/agent-capability-token/src/lib.rs` [#actagent-capability-tokensrclibrs] Source SHA-256: `a326ce327fca34441b760e229ef3b7ac9d9ae536c1899365dd538ac56ebd6918`. ```rust pub mod claims; pub mod error; pub mod scope; pub mod wire; pub use claims::{ActClaims, Confirmation, Delegation}; pub use error::{ActError, ActResult}; pub use scope::{Scope, SCOPE_SEGMENTS, WILDCARD}; pub use wire::{ claims_to_signing_payload, envelope_from_parts, verify, ActEnvelope, PublicKeyBytes, Verifier, ALGORITHM_ED25519, FORMAT_VERSION, MAX_ACT_BYTES, }; pub use wire::sign; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/agent-capability-token). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-auth (Rust) URL: https://docs.openagent.id/reference/packages/aegis-aegis-auth Markdown: https://docs.openagent.id/reference/packages/aegis-aegis-auth.md AEGIS authentication protocol — challenge-response, session management, cross-domain auth ## Purpose [#purpose] AEGIS authentication protocol — challenge-response, session management, cross-domain auth [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `aegis-auth` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/aegis-auth/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `5c9900e8560bc63b04d883f3fdc0a32a3ebbd639491124020538d47417791b28`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [ "verify" ], "verify": [ "dep:aegis-verify" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/aegis-auth/src/lib.rs` [#aegisaegis-authsrclibrs] Source SHA-256: `7b6f26da034daf413490a387eddccc9114ecb69734dba161516cf589b27c158c`. ```rust pub mod challenge; pub mod provider; pub mod session; pub mod store; pub use challenge::{build_challenge_payload, Challenge, ChallengeVerifier}; pub use provider::{ApiKeyProvider, ChallengeResponseProvider}; pub use session::SessionManager; pub use store::{InMemoryNonceStore, InMemorySessionStore, NonceStore, SessionStore}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/aegis-auth). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-delegate (Rust) URL: https://docs.openagent.id/reference/packages/aegis-aegis-delegate Markdown: https://docs.openagent.id/reference/packages/aegis-aegis-delegate.md AEGIS delegation and authority model — delegation trees, session keys, scope constraints ## Purpose [#purpose] AEGIS delegation and authority model — delegation trees, session keys, scope constraints [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `aegis-delegate` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/aegis-delegate/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `861b8fa964305bf7f14ef968b3016e8ebba0d875572d4982aa02e3bf86c3b055`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/aegis-delegate/src/lib.rs` [#aegisaegis-delegatesrclibrs] Source SHA-256: `adf9fb968b0e47f2f75c16d0639492179568b181572a17f794496e7046a5c654`. ```rust pub mod delegation_store; pub mod proof; pub mod revocation; pub mod scope; pub mod session_key; pub mod store; pub mod tree; pub use delegation_store::{DelegationStore, InMemoryDelegationStore}; pub use store::{InMemoryRevocationStore, RevocationStore}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/aegis-delegate). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-keys (Rust) URL: https://docs.openagent.id/reference/packages/aegis-aegis-keys Markdown: https://docs.openagent.id/reference/packages/aegis-aegis-keys.md AEGIS key management framework — generation, MPC, TEE, derivation, rotation, recovery ## Purpose [#purpose] AEGIS key management framework — generation, MPC, TEE, derivation, rotation, recovery [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `aegis-keys` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/aegis-keys/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `6c123be2e94880949e526eba001e3453a79d3487df193164882f55036521832d`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/aegis-keys/src/lib.rs` [#aegisaegis-keyssrclibrs] Source SHA-256: `c19c72128fbfcee36aad4232c4ce0414a1896bb0ab18984d3cd405ab4d1ce947`. ```rust pub mod derivation; pub mod generation; pub mod recovery; pub mod rotation; pub mod storage; pub mod threshold; pub use derivation::{derivation_path, derive_lineage_key}; pub use generation::{EncryptedKey, KeyGenerator, ManagedKey}; pub use recovery::{GuardianAuthorization, RecoveryCeremony}; pub use rotation::{KeyRotation, RotationRequest, RotationResult}; pub use storage::{InMemoryKeyStore, KeyStore}; pub use threshold::{generate_shares, sign_with_threshold, verify_threshold_signature}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/aegis-keys). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-store-pg (Rust) URL: https://docs.openagent.id/reference/packages/aegis-aegis-store-pg Markdown: https://docs.openagent.id/reference/packages/aegis-aegis-store-pg.md AEGIS PostgreSQL storage backends ## Purpose [#purpose] AEGIS PostgreSQL storage backends [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `aegis-store-pg` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/aegis-store-pg/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `cc3e929331df530a8792730f619583d96e6d582773a10d44a8586aae985c2102`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/aegis-store-pg/src/lib.rs` [#aegisaegis-store-pgsrclibrs] Source SHA-256: `77c32f388a08e399d52ad6f089fb8463130401d3a0d9f64121bb06621360d40d`. ```rust pub mod cache; pub mod delegations; pub mod keys; pub mod nonces; pub mod revocations; pub mod sessions; pub use cache::PgVerificationCacheStore; pub use delegations::PgDelegationStore; pub use keys::PgKeyStore; pub use nonces::PgNonceStore; pub use revocations::PgRevocationStore; pub use sessions::PgSessionStore; pub async fn run_migrations(pool: &sqlx::PgPool) -> Result<(), sqlx::Error> { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/aegis-store-pg). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-verify (Rust) URL: https://docs.openagent.id/reference/packages/aegis-aegis-verify Markdown: https://docs.openagent.id/reference/packages/aegis-aegis-verify.md AEGIS verification infrastructure — OAS document, signature, and lineage verification ## Purpose [#purpose] AEGIS verification infrastructure — OAS document, signature, and lineage verification [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `aegis-verify` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/aegis-verify/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `33675d15523de96f02b3f9c1c22ff083931f55ad44bc4c0c1a1a0c4b7cfb4a62`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/aegis-verify/src/lib.rs` [#aegisaegis-verifysrclibrs] Source SHA-256: `c8d798fb66648c528b91bacec4feac289043d5ed59797674eebc49676330f1df`. ```rust pub mod cache; pub mod pipeline; pub mod store; pub use cache::VerificationCache; pub use pipeline::VerificationPipeline; pub use store::{InMemoryVerificationCacheStore, VerificationCacheStore}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/aegis-verify). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-wallet (Rust) URL: https://docs.openagent.id/reference/packages/aegis-aegis-wallet Markdown: https://docs.openagent.id/reference/packages/aegis-aegis-wallet.md AEGIS wallet and signing infrastructure — multi-chain derivation, signing ceremony, tx pipeline ## Purpose [#purpose] AEGIS wallet and signing infrastructure — multi-chain derivation, signing ceremony, tx pipeline [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `aegis-wallet` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/aegis-wallet/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `3b3e7983132f0485450972867f784a788840db4ced3d89277bd6d9c70163340a`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/aegis-wallet/src/lib.rs` [#aegisaegis-walletsrclibrs] Source SHA-256: `81f68cbce49fa14207778757db13fdc987e7290653f90b4c20e41dbad27a6ad2`. ```rust pub mod address; pub mod batch; pub mod ceremony; pub mod external; pub mod pipeline; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/aegis-wallet). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-aegis-core (Rust) URL: https://docs.openagent.id/reference/packages/aegis-openagent-aegis-core Markdown: https://docs.openagent.id/reference/packages/aegis-openagent-aegis-core.md AEGIS core plugin interfaces, types, and error types ## Purpose [#purpose] AEGIS core plugin interfaces, types, and error types [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-aegis-core` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/openagent-aegis-core/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `6c3bf81fb6608f587fbf03df7f2b0a1bb092e00b893ca423cc6e2c5eb16a90a6`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/openagent-aegis-core/src/lib.rs` [#aegisopenagent-aegis-coresrclibrs] Source SHA-256: `88d7730fc7e6ae32363a1c3e20c911711e49b185bd5482f35302a01053d22c78`. ```rust pub mod error; pub mod plugin; pub mod types; pub use error::*; pub use plugin::*; pub use types::*; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-aegis-core). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-aegis-policy (Rust) URL: https://docs.openagent.id/reference/packages/aegis-openagent-aegis-policy Markdown: https://docs.openagent.id/reference/packages/aegis-openagent-aegis-policy.md AEGIS policy enforcement framework — spending, contract, temporal, and lineage-aware policies ## Purpose [#purpose] AEGIS policy enforcement framework — spending, contract, temporal, and lineage-aware policies [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-aegis-policy` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/openagent-aegis-policy/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `1ee7ac173df0fd66faa8ac9192868bde7148425e954d2ac4fb3d509cb17b2076`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/openagent-aegis-policy/src/lib.rs` [#aegisopenagent-aegis-policysrclibrs] Source SHA-256: `4d0513d5b022efc203ba22a565acaccec45761e802bc4d1102ac476636cdd6ab`. ```rust pub mod composition; pub mod contract; pub mod lineage; pub mod spending; pub mod temporal; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-aegis-policy). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-aegis-sdk (Rust) URL: https://docs.openagent.id/reference/packages/aegis-openagent-aegis-sdk Markdown: https://docs.openagent.id/reference/packages/aegis-openagent-aegis-sdk.md AEGIS SDK — unified high-level API for all AEGIS layers ## Purpose [#purpose] AEGIS SDK — unified high-level API for all AEGIS layers [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-aegis-sdk` | | Version | `0.2.0` | | Language | Rust | | Runtime floor | `1.85` | | Manifest | `aegis/openagent-aegis-sdk/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `2823c82255705a96613dd16e42af94de09e1381d4b834b2ac5b9d7ecb28a0c30`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "postgres": [ "aegis-store-pg" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/openagent-aegis-sdk/src/lib.rs` [#aegisopenagent-aegis-sdksrclibrs] Source SHA-256: `83968235678802fdbfb94a7eb82f2246bb076573da27fa4a3c6ab060e6e44b3a`. ```rust pub mod client; pub mod config; pub use client::{AegisClient, AegisStores}; pub use config::{AegisConfig, StorageBackend}; pub use aegis_auth; pub use aegis_delegate; pub use aegis_keys; pub use aegis_verify; pub use aegis_wallet; pub use openagent_aegis_core; pub use openagent_aegis_policy; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-aegis-sdk). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/aegis-sdk (TypeScript) URL: https://docs.openagent.id/reference/packages/aegis-sdks-typescript Markdown: https://docs.openagent.id/reference/packages/aegis-sdks-typescript.md AEGIS — Identity verification and authorization framework built on OAS ## Purpose [#purpose] AEGIS — Identity verification and authorization framework built on OAS [Read the aegis verification guide](/aegis/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `@openagentid/aegis-sdk` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `aegis/sdks/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `42125a1f52bd88c60815e937532c03861815254602b335845010294056487482`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" }, "./core": { "types": "./dist/core/index.d.ts", "import": "./dist/core/index.js" }, "./verify": { "types": "./dist/verify/index.d.ts", "import": "./dist/verify/index.js" }, "./keys": { "types": "./dist/keys/index.d.ts", "import": "./dist/keys/index.js" }, "./auth": { "types": "./dist/auth/index.d.ts", "import": "./dist/auth/index.js" }, "./policy": { "types": "./dist/policy/index.d.ts", "import": "./dist/policy/index.js" }, "./delegate": { "types": "./dist/delegate/index.d.ts", "import": "./dist/delegate/index.js" }, "./wallet": { "types": "./dist/wallet/index.d.ts", "import": "./dist/wallet/index.js" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `aegis/sdks/typescript/src/index.ts` [#aegissdkstypescriptsrcindexts] Source SHA-256: `21606ecebf9066f5920a6b1af6f731d64906d7e6c42e8f0d2b997a28a97dbda2`. ```typescript export * from "./core/index.js"; export * from "./verify/index.js"; export * from "./keys/index.js"; export * from "./auth/index.js"; export * from "./policy/index.js"; export * from "./delegate/index.js"; export * from "./wallet/index.js"; export * from "./sdk/index.js"; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/aegis-sdks-typescript). # arsenal-broker (Rust) URL: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-broker Markdown: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-broker.md mTLS gateway and capability broker for ARSENAL ## Purpose [#purpose] mTLS gateway and capability broker for ARSENAL [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `arsenal-broker` | | Version | `2.0.0` | | Language | Rust | | Runtime floor | `1.75` | | Manifest | `arsenal/crates/arsenal-broker/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `02f8bb340095ea585bd28be0661e79c13d691c5597b58363c00c2d76be56090f`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/crates/arsenal-broker/src/lib.rs` [#arsenalcratesarsenal-brokersrclibrs] Source SHA-256: `96b1bed6734958c5c5c0ce05651f84f2023928d166c7b91899604391a930a526`. ```rust pub mod audit_sink; pub mod config; pub mod consent_service; pub mod handlers; pub mod metrics; pub mod middleware; pub mod proxy_config; pub mod proxy_service; pub mod rate; pub mod revocation; pub mod server; pub mod service; pub mod ssrf_guard; pub use config::BrokerConfig; pub use consent_service::ConsentService; pub use proxy_config::{ConsentConfig, ProxyConfig}; pub use proxy_service::ProxyService; pub use server::BrokerServer; pub use service::{BrokerService, RegisteredAgent, RequestContext}; pub use ssrf_guard::SsrfGuard; pub mod prelude { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/arsenal-broker). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # arsenal-core (Rust) URL: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-core Markdown: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-core.md Core types, tokens, scopes, and constraints for ARSENAL agent key management ## Purpose [#purpose] Core types, tokens, scopes, and constraints for ARSENAL agent key management [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `arsenal-core` | | Version | `2.0.0` | | Language | Rust | | Runtime floor | `1.75` | | Manifest | `arsenal/crates/arsenal-core/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `83da7b5b43d1311121d21a3e1595bb66344be9b55faadebce814bab54541e487`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/crates/arsenal-core/src/lib.rs` [#arsenalcratesarsenal-coresrclibrs] Source SHA-256: `13dfa8779257ee1a963ab68ee6489a3bda7f79157240c782eb47e7493c93d52f`. ```rust pub mod act; pub mod audit; pub mod consent; pub mod constraints; pub mod delegation; pub mod error; pub mod fingerprint; pub mod identity; pub mod limits; pub mod policy; pub mod proxy; pub mod scope; pub mod secret; pub mod session; pub mod token; pub use audit::{AuditEvent, AuditEventKind, AuditSeverity}; pub use consent::{ConsentId, ConsentPolicy, ConsentRecord, ConsentRequest, ConsentStatus}; pub use constraints::{BindingType, Constraints, EnvironmentConstraint}; pub use delegation::{DelegationChain, DelegationConstraints}; pub use error::{ArsenalError, ArsenalResult}; pub use fingerprint::{FingerprintState, FingerprintVerification}; pub use identity::{AgentIdentity, PrincipalId, TenantId}; pub use limits::{RateLimits, UsageBudget}; pub use policy::{PolicyDocument, PolicyEffect, PolicyId}; pub use proxy::{ DestinationBinding, ProxyMetadata, ProxyRequest, ProxyResponse, TemplateVariable, VariablePrefix, VariableResolutionTable, }; pub use scope::{Permission, Scope, ScopeSet}; pub use secret::{SecretId, SecretMetadata, SecretVersion}; pub use session::{AgentSession, SessionId, SessionState}; pub use token::{AgentCapabilityToken, TokenClaims, TokenId}; pub mod prelude { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/arsenal-core). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # arsenal-crypto (Rust) URL: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-crypto Markdown: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-crypto.md Cryptographic primitives for ARSENAL - signing, encryption, key derivation ## Purpose [#purpose] Cryptographic primitives for ARSENAL - signing, encryption, key derivation [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `arsenal-crypto` | | Version | `2.0.0` | | Language | Rust | | Runtime floor | `1.75` | | Manifest | `arsenal/crates/arsenal-crypto/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `0732a412dc80b3f9d1187f94d05ff0a096b1524429d10cdf468bb73a6584abad`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/crates/arsenal-crypto/src/lib.rs` [#arsenalcratesarsenal-cryptosrclibrs] Source SHA-256: `3322fef81a38819ff0ab7b16d77ee2e93ec14425629eb7719b351f5300c0133c`. ```rust pub mod encryption; pub mod envelope; pub mod hash; pub mod kdf; pub mod keys; pub mod random; pub mod signing; pub mod token_signer; pub use encryption::{Decryptor, EncryptedData, Encryptor}; pub use envelope::{EnvelopeEncryption, WrappedKey}; pub use hash::{Hash, Hasher}; pub use kdf::{DerivedKey, KeyDerivation}; pub use keys::{EncryptionKeyPair, KeyId, SigningKeyPair}; pub use signing::{Signature, Signer, Verifier}; pub use token_signer::{TokenSigner, TokenVerifier}; pub mod prelude { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/arsenal-crypto). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # arsenal-policy (Rust) URL: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-policy Markdown: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-policy.md Declarative policy engine for ARSENAL ## Purpose [#purpose] Declarative policy engine for ARSENAL [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `arsenal-policy` | | Version | `2.0.0` | | Language | Rust | | Runtime floor | `1.75` | | Manifest | `arsenal/crates/arsenal-policy/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `c90f0b7af4c56a85752044b8a0438ef9eb5d764d95a710216e3ea0004e813ff8`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/crates/arsenal-policy/src/lib.rs` [#arsenalcratesarsenal-policysrclibrs] Source SHA-256: `6c9d8fd45c446ec98067a79fe50ca4abcef78738ee12bdc12d827f20f9f44c8c`. ```rust pub use arsenal_core::policy::{ ConditionOperator, PolicyCondition, PolicyDecision, PolicyDocument, PolicyEffect, PolicyId, PolicyRequest, PolicyRule, }; pub struct PolicyEngine { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/arsenal-policy). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # arsenal-sdk (Rust) URL: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-sdk Markdown: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-sdk.md High-level SDK for ARSENAL agents ## Purpose [#purpose] High-level SDK for ARSENAL agents [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `arsenal-sdk` | | Version | `2.0.0` | | Language | Rust | | Runtime floor | `1.75` | | Manifest | `arsenal/crates/arsenal-sdk/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `63fe1d0bec7f47123d821d235edd8abf6ed5222a77c1ada7cf5bacbc7db8b3d6`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/crates/arsenal-sdk/src/lib.rs` [#arsenalcratesarsenal-sdksrclibrs] Source SHA-256: `bf2efb4b5fed418cbe33f6e12e01871a7227603aed6223a69a5ca287e797d37e`. ```rust pub mod broker_client; pub mod capability; pub mod client; pub mod identity_loader; pub mod proxy_client; pub mod session_manager; pub mod tool_caller; pub use broker_client::BrokerClient; pub use capability::{CapabilityHandle, CapabilityRequest}; pub use client::{ArsenalClient, ArsenalClientBuilder}; pub use identity_loader::AgentIdentityLoader; pub use proxy_client::ProxyClient; pub use session_manager::SessionManager; pub use tool_caller::{Tool, ToolCallRequest, ToolCallResponse, ToolCaller}; pub mod prelude { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/arsenal-sdk). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # arsenal-store (Rust) URL: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-store Markdown: https://docs.openagent.id/reference/packages/arsenal-crates-arsenal-store.md Secret storage backends for ARSENAL - in-memory, encrypted file, and database ## Purpose [#purpose] Secret storage backends for ARSENAL - in-memory, encrypted file, and database [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `arsenal-store` | | Version | `2.0.0` | | Language | Rust | | Runtime floor | `1.75` | | Manifest | `arsenal/crates/arsenal-store/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `58046455ee75257d2c99d46eab4e699fc7f795841e830813cdb7ecb2b6d74918`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "postgres": [ "sqlx" ], "sqlite": [ "sqlx" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/crates/arsenal-store/src/lib.rs` [#arsenalcratesarsenal-storesrclibrs] Source SHA-256: `9eef468c92a9dc9b45700316aa160791082cc0d1e66682d9a61faead9a37b6dc`. ```rust pub mod consent_store; pub mod encrypted_file; pub mod fingerprint_store; pub mod key_resolver; pub mod key_wrapper; pub mod memory; pub mod traits; pub mod variable_resolver; pub use consent_store::{ConsentStore, InMemoryConsentStore}; pub use encrypted_file::EncryptedFileStore; pub use fingerprint_store::{FingerprintStore, InMemoryFingerprintStore}; pub use key_resolver::{InMemoryKeyResolver, PublicKeyResolver}; pub use key_wrapper::{KeyWrapper, SoftwareKeyWrapper}; pub use memory::InMemorySecretStore; pub use traits::{SecretStore, SecretStoreError, SecretStoreResult}; pub use variable_resolver::{InMemoryVariableResolver, VariableResolver}; pub use consent_store::SqlConsentStore; pub use fingerprint_store::SqlFingerprintStore; pub use variable_resolver::SqlVariableResolver; pub mod prelude { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/arsenal-store). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/arsenal-sdk (TypeScript) URL: https://docs.openagent.id/reference/packages/arsenal-sdks-typescript Markdown: https://docs.openagent.id/reference/packages/arsenal-sdks-typescript.md Arsenal agent-side SDK: Agent Capability Tokens (ACT), scoped credential proxy, broker client, policy engine. ## Purpose [#purpose] Arsenal agent-side SDK: Agent Capability Tokens (ACT), scoped credential proxy, broker client, policy engine. [Read the arsenal credentials guide](/arsenal/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `@openagentid/arsenal-sdk` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `arsenal/sdks/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `796fa0ebe610d74eedae73fffe388dea57a4cca9f7a28e16d8d6690dd8192c24`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./core": { "types": "./dist/core/index.d.ts", "import": "./dist/core/index.js", "require": "./dist/core/index.cjs" }, "./policy": { "types": "./dist/policy/index.d.ts", "import": "./dist/policy/index.js", "require": "./dist/policy/index.cjs" }, "./broker": { "types": "./dist/broker/index.d.ts", "import": "./dist/broker/index.js", "require": "./dist/broker/index.cjs" }, "./crypto": { "types": "./dist/crypto/index.d.ts", "import": "./dist/crypto/index.js", "require": "./dist/crypto/index.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `arsenal/sdks/typescript/src/index.ts` [#arsenalsdkstypescriptsrcindexts] Source SHA-256: `5c051c019750f7db93f82c8bf7fa0898d5aece7758429168243df58d839f745a`. ```typescript export * from "./core/index.js"; export * from "./policy/index.js"; export * from "./broker/index.js"; export * from "./sdk/index.js"; export const VERSION = "0.1.0"; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/arsenal-sdks-typescript). # Package catalog URL: https://docs.openagent.id/reference/packages Markdown: https://docs.openagent.id/reference/packages.md Source manifests, versions, features, entry points, and task guides across the OpenAgentID family. This catalog maps **64 source packages** across the six SDKs, protocol/adapters, OAS, Arsenal, AEGIS, canonical ACT, legacy clients, bridges, integration and deployment tooling. Each row links to a manifest and entry-point reference with a relevant task guide. Source inventory coverage is not a claim that all API behavior has been compiled, exercised, or published. [Download the machine-readable coverage manifest](/reference/coverage.json). ## Packages [#packages] | Package | Language | Version | Area | | --------------------------------------------------------------------------------------------------------- | ---------- | ---------------- | ------------------------ | | [agent-capability-token](/reference/packages/act-agent-capability-token) | Rust | `0.1.0` | Canonical ACT | | [aegis-auth](/reference/packages/aegis-aegis-auth) | Rust | `0.2.0` | AEGIS verification | | [aegis-delegate](/reference/packages/aegis-aegis-delegate) | Rust | `0.2.0` | AEGIS verification | | [aegis-keys](/reference/packages/aegis-aegis-keys) | Rust | `0.2.0` | AEGIS verification | | [aegis-store-pg](/reference/packages/aegis-aegis-store-pg) | Rust | `0.2.0` | AEGIS verification | | [aegis-verify](/reference/packages/aegis-aegis-verify) | Rust | `0.2.0` | AEGIS verification | | [aegis-wallet](/reference/packages/aegis-aegis-wallet) | Rust | `0.2.0` | AEGIS verification | | [openagent-aegis-core](/reference/packages/aegis-openagent-aegis-core) | Rust | `0.2.0` | AEGIS verification | | [openagent-aegis-policy](/reference/packages/aegis-openagent-aegis-policy) | Rust | `0.2.0` | AEGIS verification | | [openagent-aegis-sdk](/reference/packages/aegis-openagent-aegis-sdk) | Rust | `0.2.0` | AEGIS verification | | [@openagentid/aegis-sdk](/reference/packages/aegis-sdks-typescript) | TypeScript | `0.1.1` | AEGIS verification | | [arsenal-broker](/reference/packages/arsenal-crates-arsenal-broker) | Rust | `2.0.0` | Arsenal credentials | | [arsenal-core](/reference/packages/arsenal-crates-arsenal-core) | Rust | `2.0.0` | Arsenal credentials | | [arsenal-crypto](/reference/packages/arsenal-crates-arsenal-crypto) | Rust | `2.0.0` | Arsenal credentials | | [arsenal-policy](/reference/packages/arsenal-crates-arsenal-policy) | Rust | `2.0.0` | Arsenal credentials | | [arsenal-sdk](/reference/packages/arsenal-crates-arsenal-sdk) | Rust | `2.0.0` | Arsenal credentials | | [arsenal-store](/reference/packages/arsenal-crates-arsenal-store) | Rust | `2.0.0` | Arsenal credentials | | [@openagentid/arsenal-sdk](/reference/packages/arsenal-sdks-typescript) | TypeScript | `0.1.1` | Arsenal credentials | | [oas-anchor-eas](/reference/packages/oas-oas-oas-anchor-eas) | Rust | `1.1.1` | OAS identity | | [oas-attestation](/reference/packages/oas-oas-oas-attestation) | Rust | `1.1.1` | OAS identity | | [oas-crypto](/reference/packages/oas-oas-oas-crypto) | Rust | `1.1.1` | OAS identity | | [oas-did](/reference/packages/oas-oas-oas-did) | Rust | `1.1.1` | OAS identity | | [oas-document](/reference/packages/oas-oas-oas-document) | Rust | `1.1.1` | OAS identity | | [oas-lineage](/reference/packages/oas-oas-oas-lineage) | Rust | `1.1.1` | OAS identity | | [oas-resolve](/reference/packages/oas-oas-oas-resolve) | Rust | `1.1.1` | OAS identity | | [oas-sdk](/reference/packages/oas-oas-oas-sdk) | Rust | `1.1.1` | OAS identity | | [oas-wasm](/reference/packages/oas-oas-oas-wasm) | Rust | `1.1.1` | OAS identity | | [@openagentid/anchor-eas](/reference/packages/openagent-sdk-adapters-eas-typescript) | TypeScript | `0.1.1` | Protocol adapters | | [openagent-http](/reference/packages/openagent-sdk-adapters-http-rust) | Rust | `0.1.0` | Protocol adapters | | [@openagentid/http](/reference/packages/openagent-sdk-adapters-http-typescript) | TypeScript | `0.1.1` | Protocol adapters | | [openagent-weave](/reference/packages/openagent-sdk-adapters-weave) | Rust | `0.1.0` | Protocol adapters | | [openagent-ws](/reference/packages/openagent-sdk-adapters-websocket-rust) | Rust | `0.1.0` | Protocol adapters | | [openagent-oidc](/reference/packages/openagent-sdk-bridges-oidc-rust) | Rust | `0.1.0` | Identity bridges | | [@openagentid/oidc](/reference/packages/openagent-sdk-bridges-oidc-typescript) | TypeScript | `0.1.1` | Identity bridges | | [openagent-scim](/reference/packages/openagent-sdk-bridges-scim-rust) | Rust | `0.1.0` | Identity bridges | | [@openagentid/scim](/reference/packages/openagent-sdk-bridges-scim-typescript) | TypeScript | `0.1.1` | Identity bridges | | [conformance-runner](/reference/packages/openagent-sdk-conformance-runner-rust) | Rust | `0.1.0` | Testing and conformance | | [@openagentid/conformance-runner](/reference/packages/openagent-sdk-conformance-runner-ts) | TypeScript | `0.1.0` | Testing and conformance | | [openagent-auth-protocol](/reference/packages/openagent-sdk-crates-openagent-auth-protocol) | Rust | `0.1.0` | Authentication protocol | | [openagent-crypto-wasm](/reference/packages/openagent-sdk-crates-openagent-crypto-wasm) | Rust | `0.1.1` | Cryptographic binding | | [@openagentid/crypto-wasm](/reference/packages/openagent-sdk-crates-openagent-crypto-wasm-pkg) | TypeScript | `0.1.1` | Cryptographic binding | | [openagent-skills-policy](/reference/packages/openagent-sdk-crates-openagent-skills-policy-rust) | Rust | `0.1.0` | Skills policy | | [@openagentid/skills-policy](/reference/packages/openagent-sdk-crates-openagent-skills-policy-typescript) | TypeScript | `0.1.1` | Skills policy | | [openagent-aws-lambda](/reference/packages/openagent-sdk-deploy-aws-lambda) | TypeScript | `0.1.0` | Deployment adapters | | [openagent-cloudflare-worker](/reference/packages/openagent-sdk-deploy-cloudflare-worker) | TypeScript | `0.1.0` | Deployment adapters | | [openagent-docker](/reference/packages/openagent-sdk-deploy-docker) | TypeScript | `0.1.0` | Deployment adapters | | [openagent-vercel-edge](/reference/packages/openagent-sdk-deploy-vercel-edge) | TypeScript | `0.1.0` | Deployment adapters | | [openagent-claude-agent](/reference/packages/openagent-sdk-integrations-claude-agent-sdk-rust) | Rust | `0.1.0` | Framework integrations | | [@openagentid/claude-agent](/reference/packages/openagent-sdk-integrations-claude-agent-sdk-typescript) | TypeScript | `0.1.1` | Framework integrations | | [openagent-mcp](/reference/packages/openagent-sdk-integrations-mcp-rust) | Rust | `0.1.0` | Framework integrations | | [@openagentid/mcp](/reference/packages/openagent-sdk-integrations-mcp-typescript) | TypeScript | `0.1.1` | Framework integrations | | [create-openagent](/reference/packages/openagent-sdk-packages-create-openagent) | TypeScript | `0.1.1` | Scaffolding | | [github.com/OpenAgentID/openagent-sdk-go](/reference/packages/openagent-sdk-sdks-go) | Go | `source module` | Unified SDKs | | [id.openagent:openagent-sdk](/reference/packages/openagent-sdk-sdks-kotlin) | Kotlin | `0.1.0` | Unified SDKs | | [openagentid-sdk](/reference/packages/openagent-sdk-sdks-python) | Python | `0.1.0` | Unified SDKs | | [openagent-sdk](/reference/packages/openagent-sdk-sdks-rust) | Rust | `0.1.0` | Unified SDKs | | [OpenAgentSDK](/reference/packages/openagent-sdk-sdks-swift) | Swift | `source package` | Unified SDKs | | [@openagentid/sdk-testing](/reference/packages/openagent-sdk-sdks-testing) | TypeScript | `0.1.1` | Testing and conformance | | [@openagentid/sdk](/reference/packages/openagent-sdk-sdks-typescript) | TypeScript | `0.1.1` | Unified SDKs | | [@openagentid/client](/reference/packages/openagents-openagent-id-clients-typescript) | TypeScript | `0.1.1` | Legacy client and server | | [openagent-capability](/reference/packages/openagents-openagent-id-crates-openagent-capability) | Rust | `0.1.0` | Legacy client and server | | [openagent-client](/reference/packages/openagents-openagent-id-crates-openagent-client) | Rust | `0.1.0` | Legacy client and server | | [openagent-server](/reference/packages/openagents-openagent-id-crates-openagent-server) | Rust | `0.1.0` | Legacy client and server | | [openagent-standalone](/reference/packages/openagents-openagent-id-crates-openagent-standalone) | Rust | `0.1.0` | Legacy client and server | # oas-anchor-eas (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-anchor-eas Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-anchor-eas.md Ethereum Attestation Service (EAS) adapter for the OAS LineageAnchor trait: lineage authority resolution via EAS GraphQL plus JSON-RPC finality. ## Purpose [#purpose] Ethereum Attestation Service (EAS) adapter for the OAS LineageAnchor trait: lineage authority resolution via EAS GraphQL plus JSON-RPC finality. [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-anchor-eas` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-anchor-eas/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `802072ce0a60109157bbab8721c09f2eae763bc3390c8674a7a66166f07db2b8`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-anchor-eas/src/lib.rs` [#oasoasoas-anchor-eassrclibrs] Source SHA-256: `e7376745ce2cffd53d2c9f3cf749659adda88ebdb14f08c69180db258380d5f7`. ```rust pub mod abi; pub mod eas; pub mod error; pub use eas::{did_recipient, EasAnchor, EasConfig}; pub use error::EasError; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-anchor-eas). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-attestation (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-attestation Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-attestation.md W3C Verifiable Credential attestation support for the Open Agent Specification (OAS) ## Purpose [#purpose] W3C Verifiable Credential attestation support for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-attestation` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-attestation/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `1502b03262905663e90423d3c124634458fcdec46fe64801328ea5dec143866e`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-attestation/src/lib.rs` [#oasoasoas-attestationsrclibrs] Source SHA-256: `7effa9fd9902e4f2a6dfbb5e56081f02fd2f4eb2f75299648ce58a5cb9c64078`. ```rust pub mod credential; pub mod data_integrity_2025; pub mod error; pub mod lineage_vc; pub mod oid4vp; pub mod presentation; pub mod proof_formats; pub mod sd_jwt_vc; pub mod sign; pub mod signer; pub mod types; pub mod vc_jose; pub mod verify; pub use credential::ContextMode; pub use data_integrity_2025::{ algorithm_to_cryptosuite, cryptosuite_to_algorithm, sign_credential_data_integrity, verify_credential_data_integrity, CRYPTOSUITE_BBS_2023, CRYPTOSUITE_ECDSA_2019, CRYPTOSUITE_EDDSA_2022, DATA_INTEGRITY_PROOF_TYPE, }; pub use error::AttestationError; pub use lineage_vc::{ lineage_proof_from_credential, lineage_proof_to_credential, LineageAttestationContext, LineageAttestationData, LineageRootKind, }; pub use oid4vp::{ create_authorization_request, create_oid4vp_response, verify_oid4vp_response, AuthorizationRequest, Constraints, DescriptorMap, InputDescriptor, InputField, Oid4vpResponse, PresentationDefinition, PresentationSubmission, }; pub use presentation::{ is_authority_bearing, sign_presentation, verify_presentation, verify_presentation_holder_binding, verify_presentation_holder_binding_with_lineage, verify_presentation_holder_binding_with_resolved_lineage, OasPresentation, PresentationProof, }; pub use proof_formats::{Ed25519Signature2020Format, ProofFormat, ProofFormatId}; pub use sd_jwt_vc::{ present_sd_jwt_vc, sign_credential_sd_jwt_vc, verify_sd_jwt_vc, Disclosure, SdJwtVc, SdJwtVcHeader, SdJwtVcPayload, SdJwtVcSignOptions, }; pub use signer::{OasKeyPairSigner, OasKeyPairVerifier, Signer, Verifier, ALG_EDDSA}; pub use vc_jose::{ parse_jwt_vc, sign_credential_jwt_vc, verify_jwt_vc, JwtVc, JwtVcHeader, JwtVcPayload, JwtVcSignOptions, }; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-attestation). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-crypto (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-crypto Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-crypto.md Cryptographic primitives for the Open Agent Specification (OAS) ## Purpose [#purpose] Cryptographic primitives for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-crypto` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-crypto/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `280fefb2084ac1bd7b5ab3ef62e407570346784e3700195b646149a266411055`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "frost": [ "dep:frost-ed25519" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-crypto/src/lib.rs` [#oasoasoas-cryptosrclibrs] Source SHA-256: `d41cbcc68d6f87d9c0f487dfe80b5d398691b07a89fe2861a74728317110faaa`. ```rust pub mod derivation; pub mod encoding; pub mod error; pub mod frost; pub mod hashing; pub mod jcs; pub mod keypair; pub mod proof; pub use error::CryptoError; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-crypto). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-did (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-did Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-did.md DID parsing and validation for the Open Agent Specification (OAS) ## Purpose [#purpose] DID parsing and validation for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-did` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-did/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `02e0e677bc279913883e7f76c1998e1f21ba7bfa9fce26411015fa7503379fca`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-did/src/lib.rs` [#oasoasoas-didsrclibrs] Source SHA-256: `7d8654202dff400d34a4a1ee2e8293f14d046a389dd847b7781a7b627e945cf0`. ```rust pub mod did; pub mod error; pub mod kind; pub mod namespace; pub mod validation; pub use did::OasDid; pub use error::DidError; pub use kind::EntityKind; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-did). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-document (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-document Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-document.md OAS Identity Document types and validation for the Open Agent Specification ## Purpose [#purpose] OAS Identity Document types and validation for the Open Agent Specification [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-document` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-document/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `ef4dae55cb489bd03c118b47432cf56dc986dc3fc68a7308437556706c844b06`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-document/src/lib.rs` [#oasoasoas-documentsrclibrs] Source SHA-256: `ae6cedb59a5abc8a4b74aaa59115ee9c7fab1f715ea69bf7870a264daf7434d3`. ```rust pub mod builder; pub mod calendar; pub mod compliance; pub mod conformance; pub mod contact; pub mod document; pub mod error; pub mod governance; pub mod interop; pub mod lifecycle; pub mod lineage_section; pub mod operational; pub mod pricing; pub mod profile; pub mod proof_format; pub mod relationships; pub mod reputation; pub mod service; pub mod verification_method; pub mod visibility; pub use document::OasDocument; pub use error::DocumentError; pub use governance::{ GovernancePolicy, GovernanceSection, GovernanceTransition, GovernanceTransitionProof, }; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-document). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-lineage (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-lineage Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-lineage.md Agent lineage verification for the Open Agent Specification (OAS) ## Purpose [#purpose] Agent lineage verification for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-lineage` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-lineage/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `feae8faf45442c3bc537d0b85577e73718ca91df13be68cd4fe5d6b97a823949`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-lineage/src/lib.rs` [#oasoasoas-lineagesrclibrs] Source SHA-256: `b334f1b452eb9c64f265f349c4a530fa82ee13b20bb2827ca7476fc7e3e07177`. ```rust pub mod config; pub mod derive; pub mod error; pub mod provider; pub mod verify; pub use error::LineageError; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-lineage). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-resolve (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-resolve Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-resolve.md DID resolution for the Open Agent Specification (OAS) ## Purpose [#purpose] DID resolution for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-resolve` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-resolve/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `b04227e2ab53c65ae59a7fe060f5e3798d95d5d1abfd6e34f34ac5f5b76581de`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-resolve/src/lib.rs` [#oasoasoas-resolvesrclibrs] Source SHA-256: `cbec0de8bef5896f07fe96d25b680e99d01f120a9c7e9463ecb1a6655996d0d2`. ```rust pub mod anchored; pub mod cache; pub mod error; pub mod fallback; pub mod memory; pub mod metadata; pub mod resolver; pub use anchored::{ document_metadata_commitment, org_leaf_hash, AnchorError, AnchorRecord, AnchorStatus, AnchoredResolver, LineageAnchor, MemoryAnchor, OrgLineageRoot, }; pub use error::ResolveError; pub use anchored::{ AnchorError as GalSourceError, AnchorRecord as GalRootAnchor, AnchorStatus as GalRevocationStatus, AnchoredResolver as SigilGuardedResolver, LineageAnchor as SigilGalSource, MemoryAnchor as MemoryGalSource, OrgLineageRoot as GalOrgLineageRoot, }; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-resolve). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-sdk (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-sdk Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-sdk.md Unified SDK for the Open Agent Specification (OAS) ## Purpose [#purpose] Unified SDK for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-sdk` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-sdk/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `cd58bb9c1844091b06a1b79c1fec6ece765a04140c7d88682f4e9075c1f5d60a`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [ "resolve" ], "resolve": [ "dep:oas-resolve" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-sdk/src/lib.rs` [#oasoasoas-sdksrclibrs] Source SHA-256: `b03c0548ed311d0008bcdee9297c8dc60b2520f5090b17dc5abd3e87053e7608`. ```rust pub mod anchor_policy; pub mod attestation; pub mod config; pub mod error; pub mod identity; pub mod lineage; pub use oas_attestation as attestation_crate; pub use oas_crypto as crypto; pub use oas_did as did; pub use oas_document as document; pub use oas_lineage as lineage_crate; pub use oas_resolve as resolve; pub use error::OasError; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-sdk). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # oas-wasm (Rust) URL: https://docs.openagent.id/reference/packages/oas-oas-oas-wasm Markdown: https://docs.openagent.id/reference/packages/oas-oas-oas-wasm.md WASM compilation target for the Open Agent Specification (OAS) ## Purpose [#purpose] WASM compilation target for the Open Agent Specification (OAS) [Read the oas identity guide](/oas/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `oas-wasm` | | Version | `1.1.1` | | Language | Rust | | Runtime floor | `1.81` | | Manifest | `oas/oas/oas-wasm/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `90c78422b47eb7ef18d0e32afa5fc918dfb823ea087d6614fd5bd25701e2d56b`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `oas/oas/oas-wasm/src/lib.rs` [#oasoasoas-wasmsrclibrs] Source SHA-256: `8d2572603058d7249a6f0778adecaea168d1d4ce07764b7a36ce40c7e6b70f56`. ```rust pub mod parse_did; pub mod validate_document; pub mod verify_lineage; pub use identity_bridge::{create_hmr, create_mhr, derive_child, sign_message, verify_signature}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/oas-wasm). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/anchor-eas (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-eas-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-eas-typescript.md Ethereum Attestation Service (EAS) adapter for the OAS lineage anchor seam: resolution via EAS GraphQL, publishing via the maintained EAS SDK. ## Purpose [#purpose] Ethereum Attestation Service (EAS) adapter for the OAS lineage anchor seam: resolution via EAS GraphQL, publishing via the maintained EAS SDK. [Read the protocol adapters guide](/integrations/adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------------- | | Package | `@openagentid/anchor-eas` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/adapters/eas/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `db592e0604ac6db3177b92bfe5884689b5b784f292a8f8ad1edf2332a56cc078`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/adapters/eas/typescript/src/index.ts` [#openagent-sdkadapterseastypescriptsrcindexts] Source SHA-256: `5b3669b32db9a9bbcc16cc77c86681cd5b56debb00a78ad826847b5278f7a633`. ```typescript export const SCHEMA_STRING = export interface AnchorData { export interface AnchorRecord { export interface RevocationStatus { export function didRecipient(did: string): string { export function encodeAnchorData(data: AnchorData): Uint8Array { export interface EasResolverConfig { export class EasAnchorResolver { export interface EasPublisherConfig { export class EasAnchorPublisher { ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-adapters-eas-typescript). # openagent-http (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-http-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-http-rust.md HTTP binding for the OpenAgent Core Protocol identity flow. Axum integration, HTTP client, and discovery for agent challenge-response authentication. ## Purpose [#purpose] HTTP binding for the OpenAgent Core Protocol identity flow. Axum integration, HTTP client, and discovery for agent challenge-response authentication. [Read the protocol adapters guide](/integrations/adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-http` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/adapters/http/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `4ca366fe65bf95329299acefdb5d7c3d9746ba8c9e4b7bdd602c228946a99158`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [ "axum-integration" ], "axum-integration": [ "dep:axum", "dep:axum-core" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/adapters/http/rust/src/lib.rs` [#openagent-sdkadaptershttprustsrclibrs] Source SHA-256: `e8edfdccf52752530c137986e9048db7421eab6c4e467f7eb2573eeddc5eef63`. ```rust pub mod client; pub mod discovery; pub mod headers; pub mod server; pub mod session; pub mod transport; pub mod axum; pub use headers::{HEADER_OPENAGENT_DID, HEADER_OPENAGENT_SESSION, OPENAGENT_AUTH_SCHEME}; pub use transport::HttpTransport; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-http). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/http (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-http-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-http-typescript.md HTTP adapter for the OpenAgent Auth Protocol (OAAP). Middleware, client, and discovery for agent-to-service mutual authentication. ## Purpose [#purpose] HTTP adapter for the OpenAgent Auth Protocol (OAAP). Middleware, client, and discovery for agent-to-service mutual authentication. [Read the protocol adapters guide](/integrations/adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ----------------------------------------------------- | | Package | `@openagentid/http` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/adapters/http/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `8ddc0b86ce6740a639ef5e47a27eb98b0cadb31e84f638b90bc183ec75731a5d`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js", "require": "./dist/client.cjs" }, "./middleware": { "types": "./dist/middleware.d.ts", "import": "./dist/middleware.js", "require": "./dist/middleware.cjs" }, "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js", "require": "./dist/server.cjs" }, "./discovery": { "types": "./dist/discovery.d.ts", "import": "./dist/discovery.js", "require": "./dist/discovery.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/adapters/http/typescript/src/index.ts` [#openagent-sdkadaptershttptypescriptsrcindexts] Source SHA-256: `afe27f9a9be6735cacbaac8da89933c85a7a8afa52a16ec3ba631d7e85ad66bc`. ```typescript export { OPENAGENT_AUTH_SCHEME, HEADER_OPENAGENT_DID, HEADER_OPENAGENT_SESSION, CONTENT_TYPE_JSON, extractOpenAgentToken, buildOpenAgentHeader, } from './headers.js'; export { HttpTransport, TransportError, CHALLENGE_TYPE, canonicalChallengeBytes, identityChallengeSchema, identityVerifiedSchema, type IdentityChallenge, type IdentityProof, type IdentityVerified, type KeyType, type TrustTier, type HttpTransportConfig, } from './transport.js'; export { type ConformanceLevel, type DiscoveryDocument, discoveryDocumentSchema, WELL_KNOWN_PATH, AUTH_ENDPOINT_PATH, PROVE_ENDPOINT_PATH, fetchDiscovery, resolveAuthEndpoint, resolveProveEndpoint, } from './discovery.js'; export { DEFAULT_SESSION_TTL_SECS, DEFAULT_CHALLENGE_TTL_SECS, type ServerConfig, type SessionState, type StoredSession, type SessionStore, type VerifySignatureFn, type AuthResult, InMemorySessionStore, CoreAuthError, createServerConfig, handleDiscovery, handleChallenge, handleProve, authenticateRequest, } from './server.js'; export { type MiddlewareOptions, createOpenAgentHandler, createOpenAgentMiddleware, } from './middleware.js'; export { type ClientConfig, type SignFn, HttpAuthClient, } from './client.js'; export { AuthenticatedSession } from './session.js'; export const VERSION = '0.1.1'; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-adapters-http-typescript). # openagent-weave (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-weave Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-weave.md Weave/libp2p transport adapter for the OpenAgent Core Protocol. INFORMATIVE (Phase 2): mid-migration to the Section 15 identity flow and does not currently compile; the normative binding is HTTP. ## Purpose [#purpose] Weave/libp2p transport adapter for the OpenAgent Core Protocol. INFORMATIVE (Phase 2): mid-migration to the Section 15 identity flow and does not currently compile; the normative binding is HTTP. [Read the protocol adapters guide](/integrations/adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-weave` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/adapters/weave/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `85db4eabca334017dc870acd4f3738103f9fc11e2a2ed33aaa5b54370c281b2b`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/adapters/weave/src/lib.rs` [#openagent-sdkadaptersweavesrclibrs] Source SHA-256: `f6ff34beea33ace1e6cf696d32d2ae99a199db8044efea61e6dad53ed3b486a9`. ```rust pub mod codec; pub mod config; pub mod error; pub mod handler; pub mod peer_auth; pub mod protocol; pub mod transport; pub use config::WeaveAuthConfig; pub use error::WeaveAuthError; pub use handler::HandshakeHandler; pub use peer_auth::{PeerAuthState, PeerAuthStore}; pub use protocol::{ HandshakeRequest, HandshakeResponse, WeaveAuthBehaviour, WeaveAuthEvent, OPENAGENT_AUTH_PROTOCOL, }; pub use transport::WeaveTransport; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-weave). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-ws (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-websocket-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-adapters-websocket-rust.md WebSocket adapter for the OpenAgent Auth Protocol (OAAP) — maps the 4-step OAAP handshake onto WebSocket connections for real-time agent-to-agent communication. ## Purpose [#purpose] WebSocket adapter for the OpenAgent Auth Protocol (OAAP) — maps the 4-step OAAP handshake onto WebSocket connections for real-time agent-to-agent communication. [Read the protocol adapters guide](/integrations/adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | -------------------------------------------------- | | Package | `openagent-ws` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/adapters/websocket/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `b14d989c376e478d68d6267ebde47907345cae24915064b17e43e99ffdd80ffe`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/adapters/websocket/rust/src/lib.rs` [#openagent-sdkadapterswebsocketrustsrclibrs] Source SHA-256: `d6f1fc27284f118a123a7d0274dbc44542c94225a3b7b5c1dd2635d6276c4348`. ```rust pub mod client; pub mod error; pub mod frame; pub mod server; pub mod session; pub mod transport; pub use client::OpenAgentWsClient; pub use error::{Result, WsError}; pub use server::OpenAgentWsHandler; pub use session::AuthenticatedSession; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-ws). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-oidc (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-oidc-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-oidc-rust.md OIDC/OAuth2 bridge for OpenAgent SDK — maps between human OIDC tokens and OAS agent DIDs + Arsenal capability tokens. ## Purpose [#purpose] OIDC/OAuth2 bridge for OpenAgent SDK — maps between human OIDC tokens and OAS agent DIDs + Arsenal capability tokens. [Read the identity bridges guide](/integrations/bridges). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-oidc` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/bridges/oidc/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `d477cbd59aeb5163e1e399a23777c0edfdec7b5a27c67bf81806f7e378586374`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/bridges/oidc/rust/src/lib.rs` [#openagent-sdkbridgesoidcrustsrclibrs] Source SHA-256: `e1b78269f34977b6ddbd8eb3685e0ace43ad061c633423ab5684a6c3f88bc039`. ```rust pub mod bridge; pub mod config; pub mod discovery; pub mod error; pub mod exchange; pub mod jwks; pub mod jwt; pub mod mapping; pub use bridge::OidcBridge; pub use config::{OidcConfig, ProviderConfig}; pub use error::{OidcBridgeError, Result}; pub use exchange::{TokenExchangeRequest, TokenExchangeResponse}; pub use jwt::{ActJwtClaims, ValidatedClaims}; pub use mapping::DerivedAgent; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-oidc). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/oidc (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-oidc-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-oidc-typescript.md OIDC/OAuth2 bridge for OpenAgent SDK — maps between human OIDC tokens and OAS agent DIDs + Arsenal capability tokens. ## Purpose [#purpose] OIDC/OAuth2 bridge for OpenAgent SDK — maps between human OIDC tokens and OAS agent DIDs + Arsenal capability tokens. [Read the identity bridges guide](/integrations/bridges). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------------- | | Package | `@openagentid/oidc` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/bridges/oidc/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `23e5c0df27516de6e99bb7e1b970502ce699d6951a9b1db5c94f8ec8353ce2d1`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/bridges/oidc/typescript/src/index.ts` [#openagent-sdkbridgesoidctypescriptsrcindexts] Source SHA-256: `ef63062f0c57544bacfe0196199a7cb142c24aa896c35229cc0b303f9cd8f0ed`. ```typescript export { OidcBridge } from './bridge.js'; export { type ProviderConfig, type OidcConfig, type SingleProviderInput, providerConfigSchema, oidcConfigSchema, singleProviderConfig, findProvider, resolveFetch, } from './config.js'; export { type DiscoveryDocument, DiscoveryClient, discoveryDocumentSchema, wellKnownUrl, } from './discovery.js'; export { OidcBridgeError, type OidcErrorCode } from './errors.js'; export { type TokenExchangeRequest, type TokenExchangeResponse, type TokenExchangeError, tokenExchangeRequestSchema, GRANT_TYPE_TOKEN_EXCHANGE, TOKEN_TYPE_JWT, TOKEN_TYPE_ACT, TOKEN_TYPE_ACCESS, createJwtToActRequest, validateExchangeRequest, parseScopes, successResponse, exchangeErrors, } from './exchange.js'; export { JwksClient } from './jwks.js'; export { type ValidatedClaims, type ActJwtClaims, decodeJwtHeader, extractUnverifiedIssuer, validateJwt, buildActClaims, signActJwt, } from './jwt.js'; export { type DerivedAgent, deriveAgentFromClaims, hmrIdentifierFromClaims, mapScopes, } from './mapping.js'; export const VERSION = '0.1.1'; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-bridges-oidc-typescript). # openagent-scim (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-scim-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-scim-rust.md SCIM 2.0 provisioning bridge trait definitions for OpenAgent — enterprise agent lifecycle via RFC 7644 ## Purpose [#purpose] SCIM 2.0 provisioning bridge trait definitions for OpenAgent — enterprise agent lifecycle via RFC 7644 [Read the identity bridges guide](/integrations/bridges). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-scim` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/bridges/scim/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `44c150150afe8d7a70dc318c0fe539530464dcbc228c5f97c58fdf0439fd2fb2`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/bridges/scim/rust/src/lib.rs` [#openagent-sdkbridgesscimrustsrclibrs] Source SHA-256: `67ea054f3b8534db37953673131ee30641cdcf2978c96438d9a814c5123bd6f5`. ```rust pub mod mapping; pub mod types; pub enum ScimError { pub type ScimResult = Result; pub trait AgentStore: Send + Sync { pub trait DidRevoker: Send + Sync { pub trait DelegationCascadeRevoker: Send + Sync { pub trait ArsenalSessionInvalidator: Send + Sync { pub trait AuditSink: Send + Sync { pub trait ScimProvisioner: Send + Sync { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-scim). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/scim (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-scim-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-bridges-scim-typescript.md SCIM 2.0 provisioning bridge for OpenAgent — enterprise agent lifecycle via RFC 7644 ## Purpose [#purpose] SCIM 2.0 provisioning bridge for OpenAgent — enterprise agent lifecycle via RFC 7644 [Read the identity bridges guide](/integrations/bridges). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------------- | | Package | `@openagentid/scim` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/bridges/scim/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `3757b2dae4a9574dc1e60d5a4ef87ee54061954b420a79fc4b3c9f8b169e6e3d`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/bridges/scim/typescript/src/index.ts` [#openagent-sdkbridgesscimtypescriptsrcindexts] Source SHA-256: `3d2796fa42698240f6e77f22ac7c6a48f3fe399003489532481d3add91649d1a`. ```typescript export { createScimRouter, type ScimRouter, type ScimRouterConfig } from './server.js'; export { type ScimBridgeConfig, type ResolvedScimConfig, type Logger, resolveScimConfig, silentLogger, } from './config.js'; export { SCIM_USER_SCHEMA, OPENAGENT_AGENT_SCHEMA, SCIM_LIST_RESPONSE_SCHEMA, SCIM_ERROR_SCHEMA, SCIM_PATCH_OP_SCHEMA, SCIM_SPC_SCHEMA, SCIM_SCHEMA_SCHEMA, SCIM_RESOURCE_TYPE_SCHEMA, type ConformanceLevel, type AgentExtension, type ScimAgentResource, type ScimMeta, type ScimListResponse, type ScimErrorResponse, buildServiceProviderConfig, buildSchemas, buildResourceTypes, } from './schemas.js'; export { type AgentRecord, type CreateAgentFromScimInput, type ReplaceAgentFromScimInput, agentToScimResource, parseCreateInput, parseReplaceInput, createAgentFromScimSchema, } from './resources.js'; export { type ParsedFilter, type AttributeFilter, type LogicalFilter, type FilterOp, parseFilter, matchesFilter, ScimFilterError, } from './filtering.js'; export { type PaginationParams, parsePagination, paginateResults, } from './pagination.js'; export { type PatchOperation, type PatchRequest, parsePatchRequest, applyPatchOperations, ScimPatchError, } from './operations.js'; export { AgentProvisioner, type ProvisionerConfig, type CreateAgentParams, type AuditEvent, type AuditSink, type DidRevoker, type DelegationCascadeRevoker, type ArsenalSessionInvalidator, ProvisionerError, } from './provisioner.js'; export { type AgentStore, InMemoryAgentStore, StoreError, type StoreErrorCode, } from './store.js'; export const VERSION = '0.1.1'; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-bridges-scim-typescript). # conformance-runner (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-conformance-runner-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-conformance-runner-rust.md OpenAgent SDK conformance test runner (Rust) — loads JSON vectors and diffs against the reference Rust crypto stack ## Purpose [#purpose] OpenAgent SDK conformance test runner (Rust) — loads JSON vectors and diffs against the reference Rust crypto stack [Read the testing and conformance guide](/features/conformance). ## Source contract [#source-contract] | Field | Value | | ------------- | -------------------------------------------------- | | Package | `conformance-runner` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `None` | | Manifest | `openagent-sdk/conformance/runner-rust/Cargo.toml` | | Distribution | Internal/private source package | Manifest SHA-256: `a40c633c72bf531a20df169f4b6b2b9d7dd2e04b7f353e0b47ae4e837e1f81a0`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/conformance/runner-rust/src/main.rs` [#openagent-sdkconformancerunner-rustsrcmainrs] Source SHA-256: `1dffdfbc904c3359ca70e611476fe94ad17880ad58cb1b3a34f8e8a13e49e673`. This entry point composes the application or reuses implementation modules; inspect the source file and task guide for its callable boundary. ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/conformance-runner). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/conformance-runner (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-conformance-runner-ts Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-conformance-runner-ts.md OpenAgent SDK conformance test runner (TypeScript) — loads JSON vectors and diffs against the Node TS reference stack ## Purpose [#purpose] OpenAgent SDK conformance test runner (TypeScript) — loads JSON vectors and diffs against the Node TS reference stack [Read the testing and conformance guide](/features/conformance). ## Source contract [#source-contract] | Field | Value | | ------------- | -------------------------------------------------- | | Package | `@openagentid/conformance-runner` | | Version | `0.1.0` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/conformance/runner-ts/package.json` | | Distribution | Internal/private source package | Manifest SHA-256: `e4c5bfe587f2492752780e33458dda03e0f455205d9f24801a113da59e5b8742`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. This package is a build/deployment configuration or uses a nonstandard entry path. Its manifest is the authoritative boundary; consult the task guide before running it. # openagent-auth-protocol (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-auth-protocol Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-auth-protocol.md Transport-agnostic type layer for the OpenAgent Core Protocol identity flow (challenge-response authentication, Core Protocol Specification Section 15). ## Purpose [#purpose] Transport-agnostic type layer for the OpenAgent Core Protocol identity flow (challenge-response authentication, Core Protocol Specification Section 15). [Read the authentication protocol guide](/features/auth-protocol). ## Source contract [#source-contract] | Field | Value | | ------------- | --------------------------------------------------------- | | Package | `openagent-auth-protocol` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/crates/openagent-auth-protocol/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `a1066943a0b5ed5bc298e444fc9d7912f4f00896e2ab0a10d77ea9d208361f81`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/crates/openagent-auth-protocol/src/lib.rs` [#openagent-sdkcratesopenagent-auth-protocolsrclibrs] Source SHA-256: `986125777224d8b43f4ca1fb0a3c2b107512be4c4fcd1b8eabd61e27f3c4d240`. ```rust pub mod error; pub mod handshake; pub mod message; pub mod session; pub mod transport; pub mod types; pub use error::AuthProtocolError; pub use message::{ IdentityChallenge, IdentityProof, IdentityVerified, KeyType, TrustTier, CHALLENGE_TYPE, }; pub use session::{InMemorySessionStore, Session, SessionId, SessionState, SessionStore}; pub use transport::AuthTransport; pub use types::{ConformanceLevel, DidDocument, DiscoveryDocument, LineageLink, LineageProof}; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-auth-protocol). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/crypto-wasm (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-crypto-wasm-pkg Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-crypto-wasm-pkg.md Foundational WASM crypto primitives for OpenAgent, Arsenal, AEGIS, and OAS SDKs — one source of truth for Rust and TypeScript cryptographic correctness. ## Purpose [#purpose] Foundational WASM crypto primitives for OpenAgent, Arsenal, AEGIS, and OAS SDKs — one source of truth for Rust and TypeScript cryptographic correctness. [Read the cryptographic binding guide](/sdk/typescript). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------------------- | | Package | `@openagentid/crypto-wasm` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/crates/openagent-crypto-wasm/pkg/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `9c804c0cebbbdf81a73a8eb86450123f1935ae0d48800a9c4be560bac73b93cb`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./openagent_crypto_wasm.d.ts", "node": "./node/openagent_crypto_wasm.js", "default": "./openagent_crypto_wasm.js" }, "./package.json": "./package.json" } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. This package is a build/deployment configuration or uses a nonstandard entry path. Its manifest is the authoritative boundary; consult the task guide before running it. # openagent-crypto-wasm (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-crypto-wasm Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-crypto-wasm.md Foundational WASM crypto primitives for OpenAgent, Arsenal, AEGIS, and OAS SDKs — one source of truth for Rust and TypeScript cryptographic correctness. ## Purpose [#purpose] Foundational WASM crypto primitives for OpenAgent, Arsenal, AEGIS, and OAS SDKs — one source of truth for Rust and TypeScript cryptographic correctness. [Read the cryptographic binding guide](/sdk/typescript). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------------- | | Package | `openagent-crypto-wasm` | | Version | `0.1.1` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/crates/openagent-crypto-wasm/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `7c4b2c23aef85fbd0d656f781ad172d871135be3f647e43fac938173c02bc10a`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [ "native" ], "native": [], "wasm": [ "dep:wasm-bindgen", "dep:js-sys", "getrandom/js" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/crates/openagent-crypto-wasm/src/lib.rs` [#openagent-sdkcratesopenagent-crypto-wasmsrclibrs] Source SHA-256: `ca7f8f0e1dcb8f5effbb78f617609f811f8d519ada03695de6199cebdbf2ce9d`. ```rust pub mod aead; pub mod blake3_hash; pub mod ct; pub mod ed25519; pub mod encoding; pub mod error; pub mod frost; pub mod hkdf_sha256; pub mod jcs; pub mod kdf_password; pub mod sha; pub mod x25519; pub mod wasm_api; pub use error::CryptoError; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-crypto-wasm). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-skills-policy (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-skills-policy-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-skills-policy-rust.md Governance policy engine for agent skills — an Arsenal-composed policy layer that gates which SKILLS.md entries an agent may invoke, with rate limiting, argument constraints, time windows, consent, and hash-chained audit receipts. ## Purpose [#purpose] Governance policy engine for agent skills — an Arsenal-composed policy layer that gates which SKILLS.md entries an agent may invoke, with rate limiting, argument constraints, time windows, consent, and hash-chained audit receipts. [Read the skills policy guide](/features/skills-governance). ## Source contract [#source-contract] | Field | Value | | ------------- | -------------------------------------------------------------- | | Package | `openagent-skills-policy` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/crates/openagent-skills-policy/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `52b6461c520f0bc2587100211d795ba6d4f8e934b8241ee9337fad6354ee17d9`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/crates/openagent-skills-policy/rust/src/lib.rs` [#openagent-sdkcratesopenagent-skills-policyrustsrclibrs] Source SHA-256: `6523cde71371235b5d154fb57f0ef3abba4272d7bb7702c13ea1e3cdf6648685`. ```rust pub mod audit; pub mod did; pub mod engine; pub mod error; pub mod policy; pub mod rate; pub mod skills_md; pub use audit::{AuditChain, HashHex, Receipt}; pub use did::Did; pub use engine::{arsenal_error_from, InvocationContext, SkillsPolicy}; pub use error::{Result, SkillsPolicyError}; pub use policy::{ AuditLevel, DefaultRule, RateLimit, SkillRule, SkillsPolicyDoc, TimeWindow, CURRENT_VERSION, MAX_SKILL_RULES, }; pub use skills_md::{SkillEntry, SkillsManifest}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-skills-policy). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/skills-policy (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-skills-policy-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-crates-openagent-skills-policy-typescript.md Governance for agent skills — a specialized Arsenal policy that gates which SKILLS.md entries an agent may invoke, with rate limiting, argument constraints, time windows, consent, and hash-chained audit receipts. ## Purpose [#purpose] Governance for agent skills — a specialized Arsenal policy that gates which SKILLS.md entries an agent may invoke, with rate limiting, argument constraints, time windows, consent, and hash-chained audit receipts. [Read the skills policy guide](/features/skills-governance). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------------------------------- | | Package | `@openagentid/skills-policy` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/crates/openagent-skills-policy/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `722a94f6f21a20d6b2eeb922f09468483f466028d415fd53b61c27fd29d68d64`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/crates/openagent-skills-policy/typescript/src/index.ts` [#openagent-sdkcratesopenagent-skills-policytypescriptsrcindexts] Source SHA-256: `c1907919466729c24cc00553a48156bd77aa6c6d36b77b9a695ab38880e5395f`. ```typescript export { AuditChain, type Receipt, HASH_LEN } from "./audit.js"; export { Did } from "./did.js"; export { InvocationContext, SkillsPolicy } from "./engine.js"; export { ArgumentConstraintError, ConsentRequiredError, InvalidPolicyError, InvalidSkillsMarkdownError, NotAllowedError, OutsideTimeWindowError, RateLimitExceededError, SkillsPolicyError, } from "./errors.js"; export { RateLimiter, type RateLimitDecision } from "./rate.js"; export { type AuditLevel, CURRENT_VERSION, type DefaultRule, MAX_SKILL_RULES, type RateLimit, type SkillRule, type SkillsPolicyDoc, type TimeWindow, } from "./schema.js"; export { type SkillEntry, SkillsManifest } from "./skillsMd.js"; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-crates-openagent-skills-policy-typescript). # openagent-aws-lambda (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-aws-lambda Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-aws-lambda.md Deployment adapters source package and exported entry points. ## Purpose [#purpose] Deployment adapters package. See the linked task guide for its role in the integration. [Read the deployment adapters guide](/features/deployment-adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------- | | Package | `openagent-aws-lambda` | | Version | `0.1.0` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/deploy/aws-lambda/package.json` | | Distribution | Internal/private source package | Manifest SHA-256: `0cdeb7b22dd2ecd25e35c0c248fe0cd5fe4df1a81dca60b31b3f524c2914c35c`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. This package is a build/deployment configuration or uses a nonstandard entry path. Its manifest is the authoritative boundary; consult the task guide before running it. # openagent-cloudflare-worker (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-cloudflare-worker Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-cloudflare-worker.md Deployment adapters source package and exported entry points. ## Purpose [#purpose] Deployment adapters package. See the linked task guide for its role in the integration. [Read the deployment adapters guide](/features/deployment-adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ----------------------------------------------------- | | Package | `openagent-cloudflare-worker` | | Version | `0.1.0` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/deploy/cloudflare-worker/package.json` | | Distribution | Internal/private source package | Manifest SHA-256: `54f241083db9c1194e2e754a89e37b0c5e44c522f24fbb09bf649a32d1ef6b3d`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. This package is a build/deployment configuration or uses a nonstandard entry path. Its manifest is the authoritative boundary; consult the task guide before running it. # openagent-docker (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-docker Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-docker.md Deployment adapters source package and exported entry points. ## Purpose [#purpose] Deployment adapters package. See the linked task guide for its role in the integration. [Read the deployment adapters guide](/features/deployment-adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------ | | Package | `openagent-docker` | | Version | `0.1.0` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/deploy/docker/package.json` | | Distribution | Internal/private source package | Manifest SHA-256: `a4829acd40fa0d57fbe6a271a48e1ccc5574a5e5606ad080f790bfc7e6372fb7`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. This package is a build/deployment configuration or uses a nonstandard entry path. Its manifest is the authoritative boundary; consult the task guide before running it. # openagent-vercel-edge (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-vercel-edge Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-deploy-vercel-edge.md Deployment adapters source package and exported entry points. ## Purpose [#purpose] Deployment adapters package. See the linked task guide for its role in the integration. [Read the deployment adapters guide](/features/deployment-adapters). ## Source contract [#source-contract] | Field | Value | | ------------- | ----------------------------------------------- | | Package | `openagent-vercel-edge` | | Version | `0.1.0` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/deploy/vercel-edge/package.json` | | Distribution | Internal/private source package | Manifest SHA-256: `9602da3960d1aa66481aa07acefb3f18a2498334286dbfe9ba083bbf6e02526b`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. This package is a build/deployment configuration or uses a nonstandard entry path. Its manifest is the authoritative boundary; consult the task guide before running it. # openagent-claude-agent (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-claude-agent-sdk-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-claude-agent-sdk-rust.md OpenAgent identity, capability control, and tamper-evident audit hooks for the Claude Agent SDK. Framework-agnostic Rust trait surface — the TypeScript package is the reference integration; this crate lets any Rust agent harness adopt the same lifecycle contracts. ## Purpose [#purpose] OpenAgent identity, capability control, and tamper-evident audit hooks for the Claude Agent SDK. Framework-agnostic Rust trait surface — the TypeScript package is the reference integration; this crate lets any Rust agent harness adopt the same lifecycle contracts. [Read the framework integrations guide](/integrations/frameworks). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------------------- | | Package | `openagent-claude-agent` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/integrations/claude-agent-sdk/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `c0f0a76ddbfc1f48b105a5a3b87fdd57a8e01b82fb63169384d6e2a3bb09153a`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [ "std" ], "std": [], "skills-policy": [ "dep:openagent-skills-policy" ], "openagent-full": [ "openagent-sdk/full" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/integrations/claude-agent-sdk/rust/src/lib.rs` [#openagent-sdkintegrationsclaude-agent-sdkrustsrclibrs] Source SHA-256: `e8f91183afd16d5b68e4263a8ac0e6b53399b2e83daea317c8758d1f22ac7e51`. ```rust pub mod audit; pub mod error; pub mod hash; pub mod hooks; pub mod identity; pub mod plugin; pub mod policy; pub use error::Error; pub use hooks::{HookContext, OpenAgentHooks}; pub use plugin::{OpenAgentPlugin, PluginConfig}; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-claude-agent). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/claude-agent (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-claude-agent-sdk-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-claude-agent-sdk-typescript.md OpenAgent identity, capability control, and audit for the Claude Agent SDK — drop-in plugin that gives any Claude agent a verified did:oas:* identity, scoped credential access, and tamper-evident audit logging. ## Purpose [#purpose] OpenAgent identity, capability control, and audit for the Claude Agent SDK — drop-in plugin that gives any Claude agent a verified did:oas:\* identity, scoped credential access, and tamper-evident audit logging. [Read the framework integrations guide](/integrations/frameworks). ## Source contract [#source-contract] | Field | Value | | ------------- | --------------------------------------------------------------------- | | Package | `@openagentid/claude-agent` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/integrations/claude-agent-sdk/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `1cfcbd712df43906c5b1f876637c30c9ad551865c3406d1a0d3a19a31c4f7fb2`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./hooks": { "types": "./dist/hooks.d.ts", "import": "./dist/hooks.js", "require": "./dist/hooks.cjs" }, "./policy": { "types": "./dist/policy.d.ts", "import": "./dist/policy.js", "require": "./dist/policy.cjs" }, "./audit": { "types": "./dist/audit.d.ts", "import": "./dist/audit.js", "require": "./dist/audit.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/integrations/claude-agent-sdk/typescript/src/index.ts` [#openagent-sdkintegrationsclaude-agent-sdktypescriptsrcindexts] Source SHA-256: `d6a7837693692515edc68f9f4473fc1e6dcd90acadd7345c8d26548627ff2ccd`. ```typescript export { openAgentPlugin, type OpenAgentPlugin, type OpenAgentPluginOptions, type PluginHooks, type HookDecision, } from './plugin.js'; export { AuditChain, ConsoleAuditSink, FanOutAuditSink, GENESIS_PREV_HASH, InMemoryAuditSink, hashRecord, verifyChain, } from './audit.js'; export { AllowListSkillsPolicy, CompositeSkillsPolicy, DenyUnlessScopedSkillsPolicy, SKILL_SCOPE_PREFIX, StaticCapabilityChecker, TOOL_SCOPE_PREFIX, skillScope, toolScope, } from './policy.js'; export { onMessage, onSessionEnd, onSessionStart, onSkillInvoke, onSkillInvokeOrThrow, postToolUse, preToolUse, preToolUseOrThrow, type HookContext, type MessageInput, type OnMessageResult, type PostToolUseInput, type PreToolUseResult, type SessionStartInput, type SessionStartResult, type SkillInvokeInput, type SkillInvokeResult, type ToolUseInput, } from './hooks.js'; export { ConfigError, PluginError, PluginErrorCode, type PluginErrorCodeValue, SkillDeniedError, ToolDeniedError, } from './errors.js'; export type { export { canonicalJson, getHashAlgo, hashHex } from './hash.js'; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-integrations-claude-agent-sdk-typescript). # openagent-mcp (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-mcp-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-mcp-rust.md OpenAgent middleware for the Model Context Protocol — adds OAS identity, Arsenal capability tokens, and AEGIS authorization to any rmcp server in three lines. ## Purpose [#purpose] OpenAgent middleware for the Model Context Protocol — adds OAS identity, Arsenal capability tokens, and AEGIS authorization to any rmcp server in three lines. [Read the framework integrations guide](/integrations/frameworks). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-mcp` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/integrations/mcp/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `079021b882153a3cabef5101684aded2621376e9b3ab6d2b4d26cb1e845d364e`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "rmcp": [ "dep:rmcp" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/integrations/mcp/rust/src/lib.rs` [#openagent-sdkintegrationsmcprustsrclibrs] Source SHA-256: `11aff0aa5e83e1a0673b1faf7ed5fb90ca60cb9637f517d3e53e152186cbce35`. ```rust pub use rmcp_adapter::RmcpOpenAgent; pub use errors::{McpAuthError, McpErrorCode}; pub use handler::{ InMemoryToolHandler, RegisteredTool, ToolCall, ToolHandler, ToolResult, WithOpenAgent, WrappedHandler, }; pub use middleware::{OpenAgentMiddleware, default_require_scopes, default_scope_format}; pub use skills::{ InMemorySkillsStore, SkillsPolicy, SkillsPolicyDecision, SkillsRule, SkillsStore, DEFAULT_SKILL_TOOL_NAMES, }; pub use types::{ Agent, AuditMeta, Config, ErrorHook, Identity, IdentityVerifier, PostCallHook, PreCallHook, ScopeDeriver, VerifiedIdentity, }; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-mcp). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # @openagentid/mcp (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-mcp-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-integrations-mcp-typescript.md OpenAgent middleware for the Model Context Protocol — adds OAS identity, Arsenal capability tokens, and AEGIS authorization to any MCP server in three lines. ## Purpose [#purpose] OpenAgent middleware for the Model Context Protocol — adds OAS identity, Arsenal capability tokens, and AEGIS authorization to any MCP server in three lines. [Read the framework integrations guide](/integrations/frameworks). ## Source contract [#source-contract] | Field | Value | | ------------- | -------------------------------------------------------- | | Package | `@openagentid/mcp` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/integrations/mcp/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `bab36ae7191a98df2ad143c0a25123c1b8a3a65483e16bd6c9b20ee23efd9241`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js", "require": "./dist/server.cjs" }, "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js", "require": "./dist/client.cjs" }, "./errors": { "types": "./dist/errors.d.ts", "import": "./dist/errors.js", "require": "./dist/errors.cjs" }, "./skills": { "types": "./dist/skills.d.ts", "import": "./dist/skills.js", "require": "./dist/skills.cjs" }, "./types": { "types": "./dist/types.d.ts", "import": "./dist/types.js", "require": "./dist/types.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/integrations/mcp/typescript/src/index.ts` [#openagent-sdkintegrationsmcptypescriptsrcindexts] Source SHA-256: `5e5b7a231d0c70ff56167177dbf79163852b505707ca6b8b12eb3afab2f393ba`. ```typescript export { withOpenAgent, ANONYMOUS_IDENTITY, } from './server.js'; export type { McpServerLike } from './server.js'; export { withOpenAgentClient, buildIdentityMeta, } from './client.js'; export type { McpClientLike, OpenAgentClientConfig } from './client.js'; export { OpenAgentMcpError, MissingIdentityError, IdentityVerificationError, AuthorizationDeniedError, SkillsPolicyDeniedError, McpErrorCode, } from './errors.js'; export type { McpErrorCodeValue } from './errors.js'; export { createSkillsPolicy, combineSkillsPolicies, InMemorySkillsPolicyStore, DEFAULT_SKILL_TOOL_NAMES, } from './skills.js'; export type { export type { export { defaultRequireScopes, defaultScopeFormat } from './types.js'; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-integrations-mcp-typescript). # create-openagent (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-packages-create-openagent Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-packages-create-openagent.md Scaffold an OpenAgent project — agent, MCP server, web dashboard, or full-stack. ## Purpose [#purpose] Scaffold an OpenAgent project — agent, MCP server, web dashboard, or full-stack. [Read the scaffolding guide](/integrations/frameworks). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------------ | | Package | `create-openagent` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/packages/create-openagent/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `def40a99cf13a207d559132fb96729d2e55dc8d12da635dca677ccd5f9eb188b`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/packages/create-openagent/src/index.ts` [#openagent-sdkpackagescreate-openagentsrcindexts] Source SHA-256: `26eac891847bd5845ce32531abcc6668d8ab47bcd969937f740e436785ddf187`. This entry point composes the application or reuses implementation modules; inspect the source file and task guide for its callable boundary. ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-packages-create-openagent). # github.com/OpenAgentID/openagent-sdk-go (Go) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-go Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-go.md Unified SDKs source package and exported entry points. ## Purpose [#purpose] Unified SDKs package. See the linked task guide for its role in the integration. [Read the unified sdks guide](/sdk/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `github.com/OpenAgentID/openagent-sdk-go` | | Version | `source module` | | Language | Go | | Runtime floor | `1.26.4` | | Manifest | `openagent-sdk/sdks/go/go.mod` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `13e2f796805005c24f3b85d1ac20dc83dd83fe88dcddfd03925305914efba25c`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/go/openagent/act.go` [#openagent-sdksdksgoopenagentactgo] Source SHA-256: `163b522ae1f48fb9cc9ef2405e444b6d7574815ad53215772152ab6f50221ff0`. ```go const FormatVersion const AlgorithmEd25519 const MaxActBytes type ActClaims struct type ActEnvelope struct func DecodeEnvelope(token []byte) (*ActEnvelope, error) type Verifier struct func NewVerifier(trustedKeys [][]byte, issuer, audience string) (*Verifier, error) func (v *Verifier) WithClock(nowUnixSeconds int64) *Verifier func (v *Verifier) WithLeeway(seconds int64) *Verifier func (v *Verifier) RequiringScopes(scopes ...Scope) *Verifier func (v *Verifier) Verify(token []byte) (*ActClaims, error) func (c *ActClaims) UnmarshalCBOR(data []byte) error func DecodeUnverified(token []byte) (*ActClaims, bool) ``` ### `openagent-sdk/sdks/go/openagent/builder.go` [#openagent-sdksdksgoopenagentbuildergo] Source SHA-256: `57ed39ad7532be7f3d8f1b2f78c97ae3015df16583ac9aa4ed48ecbb8264f4f0`. ```go type VerifyBuilder struct func Verify(token []byte) *VerifyBuilder func (b *VerifyBuilder) Issuer(iss string) *VerifyBuilder func (b *VerifyBuilder) ForAudience(audience string) *VerifyBuilder func (b *VerifyBuilder) TrustedKeys(keys ...[]byte) *VerifyBuilder func (b *VerifyBuilder) RequireScope(scope Scope) *VerifyBuilder func (b *VerifyBuilder) WithLeeway(seconds int64) *VerifyBuilder func (b *VerifyBuilder) AtTime(unixSeconds int64) *VerifyBuilder func (b *VerifyBuilder) Run() (*ActClaims, error) ``` ### `openagent-sdk/sdks/go/openagent/errors.go` [#openagent-sdksdksgoopenagenterrorsgo] Source SHA-256: `e36b0830b63ebd0794203eae038df34763ea15ff445b757c60762fbc72f3d66f`. ```go type ActError struct func (e *ActError) Error() string type ConfigError struct func (e *ConfigError) Error() string ``` ### `openagent-sdk/sdks/go/openagent/keys.go` [#openagent-sdksdksgoopenagentkeysgo] Source SHA-256: `695029be63540453b28ade5a6001d59ce5cc3761287433cf592ceb70cfea17a5`. ```go const EncryptionDeriveContext type AgentKeys struct func KeysFromSeed(seed [32]byte) (*AgentKeys, error) func GenerateKeys() (*AgentKeys, error) func KeysFromSeedHex(hexSeed string) (*AgentKeys, error) func KeysFromEnv(envVar string) (*AgentKeys, error) func SaveSeed(keys *AgentKeys, path string) error func KeysFromSeedFile(path string) (*AgentKeys, error) func SeedHex(seed [32]byte) string ``` ### `openagent-sdk/sdks/go/openagent/middleware.go` [#openagent-sdksdksgoopenagentmiddlewarego] Source SHA-256: `467e40f3e0195cbadbb22bfcc80c8549b7b3b88feff4da33f7cc6c14300ef3e4`. ```go type ClaimsContextKey struct func RequireAct(verifier *Verifier, scopes ...Scope) func(http.Handler) http.Handler func RequireActFunc(verifier *Verifier, next http.HandlerFunc, scopes ...Scope) http.HandlerFunc func ClaimsFromRequest(r *http.Request) *ActClaims ``` ### `openagent-sdk/sdks/go/openagent/scope.go` [#openagent-sdksdksgoopenagentscopego] Source SHA-256: `82c0149cb34b7bc3bde8b3550c89f595961ee805439844dad4e9337a4ab9c856`. ```go const ScopeSegments const Wildcard type Scope struct func ParseScope(text string) (Scope, error) func (s Scope) Covers(requested Scope) bool func (s Scope) String() string ``` # id.openagent:openagent-sdk (Kotlin) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-kotlin Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-kotlin.md Unified SDKs source package and exported entry points. ## Purpose [#purpose] Unified SDKs package. See the linked task guide for its role in the integration. [Read the unified sdks guide](/sdk/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `id.openagent:openagent-sdk` | | Version | `0.1.0` | | Language | Kotlin | | Runtime floor | `JVM 17 / Kotlin 2.1.0` | | Manifest | `openagent-sdk/sdks/kotlin/build.gradle.kts` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `6121fcc8a39d99568cb17d3a4c9f515cf106a4bf4ad67196a14ccada5c57c2b2`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/kotlin/src/main/kotlin/id/openagent/sdk/Act.kt` [#openagent-sdksdkskotlinsrcmainkotlinidopenagentsdkactkt] Source SHA-256: `aac0a36eb4da201a849f7fbde56b007edf7fd7e53fa6c75532011165c747ae1f`. ```kotlin public object Act { public const val FORMAT_VERSION: Int = 1 public const val ALGORITHM_ED25519: String = "Ed25519" public const val MAX_ACT_BYTES: Int = 16 * 1024 public data class Claims( public data class Envelope( public fun decode(token: ByteArray): Envelope { public class Verifier( public val expectedIssuer: String, public val expectedAudience: String, public fun requiringScopes(scopes: List): Verifier = public fun withClock(nowUnixSeconds: Long): Verifier = public fun verify(token: ByteArray): Claims { public fun decodeUnverified(token: ByteArray): Claims? { ``` ### `openagent-sdk/sdks/kotlin/src/main/kotlin/id/openagent/sdk/Cbor.kt` [#openagent-sdksdkskotlinsrcmainkotlinidopenagentsdkcborkt] Source SHA-256: `bb753f89a2defadb8843cbfbd41b4646b4aa01612e658f1a626541021b52723f`. This entry point composes the application or reuses implementation modules; inspect the source file and task guide for its callable boundary. ### `openagent-sdk/sdks/kotlin/src/main/kotlin/id/openagent/sdk/Errors.kt` [#openagent-sdksdkskotlinsrcmainkotlinidopenagentsdkerrorskt] Source SHA-256: `eb339f7e1a22fbedabe3e39d498aa7caf8d36731523741dbc234449ac896652c`. ```kotlin public class Config(detail: String) : OpenAgentError("config error: $detail") public class TooLarge(size: Int, maximum: Int) : public class EnvelopeDecode(detail: String) : OpenAgentError("envelope decode failed: $detail") public class UnsupportedVersion(version: Int) : public class UnsupportedAlgorithm(alg: String) : public class MalformedSignature(detail: String) : OpenAgentError("malformed signature: $detail") public class SignatureInvalid(trustedKeyCount: Int) : public class ClaimsDecode(detail: String) : OpenAgentError("invalid claim set: $detail") public class Expired(exp: Long, now: Long) : OpenAgentError("token expired at $exp (now $now)") public class NotYetValid(nbf: Long, now: Long) : public class IssuerMismatch(expected: String, actual: String) : public class AudienceMismatch(expected: String) : public class MissingScope(scope: String) : OpenAgentError("missing required scope: $scope") public class MalformedScope(scope: String, reason: String) : ``` ### `openagent-sdk/sdks/kotlin/src/main/kotlin/id/openagent/sdk/Keys.kt` [#openagent-sdksdkskotlinsrcmainkotlinidopenagentsdkkeyskt] Source SHA-256: `dd8c91c439923eb593cf259c0996bfd2c080dc35fe641a9b8e967b20c0a99da4`. ```kotlin public object Keys { public data class AgentKeys( public fun sign(message: ByteArray): ByteArray { public fun verify(message: ByteArray, signature: ByteArray): Boolean { public fun fromSeed(seed: ByteArray): AgentKeys { public fun generate(): AgentKeys { public fun fromSeedHex(hexSeed: String): AgentKeys { public fun fromEnv(envVar: String): AgentKeys { public fun saveSeed(keys: AgentKeys, path: Path) { public fun fromSeedFile(path: Path): AgentKeys = fromSeed(Files.readAllBytes(path)) public fun seedToHex(seed: ByteArray): String = ``` ### `openagent-sdk/sdks/kotlin/src/main/kotlin/id/openagent/sdk/Ktor.kt` [#openagent-sdksdkskotlinsrcmainkotlinidopenagentsdkktorkt] Source SHA-256: `4f873085a32ecf225237d843c1d219b8647bf560a88f48fbd891e6d8690db7c6`. ```kotlin public val ActClaimsKey: AttributeKey = AttributeKey("ActClaims") public class ActAuthConfig { public val ActAuth: ApplicationPlugin = ``` ### `openagent-sdk/sdks/kotlin/src/main/kotlin/id/openagent/sdk/Scope.kt` [#openagent-sdksdkskotlinsrcmainkotlinidopenagentsdkscopekt] Source SHA-256: `46bafee5aba0dfb6052ccf66ed1969c6553ac326b48b9c63f6294a802ff7f5e6`. ```kotlin public class Scope private constructor( public val service: String, public val resource: String, public val action: String, public fun covers(requested: Scope): Boolean { public const val SEGMENT_COUNT: Int = 3 public const val WILDCARD: String = "*" public fun parse(text: String): Scope { ``` # openagentid-sdk (Python) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-python Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-python.md OpenAgent SDK — identity, authentication, and Agent Capability Token verification for autonomous agents. ## Purpose [#purpose] OpenAgent SDK — identity, authentication, and Agent Capability Token verification for autonomous agents. [Read the unified sdks guide](/sdk/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagentid-sdk` | | Version | `0.1.0` | | Language | Python | | Runtime floor | `>=3.10` | | Manifest | `openagent-sdk/sdks/python/pyproject.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `c836b6deba20c34dd194d3f947b6b0a4341be4b6a8fb9d948ac97991432355bf`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "fastapi": [ "fastapi>=0.110", "starlette>=0.37" ], "dev": [ "pytest>=8", "pytest-asyncio>=0.23" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/python/src/openagent_sdk/__init__.py` [#openagent-sdksdkspythonsrcopenagent_sdk__init__py] Source SHA-256: `b31669f5be90840ce26203143ac644952bf3bf2f1413ef602ab7fef3585910e4`. ```python from openagent_sdk import Verifier, Scope from .act import ( ALGORITHM_ED25519, FORMAT_VERSION, MAX_ACT_BYTES, ActClaims, ActEnvelope, Verifier, decode_unverified, verify, verify_builder, ) from .agent import Agent, Session from .errors import ( ActError, AudienceMismatch, ClaimsDecode, ConfigError, EnvelopeDecode, Expired, IssuerMismatch, MalformedScope, MalformedSignature, MissingScope, NotYetValid, OpenAgentError, SignatureInvalid, TooLarge, UnsupportedAlgorithm, UnsupportedVersion, ) from .keys import ( AgentKeys, from_env, from_seed, from_seed_file, from_seed_hex, generate, save_seed, seed_to_hex, ) from .scope import Scope __all__ = [ "ALGORITHM_ED25519", "FORMAT_VERSION", "MAX_ACT_BYTES", "ActClaims", "ActEnvelope", "ActError", "Agent", "AgentKeys", "AudienceMismatch", "ClaimsDecode", "ConfigError", "EnvelopeDecode", "Expired", "IssuerMismatch", "MalformedScope", "MalformedSignature", "MissingScope", "NotYetValid", "OpenAgentError", "Scope", "Session", "SignatureInvalid", "TooLarge", "UnsupportedAlgorithm", "UnsupportedVersion", "Verifier", "decode_unverified", "from_env", "from_seed", "from_seed_file", "from_seed_hex", "generate", "save_seed", "seed_to_hex", "verify", "verify_builder", "__version__", ] ``` # openagent-sdk (Rust) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-rust Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-rust.md OpenAgent SDK — Clerk for autonomous agents. One import for OAS identity, Arsenal credentials, and AEGIS verification. ## Purpose [#purpose] OpenAgent SDK — Clerk for autonomous agents. One import for OAS identity, Arsenal credentials, and AEGIS verification. [Read the unified sdks guide](/sdk/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `openagent-sdk` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagent-sdk/sdks/rust/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `f8d57ec13e688d7f15603eab61d362842cd8b5bc64a4f172f36a95e5c5cb9fee`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "aegis": [ "dep:openagent-aegis-sdk", "dep:openagent-aegis-core" ], "arsenal": [ "dep:arsenal-sdk", "dep:arsenal-core" ], "axum": [ "dep:axum" ], "full": [ "aegis", "arsenal", "axum" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/rust/src/lib.rs` [#openagent-sdksdksrustsrclibrs] Source SHA-256: `a08e99ea97d2d8baf98b88b5fc13588ae769ec424219aaba3b1cd1d7a78b22ae`. ```rust pub mod act; pub mod agent; pub mod builder; pub mod config; pub mod credentials; pub mod errors; pub mod identity; pub mod skills; pub mod verification; pub use agent::authenticate_with_verifier; pub use agent::{CreateAgentOptions, OpenAgent}; pub use builder::OpenAgentBuilder; pub use config::{BrokerMtlsConfig, OpenAgentConfig}; pub use credentials::CredentialClient; pub use errors::{OpenAgentError, Result}; pub use identity::{AgentIdentityRecord, ParsedDid}; pub use skills::{AllowListPolicy, SkillsPolicy, SkillsPolicyHandle}; pub use verification::{ authority_context_from_oas, LineageAuthorityContext, VerifiedContext, Verifier, }; pub use arsenal_sdk; pub use oas_sdk; pub use openagent_aegis_sdk; pub mod sync { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-sdk). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # OpenAgentSDK (Swift) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-swift Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-swift.md Unified SDKs source package and exported entry points. ## Purpose [#purpose] Unified SDKs package. See the linked task guide for its role in the integration. [Read the unified sdks guide](/sdk/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `OpenAgentSDK` | | Version | `source package` | | Language | Swift | | Runtime floor | `6.0` | | Manifest | `openagent-sdk/sdks/swift/Package.swift` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `e635c5b06a224b2b031f82c87fb3144d83429ddcabebae8c4d4e580cf916c58d`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/swift/Sources/OpenAgentSDK/ACT.swift` [#openagent-sdksdksswiftsourcesopenagentsdkactswift] Source SHA-256: `0c5283ee0fabfbdb2045e14418a395bef31ba62bfc8976f6ae4cc5967c0f021e`. ```swift public enum ACT { public struct Claims: Sendable { public let jti: String public let sub: String public let iss: String public let aud: [String] public let iat: Int64 public let nbf: Int64 public let exp: Int64 public let tenantId: String public let scopes: [Scope] public let ext: [String: String] public struct Envelope { public let version: Int public let alg: String public let claims: [UInt8] public let sig: [UInt8] public let kid: String? public static func decode(_ token: [UInt8]) throws -> Envelope { public struct Verifier: Sendable { public typealias Clock = @Sendable () -> Int64 public init( public func requiringScopes(_ scopes: [Scope]) -> Verifier { public func withClock(_ nowUnixSeconds: Int64) -> Verifier { public func verify(_ token: [UInt8]) throws -> Claims { ``` ### `openagent-sdk/sdks/swift/Sources/OpenAgentSDK/Agent.swift` [#openagent-sdksdksswiftsourcesopenagentsdkagentswift] Source SHA-256: `acfde779cf2fedfbccfdf5dd2b9cffe3504e3722e9939a1863408f8cabc2dadc`. ```swift public struct Agent: Sendable { public let keys: AgentKeys public let did: String? public static func create(name: String, did: String? = nil) throws -> Agent { public static func fromSeed(_ seed: Data, did: String? = nil) throws -> Agent { public struct Session: Sendable { public let baseURL: URL public let sessionToken: String public let did: String public let expiresAt: Int64 public let trustTier: String public let capabilities: [String] public var authorizationHeader: String { public func authenticate(baseURL: URL) async throws -> Session { ``` ### `openagent-sdk/sdks/swift/Sources/OpenAgentSDK/CBOR.swift` [#openagent-sdksdksswiftsourcesopenagentsdkcborswift] Source SHA-256: `0b9666f153bd871822d2b45a78fa3497bea592f66b8a4a56b9c8874bbff74f28`. This entry point composes the application or reuses implementation modules; inspect the source file and task guide for its callable boundary. ### `openagent-sdk/sdks/swift/Sources/OpenAgentSDK/Errors.swift` [#openagent-sdksdksswiftsourcesopenagentsdkerrorsswift] Source SHA-256: `a3dd114baab7eabf850a3d18be428ccfab6e1f7d55fffd59df11127d3c6aa479`. ```swift public enum OpenAgentError: Error, Equatable { public var description: String { ``` ### `openagent-sdk/sdks/swift/Sources/OpenAgentSDK/Keys.swift` [#openagent-sdksdksswiftsourcesopenagentsdkkeysswift] Source SHA-256: `c8f811e8799d6afd0785f2392122e494250768c7eac9b9445ac2f46d6f021d0b`. ```swift public struct AgentKeys: Sendable { public let seed: Data public let signingKey: Data public let verifyingKey: Data public let encryptionSecretKey: Data public let encryptionPublicKey: Data public func sign(_ message: Data) throws -> Data { public let encryptionDeriveContext = "arsenal.agent.encryption_key" public enum Keys { public static func fromSeed(_ seed: Data) throws -> AgentKeys { public static func generate() throws -> AgentKeys { public static func fromSeedHex(_ hex: String) throws -> AgentKeys { public static func fromEnv(_ envVar: String) throws -> AgentKeys { public static func saveSeed(_ keys: AgentKeys, to path: URL) throws { public static func fromSeedFile(_ path: URL) throws -> AgentKeys { public static func seedToHex(_ seed: Data) -> String { ``` ### `openagent-sdk/sdks/swift/Sources/OpenAgentSDK/Scope.swift` [#openagent-sdksdksswiftsourcesopenagentsdkscopeswift] Source SHA-256: `82e0b02605fee8ddce6ec596ee2fdbf78e298f9456afb61c6379560179109431`. ```swift public struct Scope: Equatable, Hashable, Sendable, CustomStringConvertible { public let service: String public let resource: String public let action: String public static func parse(_ text: String) throws -> Scope { public func covers(_ requested: Scope) -> Bool { public var description: String { ``` # @openagentid/sdk-testing (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-testing Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-testing.md In-memory test backends for @openagentid/sdk. NOT cryptographically sound - never load in production. ## Purpose [#purpose] In-memory test backends for @openagentid/sdk. NOT cryptographically sound - never load in production. [Read the testing and conformance guide](/features/conformance). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `@openagentid/sdk-testing` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{}` | | Manifest | `openagent-sdk/sdks/testing/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `039324ab038a662faf609e5c035d3e5742a6d63bc2f3d98d0189b9cc496bc8d0`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/testing/src/index.ts` [#openagent-sdksdkstestingsrcindexts] Source SHA-256: `3d2bc4f4b0d4b2ceceef558ae676af75b9495306c264adc8118cc8c1997db8b5`. ```typescript export class StubIdentityProvider implements IdentityProvider { export function stubArsenalClient(): ArsenalClient { export class StubVerificationClient implements VerificationClient { export function createTestingConfig( ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-sdks-testing). # @openagentid/sdk (TypeScript) URL: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-typescript Markdown: https://docs.openagent.id/reference/packages/openagent-sdk-sdks-typescript.md OpenAgent SDK — Clerk for autonomous agents. One import for identity, credentials, and verification. ## Purpose [#purpose] OpenAgent SDK — Clerk for autonomous agents. One import for identity, credentials, and verification. [Read the unified sdks guide](/sdk/overview). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------- | | Package | `@openagentid/sdk` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=20'}` | | Manifest | `openagent-sdk/sdks/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `c165566f43c808245f1550261853a428435c82e96b30e38c7feafdb0ad486f79`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs" }, "./agent": { "types": "./dist/agent.d.ts", "import": "./dist/agent.js", "require": "./dist/agent.cjs" }, "./identity": { "types": "./dist/identity.d.ts", "import": "./dist/identity.js", "require": "./dist/identity.cjs" }, "./credentials": { "types": "./dist/credentials.d.ts", "import": "./dist/credentials.js", "require": "./dist/credentials.cjs" }, "./verification": { "types": "./dist/verification.d.ts", "import": "./dist/verification.js", "require": "./dist/verification.cjs" }, "./skills": { "types": "./dist/skills.d.ts", "import": "./dist/skills.js", "require": "./dist/skills.cjs" }, "./errors": { "types": "./dist/errors.d.ts", "import": "./dist/errors.js", "require": "./dist/errors.cjs" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagent-sdk/sdks/typescript/src/index.ts` [#openagent-sdksdkstypescriptsrcindexts] Source SHA-256: `2590668b23ddcf9004fd43a485ca34610803d845804dc209f7531f64dfd13348`. ```typescript export { OpenAgent, OpenAgentRuntime, type OpenAgentInstance } from './agent.js'; export { type OpenAgentConfig, type OpenAgentClients, type ResolvedOpenAgentConfig, type CreateAgentInput, type Logger, resolveConfig, silentLogger, createAgentInputSchema, didSchema, scopeSchema, providerSchema, DEFAULT_NAMESPACE, DEFAULT_REQUEST_TIMEOUT_MS, DID_REGEX, } from './config.js'; export { type Did, type IdentityDocument, type IdentityProvider, type SignedAssertion, parseIdentityDocument, toIdentityProvider, identityDocumentSchema, } from './identity.js'; export { type ArsenalClient, type CredentialHandle, type IssuedCredential, createCredentialHandle, } from './credentials.js'; export { type AuthContext, type LineageAuthorityContext, type PrivilegedAuthorityVerifier, type VerificationClient, type VerifyRequestOptions, PrivilegedAuthorityVerificationClient, extractBearerToken, assertScopes, assertAncestor, toVerificationClient, } from './verification.js'; export { type SkillId, type SkillsPolicy, InMemorySkillsPolicy, denyAllSkills, allowAllSkills, } from './skills.js'; export { act, ActVerifierBuilder, setActCryptoBinding, type ActClaims, type ActVerifyOptions, } from './act.js'; export { withAct, requireActExpress, type RequireActConfig, } from './middleware.js'; export { keys, setKeyCryptoBinding, type AgentKeys, type KeyCryptoBinding, } from './keys.js'; export { OpenAgentError, ConfigError, InputValidationError, IdentityError, CredentialError, VerificationError, SkillDeniedError, ErrorCode, type ErrorCodeValue, type ErrorDetails, wrapError, getErrorMessage, } from './errors.js'; export const VERSION = '0.1.1'; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagent-sdk-sdks-typescript). # @openagentid/client (TypeScript) URL: https://docs.openagent.id/reference/packages/openagents-openagent-id-clients-typescript Markdown: https://docs.openagent.id/reference/packages/openagents-openagent-id-clients-typescript.md OpenAgent Core challenge-response auth client for TypeScript (browser, Node, Bun, Deno). ## Purpose [#purpose] OpenAgent Core challenge-response auth client for TypeScript (browser, Node, Bun, Deno). [Read the legacy client and server guide](/api-reference/openagent-server). ## Source contract [#source-contract] | Field | Value | | ------------- | --------------------------------------------------------- | | Package | `@openagentid/client` | | Version | `0.1.1` | | Language | TypeScript | | Runtime floor | `{'node': '>=18'}` | | Manifest | `openagents/openagent.id/clients/typescript/package.json` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `4d1e33290792ae008361f9fca6dcbe033d08f25c154ab794cc3689d8c66d5acc`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Declared package subpaths [#declared-package-subpaths] ```json { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagents/openagent.id/clients/typescript/src/index.ts` [#openagentsopenagentidclientstypescriptsrcindexts] Source SHA-256: `fcce69c8f5ad5496b966f4ac6f2f038a3e170d72d267fba3a14c6f6534507258`. ```typescript export { OpenAgentClient } from "./client.js"; export type { OpenAgentClientOptions } from "./client.js"; export { KeyPair, encodeDidKey } from "./keypair.js"; export { CHALLENGE_TYPE, parseWwwAuthenticate, validateChallenge, canonicalizeChallenge, isChallengeFresh, } from "./challenge.js"; export type { Challenge } from "./challenge.js"; export { OpenAgentClientError, InvalidUrlError, NoChallengeHeaderError, MalformedChallengeError, NetworkError, InvalidKeyError, } from "./errors.js"; export { bodyAsString, bodyAsJson } from "./types.js"; export type { export * as base64url from "./base64url.js"; export * as hex from "./hex.js"; ``` ## Exported API signatures [#exported-api-signatures] [Read resolved TypeScript exports and source documentation](/reference/typescript/openagents-openagent-id-clients-typescript). # openagent-capability (Rust) URL: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-capability Markdown: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-capability.md Agent Capability Token (ACT) verification, re-exported from the canonical agent-capability-token crate. ## Purpose [#purpose] Agent Capability Token (ACT) verification, re-exported from the canonical agent-capability-token crate. [Read the legacy client and server guide](/api-reference/openagent-server). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------------------------- | | Package | `openagent-capability` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagents/openagent.id/crates/openagent-capability/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `59158fb825d5c7fcf6190856398f415a0b979adea78e7fa3d653b7a4beb233cf`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Features and optional dependencies [#features-and-optional-dependencies] ```json { "default": [], "sign": [ "agent-capability-token/sign" ] } ``` ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagents/openagent.id/crates/openagent-capability/src/lib.rs` [#openagentsopenagentidcratesopenagent-capabilitysrclibrs] Source SHA-256: `b24b099555e8f3131cecb5682e0bfe244cce4064305779bd6f0dadf79d2efebd`. ```rust pub use agent_capability_token::{ claims_to_signing_payload, envelope_from_parts, verify, ActClaims, ActEnvelope, ActError, ActResult, Confirmation, Delegation, PublicKeyBytes, Scope, Verifier, ALGORITHM_ED25519, FORMAT_VERSION, MAX_ACT_BYTES, SCOPE_SEGMENTS, WILDCARD, }; pub use agent_capability_token::sign; pub fn require_scopes(claims: &ActClaims, required: &[Scope]) -> ActResult<()> { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-capability). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-client (Rust) URL: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-client Markdown: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-client.md OpenAgent protocol client — challenge-response auth for agents ## Purpose [#purpose] OpenAgent protocol client — challenge-response auth for agents [Read the legacy client and server guide](/api-reference/openagent-server). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------------------ | | Package | `openagent-client` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagents/openagent.id/crates/openagent-client/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `5c001f496c461f291ba35df0c5e9834d8a17e3b6cc37a56f11c23011505b7134`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagents/openagent.id/crates/openagent-client/src/lib.rs` [#openagentsopenagentidcratesopenagent-clientsrclibrs] Source SHA-256: `23b524b4bb88ff2889460df8f132972d7e3b707a7f3af5891a1f6d26c69240f4`. ```rust pub mod error; pub struct OpenAgentClient { pub struct AuthenticatedResponse { ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-client). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-server (Rust) URL: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-server Markdown: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-server.md OpenAgent protocol server middleware — challenge-response identity for agents ## Purpose [#purpose] OpenAgent protocol server middleware — challenge-response identity for agents [Read the legacy client and server guide](/api-reference/openagent-server). ## Source contract [#source-contract] | Field | Value | | ------------- | ------------------------------------------------------------ | | Package | `openagent-server` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagents/openagent.id/crates/openagent-server/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `6ad9e3d5b1cdce9f6729f09450f86448f5e55d49252aa8dc0a226649ccb4526e`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagents/openagent.id/crates/openagent-server/src/lib.rs` [#openagentsopenagentidcratesopenagent-serversrclibrs] Source SHA-256: `c43f987d28dca0c03c3934d60c2f9f82ce7cc8a39cd25885a4e8ecd524ebbadc`. ```rust pub mod authority; pub mod challenge; pub mod config; pub mod did_key; pub mod error; pub mod l1feid_client; pub mod layer; pub mod session; pub mod verify; pub use authority::{ require_authoritative_lineage, AuthorityError, LegacyLineageEvidence, MissingAuthorityVerifier, PrivilegedAuthorityRequest, PrivilegedAuthorityVerifier, }; pub use config::OpenAgentConfig; pub use l1feid_client::L1feIdClient; pub use layer::OpenAgentLayer; ``` ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-server). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # openagent-standalone (Rust) URL: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-standalone Markdown: https://docs.openagent.id/reference/packages/openagents-openagent-id-crates-openagent-standalone.md Standalone Axum binary hosting the OpenAgent challenge-response auth server ## Purpose [#purpose] Standalone Axum binary hosting the OpenAgent challenge-response auth server [Read the legacy client and server guide](/api-reference/openagent-server). ## Source contract [#source-contract] | Field | Value | | ------------- | ---------------------------------------------------------------- | | Package | `openagent-standalone` | | Version | `0.1.0` | | Language | Rust | | Runtime floor | `1.78` | | Manifest | `openagents/openagent.id/crates/openagent-standalone/Cargo.toml` | | Distribution | Source package; registry publication not verified | Manifest SHA-256: `219b9ddbbadb94445ccd1b111241d4f321b7f8ce6b4b514523cea292748f2890`. The recorded Git revision identifies the containing repository; the manifest and entry-point hashes identify this working-tree snapshot. ## Integration [#integration] Use the package root above from an authorized source checkout. Preserve sibling dependencies and their version/feature requirements. Install the runtime and compile the selected package before using its generated artifacts. The task guide describes configuration, trust boundaries, and error behavior. Test/conformance and deployment packages are supporting tools, not interchangeable production identity providers. ## Exported entry points [#exported-entry-points] The declarations below are extracted from the named entry files. This is a navigable source reference, not compiler-generated documentation of every transitive module. Feature gates and runtime requirements still apply. Private implementation files are not promoted to public APIs merely because they contain a public declaration. ### `openagents/openagent.id/crates/openagent-standalone/src/main.rs` [#openagentsopenagentidcratesopenagent-standalonesrcmainrs] Source SHA-256: `2e723a0910571464d22369932d48a0ba117ea5e88006ad68cab2d040b58da256`. This entry point composes the application or reuses implementation modules; inspect the source file and task guide for its callable boundary. ## Module signatures and options [#module-signatures-and-options] [Browse the declared public source modules](/reference/rust/openagent-standalone). This includes signatures, struct fields, enums, traits, method declarations, source comments and conditional attributes. # aegis-auth · challenge URL: https://docs.openagent.id/reference/rust/aegis-auth/challenge Markdown: https://docs.openagent.id/reference/rust/aegis-auth/challenge.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-auth/src/challenge.rs`. SHA-256: `39efc24b239da3aaa326a390e3b735a62a45b9e8b57dcb25ada5e0992ecebba3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## challenge::Challenge [#challengechallenge] A challenge issued by the verifier to an authenticating entity. The prover must sign a JCS-canonical payload containing the challenge bytes, their DID, the nonce, and the timestamp. The signed response must arrive before `expires_at`. ```rust #[derive(Debug, Clone)] pub struct Challenge { /// 32 cryptographically random bytes. pub challenge_bytes: [u8; 32], /// ISO 8601 timestamp of challenge creation. pub timestamp: DateTime, /// Verifier-generated nonce (UUID v7) to prevent replay attacks. pub nonce: String, /// When this challenge expires (creation time + 60 seconds). pub expires_at: DateTime } ``` Source line: `33`. ## challenge::Challenge::generate [#challengechallengegenerate] Generate a new random challenge. Fills 32 bytes from the OS CSPRNG, generates a UUID v7 nonce, and sets expiry to 60 seconds from now. ```rust pub fn generate() -> Self; ``` Source line: `49`. ## challenge::ChallengeVerifier [#challengechallengeverifier] Challenge-response verifier. Tracks recently used nonces to prevent replay attacks within a 5-minute window. Thread-safe via interior `RwLock`. ```rust pub struct ChallengeVerifier { } ``` Source line: `70`. ## challenge::ChallengeVerifier::new [#challengechallengeverifiernew] Create a new verifier with an empty nonce set. ```rust pub fn new() -> Self; ``` Source line: `79`. ## challenge::ChallengeVerifier::verify\_response [#challengechallengeverifierverify_response] Verify a challenge response. Performs the following checks in order: 1. Challenge has not expired. 2. Timestamp is within +/- 30 seconds of current time. 3. Nonce has not been used before. 4. Constructs JCS-canonical payload and verifies the Ed25519 signature. 5. Marks the nonce as used. # Arguments [#arguments] * `challenge` - The challenge that was issued to the prover. * `did` - The DID claimed by the prover. * `signature_b64` - Base64url-encoded Ed25519 signature over the canonical payload. * `public_key` - The prover's Ed25519 verifying key (resolved from their DID document). # Errors [#errors] Returns \[`AuthError::ChallengeInvalid`] if any check fails. Returns \[`AuthError::InvalidCredential`] if the signature is malformed or invalid. ```rust pub fn verify_response( &self, challenge: &Challenge, did: &str, signature_b64: &str, public_key: &VerifyingKey, ) -> Result<(), AuthError>; ``` Source line: `105`. ## challenge::ChallengeVerifier::clear\_nonces [#challengechallengeverifierclear_nonces] Remove all nonces from the set. In a production system, nonces would expire via TTL. This method provides a manual reset for testing or periodic cleanup. ```rust pub fn clear_nonces(&self) -> Result<(), AuthError>; ``` Source line: `186`. ## challenge::build\_challenge\_payload [#challengebuild_challenge_payload] Build the JCS-canonical payload bytes for challenge signing/verification. The canonical form is a JSON object with keys in alphabetical order: ```json {"challenge":"","did":"","nonce":"","timestamp":""} ``` JCS (RFC 8785) handles the key ordering automatically via `serde_jcs`. # Arguments [#arguments-1] * `challenge` - The challenge containing the random bytes, nonce, and timestamp. * `did` - The DID of the entity signing the challenge. # Returns [#returns] The canonical JSON bytes ready for Ed25519 signing. # Errors [#errors-1] Returns \[`AuthError::Internal`] if JCS serialization fails. ```rust pub fn build_challenge_payload(challenge: &Challenge, did: &str) -> Result, AuthError>; ``` Source line: `225`. # aegis-auth · crate URL: https://docs.openagent.id/reference/rust/aegis-auth/crate Markdown: https://docs.openagent.id/reference/rust/aegis-auth/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-auth/src/lib.rs`. SHA-256: `7b6f26da034daf413490a387eddccc9114ecb69734dba161516cf589b27c158c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## challenge [#challenge] ```rust pub mod challenge; ``` Source line: `10`. ## provider [#provider] ```rust pub mod provider; ``` Source line: `11`. ## session [#session] ```rust pub mod session; ``` Source line: `12`. ## store [#store] ```rust pub mod store; ``` Source line: `13`. ## pub use challenge::\{build\_challenge\_payload, Challenge, ChallengeVerifier}; [#pub-use-challengebuild_challenge_payload-challenge-challengeverifier] ```rust pub use challenge::{build_challenge_payload, Challenge, ChallengeVerifier}; ``` Source line: `15`. ## pub use provider::\{ApiKeyProvider, ChallengeResponseProvider}; [#pub-use-providerapikeyprovider-challengeresponseprovider] ```rust pub use provider::{ApiKeyProvider, ChallengeResponseProvider}; ``` Source line: `16`. ## pub use session::SessionManager; [#pub-use-sessionsessionmanager] ```rust pub use session::SessionManager; ``` Source line: `17`. ## pub use store::\{InMemoryNonceStore, InMemorySessionStore, NonceStore, SessionStore}; [#pub-use-storeinmemorynoncestore-inmemorysessionstore-noncestore-sessionstore] ```rust pub use store::{InMemoryNonceStore, InMemorySessionStore, NonceStore, SessionStore}; ``` Source line: `18`. # aegis-auth modules URL: https://docs.openagent.id/reference/rust/aegis-auth Markdown: https://docs.openagent.id/reference/rust/aegis-auth.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-aegis-auth). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/aegis-auth/crate) — 8 declarations * [challenge](/reference/rust/aegis-auth/challenge) — 7 declarations * [provider](/reference/rust/aegis-auth/provider) — 7 declarations * [session](/reference/rust/aegis-auth/session) — 9 declarations * [store](/reference/rust/aegis-auth/store) — 6 declarations # aegis-auth · provider URL: https://docs.openagent.id/reference/rust/aegis-auth/provider Markdown: https://docs.openagent.id/reference/rust/aegis-auth/provider.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-auth/src/provider.rs`. SHA-256: `446ccd58e86eaa6fd49ff6546b97b563275cd301d2b9206efc9d7aabc0b7571e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## provider::ChallengeResponseProvider [#providerchallengeresponseprovider] Auth provider implementing the AEGIS challenge-response protocol. Validates `AuthCredential::SignedChallenge` credentials by: 1. Resolving the DID to obtain the OAS Identity Document. 2. Extracting the authentication public key from the document. 3. Reconstructing the challenge and verifying the Ed25519 signature. Requires a DID resolver to look up the entity's public key from their DID document. ```rust pub struct ChallengeResponseProvider { } ``` Source line: `35`. ## provider::ChallengeResponseProvider::new [#providerchallengeresponseprovidernew] Create a new challenge-response provider. # Arguments [#arguments] * `resolver` - A DID resolver for looking up entity public keys. ```rust pub fn new(resolver: Arc) -> Self; ``` Source line: `46`. ## provider::ChallengeResponseProvider::verifier [#providerchallengeresponseproviderverifier] Returns a reference to the inner challenge verifier. Useful for generating challenges via `Challenge::generate()` and managing nonce state. ```rust pub fn verifier(&self) -> &ChallengeVerifier; ``` Source line: `57`. ## provider::ApiKeyProvider [#providerapikeyprovider] Simple API key auth provider for service-to-service communication. Maps opaque API keys to DIDs. Suitable for internal services that authenticate via pre-shared keys rather than challenge-response. ```rust pub struct ApiKeyProvider { } ``` Source line: `185`. ## provider::ApiKeyProvider::new [#providerapikeyprovidernew] Create a new API key provider. # Arguments [#arguments-1] * `keys` - Map from API key strings to DID strings. ```rust pub fn new(keys: HashMap) -> Self; ``` Source line: `196`. ## provider::ApiKeyProvider::register\_key [#providerapikeyproviderregister_key] Register an API key for a DID. ```rust pub fn register_key(&mut self, key: String, did: String); ``` Source line: `201`. ## provider::ApiKeyProvider::revoke\_key [#providerapikeyproviderrevoke_key] Remove an API key. ```rust pub fn revoke_key(&mut self, key: &str) -> bool; ``` Source line: `206`. # aegis-auth · session URL: https://docs.openagent.id/reference/rust/aegis-auth/session Markdown: https://docs.openagent.id/reference/rust/aegis-auth/session.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-auth/src/session.rs`. SHA-256: `a25c8ec6b3c94cbbd424956d697d6f5d9c1021be33374f4cb703c1857052ffe9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session::SessionManager [#sessionsessionmanager] Session manager with in-memory storage. Provides create, get, revoke, and cleanup operations for authentication sessions. Agent sessions are shorter-lived (1 hour default) than human sessions (24 hours default) per the AEGIS specification. ```rust pub struct SessionManager { /// Max lifetime for human sessions. pub human_max_lifetime: Duration, /// Max lifetime for agent sessions. pub agent_max_lifetime: Duration } ``` Source line: `28`. ## session::SessionManager::new [#sessionsessionmanagernew] Create a new session manager with default lifetimes. * Human sessions: 24 hours * Agent sessions: 1 hour ```rust pub fn new() -> Self; ``` Source line: `41`. ## session::SessionManager::with\_lifetimes [#sessionsessionmanagerwith_lifetimes] Create a new session manager with custom lifetimes. # Arguments [#arguments] * `human_max_lifetime` - Maximum lifetime for human sessions. * `agent_max_lifetime` - Maximum lifetime for agent sessions. ```rust pub fn with_lifetimes(human_max_lifetime: Duration, agent_max_lifetime: Duration) -> Self; ``` Source line: `55`. ## session::SessionManager::create\_session [#sessionsessionmanagercreate_session] Create a new authenticated session. Generates a UUID v7 session identifier and computes the expiry time based on the entity type (agent or human). # Arguments [#arguments-1] * `did` - DID of the authenticated entity. * `provider` - Name of the auth provider that validated the credential. * `scope` - List of authorized scopes for this session. * `is_agent` - Whether the entity is an agent (shorter session lifetime). * `device_binding` - Optional device fingerprint to bind this session to. # Returns [#returns] The newly created \[`Session`]. # Errors [#errors] Returns \[`AuthError::Internal`] if the session lock is poisoned. ```rust pub fn create_session( &self, did: &str, provider: &str, scope: Vec, is_agent: bool, device_binding: Option, ) -> Result; ``` Source line: `83`. ## session::SessionManager::get\_session [#sessionsessionmanagerget_session] Retrieve a session by ID. Returns the session if it exists and has not expired. If the session has expired, it is automatically removed and a `SessionExpired` error is returned. # Arguments [#arguments-2] * `session_id` - The session identifier to look up. # Errors [#errors-1] Returns \[`AuthError::SessionExpired`] if the session exists but has expired. Returns \[`AuthError::InvalidCredential`] if the session does not exist. Returns \[`AuthError::Internal`] if the session lock is poisoned. ```rust pub fn get_session(&self, session_id: &str) -> Result; ``` Source line: `132`. ## session::SessionManager::revoke\_session [#sessionsessionmanagerrevoke_session] Revoke a session by removing it from storage. # Arguments [#arguments-3] * `session_id` - The session identifier to revoke. # Errors [#errors-2] Returns \[`AuthError::InvalidCredential`] if the session does not exist. Returns \[`AuthError::Internal`] if the session lock is poisoned. ```rust pub fn revoke_session(&self, session_id: &str) -> Result<(), AuthError>; ``` Source line: `164`. ## session::SessionManager::is\_valid [#sessionsessionmanageris_valid] Quick validity check for a session. Returns `true` if the session exists and has not expired, `false` otherwise. Does not modify state (does not remove expired sessions). ```rust pub fn is_valid(&self, session_id: &str) -> bool; ``` Source line: `182`. ## session::SessionManager::cleanup\_expired [#sessionsessionmanagercleanup_expired] Remove all expired sessions from storage. Returns the number of sessions removed. This should be called periodically to prevent unbounded memory growth. ```rust pub fn cleanup_expired(&self) -> usize; ``` Source line: `198`. ## session::SessionManager::session\_count [#sessionsessionmanagersession_count] Returns the number of active sessions (includes expired ones not yet cleaned). ```rust pub fn session_count(&self) -> usize; ``` Source line: `211`. # aegis-auth · store URL: https://docs.openagent.id/reference/rust/aegis-auth/store Markdown: https://docs.openagent.id/reference/rust/aegis-auth/store.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-auth/src/store.rs`. SHA-256: `e56e013658859f28040b06b7de74fcdff41bf5d01d95a2fd1b476032bb93ebe3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## store::SessionStore [#storesessionstore] Pluggable storage backend for authentication sessions. Implementations may use in-memory storage, databases, or distributed caches. All operations are async to accommodate network-backed stores. ```rust #[async_trait] pub trait SessionStore: Send + Sync { /// Persist a session. Overwrites any existing session with the same ID. async fn store_session(&self, session: &Session) -> Result<(), AuthError>; /// Retrieve a session by its unique identifier. /// /// Returns `None` if no session with the given ID exists. async fn get_session(&self, session_id: &str) -> Result, AuthError>; /// Delete a session by ID. /// /// Returns `true` if a session was found and removed, `false` if no /// session with the given ID existed. async fn delete_session(&self, session_id: &str) -> Result; /// List sessions belonging to a specific DID with pagination. async fn list_by_did( &self, did: &str, pagination: Pagination, ) -> Result, AuthError>; /// Remove all expired sessions from the store. /// /// Returns the number of sessions removed. async fn cleanup_expired(&self) -> Result; } ``` Source line: `25`. ## store::InMemorySessionStore [#storeinmemorysessionstore] In-memory session store backed by a `RwLock`. Suitable for development, testing, and single-instance deployments. For production multi-node deployments, use a database-backed or distributed cache implementation of \[`SessionStore`]. ```rust pub struct InMemorySessionStore { } ``` Source line: `62`. ## store::InMemorySessionStore::new [#storeinmemorysessionstorenew] Creates a new empty in-memory session store. ```rust pub fn new() -> Self; ``` Source line: `68`. ## store::NonceStore [#storenoncestore] Pluggable storage backend for cryptographic nonce tracking. Used to prevent challenge replay attacks. Each nonce should be recorded exactly once; subsequent attempts to record the same nonce indicate a replay and should be rejected. ```rust #[async_trait] pub trait NonceStore: Send + Sync { /// Record a nonce as used. /// /// Returns `true` if the nonce was newly recorded, `false` if it was /// already present (indicating a replay attempt). async fn record_nonce(&self, nonce: &str) -> Result; /// Check whether a nonce has already been recorded. async fn has_nonce(&self, nonce: &str) -> Result; /// Remove old nonces. Returns the number of entries removed. /// /// The cleanup strategy is implementation-defined. In-memory stores /// clear all entries; persistent stores may use TTL-based eviction. async fn cleanup(&self) -> Result; } ``` Source line: `144`. ## store::InMemoryNonceStore [#storeinmemorynoncestore] In-memory nonce store backed by a `RwLock`. Records nonces in a set. Cleanup clears all recorded nonces; callers should schedule cleanup periodically to bound memory usage. ```rust pub struct InMemoryNonceStore { } ``` Source line: `169`. ## store::InMemoryNonceStore::new [#storeinmemorynoncestorenew] Creates a new empty in-memory nonce store. ```rust pub fn new() -> Self; ``` Source line: `175`. # aegis-delegate · crate URL: https://docs.openagent.id/reference/rust/aegis-delegate/crate Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/lib.rs`. SHA-256: `adf9fb968b0e47f2f75c16d0639492179568b181572a17f794496e7046a5c654`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## delegation\_store [#delegation_store] ```rust pub mod delegation_store; ``` Source line: `5`. ## proof [#proof] ```rust pub mod proof; ``` Source line: `6`. ## revocation [#revocation] ```rust pub mod revocation; ``` Source line: `7`. ## scope [#scope] ```rust pub mod scope; ``` Source line: `8`. ## session\_key [#session_key] ```rust pub mod session_key; ``` Source line: `9`. ## store [#store] ```rust pub mod store; ``` Source line: `10`. ## tree [#tree] ```rust pub mod tree; ``` Source line: `11`. ## pub use delegation\_store::\{DelegationStore, InMemoryDelegationStore}; [#pub-use-delegation_storedelegationstore-inmemorydelegationstore] ```rust pub use delegation_store::{DelegationStore, InMemoryDelegationStore}; ``` Source line: `13`. ## pub use store::\{InMemoryRevocationStore, RevocationStore}; [#pub-use-storeinmemoryrevocationstore-revocationstore] ```rust pub use store::{InMemoryRevocationStore, RevocationStore}; ``` Source line: `14`. # aegis-delegate · delegation_store URL: https://docs.openagent.id/reference/rust/aegis-delegate/delegation_store Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/delegation_store.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/delegation_store.rs`. SHA-256: `54ccefdfa3f530fe12cd3e2c32102be1d7ff7f37b7c3c9b04ff5b04037ae25be`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## delegation\_store::DelegationStore [#delegation_storedelegationstore] Pluggable storage backend for delegation records. Implementations may use in-memory storage, databases, or distributed caches. All operations are async to accommodate network-backed stores. This trait provides CRUD operations on individual delegations, separate from the tree-based structural operations in \[`crate::tree::DelegationTree`]. ```rust #[async_trait] pub trait DelegationStore: Send + Sync { /// Persist a delegation. Overwrites any existing delegation with the same ID. async fn store_delegation(&self, delegation: &Delegation) -> Result<(), DelegationError>; /// Retrieve a delegation by its unique identifier. /// /// Returns `None` if no delegation with the given ID exists. async fn get_delegation(&self, id: &str) -> Result, DelegationError>; /// List delegations granted by a specific delegator DID with pagination. async fn list_by_delegator( &self, delegator_did: &str, pagination: Pagination, ) -> Result, DelegationError>; /// List delegations received by a specific delegate DID with pagination. async fn list_by_delegate( &self, delegate_did: &str, pagination: Pagination, ) -> Result, DelegationError>; /// Delete a delegation by ID. /// /// Returns `true` if a delegation was found and removed, `false` if no /// delegation with the given ID existed. async fn delete_delegation(&self, id: &str) -> Result; } ``` Source line: `27`. ## delegation\_store::InMemoryDelegationStore [#delegation_storeinmemorydelegationstore] In-memory delegation store backed by a `RwLock`. Suitable for development, testing, and single-instance deployments. For production multi-node deployments, use a database-backed implementation of \[`DelegationStore`]. ```rust pub struct InMemoryDelegationStore { } ``` Source line: `66`. ## delegation\_store::InMemoryDelegationStore::new [#delegation_storeinmemorydelegationstorenew] Creates a new empty in-memory delegation store. ```rust pub fn new() -> Self; ``` Source line: `72`. # aegis-delegate modules URL: https://docs.openagent.id/reference/rust/aegis-delegate Markdown: https://docs.openagent.id/reference/rust/aegis-delegate.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-aegis-delegate). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/aegis-delegate/crate) — 9 declarations * [delegation\_store](/reference/rust/aegis-delegate/delegation_store) — 3 declarations * [proof](/reference/rust/aegis-delegate/proof) — 2 declarations * [revocation](/reference/rust/aegis-delegate/revocation) — 5 declarations * [scope](/reference/rust/aegis-delegate/scope) — 3 declarations * [session\_key](/reference/rust/aegis-delegate/session_key) — 1 declarations * [store](/reference/rust/aegis-delegate/store) — 3 declarations * [tree](/reference/rust/aegis-delegate/tree) — 7 declarations # aegis-delegate · proof URL: https://docs.openagent.id/reference/rust/aegis-delegate/proof Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/proof.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/proof.rs`. SHA-256: `2c5d8b0abe8f720355b2244a5b8da6b1ceaa9de670921a3d7cfedec71503dfd5`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proof::create\_delegation\_proof [#proofcreate_delegation_proof] Creates a delegation proof by signing the delegation with the delegator's key. Steps per spec §9.7: 1. Construct delegation object (excluding proof field) 2. Canonicalize via JCS (RFC 8785) 3. Sign canonical bytes with delegator's delegation key (Ed25519) Returns a fully formed \[`Delegation`] with an attached cryptographic proof. ```rust pub fn create_delegation_proof( delegator_did: &str, delegate_did: &str, scope: DelegationScope, expires: Option>, signing_key: &SigningKey, verification_method: &str, ) -> Result; ``` Source line: `43`. ## proof::verify\_delegation\_proof [#proofverify_delegation_proof] Verifies a delegation proof against the delegator's public key. Reconstructs the canonical form of the delegation (without the proof), then verifies the Ed25519 signature contained in the proof's JWS field. ```rust pub fn verify_delegation_proof( delegation: &Delegation, delegator_public_key: &VerifyingKey, ) -> Result; ``` Source line: `95`. # aegis-delegate · revocation URL: https://docs.openagent.id/reference/rust/aegis-delegate/revocation Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/revocation.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/revocation.rs`. SHA-256: `7f38fdd0004282852e07d180595441146d8837ea3f2ae230fbec8a6924f37471`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## revocation::RevocationRegistry [#revocationrevocationregistry] Tracks revoked delegation IDs. All operations are thread-safe via an internal \[`RwLock`]. This is an in-memory registry; for persistence, a backing store should be layered on top. ```rust pub struct RevocationRegistry { } ``` Source line: `16`. ## revocation::RevocationRegistry::new [#revocationrevocationregistrynew] Creates a new empty revocation registry. ```rust pub fn new() -> Self; ``` Source line: `22`. ## revocation::RevocationRegistry::revoke [#revocationrevocationregistryrevoke] Marks a single delegation as revoked. ```rust pub fn revoke(&self, delegation_id: &str); ``` Source line: `29`. ## revocation::RevocationRegistry::is\_revoked [#revocationrevocationregistryis_revoked] Checks whether a delegation has been revoked. ```rust pub fn is_revoked(&self, delegation_id: &str) -> bool; ``` Source line: `36`. ## revocation::RevocationRegistry::revoke\_cascade [#revocationrevocationregistryrevoke_cascade] Revokes multiple delegations at once (cascade revocation). This is typically used after [`DelegationTree::revoke`](crate::tree::DelegationTree::revoke) returns a list of all transitively affected delegation IDs. ```rust pub fn revoke_cascade(&self, ids: &[String]); ``` Source line: `51`. # aegis-delegate · scope URL: https://docs.openagent.id/reference/rust/aegis-delegate/scope Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/scope.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/scope.rs`. SHA-256: `4229dada749b1877d8702352262536497079b1ae88cc65baed226f73040228f0`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## scope::is\_scope\_subset [#scopeis_scope_subset] Checks if `child` scope is a subset of `parent` scope (no-amplification rule §9.6). A child scope is a subset when: * Every action in child is present in parent (or parent has no actions, meaning wildcard) * Every resource in child is present in parent (or parent has no restrictions) * Every chain in child is present in parent (or parent has no restrictions) * Child limits are at least as restrictive as parent limits ```rust pub fn is_scope_subset(child: &DelegationScope, parent: &DelegationScope) -> bool; ``` Source line: `17`. ## scope::intersect\_scopes [#scopeintersect_scopes] Computes the intersection of two scopes (intersection narrowing rule §9.6). For each dimension: * If either side is empty (wildcard), use the other side's restriction * Otherwise, take the set intersection * For limits, take the most restrictive value ```rust pub fn intersect_scopes(a: &DelegationScope, b: &DelegationScope) -> DelegationScope; ``` Source line: `131`. ## scope::validate\_scope [#scopevalidate_scope] Validates that a delegation scope is well-formed. A scope is well-formed if: * Actions, resources, and chains contain no empty strings * If limits are present, numeric fields parse as valid numbers ```rust pub fn validate_scope(scope: &DelegationScope) -> Result<(), DelegationError>; ``` Source line: `257`. # aegis-delegate · session_key URL: https://docs.openagent.id/reference/rust/aegis-delegate/session_key Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/session_key.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/session_key.rs`. SHA-256: `76d7efb78b87181ecc07a35c09843cc3cea1e89c94cc505e4c1ad73237f60753`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session\_key::create\_session\_key [#session_keycreate_session_key] Creates a session key (temporary, scoped, max 24h). Generates a fresh Ed25519 keypair for the session. The public key is encoded as multibase (base64url) and stored in the \[`SessionKey`] struct. The session key grant is signed by the principal's identity key. # Errors [#errors] Returns \[`DelegationError`] if: * The requested lifetime exceeds 24 hours * JCS canonicalization fails # Returns [#returns] A tuple of `(SessionKey, SigningKey)` where the `SigningKey` is the ephemeral private key for the session. ```rust pub fn create_session_key( principal_did: &str, scope: DelegationScope, max_transactions: Option, lifetime: Duration, principal_signing_key: &SigningKey, verification_method: &str, ) -> Result<(SessionKey, SigningKey), DelegationError>; ``` Source line: `54`. # aegis-delegate · store URL: https://docs.openagent.id/reference/rust/aegis-delegate/store Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/store.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/store.rs`. SHA-256: `b554fa623706e5d6e65dd8a3bc058a232c020a72187b6058305becf4ebb7f80d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## store::RevocationStore [#storerevocationstore] Pluggable storage backend for tracking revoked delegation IDs. Implementations may use in-memory storage, databases, or distributed caches. All operations are async to accommodate network-backed stores. This trait complements \[`crate::revocation::RevocationRegistry`] by providing an async, error-aware interface suitable for production persistence backends. ```rust #[async_trait] pub trait RevocationStore: Send + Sync { /// Mark a delegation as revoked. /// /// Revoking an already-revoked delegation is idempotent and does not /// return an error. async fn revoke(&self, delegation_id: &str) -> Result<(), DelegationError>; /// Check whether a delegation has been revoked. async fn is_revoked(&self, delegation_id: &str) -> Result; /// Revoke multiple delegations at once (batch/cascade revocation). /// /// This is typically used after cascade revocation computes the full /// set of transitively affected delegation IDs. async fn revoke_batch(&self, ids: &[String]) -> Result<(), DelegationError>; } ``` Source line: `28`. ## store::InMemoryRevocationStore [#storeinmemoryrevocationstore] In-memory revocation store backed by a `RwLock`. Suitable for development, testing, and single-instance deployments. For production multi-node deployments, use a database-backed implementation of \[`RevocationStore`]. ```rust pub struct InMemoryRevocationStore { } ``` Source line: `54`. ## store::InMemoryRevocationStore::new [#storeinmemoryrevocationstorenew] Creates a new empty in-memory revocation store. ```rust pub fn new() -> Self; ``` Source line: `60`. # aegis-delegate · tree URL: https://docs.openagent.id/reference/rust/aegis-delegate/tree Markdown: https://docs.openagent.id/reference/rust/aegis-delegate/tree.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-delegate/src/tree.rs`. SHA-256: `1c3cc47d0b40fb63bfbc6ecc4dc089718fe7432bdf751511ad976de283c916a4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## tree::DelegationTree [#treedelegationtree] A delegation tree rooted at a human root. Stores delegations indexed by delegate DID and by delegation ID. Max depth is configurable (default 8). ```rust pub struct DelegationTree { } ``` Source line: `17`. ## tree::DelegationTree::new [#treedelegationtreenew] Creates a new empty delegation tree with the given maximum depth. ```rust pub fn new(max_depth: u32) -> Self; ``` Source line: `28`. ## tree::DelegationTree::add\_delegation [#treedelegationtreeadd_delegation] Adds a delegation to the tree. Validates: * The delegation depth does not exceed max\_depth * The delegation scope is a subset of the delegator's effective scope (no-amplification rule, §9.6) ```rust pub fn add_delegation(&mut self, delegation: Delegation) -> Result<(), DelegationError>; ``` Source line: `42`. ## tree::DelegationTree::get\_delegation\_chain [#treedelegationtreeget_delegation_chain] Gets the delegation chain from a delegate up to the root. Returns delegations in order from the immediate delegation (closest to the delegate) up to the root delegation. ```rust pub fn get_delegation_chain(&self, delegate_did: &str) -> Vec<&Delegation>; ``` Source line: `85`. ## tree::DelegationTree::effective\_scope [#treedelegationtreeeffective_scope] Computes the effective scope for a delegate. This is the intersection of all scopes in the delegation chain, implementing the intersection narrowing rule (§9.6 rule 2). ```rust pub fn effective_scope(&self, delegate_did: &str) -> Option; ``` Source line: `115`. ## tree::DelegationTree::depth [#treedelegationtreedepth] Returns the depth of a delegate in the tree. A root entity (not a delegate of anyone) has depth 0. A direct delegate of a root has depth 1, and so on. ```rust pub fn depth(&self, delegate_did: &str) -> u32; ``` Source line: `133`. ## tree::DelegationTree::revoke [#treedelegationtreerevoke] Revokes a delegation and all sub-delegations (cascade revocation). Returns the list of all revoked delegation IDs, including the original and all transitively dependent delegations. ```rust pub fn revoke(&mut self, delegation_id: &str) -> Result, DelegationError>; ``` Source line: `141`. # aegis-keys · crate URL: https://docs.openagent.id/reference/rust/aegis-keys/crate Markdown: https://docs.openagent.id/reference/rust/aegis-keys/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/lib.rs`. SHA-256: `c19c72128fbfcee36aad4232c4ce0414a1896bb0ab18984d3cd405ab4d1ce947`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## derivation [#derivation] ```rust pub mod derivation; ``` Source line: `13`. ## generation [#generation] ```rust pub mod generation; ``` Source line: `14`. ## recovery [#recovery] ```rust pub mod recovery; ``` Source line: `15`. ## rotation [#rotation] ```rust pub mod rotation; ``` Source line: `16`. ## storage [#storage] ```rust pub mod storage; ``` Source line: `17`. ## threshold [#threshold] ```rust pub mod threshold; ``` Source line: `18`. ## pub use derivation::\{derivation\_path, derive\_lineage\_key}; [#pub-use-derivationderivation_path-derive_lineage_key] ```rust pub use derivation::{derivation_path, derive_lineage_key}; ``` Source line: `21`. ## pub use generation::\{EncryptedKey, KeyGenerator, ManagedKey}; [#pub-use-generationencryptedkey-keygenerator-managedkey] ```rust pub use generation::{EncryptedKey, KeyGenerator, ManagedKey}; ``` Source line: `22`. ## pub use recovery::\{GuardianAuthorization, RecoveryCeremony}; [#pub-use-recoveryguardianauthorization-recoveryceremony] ```rust pub use recovery::{GuardianAuthorization, RecoveryCeremony}; ``` Source line: `23`. ## pub use rotation::\{KeyRotation, RotationRequest, RotationResult}; [#pub-use-rotationkeyrotation-rotationrequest-rotationresult] ```rust pub use rotation::{KeyRotation, RotationRequest, RotationResult}; ``` Source line: `24`. ## pub use storage::\{InMemoryKeyStore, KeyStore}; [#pub-use-storageinmemorykeystore-keystore] ```rust pub use storage::{InMemoryKeyStore, KeyStore}; ``` Source line: `25`. ## pub use threshold::\{generate\_shares, sign\_with\_threshold, verify\_threshold\_signature}; [#pub-use-thresholdgenerate_shares-sign_with_threshold-verify_threshold_signature] ```rust pub use threshold::{generate_shares, sign_with_threshold, verify_threshold_signature}; ``` Source line: `26`. # aegis-keys · derivation URL: https://docs.openagent.id/reference/rust/aegis-keys/derivation Markdown: https://docs.openagent.id/reference/rust/aegis-keys/derivation.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/derivation.rs`. SHA-256: `bf2ba0570408be6fdb11d6e4d93fdfc51255b5970f1a9c2911e6203cbe2bd2de`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## derivation::derive\_lineage\_key [#derivationderive_lineage_key] Derive a lineage key from a parent private key using HKDF-SHA256. This implements the OAS lineage key derivation scheme where child keys are deterministically derived from parent keys, enabling cryptographic proof of the lineage chain. # Algorithm [#algorithm] ```text HKDF-SHA256( IKM = parent_private_key (32 bytes), Salt = child_did_utf8, Info = "oas-lineage-v1" || generation_be32, L = 32 ) ``` # Arguments [#arguments] * `parent_private` - The parent entity's 32-byte Ed25519 private key material. * `child_did` - The child entity's DID string, used as salt. * `generation` - The lineage generation number (distance from human root). # Returns [#returns] 32 bytes of derived key material suitable for constructing a child Ed25519 signing key. # Errors [#errors] Returns `KeyError::DerivationFailed` if HKDF expansion fails. ```rust pub fn derive_lineage_key( parent_private: &[u8; 32], child_did: &str, generation: u32, ) -> Result<[u8; 32], KeyError>; ``` Source line: `43`. ## derivation::derivation\_path [#derivationderivation_path] Build a BIP-44 derivation path for a given blockchain chain. Returns the standard `m/44'/coin_type'/account'/0/index` path used for HD key derivation across different blockchains. # Arguments [#arguments-1] * `chain` - The target blockchain (determines the coin type). * `account` - The account index. * `index` - The address index within the account. # Returns [#returns-1] A BIP-44 derivation path string like `m/44'/60'/0'/0/0` for Ethereum. ```rust pub fn derivation_path(chain: Chain, account: u32, index: u32) -> String; ``` Source line: `82`. # aegis-keys · generation URL: https://docs.openagent.id/reference/rust/aegis-keys/generation Markdown: https://docs.openagent.id/reference/rust/aegis-keys/generation.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/generation.rs`. SHA-256: `269bc2cd45a672afd924e928f31b343efb09b3ea812d06d0ffce261ae1bc4a35`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## generation::ManagedKey [#generationmanagedkey] A managed key with metadata (AEGIS Spec SS6.2). The private key is stored in encrypted form and never exposed directly. All access to the signing key requires the encryption key. ```rust #[derive(Debug)] pub struct ManagedKey { /// Unique key identifier (UUID v7-based). pub key_id: String, /// Role of this key within the AEGIS identity framework. pub role: KeyRole, /// How this key was generated. pub generation_mode: KeyGenerationMode, /// The Ed25519 verifying (public) key. pub public_key: VerifyingKey, /// Timestamp when this key was created. pub created_at: DateTime } ``` Source line: `26`. ## generation::ManagedKey::from\_stored\_parts [#generationmanagedkeyfrom_stored_parts] Reconstruct a `ManagedKey` from its serialized components. This constructor is intended for storage backends that need to reconstitute a `ManagedKey` from persisted columns. # Errors [#errors] Returns `KeyError::StorageError` if the nonce length is invalid or the public key bytes are malformed. ```rust pub fn from_stored_parts( key_id: String, role: KeyRole, generation_mode: KeyGenerationMode, public_key: VerifyingKey, ciphertext: Vec, nonce: Vec, created_at: DateTime, ) -> Result; ``` Source line: `51`. ## generation::ManagedKey::public\_key\_multibase [#generationmanagedkeypublic_key_multibase] Returns the public key encoded as multibase base58btc (with `z` prefix). This is the canonical format for `publicKeyMultibase` in OAS Identity Documents. ```rust pub fn public_key_multibase(&self) -> String; ``` Source line: `74`. ## generation::ManagedKey::decrypt\_private [#generationmanagedkeydecrypt_private] Decrypt the private key using the provided encryption key. The caller is responsible for zeroizing the returned `SigningKey` when done. ```rust pub fn decrypt_private(&self, encryption_key: &[u8; 32]) -> Result; ``` Source line: `81`. ## generation::ManagedKey::encrypted\_ciphertext [#generationmanagedkeyencrypted_ciphertext] Returns the encrypted private key ciphertext bytes (for serialization/storage). ```rust pub fn encrypted_ciphertext(&self) -> &[u8]; ``` Source line: `86`. ## generation::ManagedKey::encrypted\_nonce [#generationmanagedkeyencrypted_nonce] Returns the encrypted private key nonce bytes (for serialization/storage). ```rust pub fn encrypted_nonce(&self) -> &[u8]; ``` Source line: `91`. ## generation::EncryptedKey [#generationencryptedkey] An encrypted private key blob (AEGIS Spec SS6.8). Uses AES-256-GCM with a random 96-bit nonce. The ciphertext contains the 32-byte Ed25519 signing key material plus a 16-byte authentication tag. ```rust #[derive(Debug)] pub struct EncryptedKey { } ``` Source line: `101`. ## generation::EncryptedKey::encrypt [#generationencryptedkeyencrypt] Encrypt an Ed25519 signing key with AES-256-GCM. # Arguments [#arguments] * `signing_key` - The signing key to encrypt. * `encryption_key` - A 32-byte AES-256 key. # Errors [#errors-1] Returns `KeyError::GenerationFailed` if AES-256-GCM encryption fails. ```rust pub fn encrypt(signing_key: &SigningKey, encryption_key: &[u8; 32]) -> Result; ``` Source line: `117`. ## generation::EncryptedKey::decrypt [#generationencryptedkeydecrypt] Decrypt the private key using the provided AES-256 encryption key. # Arguments [#arguments-1] * `encryption_key` - The 32-byte AES-256 key used during encryption. # Errors [#errors-2] Returns `KeyError::GenerationFailed` if decryption fails (wrong key or tampered data). ```rust pub fn decrypt(&self, encryption_key: &[u8; 32]) -> Result; ``` Source line: `151`. ## generation::EncryptedKey::ciphertext [#generationencryptedkeyciphertext] Returns the ciphertext bytes (for serialization/storage). ```rust pub fn ciphertext(&self) -> &[u8]; ``` Source line: `192`. ## generation::EncryptedKey::nonce [#generationencryptedkeynonce] Returns the nonce bytes (for serialization/storage). ```rust pub fn nonce(&self) -> &[u8]; ``` Source line: `197`. ## generation::EncryptedKey::from\_parts [#generationencryptedkeyfrom_parts] Reconstruct an `EncryptedKey` from stored ciphertext and nonce. # Errors [#errors-3] Returns `KeyError::StorageError` if the nonce length is invalid. ```rust pub fn from_parts(ciphertext: Vec, nonce: Vec) -> Result; ``` Source line: `206`. ## generation::KeyGenerator [#generationkeygenerator] Key generator supporting multiple generation modes (AEGIS Spec SS6.2). Currently implements the `Direct` generation mode using OS CSPRNG. MPC, TEE, and HSM modes will be added as their respective backends become available. ```rust pub struct KeyGenerator; ``` Source line: `239`. ## generation::KeyGenerator::generate\_direct [#generationkeygeneratorgenerate_direct] Generate a new Ed25519 keypair using CSPRNG (direct generation mode). The generated signing key is immediately encrypted with the provided encryption key and stored inside the returned `ManagedKey`. The raw signing key material never leaves memory unencrypted beyond the scope of this function. # Arguments [#arguments-2] * `role` - The role this key will serve (identity, authentication, etc.). * `encryption_key` - A 32-byte AES-256 key used to encrypt the private key at rest. # Errors [#errors-4] Returns `KeyError::GenerationFailed` if key encryption fails. ```rust pub fn generate_direct( role: KeyRole, encryption_key: &[u8; 32], ) -> Result; ``` Source line: `257`. ## generation::KeyGenerator::generate\_key\_id [#generationkeygeneratorgenerate_key_id] Generate a UUID v7-based key identifier. UUID v7 is time-ordered, which allows keys to be naturally sorted by creation time. The format is `key-`. ```rust pub fn generate_key_id() -> String; ``` Source line: `283`. # aegis-keys modules URL: https://docs.openagent.id/reference/rust/aegis-keys Markdown: https://docs.openagent.id/reference/rust/aegis-keys.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-aegis-keys). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/aegis-keys/crate) — 12 declarations * [derivation](/reference/rust/aegis-keys/derivation) — 2 declarations * [generation](/reference/rust/aegis-keys/generation) — 15 declarations * [recovery](/reference/rust/aegis-keys/recovery) — 9 declarations * [rotation](/reference/rust/aegis-keys/rotation) — 7 declarations * [storage](/reference/rust/aegis-keys/storage) — 5 declarations * [threshold](/reference/rust/aegis-keys/threshold) — 4 declarations # aegis-keys · recovery URL: https://docs.openagent.id/reference/rust/aegis-keys/recovery Markdown: https://docs.openagent.id/reference/rust/aegis-keys/recovery.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/recovery.rs`. SHA-256: `036f0e6d4f999ac13319be0ac49b2584670a98441175ad504dda798b518bb14d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## recovery::RecoveryCeremony [#recoveryrecoveryceremony] A recovery ceremony state machine (AEGIS Spec SS6.7). Recovery is a multi-phase process: 1. Ceremony is initiated with a `RecoveryConfig` specifying guardians and threshold. 2. Guardians provide signed authorizations, each adding their weight. 3. Once total weight reaches the threshold, the ceremony is "threshold met." 4. A mandatory timelock period must also elapse before execution is permitted. 5. Only when BOTH conditions are met (`can_execute()`) may recovery proceed. The timelock prevents immediate recovery, giving the legitimate key holder time to detect and abort unauthorized recovery attempts. ```rust #[derive(Debug)] pub struct RecoveryCeremony { /// Unique identifier for this recovery ceremony. pub ceremony_id: String, /// Recovery configuration (guardians, threshold, timelock). pub config: RecoveryConfig, /// Accumulated guardian authorizations. pub authorizations: Vec, /// When the ceremony was initiated. pub initiated_at: DateTime, /// Timestamp before which recovery cannot execute (timelock expiry). pub timelock_until: DateTime } ``` Source line: `25`. ## recovery::GuardianAuthorization [#recoveryguardianauthorization] A signed authorization from a recovery guardian. ```rust #[derive(Debug, Clone)] pub struct GuardianAuthorization { /// The guardian providing authorization. pub guardian: Guardian, /// When the authorization was provided. pub authorized_at: DateTime, /// Cryptographic signature proving the guardian's consent. pub signature: String } ``` Source line: `40`. ## recovery::RecoveryCeremony::new [#recoveryrecoveryceremonynew] Create a new recovery ceremony. Initializes the ceremony with a unique ID, records the initiation time, and computes the timelock expiry based on the config's timelock duration. # Arguments [#arguments] * `config` - The recovery configuration specifying guardians, threshold, and timelock. # Returns [#returns] A new `RecoveryCeremony` with no authorizations accumulated. ```rust pub fn new(config: RecoveryConfig) -> Self; ``` Source line: `62`. ## recovery::RecoveryCeremony::add\_authorization [#recoveryrecoveryceremonyadd_authorization] Add a guardian's authorization to the ceremony. The guardian must be listed in the recovery config. Duplicate authorizations from the same guardian are rejected. # Arguments [#arguments-1] * `auth` - The guardian's signed authorization. # Errors [#errors] Returns `KeyError::RecoveryFailed` if: * The guardian is not in the recovery config * The guardian has already authorized ```rust pub fn add_authorization(&mut self, auth: GuardianAuthorization) -> Result<(), KeyError>; ``` Source line: `90`. ## recovery::RecoveryCeremony::is\_threshold\_met [#recoveryrecoveryceremonyis_threshold_met] Check whether the accumulated guardian weight meets the threshold. Each guardian has a weight; this returns `true` when the sum of weights from authorized guardians reaches or exceeds the configured threshold. ```rust pub fn is_threshold_met(&self) -> bool; ``` Source line: `130`. ## recovery::RecoveryCeremony::is\_timelock\_expired [#recoveryrecoveryceremonyis_timelock_expired] Check whether the mandatory timelock period has expired. The timelock prevents immediate recovery execution, giving the legitimate owner time to detect and abort unauthorized attempts. ```rust pub fn is_timelock_expired(&self) -> bool; ``` Source line: `140`. ## recovery::RecoveryCeremony::can\_execute [#recoveryrecoveryceremonycan_execute] Check whether recovery can proceed. Recovery requires BOTH conditions to be met: 1. The accumulated guardian weight reaches the threshold. 2. The timelock period has elapsed. ```rust pub fn can_execute(&self) -> bool; ``` Source line: `149`. ## recovery::RecoveryCeremony::accumulated\_weight [#recoveryrecoveryceremonyaccumulated_weight] Returns the total accumulated authorization weight. ```rust pub fn accumulated_weight(&self) -> u32; ``` Source line: `154`. ## recovery::RecoveryCeremony::authorization\_count [#recoveryrecoveryceremonyauthorization_count] Returns the number of guardians who have authorized. ```rust pub fn authorization_count(&self) -> usize; ``` Source line: `159`. # aegis-keys · rotation URL: https://docs.openagent.id/reference/rust/aegis-keys/rotation Markdown: https://docs.openagent.id/reference/rust/aegis-keys/rotation.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/rotation.rs`. SHA-256: `dd629129b75d43cfb74e0fa4b837843ceda291b2df3487d6efb5c12c44a320c6`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## rotation::KeyRotation [#rotationkeyrotation] Key rotation coordinator (AEGIS Spec SS6.6). Manages the lifecycle of key rotation events. When a rotation is initiated, a new key is generated and both keys remain valid for the duration of the grace period. ```rust pub struct KeyRotation; ``` Source line: `20`. ## rotation::RotationRequest [#rotationrotationrequest] A request to rotate a key. ```rust pub struct RotationRequest { /// The key ID being rotated. pub key_id: String, /// Grace period during which both old and new keys are valid. pub grace_period: Duration } ``` Source line: `23`. ## rotation::RotationResult [#rotationrotationresult] The result of a successful key rotation. ```rust pub struct RotationResult { /// The ID of the key being replaced. pub old_key_id: String, /// The newly generated replacement key. pub new_key: ManagedKey, /// Timestamp when the grace period ends and the old key is fully retired. pub grace_period_ends: DateTime } ``` Source line: `31`. ## rotation::KeyRotation::initiate [#rotationkeyrotationinitiate] Initiate key rotation for an existing managed key. Generates a new key with the same role as the old key. Both the old and new keys are considered valid until the grace period expires. After the grace period, the old key should be decommissioned. # Arguments [#arguments] * `old` - The existing managed key to rotate away from. * `encryption_key` - A 32-byte AES-256 key for encrypting the new key's private material. # Returns [#returns] A `RotationResult` containing the new key and grace period metadata. # Errors [#errors] Returns `KeyError::RotationFailed` if the new key could not be generated. ```rust pub fn initiate( old: &ManagedKey, encryption_key: &[u8; 32], ) -> Result; ``` Source line: `59`. ## rotation::KeyRotation::initiate\_with\_grace [#rotationkeyrotationinitiate_with_grace] Initiate key rotation with a custom grace period. # Arguments [#arguments-1] * `old` - The existing managed key to rotate away from. * `encryption_key` - A 32-byte AES-256 key for encrypting the new key's private material. * `grace_period` - Duration during which both old and new keys are valid. # Errors [#errors-1] Returns `KeyError::RotationFailed` if the new key could not be generated. ```rust pub fn initiate_with_grace( old: &ManagedKey, encryption_key: &[u8; 32], grace_period: Duration, ) -> Result; ``` Source line: `77`. ## rotation::KeyRotation::is\_grace\_period\_expired [#rotationkeyrotationis_grace_period_expired] Check whether a grace period has expired. Returns `true` if the current time is past the grace period end, meaning the old key should be decommissioned. ```rust pub fn is_grace_period_expired(result: &RotationResult) -> bool; ``` Source line: `101`. ## rotation::is\_rotation\_eligible [#rotationis_rotation_eligible] Convenience function to check if a key role is eligible for rotation. Session keys are not rotated -- they are short-lived and simply expire. Recovery keys require a special ceremony rather than standard rotation. ```rust pub fn is_rotation_eligible(role: KeyRole) -> bool; ``` Source line: `110`. # aegis-keys · storage URL: https://docs.openagent.id/reference/rust/aegis-keys/storage Markdown: https://docs.openagent.id/reference/rust/aegis-keys/storage.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/storage.rs`. SHA-256: `4a9430472f0b46e26843f729358c3202623f174053dcc5b212667a966422f103`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## storage::KeyStore [#storagekeystore] Trait for key storage backends (AEGIS Spec SS6.8). All key storage backends must be thread-safe (`Send + Sync`) and support async operations. Implementations may store keys in memory, on disk, in a database, or in a hardware security module. The stored `ManagedKey` already contains the encrypted private key material, so the storage backend does not need to perform additional encryption. ```rust #[async_trait] pub trait KeyStore: Send + Sync { /// Store a managed key. /// /// If a key with the same `key_id` already exists, it is overwritten. /// /// # Errors /// /// Returns `KeyError::StorageError` if the storage operation fails. async fn store(&self, key: &ManagedKey) -> Result<(), KeyError>; /// Load a managed key by its ID. /// /// # Errors /// /// Returns `KeyError::NotFound` if no key with the given ID exists. /// Returns `KeyError::StorageError` if the load operation fails. async fn load(&self, key_id: &str) -> Result; /// Delete a managed key by its ID. /// /// # Errors /// /// Returns `KeyError::NotFound` if no key with the given ID exists. /// Returns `KeyError::StorageError` if the delete operation fails. async fn delete(&self, key_id: &str) -> Result<(), KeyError>; /// List key IDs, optionally filtered by role. /// /// # Arguments /// /// * `role` - If `Some`, only keys with this role are returned. /// If `None`, all key IDs are returned. /// /// # Errors /// /// Returns `KeyError::StorageError` if the list operation fails. async fn list( &self, role: Option, pagination: Pagination, ) -> Result, KeyError>; } ``` Source line: `26`. ## storage::InMemoryKeyStore [#storageinmemorykeystore] In-memory key store for testing and development. Keys are stored in a `HashMap` protected by a `std::sync::RwLock`. This implementation is NOT suitable for production use as keys are lost when the process exits. ```rust pub struct InMemoryKeyStore { } ``` Source line: `125`. ## storage::InMemoryKeyStore::new [#storageinmemorykeystorenew] Create a new empty in-memory key store. ```rust pub fn new() -> Self; ``` Source line: `131`. ## storage::InMemoryKeyStore::len [#storageinmemorykeystorelen] Returns the number of keys currently stored. ```rust pub fn len(&self) -> usize; ``` Source line: `138`. ## storage::InMemoryKeyStore::is\_empty [#storageinmemorykeystoreis_empty] Returns `true` if the store contains no keys. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `144`. # aegis-keys · threshold URL: https://docs.openagent.id/reference/rust/aegis-keys/threshold Markdown: https://docs.openagent.id/reference/rust/aegis-keys/threshold.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-keys/src/threshold.rs`. SHA-256: `eb57d17d0e98d3cd7804edb24fa1ddeb9ac82eeaaa46f2495595d4f5fe48b8a0`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## threshold::ThresholdKeyPackages [#thresholdthresholdkeypackages] Result of threshold key generation. ```rust pub struct ThresholdKeyPackages { /// Per-participant key packages (one per signer). pub key_packages: BTreeMap, /// The group public key (verifying key for the threshold group). pub public_key_package: frost::keys::PublicKeyPackage } ``` Source line: `15`. ## threshold::generate\_shares [#thresholdgenerate_shares] Generate threshold key shares using FROST trusted dealer. Creates a t-of-n threshold key setup where `min_signers` (t) out of `max_signers` (n) participants are required to produce a valid signature. # Arguments [#arguments] * `min_signers` - Minimum number of signers required (threshold t) * `max_signers` - Total number of participants (n) # Errors [#errors] Returns `KeyError::GenerationFailed` if FROST key generation fails. ```rust pub fn generate_shares( min_signers: u16, max_signers: u16, ) -> Result; ``` Source line: `33`. ## threshold::sign\_with\_threshold [#thresholdsign_with_threshold] Perform a complete threshold signing round (for testing/single-process use). In production, each step would happen on a separate machine. This function runs the full 2-round FROST protocol in a single process for validation. # Arguments [#arguments-1] * `message` - The message bytes to sign * `key_packages` - Per-participant key packages (at least t of them) * `public_key_package` - The group public key package # Errors [#errors-1] Returns `KeyError::SigningFailed` if any round fails. ```rust pub fn sign_with_threshold( message: &[u8], key_packages: &BTreeMap, public_key_package: &frost::keys::PublicKeyPackage, ) -> Result; ``` Source line: `77`. ## threshold::verify\_threshold\_signature [#thresholdverify_threshold_signature] Verify a FROST threshold signature against the group public key. # Arguments [#arguments-2] * `message` - The original message bytes * `signature` - The aggregated FROST signature * `public_key_package` - The group public key package # Returns [#returns] `true` if the signature is valid, `false` otherwise. ```rust pub fn verify_threshold_signature( message: &[u8], signature: &frost::Signature, public_key_package: &frost::keys::PublicKeyPackage, ) -> bool; ``` Source line: `130`. # aegis-wallet · address URL: https://docs.openagent.id/reference/rust/aegis-wallet/address Markdown: https://docs.openagent.id/reference/rust/aegis-wallet/address.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-wallet/src/address.rs`. SHA-256: `5191155b4074c5a8a3c9cedc9d0e284b069ee4360046f048bb84f9d72fc58b18`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## address::WalletAddress [#addresswalletaddress] A derived wallet address for a specific chain. ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct WalletAddress { /// The blockchain chain this address targets. pub chain: Chain, /// The derived address string in chain-native format. pub address: String, /// The BIP-44/SLIP-0010 derivation path used. pub derivation_path: String, /// Hex-encoded public key used for derivation. pub public_key_hex: String } ``` Source line: `15`. ## address::AddressDeriver [#addressaddressderiver] Multi-chain address deriver. Computes addresses from raw public key bytes for each supported chain, using chain-specific encoding rules. ```rust pub struct AddressDeriver; ``` Source line: `30`. ## address::AddressDeriver::derivation\_path [#addressaddressderiverderivation_path] Returns the BIP-44/SLIP-0010 derivation path for a given chain. Path format follows BIP-44: `m/44'/'/'/0/` with chain-specific variations for SLIP-0010 chains (Solana, Aptos, Sui). ```rust pub fn derivation_path(chain: Chain, account: u32, index: u32) -> String; ``` Source line: `37`. ## address::AddressDeriver::derive\_address [#addressaddressderiverderive_address] Derive a wallet address from raw public key bytes for a given chain. Each chain uses its own address encoding: * Ethereum/EVM: `0x` + hex of last 20 bytes of Keccak-256 hash * Solana: base58-encoded public key * Bitcoin: BIP-173 bech32 P2WPKH over HASH160(public key) * Cosmos: bech32 over HASH160(public key) * Osmosis: bech32 over HASH160(public key) * Aptos/Sui: `0x` + hex of SHA-256 of public key * StarkNet: `0x0` + hex prefix ```rust pub fn derive_address( chain: Chain, public_key_bytes: &[u8], ) -> Result; ``` Source line: `80`. ## address::AddressDeriver::derive\_all [#addressaddressderiverderive_all] Derive addresses for multiple chains from the same public key. ```rust pub fn derive_all( public_key_bytes: &[u8], chains: &[Chain], ) -> Result, WalletError>; ``` Source line: `104`. ## address::hex::encode [#addresshexencode] ```rust pub fn encode(bytes: &[u8]) -> String; ``` Source line: `283`. # aegis-wallet · batch URL: https://docs.openagent.id/reference/rust/aegis-wallet/batch Markdown: https://docs.openagent.id/reference/rust/aegis-wallet/batch.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-wallet/src/batch.rs`. SHA-256: `96a13662307da6923a4bd7ad5e97ad451e8c2a5d47a6afea43f1b4b174cd4590`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## batch::BatchResult [#batchbatchresult] Result of a batch signing operation. ```rust #[derive(Debug)] pub struct BatchResult { /// The batch mode that was used. pub mode: BatchMode, /// Per-transaction results (Ok for signed, Err for failures). pub results: Vec>, /// Total number of transactions in the batch. pub total: usize, /// Number of transactions that were successfully signed. pub succeeded: usize } ``` Source line: `15`. ## batch::execute\_batch [#batchexecute_batch] Execute batch transaction signing through the authorization pipeline. # Modes [#modes] * `AllOrNothing`: Pre-validates all transactions first (dry-run). If any would fail, returns an error without signing any. If all pass validation, signs all of them. * `BestEffort`: Attempts each transaction independently. Failures are recorded in the results vec but do not prevent other transactions from being signed. # Errors [#errors] In `AllOrNothing` mode, returns `WalletError::BatchPartialFailure` if any transaction in the batch fails authorization or signing. In `BestEffort` mode, the function itself only returns `Err` for catastrophic/infrastructure failures. Individual transaction failures are captured in `BatchResult::results`. ```rust pub async fn execute_batch( pipeline: &TransactionPipeline, transactions: Vec<(Transaction, AuthContext, PolicyDecision)>, mode: BatchMode, ) -> Result; ``` Source line: `46`. # aegis-wallet · ceremony URL: https://docs.openagent.id/reference/rust/aegis-wallet/ceremony Markdown: https://docs.openagent.id/reference/rust/aegis-wallet/ceremony.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-wallet/src/ceremony.rs`. SHA-256: `a055fca11bc466142b5dd1c9b53c850fcd5abd683995151fedd37f61341c366a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## ceremony::SigningRequest [#ceremonysigningrequest] A request to sign a message within a signing ceremony. ```rust #[derive(Debug, Clone)] pub struct SigningRequest { /// Raw message bytes to sign. pub message: Vec, /// DID of the entity requesting the signature. pub signer_did: String, /// Optional chain context (for chain-specific signing rules). pub chain: Option } ``` Source line: `15`. ## ceremony::SigningResult [#ceremonysigningresult] The result of a signing ceremony. ```rust #[derive(Debug, Clone)] pub struct SigningResult { /// The raw signature bytes. pub signature: Vec, /// The public key of the signer. pub public_key: Vec, /// The signing mode used. pub mode: SigningMode } ``` Source line: `26`. ## ceremony::SigningBackend [#ceremonysigningbackend] Trait for pluggable signing backends. Implementations include direct key signing, MPC threshold signing, TEE-enclave signing, and external KMS delegation. ```rust #[async_trait] pub trait SigningBackend: Send + Sync { /// Execute a signing ceremony for the given request. async fn sign(&self, request: &SigningRequest) -> Result; /// Return the public key bytes for this signer. fn public_key(&self) -> &[u8]; /// The signing mode this backend implements. fn mode(&self) -> SigningMode; } ``` Source line: `40`. ## ceremony::DirectSigner [#ceremonydirectsigner] Direct signing backend using a single Ed25519 key. The key material is zeroized when the struct is dropped. ```rust #[derive(ZeroizeOnDrop)] pub struct DirectSigner { } ``` Source line: `55`. ## ceremony::DirectSigner::new [#ceremonydirectsignernew] Create a new direct signer from an Ed25519 signing key. ```rust pub fn new(signing_key: SigningKey) -> Self; ``` Source line: `66`. ## ceremony::DirectSigner::verifying\_key [#ceremonydirectsignerverifying_key] Return the Ed25519 verifying (public) key. ```rust pub fn verifying_key(&self) -> VerifyingKey; ``` Source line: `75`. ## ceremony::verify\_signature [#ceremonyverify_signature] Verify an Ed25519 signature against a message and public key. Convenience function for verifying signatures produced by `DirectSigner`. ```rust pub fn verify_signature( public_key_bytes: &[u8], message: &[u8], signature_bytes: &[u8], ) -> Result; ``` Source line: `114`. # aegis-wallet · crate URL: https://docs.openagent.id/reference/rust/aegis-wallet/crate Markdown: https://docs.openagent.id/reference/rust/aegis-wallet/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-wallet/src/lib.rs`. SHA-256: `81f68cbce49fa14207778757db13fdc987e7290653f90b4c20e41dbad27a6ad2`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## address [#address] ```rust pub mod address; ``` Source line: `5`. ## batch [#batch] ```rust pub mod batch; ``` Source line: `6`. ## ceremony [#ceremony] ```rust pub mod ceremony; ``` Source line: `7`. ## external [#external] ```rust pub mod external; ``` Source line: `8`. ## pipeline [#pipeline] ```rust pub mod pipeline; ``` Source line: `9`. # aegis-wallet · external URL: https://docs.openagent.id/reference/rust/aegis-wallet/external Markdown: https://docs.openagent.id/reference/rust/aegis-wallet/external.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-wallet/src/external.rs`. SHA-256: `6c01aa5e92517f9a44fcbf3a8ec698289ab07be900c3e615f1ebb6aebcd1cbe8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## external::ExternalSigner [#externalexternalsigner] External signer interface for organizations with existing KMS/HSM. Implementors provide their own signing logic (AWS KMS, GCP Cloud KMS, Hashicorp Vault, hardware tokens, etc.) and expose a uniform interface to the AEGIS wallet infrastructure. ```rust #[async_trait] pub trait ExternalSigner: Send + Sync { /// Sign an arbitrary message using the external signing service. async fn sign(&self, message: &[u8]) -> Result, WalletError>; /// Return the public key bytes from the external signer. fn get_public_key(&self) -> Vec; } ``` Source line: `20`. ## external::ExternalSignerAdapter [#externalexternalsigneradapter] Adapter that wraps any `ExternalSigner` into a `SigningBackend`. This allows external KMS implementations to participate in the standard AEGIS signing ceremony and transaction pipeline. ```rust pub struct ExternalSignerAdapter { } ``` Source line: `32`. ## external::ExternalSignerAdapter::new [#externalexternalsigneradapternew] Create a new adapter wrapping the given external signer. ```rust pub fn new(signer: Box) -> Self; ``` Source line: `41`. # aegis-wallet modules URL: https://docs.openagent.id/reference/rust/aegis-wallet Markdown: https://docs.openagent.id/reference/rust/aegis-wallet.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-aegis-wallet). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/aegis-wallet/crate) — 5 declarations * [address](/reference/rust/aegis-wallet/address) — 6 declarations * [batch](/reference/rust/aegis-wallet/batch) — 2 declarations * [ceremony](/reference/rust/aegis-wallet/ceremony) — 7 declarations * [external](/reference/rust/aegis-wallet/external) — 3 declarations * [pipeline](/reference/rust/aegis-wallet/pipeline) — 7 declarations # aegis-wallet · pipeline URL: https://docs.openagent.id/reference/rust/aegis-wallet/pipeline Markdown: https://docs.openagent.id/reference/rust/aegis-wallet/pipeline.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-wallet/src/pipeline.rs`. SHA-256: `1f47e8f5e14516e501da3b8918bb652f9eb88ed911433066fbeff83b12a1fbea`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## pipeline::Transaction [#pipelinetransaction] A transaction to authorize and sign. ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Transaction { /// Unique transaction identifier. pub tx_id: String, /// DID of the sender. pub from_did: String, /// Destination address or DID. pub to: String, /// Target blockchain network. pub chain: String, /// Transaction payload (calldata, transfer encoding, etc.). pub data: Vec, /// Optional value being transferred (chain-native representation). pub value: Option } ``` Source line: `26`. ## pipeline::Transaction::new [#pipelinetransactionnew] Create a new transaction with an auto-generated UUIDv7 identifier. ```rust pub fn new(from_did: String, to: String, chain: String, data: Vec) -> Self; ``` Source line: `43`. ## pipeline::Transaction::with\_value [#pipelinetransactionwith_value] Create a new transaction with an explicit value. ```rust pub fn with_value(mut self, value: String) -> Self; ``` Source line: `55`. ## pipeline::AuthorizedTransaction [#pipelineauthorizedtransaction] The result of a fully authorized and signed transaction. ```rust #[derive(Debug, Clone)] pub struct AuthorizedTransaction { /// The original transaction. pub transaction: Transaction, /// The cryptographic signature over the transaction data. pub signature: Vec, /// Obligations that were fulfilled during authorization. pub fulfilled_obligations: Vec } ``` Source line: `63`. ## pipeline::TransactionPipeline [#pipelinetransactionpipeline] The full transaction authorization pipeline per AEGIS Spec SS10.4. Enforces a strict five-step process: 1. Verify the caller's identity is valid (not expired). 2. Check delegation scope for direct or delegated authorization. 3. Evaluate policy decision (must be allowed). 4. Fulfill all obligations (log obligations are recorded; others that cannot be fulfilled immediately cause failure). 5. Sign the transaction data via the configured signing backend. If any step fails, the pipeline returns an error and the transaction is NOT signed. ```rust pub struct TransactionPipeline { } ``` Source line: `84`. ## pipeline::TransactionPipeline::new [#pipelinetransactionpipelinenew] Create a new transaction pipeline with the given signing backend. ```rust pub fn new(signer: Arc) -> Self; ``` Source line: `91`. ## pipeline::TransactionPipeline::authorize\_and\_sign [#pipelinetransactionpipelineauthorize_and_sign] Execute the full authorization pipeline for a single transaction. # Errors [#errors] Returns `WalletError::AuthorizationFailed` if identity verification fails, `WalletError::PolicyDenied` if policy denies the transaction, `WalletError::ObligationFailed` if an obligation cannot be fulfilled, or `WalletError::SigningFailed` if the signing ceremony fails. ```rust pub async fn authorize_and_sign( &self, tx: Transaction, auth: &AuthContext, policy_decision: &PolicyDecision, ) -> Result; ``` Source line: `103`. # aegis-store-pg · cache URL: https://docs.openagent.id/reference/rust/aegis-store-pg/cache Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/cache.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/cache.rs`. SHA-256: `547eebeb30ac81b9b3b3e59b462b3ec398e94155ae70f2d389e94fe6340f27da`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## cache::PgVerificationCacheStore [#cachepgverificationcachestore] PostgreSQL-backed verification cache store. Caches `VerificationResult` records in the `aegis_verification_cache` table. The result is serialized as a JSONB column. Expiration is tracked via the `expires_at` column; expired entries are not returned by `get_cached`. ```rust pub struct PgVerificationCacheStore { } ``` Source line: `17`. ## cache::PgVerificationCacheStore::new [#cachepgverificationcachestorenew] Create a new PostgreSQL verification cache store with the given connection pool and TTL (in seconds). The TTL is capped at 300 seconds per the AEGIS specification. ```rust pub fn new(pool: PgPool, ttl_secs: i64) -> Self; ``` Source line: `31`. # aegis-store-pg · crate URL: https://docs.openagent.id/reference/rust/aegis-store-pg/crate Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/lib.rs`. SHA-256: `77c32f388a08e399d52ad6f089fb8463130401d3a0d9f64121bb06621360d40d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## cache [#cache] ```rust pub mod cache; ``` Source line: `13`. ## delegations [#delegations] ```rust pub mod delegations; ``` Source line: `14`. ## keys [#keys] ```rust pub mod keys; ``` Source line: `15`. ## nonces [#nonces] ```rust pub mod nonces; ``` Source line: `16`. ## revocations [#revocations] ```rust pub mod revocations; ``` Source line: `17`. ## sessions [#sessions] ```rust pub mod sessions; ``` Source line: `18`. ## pub use cache::PgVerificationCacheStore; [#pub-use-cachepgverificationcachestore] ```rust pub use cache::PgVerificationCacheStore; ``` Source line: `20`. ## pub use delegations::PgDelegationStore; [#pub-use-delegationspgdelegationstore] ```rust pub use delegations::PgDelegationStore; ``` Source line: `21`. ## pub use keys::PgKeyStore; [#pub-use-keyspgkeystore] ```rust pub use keys::PgKeyStore; ``` Source line: `22`. ## pub use nonces::PgNonceStore; [#pub-use-noncespgnoncestore] ```rust pub use nonces::PgNonceStore; ``` Source line: `23`. ## pub use revocations::PgRevocationStore; [#pub-use-revocationspgrevocationstore] ```rust pub use revocations::PgRevocationStore; ``` Source line: `24`. ## pub use sessions::PgSessionStore; [#pub-use-sessionspgsessionstore] ```rust pub use sessions::PgSessionStore; ``` Source line: `25`. ## ::run\_migrations [#run_migrations] Run the AEGIS migration SQL against the provided PostgreSQL connection pool. Creates all required tables and indexes if they do not already exist. # Errors [#errors] Returns `sqlx::Error` if the migration SQL fails to execute. ```rust pub async fn run_migrations(pool: &sqlx::PgPool) -> Result<(), sqlx::Error>; ``` Source line: `34`. # aegis-store-pg · delegations URL: https://docs.openagent.id/reference/rust/aegis-store-pg/delegations Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/delegations.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/delegations.rs`. SHA-256: `680f56788d96f0965c598ef298a9899b1e3cee93a739af9b386bd568dff7834e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## delegations::PgDelegationStore [#delegationspgdelegationstore] PostgreSQL-backed delegation store. Stores `Delegation` records in the `aegis_delegations` table. The `scope` and `proof` fields are serialized as JSONB columns. ```rust pub struct PgDelegationStore { } ``` Source line: `18`. ## delegations::PgDelegationStore::new [#delegationspgdelegationstorenew] Create a new PostgreSQL delegation store with the given connection pool. ```rust pub fn new(pool: PgPool) -> Self; ``` Source line: `24`. # aegis-store-pg modules URL: https://docs.openagent.id/reference/rust/aegis-store-pg Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-aegis-store-pg). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/aegis-store-pg/crate) — 13 declarations * [cache](/reference/rust/aegis-store-pg/cache) — 2 declarations * [delegations](/reference/rust/aegis-store-pg/delegations) — 2 declarations * [keys](/reference/rust/aegis-store-pg/keys) — 2 declarations * [nonces](/reference/rust/aegis-store-pg/nonces) — 2 declarations * [revocations](/reference/rust/aegis-store-pg/revocations) — 2 declarations * [sessions](/reference/rust/aegis-store-pg/sessions) — 2 declarations # aegis-store-pg · keys URL: https://docs.openagent.id/reference/rust/aegis-store-pg/keys Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/keys.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/keys.rs`. SHA-256: `a2bae48bb084336fe461aa32c18eb5b6ab03ff2d9c0b2456c66c9c6dd71e73be`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## keys::PgKeyStore [#keyspgkeystore] PostgreSQL-backed key store. Stores `ManagedKey` records in the `aegis_keys` table. The encrypted private key material (ciphertext + nonce) is stored as `BYTEA` columns. ```rust pub struct PgKeyStore { } ``` Source line: `17`. ## keys::PgKeyStore::new [#keyspgkeystorenew] Create a new PostgreSQL key store with the given connection pool. ```rust pub fn new(pool: PgPool) -> Self; ``` Source line: `23`. # aegis-store-pg · nonces URL: https://docs.openagent.id/reference/rust/aegis-store-pg/nonces Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/nonces.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/nonces.rs`. SHA-256: `a099b856aa257643b6db7d2b951e16b6365fda223b694d29aa0d21d3727710f7`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## nonces::PgNonceStore [#noncespgnoncestore] PostgreSQL-backed nonce store. Records nonces in the `aegis_nonces` table. The primary key constraint on `nonce` ensures that duplicate insertions are detected, which is used to identify replay attempts. ```rust pub struct PgNonceStore { } ``` Source line: `17`. ## nonces::PgNonceStore::new [#noncespgnoncestorenew] Create a new PostgreSQL nonce store with the given connection pool and TTL for cleanup. The `ttl_secs` parameter controls how old a nonce must be before `cleanup()` will remove it. A value of 0 means cleanup removes all nonces. ```rust pub fn new(pool: PgPool, ttl_secs: i64) -> Self; ``` Source line: `31`. # aegis-store-pg · revocations URL: https://docs.openagent.id/reference/rust/aegis-store-pg/revocations Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/revocations.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/revocations.rs`. SHA-256: `0d29d60c44af9fe3227dc5a913c4c7b81cb8ffdb67f88f9307a1d38b7d214baa`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## revocations::PgRevocationStore [#revocationspgrevocationstore] PostgreSQL-backed revocation store. Records revoked delegation IDs in the `aegis_revocations` table. Uses `ON CONFLICT DO NOTHING` for idempotent revocation. ```rust pub struct PgRevocationStore { } ``` Source line: `16`. ## revocations::PgRevocationStore::new [#revocationspgrevocationstorenew] Create a new PostgreSQL revocation store with the given connection pool. ```rust pub fn new(pool: PgPool) -> Self; ``` Source line: `22`. # aegis-store-pg · sessions URL: https://docs.openagent.id/reference/rust/aegis-store-pg/sessions Markdown: https://docs.openagent.id/reference/rust/aegis-store-pg/sessions.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-store-pg/src/sessions.rs`. SHA-256: `4d1266a446ccc3d8c9d65b987bed63bd3bcfcf6cd6929637db9a28d54ec98eda`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## sessions::PgSessionStore [#sessionspgsessionstore] PostgreSQL-backed session store. Stores `Session` records in the `aegis_sessions` table. Scope is serialized as a JSON array and device binding as an optional TEXT column. ```rust pub struct PgSessionStore { } ``` Source line: `16`. ## sessions::PgSessionStore::new [#sessionspgsessionstorenew] Create a new PostgreSQL session store with the given connection pool. ```rust pub fn new(pool: PgPool) -> Self; ``` Source line: `22`. # aegis-verify · cache URL: https://docs.openagent.id/reference/rust/aegis-verify/cache Markdown: https://docs.openagent.id/reference/rust/aegis-verify/cache.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-verify/src/cache.rs`. SHA-256: `b43d476e5c7adaa9f355df896ee1e0382f6d5d87adb6d3d12a6be942e79124ee`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## cache::VerificationCache [#cacheverificationcache] A TTL-based cache for OAS document verification results. Stores \[`VerificationResult`] entries keyed by DID string. Each entry expires after a configurable duration (capped at 300 seconds per AEGIS Specification §5.8). # Thread Safety [#thread-safety] Uses `RwLock` for interior mutability, allowing concurrent reads with exclusive writes. ```rust pub struct VerificationCache { } ``` Source line: `44`. ## cache::VerificationCache::new [#cacheverificationcachenew] Creates a new cache with the specified TTL in seconds. The TTL is capped at 300 seconds per the AEGIS specification. Values exceeding this limit are silently clamped. # Arguments [#arguments] * `ttl_secs` - Time-to-live in seconds (capped at 300). ```rust pub fn new(ttl_secs: u64) -> Self; ``` Source line: `71`. ## cache::VerificationCache::get [#cacheverificationcacheget] Returns a cached verification result if present and not expired. Expired entries are lazily evicted: if a cached entry is found but has exceeded its TTL, it is not returned but remains in the map until the next write operation or explicit invalidation. # Arguments [#arguments-1] * `did` - The DID to look up. # Returns [#returns] `Some(VerificationResult)` if a valid, non-expired entry exists. `None` if the DID is not cached or the entry has expired. ```rust pub fn get(&self, did: &str) -> Option; ``` Source line: `93`. ## cache::VerificationCache::insert [#cacheverificationcacheinsert] Inserts a verification result into the cache. If an entry already exists for the given DID, it is replaced. # Arguments [#arguments-2] * `did` - The DID to cache. * `result` - The verification result to store. ```rust pub fn insert(&self, did: &str, result: VerificationResult); ``` Source line: `111`. ## cache::VerificationCache::invalidate [#cacheverificationcacheinvalidate] Removes a specific entry from the cache. # Arguments [#arguments-3] * `did` - The DID to invalidate. ```rust pub fn invalidate(&self, did: &str); ``` Source line: `129`. ## cache::VerificationCache::clear [#cacheverificationcacheclear] Removes all entries from the cache. ```rust pub fn clear(&self); ``` Source line: `136`. ## cache::VerificationCache::len [#cacheverificationcachelen] Returns the number of entries currently in the cache (including expired). ```rust pub fn len(&self) -> usize; ``` Source line: `143`. ## cache::VerificationCache::is\_empty [#cacheverificationcacheis_empty] Returns true if the cache contains no entries. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `148`. ## cache::VerificationCache::ttl [#cacheverificationcachettl] Returns the configured TTL duration. ```rust pub fn ttl(&self) -> Duration; ``` Source line: `153`. # aegis-verify · crate URL: https://docs.openagent.id/reference/rust/aegis-verify/crate Markdown: https://docs.openagent.id/reference/rust/aegis-verify/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-verify/src/lib.rs`. SHA-256: `c8d798fb66648c528b91bacec4feac289043d5ed59797674eebc49676330f1df`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## cache [#cache] ```rust pub mod cache; ``` Source line: `14`. ## pipeline [#pipeline] ```rust pub mod pipeline; ``` Source line: `15`. ## store [#store] ```rust pub mod store; ``` Source line: `16`. ## pub use cache::VerificationCache; [#pub-use-cacheverificationcache] ```rust pub use cache::VerificationCache; ``` Source line: `18`. ## pub use pipeline::VerificationPipeline; [#pub-use-pipelineverificationpipeline] ```rust pub use pipeline::VerificationPipeline; ``` Source line: `19`. ## pub use store::\{InMemoryVerificationCacheStore, VerificationCacheStore}; [#pub-use-storeinmemoryverificationcachestore-verificationcachestore] ```rust pub use store::{InMemoryVerificationCacheStore, VerificationCacheStore}; ``` Source line: `20`. # aegis-verify modules URL: https://docs.openagent.id/reference/rust/aegis-verify Markdown: https://docs.openagent.id/reference/rust/aegis-verify.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-aegis-verify). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/aegis-verify/crate) — 6 declarations * [cache](/reference/rust/aegis-verify/cache) — 9 declarations * [pipeline](/reference/rust/aegis-verify/pipeline) — 5 declarations * [store](/reference/rust/aegis-verify/store) — 4 declarations # aegis-verify · pipeline URL: https://docs.openagent.id/reference/rust/aegis-verify/pipeline Markdown: https://docs.openagent.id/reference/rust/aegis-verify/pipeline.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-verify/src/pipeline.rs`. SHA-256: `ae488b14dd9bfc2ea06b1b97ae7f8bf769baa207de423ba1e81e1a190b56393a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## pipeline::VerificationPipeline [#pipelineverificationpipeline] The AEGIS Verification Pipeline. Performs complete verification of OAS identity documents per AEGIS Specification §5. The pipeline: 1. Resolves the DID via registered resolver plugins 2. Validates the document structure 3. Verifies the Ed25519Signature2020 document proof 4. Checks revocation status 5. Verifies lineage chain to human root 6. Checks human root liveness 7. Computes the verified conformance level Results are cached with a configurable TTL (max 300 seconds). ```rust pub struct VerificationPipeline { } ``` Source line: `85`. ## pipeline::VerificationPipeline::new [#pipelineverificationpipelinenew] Creates a new verification pipeline. # Arguments [#arguments] * `registry` - The AEGIS plugin registry containing DID resolvers. * `config` - Verification configuration (timeouts, depth, cache TTL). ```rust pub fn new(registry: Arc, config: VerificationConfig) -> Self; ``` Source line: `101`. ## pipeline::VerificationPipeline::verify [#pipelineverificationpipelineverify] Performs a full verification of an OAS identity document. Returns a cached result if available and not expired. Otherwise, runs the complete verification pipeline and caches the result. # Arguments [#arguments-1] * `did` - The `did:oas` identifier to verify. # Returns [#returns] A \[`VerificationResult`] containing the verification outcome. # Errors [#errors] Returns \[`VerificationError`] if any step of the pipeline fails with an unrecoverable error (e.g., resolution failure, invalid signature). ```rust pub async fn verify(&self, did: &str) -> Result; ``` Source line: `127`. ## pipeline::VerificationPipeline::verify\_force\_refresh [#pipelineverificationpipelineverify_force_refresh] Performs a full verification bypassing the cache. Always runs the complete pipeline regardless of cached results. The fresh result is stored in the cache, replacing any previous entry. # Arguments [#arguments-2] * `did` - The `did:oas` identifier to verify. # Returns [#returns-1] A fresh \[`VerificationResult`]. # Errors [#errors-1] Returns \[`VerificationError`] if verification fails. ```rust pub async fn verify_force_refresh( &self, did: &str, ) -> Result; ``` Source line: `155`. ## pipeline::VerificationPipeline::cache [#pipelineverificationpipelinecache] Returns a reference to the internal cache for inspection. ```rust pub fn cache(&self) -> &VerificationCache; ``` Source line: `166`. # aegis-verify · store URL: https://docs.openagent.id/reference/rust/aegis-verify/store Markdown: https://docs.openagent.id/reference/rust/aegis-verify/store.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/aegis-verify/src/store.rs`. SHA-256: `ee67ee8eec84a09c8a2662d8802c49e56c61f669e5d0a200b33b1fdabe569cea`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## store::VerificationCacheStore [#storeverificationcachestore] Pluggable storage backend for verification result caching. Implementations may use in-memory storage, databases, or distributed caches. All operations are async to accommodate network-backed stores. This trait complements \[`crate::cache::VerificationCache`] by providing an async, error-aware interface suitable for production persistence backends. The existing `VerificationCache` can be adapted to use a `VerificationCacheStore` internally. ```rust #[async_trait] pub trait VerificationCacheStore: Send + Sync { /// Retrieve a cached verification result for the given DID. /// /// Returns `None` if no cached result exists or if the cached entry /// has expired. Implementations should not return expired entries. async fn get_cached(&self, did: &str) -> Result, VerificationError>; /// Store a verification result in the cache for the given DID. /// /// If an entry already exists for the DID, it is replaced. async fn store_cached( &self, did: &str, result: &VerificationResult, ) -> Result<(), VerificationError>; /// Invalidate (remove) a cached entry for the given DID. /// /// Does not return an error if no entry existed. async fn invalidate(&self, did: &str) -> Result<(), VerificationError>; /// Remove all expired entries from the cache. /// /// Returns the number of entries removed. async fn cleanup_expired(&self) -> Result; } ``` Source line: `30`. ## store::InMemoryVerificationCacheStore [#storeinmemoryverificationcachestore] In-memory verification cache store backed by a `RwLock`. Stores \[`VerificationResult`] entries keyed by DID string with a configurable TTL (capped at 300 seconds per specification). Suitable for development, testing, and single-instance deployments. For production multi-node deployments, use a database-backed or distributed cache implementation of \[`VerificationCacheStore`]. ```rust pub struct InMemoryVerificationCacheStore { } ``` Source line: `85`. ## store::InMemoryVerificationCacheStore::new [#storeinmemoryverificationcachestorenew] Creates a new in-memory verification cache store with the specified TTL in seconds. The TTL is capped at 300 seconds per the AEGIS specification. Values exceeding this limit are silently clamped. ```rust pub fn new(ttl_secs: u64) -> Self; ``` Source line: `96`. ## store::InMemoryVerificationCacheStore::ttl [#storeinmemoryverificationcachestorettl] Returns the configured TTL duration. ```rust pub fn ttl(&self) -> Duration; ``` Source line: `105`. # agent-capability-token · claims URL: https://docs.openagent.id/reference/rust/agent-capability-token/claims Markdown: https://docs.openagent.id/reference/rust/agent-capability-token/claims.md Declared module signatures, types, configuration, and source documentation. Source: `act/agent-capability-token/src/claims.rs`. SHA-256: `86db89e62b3fa97ec758d96d606bec63495b139630cc33fc19854b074155732d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## claims::Confirmation [#claimsconfirmation] Proof-of-possession binding. ANVIL section 5.2 requires that an ACT be bound to the agent's OAS DID by proof-of-possession. A verifier that ignores this claim cannot tell a legitimate holder from someone replaying a captured token, which is why it is typed here rather than left to the extension map. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Confirmation { /// Fingerprint of the key the holder must demonstrate control of. pub key_fingerprint: String, /// Algorithm the fingerprint and possession proof use, for example /// `"Ed25519"`. pub alg: String } ``` Source line: `31`. ## claims::Delegation [#claimsdelegation] Constraints governing whether and how this token may be delegated onward. ANVIL section 5.2 requires that an agent not delegate capabilities it does not hold, and that child capabilities be a strict subset of the parent's. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Delegation { /// Whether onward delegation is permitted at all. pub allow_delegation: bool, /// Remaining delegation depth. Zero forbids further delegation. pub max_depth: u8, /// Subset of scopes that may be delegated. `None` means the holder's full /// scope set is delegatable, subject to `allow_delegation`. #[serde(default, skip_serializing_if = "Option::is_none")] pub delegatable_scopes: Option>, /// Whether any recipient may receive a delegation. pub allow_any_delegate: bool, /// DIDs permitted to receive a delegation when `allow_any_delegate` is /// false. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub allowed_delegates: Vec, /// Minimum reduction in lifetime, in seconds, that a delegated token must /// apply relative to this one. #[serde(default)] pub min_ttl_reduction_seconds: i64 } ``` Source line: `44`. ## claims::ActClaims [#claimsactclaims] The claim set carried inside an ACT envelope. Field names are the wire keys. Unknown top-level keys are ignored on decode so that a newer issuer can add typed claims without breaking existing verifiers; issuer-specific claims belong in \[`ActClaims::ext`] instead. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ActClaims { /// Token identifier, unique per issuance. Text, not bytes - a UUID here is /// carried in its canonical hyphenated form. pub jti: String, /// Subject: the OAS DID of the agent this token was issued to. pub sub: String, /// Issuer: the broker instance that minted this token. pub iss: String, /// Audiences this token is valid for. /// /// Decodes from either a single string or an array of strings, since a /// single-audience token is the common case and writing it as a bare string /// is the conventional CBOR/JWT shorthand. #[serde(deserialize_with = "audience_from_string_or_array")] pub aud: Vec, /// Issued-at time, in seconds since the Unix epoch. pub iat: i64, /// Not-before time, in seconds since the Unix epoch. #[serde(default)] pub nbf: i64, /// Expiry time, in seconds since the Unix epoch. pub exp: i64, /// Tenant this token is scoped to. pub tenant_id: String, /// Granted capability scopes, as a flat array. pub scope: Vec, /// Proof-of-possession binding. See [`Confirmation`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub cnf: Option, /// Onward delegation constraints. See [`Delegation`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub delegation: Option, /// Issuer-defined claims, carried inside the signature and passed through /// unaltered. /// /// This is where rate limits, budgets, device and network bindings, and /// audit trace belong. A verifier that does not understand a key here must /// preserve it rather than drop it, so that a downstream component which /// does understand it still receives an intact, signed value. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub ext: BTreeMap } ``` Source line: `71`. ## claims::ActClaims::validate\_structure [#claimsactclaimsvalidate_structure] Checks the claim set is structurally sound, independent of signature or clock. Called during verification before any policy check. Kept public so an issuer can reject a malformed claim set at mint time rather than discovering it at the verifier. # Errors [#errors] Returns \[`ActError::EmptyClaim`] for a required claim that is blank, and \[`ActError::EmptyValidityWindow`] if `nbf` is not before `exp`. ```rust pub fn validate_structure(&self) -> ActResult<()>; ``` Source line: `155`. ## claims::ActClaims::authorizes [#claimsactclaimsauthorizes] Whether the granted scopes authorize `requested`. Wildcards in the grant expand; wildcards in the request do not. See \[`Scope::covers`]. ```rust #[must_use] pub fn authorizes(&self, requested: &Scope) -> bool; ``` Source line: `186`. ## claims::ActClaims::has\_audience [#claimsactclaimshas_audience] Whether this token lists `audience` among its audiences. ```rust #[must_use] pub fn has_audience(&self, audience: &str) -> bool; ``` Source line: `192`. # agent-capability-token · crate URL: https://docs.openagent.id/reference/rust/agent-capability-token/crate Markdown: https://docs.openagent.id/reference/rust/agent-capability-token/crate.md Declared module signatures, types, configuration, and source documentation. Source: `act/agent-capability-token/src/lib.rs`. SHA-256: `a326ce327fca34441b760e229ef3b7ac9d9ae536c1899365dd538ac56ebd6918`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## claims [#claims] ```rust pub mod claims; ``` Source line: `63`. ## error [#error] ```rust pub mod error; ``` Source line: `64`. ## scope [#scope] ```rust pub mod scope; ``` Source line: `65`. ## wire [#wire] ```rust pub mod wire; ``` Source line: `66`. ## pub use claims::\{ActClaims, Confirmation, Delegation}; [#pub-use-claimsactclaims-confirmation-delegation] ```rust pub use claims::{ActClaims, Confirmation, Delegation}; ``` Source line: `68`. ## pub use error::\{ActError, ActResult}; [#pub-use-erroracterror-actresult] ```rust pub use error::{ActError, ActResult}; ``` Source line: `69`. ## pub use scope::\{Scope, SCOPE\_SEGMENTS, WILDCARD}; [#pub-use-scopescope-scope_segments-wildcard] ```rust pub use scope::{Scope, SCOPE_SEGMENTS, WILDCARD}; ``` Source line: `70`. ## pub use wire::\{ [#pub-use-wire] claims\_to\_signing\_payload, envelope\_from\_parts, verify, ActEnvelope, PublicKeyBytes, Verifier, ALGORITHM\_ED25519, FORMAT\_VERSION, MAX\_ACT\_BYTES, }; ```rust pub use wire::{ claims_to_signing_payload, envelope_from_parts, verify, ActEnvelope, PublicKeyBytes, Verifier, ALGORITHM_ED25519, FORMAT_VERSION, MAX_ACT_BYTES, }; ``` Source line: `71`. ## pub use wire::sign; [#pub-use-wiresign] ```rust #[cfg(feature = "sign")] pub use wire::sign; ``` Source line: `77`. # agent-capability-token · error URL: https://docs.openagent.id/reference/rust/agent-capability-token/error Markdown: https://docs.openagent.id/reference/rust/agent-capability-token/error.md Declared module signatures, types, configuration, and source documentation. Source: `act/agent-capability-token/src/error.rs`. SHA-256: `0f6e05a67798b4bd4503b6522a733e617a9aef0893ef65185684ed1a8f1bc6cc`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::ActError [#erroracterror] Error types for ACT encoding, decoding and verification. Failures encountered while decoding or verifying an ACT. Variants are deliberately specific so callers can distinguish an expired token from a forged one in logs and metrics. A verifier that collapses these into a single "invalid token" outcome loses the ability to alarm on forgery while staying quiet about ordinary expiry. ```rust #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum ActError { /// The encoded token exceeded [`crate::MAX_ACT_BYTES`]. /// /// Checked before any parsing, so a hostile payload cannot force /// unbounded allocation. #[error("token is {actual} bytes, exceeding the {limit}-byte maximum")] TooLarge { /// Size of the rejected input. actual: usize, /// The configured ceiling. limit: usize, }, /// The outer envelope was not well-formed CBOR, or did not match the /// envelope schema. #[error("envelope decode failed: {0}")] EnvelopeDecode(String), /// The claims payload inside the envelope was not well-formed CBOR, or did /// not match the claims schema. #[error("claims decode failed: {0}")] ClaimsDecode(String), /// The envelope declared a format version this build does not implement. /// /// Carried explicitly so a rollout can distinguish "forged" from "newer /// than me", which are operationally opposite situations. #[error("unsupported ACT format version {found}, this build supports {supported}")] UnsupportedVersion { /// Version declared by the envelope. found: u64, /// Version this build implements. supported: u64, }, /// The envelope declared a signature algorithm this build does not /// implement. #[error("unsupported signature algorithm {0:?}, this build implements Ed25519")] UnsupportedAlgorithm(String), /// The signature field was absent. #[error("envelope carries no signature")] MissingSignature, /// The signature was present but not 64 bytes. #[error("signature is {0} bytes, expected exactly 64")] MalformedSignature(usize), /// A configured trusted key was not a valid Ed25519 public key. /// /// Distinguished from a verification failure because it is a /// misconfiguration on the verifier's side, not a problem with the token. #[error("trusted key at index {index} is not a valid Ed25519 key: {reason}")] MalformedTrustedKey { /// Position in the supplied key set. index: usize, /// Underlying reason. reason: String, }, /// No trusted keys were supplied, so no token could ever verify. #[error("at least one trusted issuer key is required")] NoTrustedKeys, /// The signature did not validate against any trusted key. #[error("signature did not validate against any of {tried} trusted keys")] SignatureInvalid { /// Number of keys attempted. tried: usize, }, /// `exp` is at or before the current time. #[error("token expired at {expired_at} (now {now})")] Expired { /// The `exp` claim. expired_at: i64, /// Time used for the comparison. now: i64, }, /// `nbf` is after the current time. #[error("token not valid until {valid_from} (now {now})")] NotYetValid { /// The `nbf` claim. valid_from: i64, /// Time used for the comparison. now: i64, }, /// `iss` did not match the expected issuer. #[error("issuer mismatch: expected {expected:?}, found {found:?}")] IssuerMismatch { /// Issuer the verifier requires. expected: String, /// Issuer the token carries. found: String, }, /// `aud` did not include the expected audience. #[error("audience mismatch: expected {expected:?}, found {found:?}")] AudienceMismatch { /// Audience the verifier requires. expected: String, /// Audiences the token carries. found: Vec, }, /// A required scope was absent from `scope`. #[error("missing required scope {0:?}")] MissingScope(String), /// A scope did not match the `service:resource:action` grammar. #[error("scope {value:?} is malformed: {reason}")] MalformedScope { /// The offending scope string. value: String, /// Why it was rejected. reason: &'static str, }, /// A structurally required claim was empty. #[error("claim {0} must not be empty")] EmptyClaim(&'static str), /// `exp` was not after `nbf`, so the token has no valid window. #[error("token validity window is empty: nbf {nbf} is not before exp {exp}")] EmptyValidityWindow { /// The `nbf` claim. nbf: i64, /// The `exp` claim. exp: i64, }, /// Serializing claims or an envelope failed. #[error("encode failed: {0}")] Encode(String), } ``` Source line: `11`. ## error::ActResult [#erroractresult] Result alias for ACT operations. ```rust pub type ActResult = Result; ``` Source line: `150`. # agent-capability-token modules URL: https://docs.openagent.id/reference/rust/agent-capability-token Markdown: https://docs.openagent.id/reference/rust/agent-capability-token.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/act-agent-capability-token). [Focused integration guide](/arsenal/act-tokens). ## Modules [#modules] * [crate](/reference/rust/agent-capability-token/crate) — 9 declarations * [claims](/reference/rust/agent-capability-token/claims) — 6 declarations * [error](/reference/rust/agent-capability-token/error) — 2 declarations * [scope](/reference/rust/agent-capability-token/scope) — 9 declarations * [wire](/reference/rust/agent-capability-token/wire) — 16 declarations # agent-capability-token · scope URL: https://docs.openagent.id/reference/rust/agent-capability-token/scope Markdown: https://docs.openagent.id/reference/rust/agent-capability-token/scope.md Declared module signatures, types, configuration, and source documentation. Source: `act/agent-capability-token/src/scope.rs`. SHA-256: `4958ce88d532883b39de4c8600bbf1dc51733ad13e92e0dc5c4b82b3b66ece7d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## scope::WILDCARD [#scopewildcard] The wildcard segment, which matches any value in its position. ```rust pub const WILDCARD: &str; ``` Source line: `14`. ## scope::SCOPE\_SEGMENTS [#scopescope_segments] Number of colon-separated segments in a well-formed scope. ```rust pub const SCOPE_SEGMENTS: usize; ``` Source line: `17`. ## scope::Scope [#scopescope] A validated capability scope in `service:resource:action` form. Serializes as a plain string, so the wire representation is a flat array of strings rather than a nested structure. # Examples [#examples] ``` use agent_capability_token::Scope; let scope: Scope = "tools:calendar:invoke".parse()?; assert_eq!(scope.service(), "tools"); assert_eq!(scope.action(), "invoke"); // A granted wildcard covers a specific request. let granted: Scope = "runtime:platform:*".parse()?; let requested: Scope = "runtime:platform:spawn".parse()?; assert!(granted.covers(&requested)); # Ok::<(), agent_capability_token::ActError>(()) ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Scope { } ``` Source line: `40`. ## scope::Scope::parse [#scopescopeparse] Parses and validates a scope string. # Errors [#errors] Returns \[`ActError::MalformedScope`] unless the input has exactly three non-empty colon-separated segments. ```rust pub fn parse(value: impl Into) -> ActResult; ``` Source line: `54`. ## scope::Scope::service [#scopescopeservice] The service segment. ```rust #[must_use] pub fn service(&self) -> &str; ``` Source line: `91`. ## scope::Scope::resource [#scopescoperesource] The resource segment. ```rust #[must_use] pub fn resource(&self) -> &str; ``` Source line: `97`. ## scope::Scope::action [#scopescopeaction] The action segment. ```rust #[must_use] pub fn action(&self) -> &str; ``` Source line: `103`. ## scope::Scope::as\_str [#scopescopeas_str] The scope as it appears on the wire. ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `109`. ## scope::Scope::covers [#scopescopecovers] Whether this scope, treated as a grant, authorizes `requested`. A \[`WILDCARD`] segment in the grant matches any value in the same position. The comparison is directional: a wildcard in `requested` is matched literally, so a caller cannot widen its own authority by asking for `*`. ```rust #[must_use] pub fn covers(&self, requested: &Self) -> bool; ``` Source line: `120`. # agent-capability-token · wire URL: https://docs.openagent.id/reference/rust/agent-capability-token/wire Markdown: https://docs.openagent.id/reference/rust/agent-capability-token/wire.md Declared module signatures, types, configuration, and source documentation. Source: `act/agent-capability-token/src/wire.rs`. SHA-256: `c72d2909a9791584b9c5611732b7cc6b43de3de6a3ac4002e4359870c358d24f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## wire::FORMAT\_VERSION [#wireformat_version] Current ACT format version. ```rust pub const FORMAT_VERSION: u64; ``` Source line: `34`. ## wire::ALGORITHM\_ED25519 [#wirealgorithm_ed25519] The only signature algorithm this version defines. ```rust pub const ALGORITHM_ED25519: &str; ``` Source line: `37`. ## wire::MAX\_ACT\_BYTES [#wiremax_act_bytes] Maximum accepted size of an encoded ACT, in bytes. Enforced before parsing so an oversized payload cannot drive allocation. ```rust pub const MAX_ACT_BYTES: usize; ``` Source line: `42`. ## wire::PublicKeyBytes [#wirepublickeybytes] A raw Ed25519 public key. Kept as a plain array so this crate does not impose a key-handle type on callers, who typically hold a rotating set loaded from their issuer's key endpoint. ```rust pub type PublicKeyBytes = [u8; 32]; ``` Source line: `52`. ## wire::ActEnvelope [#wireactenvelope] The outer envelope, as it appears on the wire. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ActEnvelope { /// Format version. pub v: u64, /// Signature algorithm identifier. pub alg: String, /// CBOR-encoded claims. These exact bytes are what the signature covers. pub claims: serde_bytes::ByteBuf, /// Raw signature over `claims`. pub sig: serde_bytes::ByteBuf, /// Optional key identifier, so a verifier can select a key during rotation /// instead of trying every trusted key. #[serde(default, skip_serializing_if = "Option::is_none")] pub kid: Option } ``` Source line: `56`. ## wire::ActEnvelope::decode [#wireactenvelopedecode] Decodes an envelope without verifying its signature. Useful for reading `kid` in order to select a verification key. The claims inside are unauthenticated until \[`verify`] succeeds, and must not be used for any authorization decision. # Errors [#errors] Returns \[`ActError::TooLarge`] above \[`MAX_ACT_BYTES`], \[`ActError::EnvelopeDecode`] for malformed CBOR, \[`ActError::UnsupportedVersion`] or \[`ActError::UnsupportedAlgorithm`] for a format this build does not implement. ```rust pub fn decode(bytes: &[u8]) -> ActResult; ``` Source line: `84`. ## wire::ActEnvelope::encode [#wireactenvelopeencode] Serializes this envelope to CBOR. # Errors [#errors-1] Returns \[`ActError::Encode`] if serialization fails. ```rust pub fn encode(&self) -> ActResult>; ``` Source line: `113`. ## wire::Verifier [#wireverifier] What a verifier requires of a token. ```rust #[derive(Debug, Clone)] pub struct Verifier { } ``` Source line: `122`. ## wire::Verifier::new [#wireverifiernew] Builds a verifier. # Errors [#errors-2] Returns \[`ActError::NoTrustedKeys`] if `trusted_keys` is empty, since no token could then ever verify and the misconfiguration should surface at construction rather than as a stream of signature failures. ```rust pub fn new( trusted_keys: Vec, expected_issuer: impl Into, expected_audience: impl Into, ) -> ActResult; ``` Source line: `139`. ## wire::Verifier::requiring\_scopes [#wireverifierrequiring_scopes] Requires that the token grant every scope in `scopes`. ```rust #[must_use] pub fn requiring_scopes(mut self, scopes: impl IntoIterator) -> Self; ``` Source line: `159`. ## wire::Verifier::with\_leeway\_seconds [#wireverifierwith_leeway_seconds] Allows `seconds` of clock skew on the `nbf` and `exp` checks. Applied symmetrically. Callers running across hosts without tightly synchronized clocks need a small allowance here; leaving it at zero makes a token minted moments ago fail at a verifier whose clock trails the issuer's. ```rust #[must_use] pub fn with_leeway_seconds(mut self, seconds: i64) -> Self; ``` Source line: `171`. ## wire::Verifier::with\_clock [#wireverifierwith_clock] Pins the time used for temporal checks, in seconds since the Unix epoch. Intended for tests and for replaying a decision at a known instant. ```rust #[must_use] pub fn with_clock(mut self, now_unix_seconds: i64) -> Self; ``` Source line: `180`. ## wire::verify [#wireverify] Verifies an encoded ACT and returns its claims. The order matters. Signature verification precedes every claim check, so a forged token is rejected before any of its unauthenticated content is used to make a decision or shape a log line. 1. Enforce the size ceiling and decode the envelope. 2. Verify the Ed25519 signature over the raw `claims` bytes. 3. Decode the claims and check they are structurally sound. 4. Check the temporal window, issuer, audience, and required scopes. # Errors [#errors-3] Returns the \[`ActError`] variant describing the first failed step. # Examples [#examples] ``` use agent_capability_token::{verify, ActError, Verifier}; let verifier = Verifier::new(vec![[0u8; 32]], "arsenal:broker:prod-1", "omerta")?; // An empty payload is not a valid envelope. assert!(matches!(verify(&[], &verifier), Err(ActError::EnvelopeDecode(_)))); # Ok::<(), ActError>(()) ``` ```rust pub fn verify(token_bytes: &[u8], verifier: &Verifier) -> ActResult; ``` Source line: `232`. ## wire::claims\_to\_signing\_payload [#wireclaims_to_signing_payload] Encodes claims into the exact byte string the signature must cover. Exposed so an issuer holding its key in an HSM, or any other signer that cannot hand over private key material, can produce the payload here and sign it elsewhere. # Errors [#errors-4] Returns \[`ActError::Encode`] if serialization fails. ```rust pub fn claims_to_signing_payload(claims: &ActClaims) -> ActResult>; ``` Source line: `341`. ## wire::envelope\_from\_parts [#wireenvelope_from_parts] Assembles an envelope from claims bytes and a detached signature. Pairs with \[`claims_to_signing_payload`] for signers that hold their key outside the process. # Errors [#errors-5] Returns \[`ActError::MalformedSignature`] unless `signature` is 64 bytes, and \[`ActError::TooLarge`] if the assembled token exceeds \[`MAX_ACT_BYTES`]. ```rust pub fn envelope_from_parts( claims_bytes: Vec, signature: &[u8], kid: Option, ) -> ActResult>; ``` Source line: `357`. ## wire::sign [#wiresign] Signs claims with an in-process key and returns an encoded ACT. Behind the `sign` feature: a verifier has no reason to link signing code, and most deployments verify in far more places than they mint. # Errors [#errors-6] Returns \[`ActError::Encode`] if serialization fails, or \[`ActError::TooLarge`] if the assembled token exceeds \[`MAX_ACT_BYTES`]. ```rust #[cfg(feature = "sign")] pub fn sign( claims: &ActClaims, signing_key: &ed25519_dalek::SigningKey, kid: Option, ) -> ActResult>; ``` Source line: `394`. # arsenal-policy · crate URL: https://docs.openagent.id/reference/rust/arsenal-policy/crate Markdown: https://docs.openagent.id/reference/rust/arsenal-policy/crate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-policy/src/lib.rs`. SHA-256: `6c9d8fd45c446ec98067a79fe50ca4abcef78738ee12bdc12d827f20f9f44c8c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## pub use arsenal\_core::policy::\{ [#pub-use-arsenal_corepolicy] ConditionOperator, PolicyCondition, PolicyDecision, PolicyDocument, PolicyEffect, PolicyId, PolicyRequest, PolicyRule, }; ```rust pub use arsenal_core::policy::{ ConditionOperator, PolicyCondition, PolicyDecision, PolicyDocument, PolicyEffect, PolicyId, PolicyRequest, PolicyRule, }; ``` Source line: `13`. ## ::PolicyEngine [#policyengine] Policy engine for evaluating multiple policies ```rust pub struct PolicyEngine { } ``` Source line: `19`. ## ::PolicyEngine::new [#policyenginenew] Create a new policy engine ```rust #[must_use] pub fn new() -> Self; ``` Source line: `27`. ## ::PolicyEngine::add\_policy [#policyengineadd_policy] Add a policy ```rust pub fn add_policy(&mut self, policy: PolicyDocument); ``` Source line: `34`. ## ::PolicyEngine::remove\_policy [#policyengineremove_policy] Remove a policy ```rust pub fn remove_policy(&mut self, policy_id: &str) -> Option; ``` Source line: `39`. ## ::PolicyEngine::evaluate [#policyengineevaluate] Evaluate all policies for a request Returns the decision from the highest-priority matching policy. If no policies match, returns Deny by default. ```rust #[must_use] pub fn evaluate(&self, request: &PolicyRequest) -> PolicyDecision; ``` Source line: `48`. ## ::PolicyEngine::get\_policy [#policyengineget_policy] Get a policy by ID ```rust #[must_use] pub fn get_policy(&self, policy_id: &str) -> Option<&PolicyDocument>; ``` Source line: `69`. ## ::PolicyEngine::policy\_ids [#policyenginepolicy_ids] Get all policy IDs ```rust #[must_use] pub fn policy_ids(&self) -> Vec; ``` Source line: `75`. # arsenal-policy modules URL: https://docs.openagent.id/reference/rust/arsenal-policy Markdown: https://docs.openagent.id/reference/rust/arsenal-policy.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/arsenal-crates-arsenal-policy). [Focused integration guide](/arsenal/overview). ## Modules [#modules] * [crate](/reference/rust/arsenal-policy/crate) — 8 declarations # arsenal-crypto · crate URL: https://docs.openagent.id/reference/rust/arsenal-crypto/crate Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/crate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/lib.rs`. SHA-256: `3322fef81a38819ff0ab7b16d77ee2e93ec14425629eb7719b351f5300c0133c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## encryption [#encryption] ```rust pub mod encryption; ``` Source line: `23`. ## envelope [#envelope] ```rust pub mod envelope; ``` Source line: `24`. ## hash [#hash] ```rust pub mod hash; ``` Source line: `25`. ## kdf [#kdf] ```rust pub mod kdf; ``` Source line: `26`. ## keys [#keys] ```rust pub mod keys; ``` Source line: `27`. ## random [#random] ```rust pub mod random; ``` Source line: `28`. ## signing [#signing] ```rust pub mod signing; ``` Source line: `29`. ## token\_signer [#token_signer] ```rust pub mod token_signer; ``` Source line: `30`. ## pub use encryption::\{Decryptor, EncryptedData, Encryptor}; [#pub-use-encryptiondecryptor-encrypteddata-encryptor] ```rust pub use encryption::{Decryptor, EncryptedData, Encryptor}; ``` Source line: `32`. ## pub use envelope::\{EnvelopeEncryption, WrappedKey}; [#pub-use-envelopeenvelopeencryption-wrappedkey] ```rust pub use envelope::{EnvelopeEncryption, WrappedKey}; ``` Source line: `33`. ## pub use hash::\{Hash, Hasher}; [#pub-use-hashhash-hasher] ```rust pub use hash::{Hash, Hasher}; ``` Source line: `34`. ## pub use kdf::\{DerivedKey, KeyDerivation}; [#pub-use-kdfderivedkey-keyderivation] ```rust pub use kdf::{DerivedKey, KeyDerivation}; ``` Source line: `35`. ## pub use keys::\{EncryptionKeyPair, KeyId, SigningKeyPair}; [#pub-use-keysencryptionkeypair-keyid-signingkeypair] ```rust pub use keys::{EncryptionKeyPair, KeyId, SigningKeyPair}; ``` Source line: `36`. ## pub use signing::\{Signature, Signer, Verifier}; [#pub-use-signingsignature-signer-verifier] ```rust pub use signing::{Signature, Signer, Verifier}; ``` Source line: `37`. ## pub use token\_signer::\{TokenSigner, TokenVerifier}; [#pub-use-token_signertokensigner-tokenverifier] ```rust pub use token_signer::{TokenSigner, TokenVerifier}; ``` Source line: `38`. ## prelude [#prelude] Re-export common types ```rust pub mod prelude; ``` Source line: `41`. ## pub use super::encryption::\{Decryptor, Encryptor}; [#pub-use-superencryptiondecryptor-encryptor] ```rust pub use super::encryption::{Decryptor, Encryptor}; ``` Source line: `42`. ## pub use super::keys::\{EncryptionKeyPair, SigningKeyPair}; [#pub-use-superkeysencryptionkeypair-signingkeypair] ```rust pub use super::keys::{EncryptionKeyPair, SigningKeyPair}; ``` Source line: `43`. ## pub use super::signing::\{Signature, Signer, Verifier}; [#pub-use-supersigningsignature-signer-verifier] ```rust pub use super::signing::{Signature, Signer, Verifier}; ``` Source line: `44`. ## pub use super::token\_signer::\{TokenSigner, TokenVerifier}; [#pub-use-supertoken_signertokensigner-tokenverifier] ```rust pub use super::token_signer::{TokenSigner, TokenVerifier}; ``` Source line: `45`. # arsenal-crypto · encryption URL: https://docs.openagent.id/reference/rust/arsenal-crypto/encryption Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/encryption.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/encryption.rs`. SHA-256: `0ca517f8ed5758f6c0c4a05cd1e1985c6bebb9c0b52e0135b665d3b8f3e8ecf9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## encryption::EncryptionAlgorithm [#encryptionencryptionalgorithm] Encryption algorithm ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum EncryptionAlgorithm { /// XChaCha20-Poly1305 (recommended) XChaCha20Poly1305, /// AES-256-GCM Aes256Gcm, } ``` Source line: `20`. ## encryption::EncryptionAlgorithm::nonce\_size [#encryptionencryptionalgorithmnonce_size] Get the nonce size for this algorithm ```rust #[must_use] pub const fn nonce_size(&self) -> usize; ``` Source line: `30`. ## encryption::EncryptionAlgorithm::key\_size [#encryptionencryptionalgorithmkey_size] Get the key size for this algorithm ```rust #[must_use] pub const fn key_size(&self) -> usize; ``` Source line: `39`. ## encryption::EncryptionAlgorithm::tag\_size [#encryptionencryptionalgorithmtag_size] Get the auth tag size ```rust #[must_use] pub const fn tag_size(&self) -> usize; ``` Source line: `45`. ## encryption::EncryptedData [#encryptionencrypteddata] Encrypted data container ```rust #[derive(Clone, Serialize, Deserialize)] pub struct EncryptedData { } ``` Source line: `52`. ## encryption::EncryptedData::ciphertext [#encryptionencrypteddataciphertext] Get the ciphertext ```rust #[must_use] pub fn ciphertext(&self) -> &[u8]; ``` Source line: `67`. ## encryption::EncryptedData::nonce [#encryptionencrypteddatanonce] Get the nonce ```rust #[must_use] pub fn nonce(&self) -> &[u8]; ``` Source line: `73`. ## encryption::EncryptedData::algorithm [#encryptionencrypteddataalgorithm] Get the algorithm ```rust #[must_use] pub fn algorithm(&self) -> EncryptionAlgorithm; ``` Source line: `79`. ## encryption::EncryptedData::total\_size [#encryptionencrypteddatatotal_size] Get the total size (ciphertext + nonce + overhead) ```rust #[must_use] pub fn total_size(&self) -> usize; ``` Source line: `85`. ## encryption::EncryptedData::to\_bytes [#encryptionencrypteddatato_bytes] Serialize to bytes (nonce || ciphertext) ```rust #[must_use] pub fn to_bytes(&self) -> Vec; ``` Source line: `91`. ## encryption::EncryptedData::from\_bytes [#encryptionencrypteddatafrom_bytes] Deserialize from bytes # Errors [#errors] Returns an error if the data is malformed ```rust pub fn from_bytes(bytes: &[u8], algorithm: EncryptionAlgorithm) -> ArsenalResult; ``` Source line: `102`. ## encryption::SymmetricKey [#encryptionsymmetrickey] Symmetric encryption key (zeroized on drop) ```rust #[derive(Clone)] pub struct SymmetricKey { } ``` Source line: `132`. ## encryption::SymmetricKey::new [#encryptionsymmetrickeynew] Create a new key from bytes ```rust #[must_use] pub fn new(bytes: [u8; 32], algorithm: EncryptionAlgorithm) -> Self; ``` Source line: `153`. ## encryption::SymmetricKey::generate [#encryptionsymmetrickeygenerate] Generate a new random key # Errors [#errors-1] Returns an error if random generation fails ```rust pub fn generate(algorithm: EncryptionAlgorithm) -> ArsenalResult; ``` Source line: `161`. ## encryption::SymmetricKey::as\_bytes [#encryptionsymmetrickeyas_bytes] Get the key bytes (use carefully) ```rust #[must_use] pub fn as_bytes(&self) -> &[u8; 32]; ``` Source line: `168`. ## encryption::SymmetricKey::algorithm [#encryptionsymmetrickeyalgorithm] Get the algorithm ```rust #[must_use] pub fn algorithm(&self) -> EncryptionAlgorithm; ``` Source line: `174`. ## encryption::Encryptor [#encryptionencryptor] Trait for encryption operations ```rust pub trait Encryptor { /// Encrypt data /// /// # Errors /// Returns an error if encryption fails fn encrypt(&self, plaintext: &[u8]) -> ArsenalResult; /// Encrypt data with associated data (AEAD) /// /// # Errors /// Returns an error if encryption fails fn encrypt_with_aad(&self, plaintext: &[u8], aad: &[u8]) -> ArsenalResult; } ``` Source line: `189`. ## encryption::Decryptor [#encryptiondecryptor] Trait for decryption operations ```rust pub trait Decryptor { /// Decrypt data /// /// # Errors /// Returns an error if decryption fails fn decrypt(&self, encrypted: &EncryptedData) -> ArsenalResult>; /// Decrypt data with associated data verification /// /// # Errors /// Returns an error if decryption fails or AAD doesn't match fn decrypt_with_aad(&self, encrypted: &EncryptedData, aad: &[u8]) -> ArsenalResult>; } ``` Source line: `204`. # arsenal-crypto · envelope URL: https://docs.openagent.id/reference/rust/arsenal-crypto/envelope Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/envelope.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/envelope.rs`. SHA-256: `2ba8cd6bce3f4c7a97f86fab89bb693cfde4907fb8e79f3e3c7f664161551604`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## envelope::WrappedKey [#envelopewrappedkey] A wrapped key (DEK encrypted with KEK) ```rust #[derive(Clone, Serialize, Deserialize)] pub struct WrappedKey { /// The encrypted DEK pub encrypted_dek: EncryptedData, /// Identifier of the KEK used pub kek_id: String, /// Algorithm used for the DEK pub dek_algorithm: EncryptionAlgorithm, /// When this wrapped key was created pub created_at: chrono::DateTime, /// When this wrapped key expires pub expires_at: chrono::DateTime } ``` Source line: `44`. ## envelope::WrappedKey::is\_expired [#envelopewrappedkeyis_expired] Check if this wrapped key has expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `60`. ## envelope::EnvelopeEncryption [#envelopeenvelopeencryption] Envelope encryption for protecting secrets ```rust pub struct EnvelopeEncryption { } ``` Source line: `76`. ## envelope::EnvelopeEncryption::new [#envelopeenvelopeencryptionnew] Create a new envelope encryption instance ```rust #[must_use] pub fn new(kek: SymmetricKey, kek_id: impl Into) -> Self; ``` Source line: `88`. ## envelope::EnvelopeEncryption::with\_ttl [#envelopeenvelopeencryptionwith_ttl] Create with a specific TTL ```rust #[must_use] pub fn with_ttl(mut self, ttl_seconds: i64) -> Self; ``` Source line: `98`. ## envelope::EnvelopeEncryption::kek\_id [#envelopeenvelopeencryptionkek_id] Get the KEK ID ```rust #[must_use] pub fn kek_id(&self) -> &str; ``` Source line: `105`. ## envelope::EnvelopeEncryption::encrypt [#envelopeenvelopeencryptionencrypt] Encrypt data using envelope encryption # Errors [#errors] Returns an error if encryption fails ```rust pub fn encrypt(&self, plaintext: &[u8]) -> ArsenalResult; ``` Source line: `113`. ## envelope::EnvelopeEncryption::encrypt\_with\_aad [#envelopeenvelopeencryptionencrypt_with_aad] Encrypt data with associated data (AEAD) # Errors [#errors-1] Returns an error if encryption fails ```rust pub fn encrypt_with_aad( &self, plaintext: &[u8], aad: &[u8], ) -> ArsenalResult; ``` Source line: `134`. ## envelope::EnvelopeEncryption::decrypt [#envelopeenvelopeencryptiondecrypt] Decrypt envelope-encrypted data # Errors [#errors-2] Returns an error if decryption fails ```rust pub fn decrypt(&self, envelope: &EnvelopeEncryptedData) -> ArsenalResult>; ``` Source line: `155`. ## envelope::EnvelopeEncryption::decrypt\_with\_aad [#envelopeenvelopeencryptiondecrypt_with_aad] Decrypt with associated data verification # Errors [#errors-3] Returns an error if decryption fails or AAD doesn't match ```rust pub fn decrypt_with_aad( &self, envelope: &EnvelopeEncryptedData, aad: &[u8], ) -> ArsenalResult>; ``` Source line: `176`. ## envelope::EnvelopeEncryption::rewrap\_key [#envelopeenvelopeencryptionrewrap_key] Re-wrap a key with a new KEK (for key rotation) # Errors [#errors-4] Returns an error if re-wrapping fails ```rust pub fn rewrap_key( &self, wrapped: &WrappedKey, new_kek: &EnvelopeEncryption, ) -> ArsenalResult; ``` Source line: `236`. ## envelope::EnvelopeEncryptedData [#envelopeenvelopeencrypteddata] Data encrypted using envelope encryption ```rust #[derive(Clone, Serialize, Deserialize)] pub struct EnvelopeEncryptedData { /// The wrapped DEK pub wrapped_key: WrappedKey, /// The encrypted data pub encrypted_data: EncryptedData } ``` Source line: `257`. ## envelope::SessionSecretWrapper [#envelopesessionsecretwrapper] Session-bound secret wrapping Wraps secrets for delivery to a specific session, ensuring the secret can only be unwrapped within that session. ```rust pub struct SessionSecretWrapper { } ``` Source line: `277`. ## envelope::SessionSecretWrapper::new [#envelopesessionsecretwrappernew] Create a new session secret wrapper ```rust #[must_use] pub fn new(session_secret: &[u8; 32], session_id: impl Into + Clone) -> Self; ``` Source line: `287`. ## envelope::SessionSecretWrapper::wrap [#envelopesessionsecretwrapperwrap] Wrap a secret for this session # Errors [#errors-5] Returns an error if wrapping fails ```rust pub fn wrap(&self, secret: &[u8], ttl_seconds: i64) -> ArsenalResult; ``` Source line: `302`. ## envelope::SessionSecretWrapper::unwrap [#envelopesessionsecretwrapperunwrap] Unwrap a secret # Errors [#errors-6] Returns an error if unwrapping fails ```rust pub fn unwrap(&self, wrapped: &SessionWrappedSecret) -> ArsenalResult>; ``` Source line: `322`. ## envelope::SessionWrappedSecret [#envelopesessionwrappedsecret] A secret wrapped for a specific session ```rust #[derive(Clone, Serialize, Deserialize)] pub struct SessionWrappedSecret { } ``` Source line: `361`. ## envelope::SessionWrappedSecret::is\_expired [#envelopesessionwrappedsecretis_expired] Check if expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `375`. ## envelope::SessionWrappedSecret::session\_id [#envelopesessionwrappedsecretsession_id] Get the session ID ```rust #[must_use] pub fn session_id(&self) -> &str; ``` Source line: `381`. ## envelope::HybridEncryption [#envelopehybridencryption] Hybrid encryption using X25519 + XChaCha20-Poly1305 Used for encrypting data to a recipient's public key. ```rust pub struct HybridEncryption; ``` Source line: `398`. ## envelope::HybridEncryption::encrypt\_to [#envelopehybridencryptionencrypt_to] Encrypt data to a recipient's public key # Errors [#errors-7] Returns an error if encryption fails ```rust pub fn encrypt_to( recipient_public_key: &[u8; 32], plaintext: &[u8], ) -> ArsenalResult; ``` Source line: `405`. ## envelope::HybridEncryption::decrypt\_with [#envelopehybridencryptiondecrypt_with] Decrypt data using recipient's private key # Errors [#errors-8] Returns an error if decryption fails ```rust pub fn decrypt_with( recipient_key_pair: &EncryptionKeyPair, encrypted: &HybridEncryptedData, ) -> ArsenalResult>; ``` Source line: `433`. ## envelope::HybridEncryptedData [#envelopehybridencrypteddata] Data encrypted using hybrid encryption ```rust #[derive(Clone, Serialize, Deserialize)] pub struct HybridEncryptedData { /// Ephemeral public key pub ephemeral_public_key: [u8; 32], /// The encrypted data pub encrypted: EncryptedData } ``` Source line: `453`. # arsenal-crypto · hash URL: https://docs.openagent.id/reference/rust/arsenal-crypto/hash Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/hash.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/hash.rs`. SHA-256: `9621f169b03ad4b071e4f054751737da83041277e4cf08f8c2ce264cbc103db1`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## hash::Hash [#hashhash] A 32-byte hash output ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Hash([u8; 32]); ``` Source line: `16`. ## hash::Hash::from\_bytes [#hashhashfrom_bytes] Create a hash from raw bytes ```rust #[must_use] pub const fn from_bytes(bytes: [u8; 32]) -> Self; ``` Source line: `21`. ## hash::Hash::digest [#hashhashdigest] Hash some data ```rust #[must_use] pub fn digest(data: &[u8]) -> Self; ``` Source line: `27`. ## hash::Hash::digest\_many [#hashhashdigest_many] Hash multiple pieces of data ```rust #[must_use] pub fn digest_many(parts: &[&[u8]]) -> Self; ``` Source line: `33`. ## hash::Hash::keyed [#hashhashkeyed] Create a keyed hash (MAC) ```rust #[must_use] pub fn keyed(key: &[u8; 32], data: &[u8]) -> Self; ``` Source line: `43`. ## hash::Hash::as\_bytes [#hashhashas_bytes] Get the raw bytes ```rust #[must_use] pub const fn as_bytes(&self) -> &[u8; 32]; ``` Source line: `49`. ## hash::Hash::to\_hex [#hashhashto_hex] Convert to hex string ```rust #[must_use] pub fn to_hex(&self) -> String; ``` Source line: `55`. ## hash::Hash::from\_hex [#hashhashfrom_hex] Parse from hex string # Errors [#errors] Returns an error if the hex string is invalid ```rust pub fn from_hex(hex_str: &str) -> ArsenalResult; ``` Source line: `63`. ## hash::Hash::ct\_eq [#hashhashct_eq] Constant-time comparison ```rust #[must_use] pub fn ct_eq(&self, other: &Self) -> bool; ``` Source line: `76`. ## hash::Hash::verify\_keyed [#hashhashverify_keyed] Verify a keyed hash ```rust #[must_use] pub fn verify_keyed(key: &[u8; 32], data: &[u8], expected: &Self) -> bool; ``` Source line: `86`. ## hash::Hasher [#hashhasher] Incremental hasher for large data ```rust pub struct Hasher { } ``` Source line: `111`. ## hash::Hasher::new [#hashhashernew] Create a new hasher ```rust #[must_use] pub fn new() -> Self; ``` Source line: `118`. ## hash::Hasher::new\_keyed [#hashhashernew_keyed] Create a keyed hasher ```rust #[must_use] pub fn new_keyed(key: &[u8; 32]) -> Self; ``` Source line: `126`. ## hash::Hasher::new\_derive\_key [#hashhashernew_derive_key] Create a hasher for key derivation ```rust #[must_use] pub fn new_derive_key(context: &str) -> Self; ``` Source line: `134`. ## hash::Hasher::update [#hashhasherupdate] Update the hasher with more data ```rust pub fn update(&mut self, data: &[u8]) -> &mut Self; ``` Source line: `141`. ## hash::Hasher::finalize [#hashhasherfinalize] Finalize and get the hash ```rust #[must_use] pub fn finalize(self) -> Hash; ``` Source line: `148`. ## hash::Hasher::finalize\_xof [#hashhasherfinalize_xof] Finalize with extended output ```rust pub fn finalize_xof(self, output: &mut [u8]); ``` Source line: `153`. ## hash::Hasher::reset [#hashhasherreset] Reset the hasher for reuse ```rust pub fn reset(&mut self); ``` Source line: `159`. ## hash::HashChain [#hashhashchain] Hash chain for audit log integrity ```rust #[derive(Debug, Clone)] pub struct HashChain { } ``` Source line: `178`. ## hash::HashChain::new [#hashhashchainnew] Create a new hash chain with a genesis hash ```rust #[must_use] pub fn new() -> Self; ``` Source line: `188`. ## hash::HashChain::from\_head [#hashhashchainfrom_head] Create from an existing head hash ```rust #[must_use] pub fn from_head(head: Hash, count: u64) -> Self; ``` Source line: `199`. ## hash::HashChain::append [#hashhashchainappend] Add an entry to the chain ```rust pub fn append(&mut self, data: &[u8]) -> Hash; ``` Source line: `204`. ## hash::HashChain::head [#hashhashchainhead] Get the current head hash ```rust #[must_use] pub fn head(&self) -> &Hash; ``` Source line: `216`. ## hash::HashChain::count [#hashhashchaincount] Get the entry count ```rust #[must_use] pub fn count(&self) -> u64; ``` Source line: `222`. ## hash::HashChain::verify\_sequence [#hashhashchainverify_sequence] Verify that a sequence of entries produces the expected head ```rust #[must_use] pub fn verify_sequence(entries: &[&[u8]], expected_head: &Hash) -> bool; ``` Source line: `228`. ## hash::MerkleTree [#hashmerkletree] Merkle tree for efficient verification of large datasets ```rust #[derive(Debug, Clone)] pub struct MerkleTree { } ``` Source line: `245`. ## hash::MerkleTree::new [#hashmerkletreenew] Create a new empty Merkle tree ```rust #[must_use] pub fn new() -> Self; ``` Source line: `257`. ## hash::MerkleTree::from\_leaves [#hashmerkletreefrom_leaves] Build a Merkle tree from leaf data ```rust #[must_use] pub fn from_leaves(leaf_data: &[&[u8]]) -> Self; ``` Source line: `267`. ## hash::MerkleTree::add\_leaf [#hashmerkletreeadd_leaf] Add a leaf to the tree ```rust pub fn add_leaf(&mut self, data: &[u8]); ``` Source line: `277`. ## hash::MerkleTree::compute\_root [#hashmerkletreecompute_root] Compute the root hash ```rust pub fn compute_root(&mut self) -> Option; ``` Source line: `283`. ## hash::MerkleTree::root [#hashmerkletreeroot] Get the root hash ```rust #[must_use] pub fn root(&self) -> Option<&Hash>; ``` Source line: `316`. ## hash::MerkleTree::len [#hashmerkletreelen] Get the number of leaves ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `322`. ## hash::MerkleTree::is\_empty [#hashmerkletreeis_empty] Check if the tree is empty ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `328`. ## hash::fingerprint\_init [#hashfingerprint_init] Initialize a fingerprint hash chain state. Computes: `BLAKE3("arsenal.fingerprint.init" || agent_did || timestamp || nonce)` This is the server-side computation that matches \[`arsenal_core::fingerprint::FingerprintState::init`]. ```rust #[must_use] pub fn fingerprint_init( agent_did: &str, timestamp: &chrono::DateTime, nonce: &[u8; 32], ) -> [u8; 32]; ``` Source line: `348`. ## hash::fingerprint\_advance [#hashfingerprint_advance] Advance a fingerprint hash chain by one step. Computes: `BLAKE3("arsenal.fingerprint.advance" || state_n || request_id || timestamp)` ```rust #[must_use] pub fn fingerprint_advance( current_state: &[u8; 32], request_id: &uuid::Uuid, timestamp: &chrono::DateTime, ) -> [u8; 32]; ``` Source line: `365`. ## hash::fingerprint\_hash [#hashfingerprint_hash] Compute the fingerprint to send as a header from the chain state. The fingerprint is `BLAKE3(state_n)` — the raw state is never transmitted, only its hash. This prevents state reconstruction if the fingerprint header is intercepted. ```rust #[must_use] pub fn fingerprint_hash(state: &[u8; 32]) -> [u8; 32]; ``` Source line: `384`. # arsenal-crypto modules URL: https://docs.openagent.id/reference/rust/arsenal-crypto Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/arsenal-crates-arsenal-crypto). [Focused integration guide](/arsenal/overview). ## Modules [#modules] * [crate](/reference/rust/arsenal-crypto/crate) — 20 declarations * [encryption](/reference/rust/arsenal-crypto/encryption) — 18 declarations * [envelope](/reference/rust/arsenal-crypto/envelope) — 23 declarations * [hash](/reference/rust/arsenal-crypto/hash) — 36 declarations * [kdf](/reference/rust/arsenal-crypto/kdf) — 26 declarations * [keys](/reference/rust/arsenal-crypto/keys) — 40 declarations * [random](/reference/rust/arsenal-crypto/random) — 13 declarations * [signing](/reference/rust/arsenal-crypto/signing) — 23 declarations * [token\_signer](/reference/rust/arsenal-crypto/token_signer) — 20 declarations # arsenal-crypto · kdf URL: https://docs.openagent.id/reference/rust/arsenal-crypto/kdf Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/kdf.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/kdf.rs`. SHA-256: `f900fbc6fdc13ce45694fea8fe5b1f2c5192433e7e3a9b471f0f92e226a66b34`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## kdf::DerivedKey [#kdfderivedkey] A derived key (zeroized on drop) ```rust #[derive(Clone, Zeroize, ZeroizeOnDrop)] pub struct DerivedKey { } ``` Source line: `16`. ## kdf::DerivedKey::from\_bytes [#kdfderivedkeyfrom_bytes] Create from bytes ```rust #[must_use] pub fn from_bytes(bytes: Vec) -> Self; ``` Source line: `23`. ## kdf::DerivedKey::as\_bytes [#kdfderivedkeyas_bytes] Get the key bytes ```rust #[must_use] pub fn as_bytes(&self) -> &[u8]; ``` Source line: `29`. ## kdf::DerivedKey::as\_array\_32 [#kdfderivedkeyas_array_32] Get as fixed-size array if length matches ```rust #[must_use] pub fn as_array_32(&self) -> Option<[u8; 32]>; ``` Source line: `35`. ## kdf::DerivedKey::len [#kdfderivedkeylen] Get the length ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `47`. ## kdf::DerivedKey::is\_empty [#kdfderivedkeyis_empty] Check if empty ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `53`. ## kdf::KeyDerivation [#kdfkeyderivation] Key derivation trait ```rust pub trait KeyDerivation { /// Derive a key the specified length /// /// # Errors /// Returns an error if derivation fails fn derive(&self, length: usize) -> ArsenalResult; /// Derive a 32-byte key /// /// # Errors /// Returns an error if derivation fails fn derive_32(&self) -> ArsenalResult<[u8; 32]> ; } ``` Source line: `65`. ## kdf::HkdfDeriver [#kdfhkdfderiver] HKDF key derivation ```rust pub struct HkdfDeriver { } ``` Source line: `88`. ## kdf::HkdfDeriver::new [#kdfhkdfderivernew] Create a new HKDF deriver from input key material ```rust #[must_use] pub fn new(ikm: &[u8], salt: Option<&[u8]>) -> Self; ``` Source line: `96`. ## kdf::HkdfDeriver::from\_shared\_secret [#kdfhkdfderiverfrom_shared_secret] Create from ad secret (e.g., from Diffie-Hellman) ```rust #[must_use] pub fn from_shared_secret(shared_secret: &[u8], context: &str) -> Self; ``` Source line: `103`. ## kdf::HkdfDeriver::derive\_with\_info [#kdfhkdfderiverderive_with_info] Derive with additional info # Errors [#errors] Returns an error if derivation fails ```rust pub fn derive_with_info(&self, info: &[u8], length: usize) -> ArsenalResult; ``` Source line: `113`. ## kdf::Blake3Deriver [#kdfblake3deriver] BLAKE3 key derivation (faster alternative to HKDF) ```rust pub struct Blake3Deriver { } ``` Source line: `135`. ## kdf::Blake3Deriver::new [#kdfblake3derivernew] Create a new BLAKE3 deriver ```rust #[must_use] pub fn new(ikm: &[u8], context: impl Into) -> Self; ``` Source line: `145`. ## kdf::Blake3Deriver::derive\_with\_info [#kdfblake3deriverderive_with_info] Derive with additional info ```rust #[must_use] pub fn derive_with_info(&self, info: &[u8], length: usize) -> DerivedKey; ``` Source line: `154`. ## kdf::Argon2Params [#kdfargon2params] Argon2id parameters for password hashing ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Argon2Params { /// Memory cost in KiB pub memory_kib: u32, /// Time cost (iterations) pub time_cost: u32, /// Parallelism pub parallelism: u32, /// Output length pub output_len: usize } ``` Source line: `189`. ## kdf::Argon2Deriver [#kdfargon2deriver] Argon2id password-based key derivation ```rust pub struct Argon2Deriver { } ``` Source line: `213`. ## kdf::Argon2Deriver::new [#kdfargon2derivernew] Create a new Argon2 deriver with random salt # Errors [#errors-1] Returns an error if random generation fails ```rust pub fn new(params: Argon2Params) -> ArsenalResult; ``` Source line: `223`. ## kdf::Argon2Deriver::with\_salt [#kdfargon2deriverwith_salt] Create with a specific salt ```rust #[must_use] pub fn with_salt(params: Argon2Params, salt: [u8; 16]) -> Self; ``` Source line: `230`. ## kdf::Argon2Deriver::salt [#kdfargon2deriversalt] Get the salt (needed for verification) ```rust #[must_use] pub fn salt(&self) -> &[u8; 16]; ``` Source line: `236`. ## kdf::Argon2Deriver::derive\_from\_password [#kdfargon2deriverderive_from_password] Derive a key from a password # Errors [#errors-2] Returns an error if derivation fails ```rust pub fn derive_from_password(&self, password: &[u8]) -> ArsenalResult; ``` Source line: `244`. ## kdf::SessionKeyDeriver [#kdfsessionkeyderiver] Session key deriver for deriving session-specific keys ```rust pub struct SessionKeyDeriver { } ``` Source line: `280`. ## kdf::SessionKeyDeriver::new [#kdfsessionkeyderivernew] Create a new session key deriver ```rust #[must_use] pub fn new(base_key: [u8; 32], session_id: impl Into) -> Self; ``` Source line: `290`. ## kdf::SessionKeyDeriver::derive\_for\_purpose [#kdfsessionkeyderiverderive_for_purpose] Derive a key for a specific purpose ```rust #[must_use] pub fn derive_for_purpose(&self, purpose: &str) -> [u8; 32]; ``` Source line: `299`. ## kdf::SessionKeyDeriver::derive\_encryption\_key [#kdfsessionkeyderiverderive_encryption_key] Derive encryption key ```rust #[must_use] pub fn derive_encryption_key(&self) -> [u8; 32]; ``` Source line: `308`. ## kdf::SessionKeyDeriver::derive\_mac\_key [#kdfsessionkeyderiverderive_mac_key] Derive MAC key ```rust #[must_use] pub fn derive_mac_key(&self) -> [u8; 32]; ``` Source line: `314`. ## kdf::SessionKeyDeriver::derive\_wrap\_key [#kdfsessionkeyderiverderive_wrap_key] Derive wrapping key ```rust #[must_use] pub fn derive_wrap_key(&self) -> [u8; 32]; ``` Source line: `320`. # arsenal-crypto · keys URL: https://docs.openagent.id/reference/rust/arsenal-crypto/keys Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/keys.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/keys.rs`. SHA-256: `87bca94390697ce74aa11e8bb88dd167369ac7e478da8c748f6295524ae8d684`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## keys::KeyId [#keyskeyid] Key identifier for key management ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct KeyId(String); ``` Source line: `19`. ## keys::KeyId::new [#keyskeyidnew] Create a new key ID # Errors [#errors] Returns an error if the ID is invalid ```rust pub fn new(id: impl Into) -> ArsenalResult; ``` Source line: `26`. ## keys::KeyId::generate [#keyskeyidgenerate] Generate a new random key ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `36`. ## keys::KeyId::as\_str [#keyskeyidas_str] Get the inner string ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `42`. ## keys::SigningKeyPair [#keyssigningkeypair] Ed25519 signing key pair ```rust pub struct SigningKeyPair { } ``` Source line: `60`. ## keys::SigningKeyPair::generate [#keyssigningkeypairgenerate] Generate a new random key pair # Errors [#errors-1] Returns an error if random generation fails ```rust pub fn generate() -> ArsenalResult; ``` Source line: `72`. ## keys::SigningKeyPair::from\_seed [#keyssigningkeypairfrom_seed] Create from existing seed bytes # Errors [#errors-2] Returns an error if the seed is invalid ```rust pub fn from_seed(seed: &[u8; 32]) -> ArsenalResult; ``` Source line: `88`. ## keys::SigningKeyPair::from\_seed\_with\_id [#keyssigningkeypairfrom_seed_with_id] Create from existing seed with a specific key ID # Errors [#errors-3] Returns an error if the seed is invalid ```rust pub fn from_seed_with_id(seed: &[u8; 32], key_id: KeyId) -> ArsenalResult; ``` Source line: `100`. ## keys::SigningKeyPair::verifying\_key [#keyssigningkeypairverifying_key] Get the public verifying key ```rust #[must_use] pub fn verifying_key(&self) -> VerifyingKey; ``` Source line: `110`. ## keys::SigningKeyPair::public\_key\_bytes [#keyssigningkeypairpublic_key_bytes] Get the public key bytes ```rust #[must_use] pub fn public_key_bytes(&self) -> [u8; 32]; ``` Source line: `116`. ## keys::SigningKeyPair::fingerprint [#keyssigningkeypairfingerprint] Get the key fingerprint ```rust #[must_use] pub fn fingerprint(&self) -> KeyFingerprint; ``` Source line: `122`. ## keys::SigningKeyPair::key\_id [#keyssigningkeypairkey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> &KeyId; ``` Source line: `128`. ## keys::SigningKeyPair::sign [#keyssigningkeypairsign] Sign a message ```rust #[must_use] pub fn sign(&self, message: &[u8]) -> [u8; 64]; ``` Source line: `134`. ## keys::SigningKeyPair::export\_seed [#keyssigningkeypairexport_seed] Export the seed (use with extreme caution) This returns the private key material. Handle with care! ```rust #[must_use] pub fn export_seed(&self) -> [u8; 32]; ``` Source line: `143`. ## keys::PublicSigningKey [#keyspublicsigningkey] Public key for signature verification ```rust #[derive(Clone, Serialize, Deserialize)] pub struct PublicSigningKey { } ``` Source line: `159`. ## keys::PublicSigningKey::from\_bytes [#keyspublicsigningkeyfrom_bytes] Create from bytes # Errors [#errors-4] Returns an error if the bytes are invalid ```rust pub fn from_bytes(bytes: [u8; 32], key_id: KeyId) -> ArsenalResult; ``` Source line: `171`. ## keys::PublicSigningKey::from\_signing\_key [#keyspublicsigningkeyfrom_signing_key] Create from a signing key pair ```rust #[must_use] pub fn from_signing_key(key_pair: &SigningKeyPair) -> Self; ``` Source line: `180`. ## keys::PublicSigningKey::as\_bytes [#keyspublicsigningkeyas_bytes] Get the key bytes ```rust #[must_use] pub fn as_bytes(&self) -> &[u8; 32]; ``` Source line: `189`. ## keys::PublicSigningKey::key\_id [#keyspublicsigningkeykey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> &KeyId; ``` Source line: `195`. ## keys::PublicSigningKey::fingerprint [#keyspublicsigningkeyfingerprint] Get the fingerprint ```rust #[must_use] pub fn fingerprint(&self) -> KeyFingerprint; ``` Source line: `201`. ## keys::PublicSigningKey::verify [#keyspublicsigningkeyverify] Verify a signature # Errors [#errors-5] Returns an error if verification fails ```rust pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> ArsenalResult<()>; ``` Source line: `209`. ## keys::EncryptionKeyPair [#keysencryptionkeypair] X25519 key pair for key exchange and encryption ```rust pub struct EncryptionKeyPair { } ``` Source line: `233`. ## keys::EncryptionKeyPair::generate [#keysencryptionkeypairgenerate] Generate a new random key pair # Errors [#errors-6] Returns an error if random generation fails ```rust pub fn generate() -> ArsenalResult; ``` Source line: `247`. ## keys::EncryptionKeyPair::from\_seed [#keysencryptionkeypairfrom_seed] Create from existing seed bytes # Errors [#errors-7] Returns an error if the seed is invalid ```rust pub fn from_seed(seed: &[u8; 32]) -> ArsenalResult; ``` Source line: `265`. ## keys::EncryptionKeyPair::public\_key [#keysencryptionkeypairpublic_key] Get the public key ```rust #[must_use] pub fn public_key(&self) -> &X25519PublicKey; ``` Source line: `278`. ## keys::EncryptionKeyPair::public\_key\_bytes [#keysencryptionkeypairpublic_key_bytes] Get the public key bytes ```rust #[must_use] pub fn public_key_bytes(&self) -> [u8; 32]; ``` Source line: `284`. ## keys::EncryptionKeyPair::fingerprint [#keysencryptionkeypairfingerprint] Get the key fingerprint ```rust #[must_use] pub fn fingerprint(&self) -> KeyFingerprint; ``` Source line: `290`. ## keys::EncryptionKeyPair::key\_id [#keysencryptionkeypairkey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> &KeyId; ``` Source line: `296`. ## keys::EncryptionKeyPair::diffie\_hellman [#keysencryptionkeypairdiffie_hellman] Perform Diffie-Hellman key exchange ```rust #[must_use] pub fn diffie_hellman(&self, their_public: &X25519PublicKey) -> [u8; 32]; ``` Source line: `302`. ## keys::EncryptionKeyPair::diffie\_hellman\_bytes [#keysencryptionkeypairdiffie_hellman_bytes] Perform Diffie-Hellman with public key bytes # Errors [#errors-8] Returns an error if the public key is invalid ```rust pub fn diffie_hellman_bytes(&self, their_public: &[u8; 32]) -> ArsenalResult<[u8; 32]>; ``` Source line: `310`. ## keys::PublicEncryptionKey [#keyspublicencryptionkey] Public encryption key ```rust #[derive(Clone, Serialize, Deserialize)] pub struct PublicEncryptionKey { } ``` Source line: `327`. ## keys::PublicEncryptionKey::from\_bytes [#keyspublicencryptionkeyfrom_bytes] Create from bytes ```rust #[must_use] pub fn from_bytes(bytes: [u8; 32], key_id: KeyId) -> Self; ``` Source line: `337`. ## keys::PublicEncryptionKey::from\_key\_pair [#keyspublicencryptionkeyfrom_key_pair] Create from an encryption key pair ```rust #[must_use] pub fn from_key_pair(key_pair: &EncryptionKeyPair) -> Self; ``` Source line: `343`. ## keys::PublicEncryptionKey::as\_bytes [#keyspublicencryptionkeyas_bytes] Get the key bytes ```rust #[must_use] pub fn as_bytes(&self) -> &[u8; 32]; ``` Source line: `352`. ## keys::PublicEncryptionKey::key\_id [#keyspublicencryptionkeykey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> &KeyId; ``` Source line: `358`. ## keys::PublicEncryptionKey::fingerprint [#keyspublicencryptionkeyfingerprint] Get the fingerprint ```rust #[must_use] pub fn fingerprint(&self) -> KeyFingerprint; ``` Source line: `364`. ## keys::PublicEncryptionKey::to\_x25519 [#keyspublicencryptionkeyto_x25519] Convert to X25519 public key ```rust #[must_use] pub fn to_x25519(&self) -> X25519PublicKey; ``` Source line: `370`. ## keys::KeyUsage [#keyskeyusage] Key usage restrictions ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum KeyUsage { /// Key can be used for signing Sign, /// Key can be used for verification Verify, /// Key can be used for encryption Encrypt, /// Key can be used for decryption Decrypt, /// Key can be used for key wrapping WrapKey, /// Key can be used for key unwrapping UnwrapKey, /// Key can be used for key derivation DeriveKey, } ``` Source line: `387`. ## keys::KeyMetadata [#keyskeymetadata] Key metadata ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KeyMetadata { /// Key ID pub key_id: KeyId, /// Key algorithm pub algorithm: KeyAlgorithm, /// Allowed usages pub usages: Vec, /// When the key was created pub created_at: chrono::DateTime, /// When the key expires (if ever) pub expires_at: Option>, /// Whether the key is currently active pub is_active: bool } ``` Source line: `406`. ## keys::KeyAlgorithm [#keyskeyalgorithm] Key algorithm ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum KeyAlgorithm { /// Ed25519 signing Ed25519, /// X25519 key exchange X25519, /// AES-256-GCM encryption Aes256Gcm, /// XChaCha20-Poly1305 encryption XChaCha20Poly1305, } ``` Source line: `424`. # arsenal-crypto · random URL: https://docs.openagent.id/reference/rust/arsenal-crypto/random Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/random.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/random.rs`. SHA-256: `912c264105e8593542b2c334f0efb08159e93d0491032f70319ea1fa3c53bb39`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## random::fill\_random [#randomfill_random] Fill a buffer with cryptographically secure random bytes # Errors [#errors] Returns an error if the system random number generator fails ```rust pub fn fill_random(buffer: &mut [u8]) -> ArsenalResult<()>; ``` Source line: `14`. ## random::random\_bytes [#randomrandom_bytes] Generate a fixed-size array of random bytes # Errors [#errors-1] Returns an error if the system random number generator fails ```rust pub fn random_bytes() -> ArsenalResult<[u8; N]>; ``` Source line: `27`. ## random::random\_key\_32 [#randomrandom_key_32] Generate a random 32-byte key # Errors [#errors-2] Returns an error if the system random number generator fails ```rust pub fn random_key_32() -> ArsenalResult<[u8; 32]>; ``` Source line: `37`. ## random::random\_nonce\_12 [#randomrandom_nonce_12] Generate a random 12-byte nonce (for AES-GCM) # Errors [#errors-3] Returns an error if the system random number generator fails ```rust pub fn random_nonce_12() -> ArsenalResult<[u8; 12]>; ``` Source line: `45`. ## random::random\_nonce\_24 [#randomrandom_nonce_24] Generate a random 24-byte nonce (for XChaCha20-Poly1305) # Errors [#errors-4] Returns an error if the system random number generator fails ```rust pub fn random_nonce_24() -> ArsenalResult<[u8; 24]>; ``` Source line: `53`. ## random::SecureRandom [#randomsecurerandom] Secure random bytes that are zeroized on drop ```rust #[derive(Clone, Zeroize)] #[zeroize(drop)] pub struct SecureRandom { } ``` Source line: `60`. ## random::SecureRandom\::generate [#randomsecurerandomngenerate] Generate new secure random bytes # Errors [#errors-5] Returns an error if the system random number generator fails ```rust pub fn generate() -> ArsenalResult; ``` Source line: `69`. ## random::SecureRandom\::as\_bytes [#randomsecurerandomnas_bytes] Get the bytes (use carefully) ```rust #[must_use] pub fn as_bytes(&self) -> &[u8; N]; ``` Source line: `76`. ## random::SecureRandom\::len [#randomsecurerandomnlen] Get the length ```rust #[must_use] pub const fn len(&self) -> usize; ``` Source line: `82`. ## random::SecureRandom\::is\_empty [#randomsecurerandomnis_empty] Check if empty (always false for N > 0) ```rust #[must_use] pub const fn is_empty(&self) -> bool; ``` Source line: `88`. ## random::random\_u64 [#randomrandom_u64] Generate a random u64 value # Errors [#errors-6] Returns an error if the system random number generator fails ```rust pub fn random_u64() -> ArsenalResult; ``` Source line: `103`. ## random::random\_u32 [#randomrandom_u32] Generate a random u32 value # Errors [#errors-7] Returns an error if the system random number generator fails ```rust pub fn random_u32() -> ArsenalResult; ``` Source line: `112`. ## random::random\_range [#randomrandom_range] Generate a random value in the range \[0, max) # Errors [#errors-8] Returns an error if the system random number generator fails ```rust pub fn random_range(max: u64) -> ArsenalResult; ``` Source line: `121`. # arsenal-crypto · signing URL: https://docs.openagent.id/reference/rust/arsenal-crypto/signing Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/signing.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/signing.rs`. SHA-256: `3da22c23604ef895aad9ac28d81e12413f8a25039673e5024fd2f95e6a2309cd`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## signing::Signature [#signingsignature] A detached Ed25519 signature ```rust #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Signature { } ``` Source line: `15`. ## signing::signature\_bytes::serialize [#signingsignature_bytesserialize] ```rust pub fn serialize(bytes: &[u8; 64], serializer: S) -> Result where S: Serializer,; ``` Source line: `27`. ## signing::signature\_bytes::deserialize [#signingsignature_bytesdeserialize] ```rust pub fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 64], D::Error> where D: Deserializer<'de>,; ``` Source line: `40`. ## signing::Signature::from\_bytes [#signingsignaturefrom_bytes] Create a signature from bytes ```rust #[must_use] pub fn from_bytes(bytes: [u8; 64], key_id: KeyId) -> Self; ``` Source line: `66`. ## signing::Signature::as\_bytes [#signingsignatureas_bytes] Get the signature bytes ```rust #[must_use] pub fn as_bytes(&self) -> &[u8; 64]; ``` Source line: `72`. ## signing::Signature::key\_id [#signingsignaturekey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> &KeyId; ``` Source line: `78`. ## signing::Signature::to\_base64 [#signingsignatureto_base64] Encode as base64 ```rust #[must_use] pub fn to_base64(&self) -> String; ``` Source line: `84`. ## signing::Signature::from\_base64 [#signingsignaturefrom_base64] Decode from base64 # Errors [#errors] Returns an error if decoding fails ```rust pub fn from_base64(encoded: &str, key_id: KeyId) -> ArsenalResult; ``` Source line: `93`. ## signing::Signer [#signingsigner] Trait for types that can sign messages ```rust pub trait Signer { /// Sign a message fn sign(&self, message: &[u8]) -> Signature; /// Get the key ID fn key_id(&self) -> &KeyId; } ``` Source line: `122`. ## signing::Verifier [#signingverifier] Trait for types that can verify signatures ```rust pub trait Verifier { /// Verify a signature /// /// # Errors /// Returns an error if verification fails fn verify(&self, message: &[u8], signature: &Signature) -> ArsenalResult<()>; /// Get the key ID fn key_id(&self) -> &KeyId; } ``` Source line: `142`. ## signing::SignedData [#signingsigneddata] Signed data container ```rust #[derive(Clone, Serialize, Deserialize)] pub struct SignedData { /// The data pub data: T, /// The signature over the serialized data pub signature: Signature } ``` Source line: `165`. ## signing::SignedData\::sign [#signingsigneddatatsign] Create signed data # Errors [#errors-1] Returns an error if serialization fails ```rust pub fn sign(data: T, signer: &impl Signer) -> ArsenalResult; ``` Source line: `177`. ## signing::SignedData\::verify [#signingsigneddatatverify] Verify the signature # Errors [#errors-2] Returns an error if verification fails ```rust pub fn verify(&self, verifier: &impl Verifier) -> ArsenalResult<()>; ``` Source line: `189`. ## signing::MultiSignature [#signingmultisignature] Multi-signature container for threshold signing ```rust #[derive(Clone, Serialize, Deserialize)] pub struct MultiSignature { } ``` Source line: `218`. ## signing::MultiSignature::new [#signingmultisignaturenew] Create a new multi-signature container ```rust #[must_use] pub fn new(threshold: usize) -> Self; ``` Source line: `228`. ## signing::MultiSignature::add\_signature [#signingmultisignatureadd_signature] Add a signature ```rust pub fn add_signature(&mut self, signature: Signature); ``` Source line: `236`. ## signing::MultiSignature::is\_complete [#signingmultisignatureis_complete] Check if threshold is met ```rust #[must_use] pub fn is_complete(&self) -> bool; ``` Source line: `249`. ## signing::MultiSignature::count [#signingmultisignaturecount] Get the number of signatures ```rust #[must_use] pub fn count(&self) -> usize; ``` Source line: `255`. ## signing::MultiSignature::threshold [#signingmultisignaturethreshold] Get the threshold ```rust #[must_use] pub fn threshold(&self) -> usize; ``` Source line: `261`. ## signing::MultiSignature::signatures [#signingmultisignaturesignatures] Get the signatures ```rust #[must_use] pub fn signatures(&self) -> &[Signature]; ``` Source line: `267`. ## signing::MultiSignature::verify\_all [#signingmultisignatureverify_all] Verify all signatures against a message # Errors [#errors-3] Returns an error if any signature is invalid or threshold not met ```rust pub fn verify_all(&self, message: &[u8], verifiers: &[&impl Verifier]) -> ArsenalResult<()>; ``` Source line: `275`. ## signing::sign\_consent\_record [#signingsign_consent_record] Sign a consent record's canonical bytes. The consent record should be serialized to its canonical form (via \[`arsenal_core::consent::ConsentRecord::signing_bytes`]) before calling this function. # Errors [#errors-4] Returns an error if signing fails. ```rust #[must_use] pub fn sign_consent_record(key: &SigningKeyPair, record_bytes: &[u8]) -> Signature; ``` Source line: `328`. ## signing::verify\_consent\_signature [#signingverify_consent_signature] Verify a consent record's signature. The consent record should be serialized to its canonical form (via \[`arsenal_core::consent::ConsentRecord::signing_bytes`]) before calling this function. # Errors [#errors-5] Returns an error if verification fails. ```rust pub fn verify_consent_signature( key: &PublicSigningKey, record_bytes: &[u8], signature: &Signature, ) -> ArsenalResult; ``` Source line: `341`. # arsenal-crypto · token_signer URL: https://docs.openagent.id/reference/rust/arsenal-crypto/token_signer Markdown: https://docs.openagent.id/reference/rust/arsenal-crypto/token_signer.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-crypto/src/token_signer.rs`. SHA-256: `d4f36288952c34e71c4fda2e0009a691212dd6abe71f5a77eed5938fcbe90c18`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## token\_signer::TokenSigner [#token_signertokensigner] Token signer for creating signed ACTs ```rust pub struct TokenSigner { } ``` Source line: `46`. ## token\_signer::TokenSigner::new [#token_signertokensignernew] Create a new token signer ```rust #[must_use] pub fn new(key_pair: SigningKeyPair, issuer: impl Into) -> Self; ``` Source line: `56`. ## token\_signer::TokenSigner::key\_id [#token_signertokensignerkey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> &KeyId; ``` Source line: `65`. ## token\_signer::TokenSigner::public\_key [#token_signertokensignerpublic_key] Get the public key for verification ```rust #[must_use] pub fn public_key(&self) -> PublicSigningKey; ``` Source line: `71`. ## token\_signer::TokenSigner::issuer [#token_signertokensignerissuer] Get the issuer ```rust #[must_use] pub fn issuer(&self) -> &str; ``` Source line: `77`. ## token\_signer::TokenSigner::sign [#token_signertokensignersign] Sign a token # Errors [#errors] Returns an error if signing fails ```rust pub fn sign(&self, token: &mut AgentCapabilityToken) -> ArsenalResult<()>; ``` Source line: `85`. ## token\_signer::TokenSigner::sign\_token [#token_signertokensignersign_token] Sign and return a new token # Errors [#errors-1] Returns an error if signing fails ```rust pub fn sign_token( &self, mut token: AgentCapabilityToken, ) -> ArsenalResult; ``` Source line: `104`. ## token\_signer::TokenVerifier [#token_signertokenverifier] Token verifier for validating signed ACTs ```rust pub struct TokenVerifier { } ``` Source line: `123`. ## token\_signer::TokenVerifier::new [#token_signertokenverifiernew] Create a new token verifier ```rust #[must_use] pub fn new() -> Self; ``` Source line: `135`. ## token\_signer::TokenVerifier::with\_public\_key [#token_signertokenverifierwith_public_key] Add a public key for verification ```rust #[must_use] pub fn with_public_key(mut self, key: PublicSigningKey) -> Self; ``` Source line: `145`. ## token\_signer::TokenVerifier::with\_public\_keys [#token_signertokenverifierwith_public_keys] Add multiple public keys ```rust #[must_use] pub fn with_public_keys(mut self, keys: Vec) -> Self; ``` Source line: `152`. ## token\_signer::TokenVerifier::with\_expected\_issuers [#token_signertokenverifierwith_expected_issuers] Set expected issuers ```rust #[must_use] pub fn with_expected_issuers(mut self, issuers: Vec) -> Self; ``` Source line: `159`. ## token\_signer::TokenVerifier::with\_expected\_audiences [#token_signertokenverifierwith_expected_audiences] Set expected audiences ```rust #[must_use] pub fn with_expected_audiences(mut self, audiences: Vec) -> Self; ``` Source line: `166`. ## token\_signer::TokenVerifier::verify [#token_signertokenverifierverify] Verify a token # Errors [#errors-2] Returns an error if verification fails ```rust pub fn verify(&self, token: &AgentCapabilityToken) -> ArsenalResult; ``` Source line: `175`. ## token\_signer::VerificationResult [#token_signerverificationresult] Result of token verification ```rust #[derive(Debug, Clone)] pub struct VerificationResult { /// Key ID that verified the token pub verified_by: KeyId, /// Whether the claims are valid pub claims_valid: bool } ``` Source line: `269`. ## token\_signer::SignedToken [#token_signersignedtoken] Signed token for transport ```rust #[derive(Clone, Serialize, Deserialize)] pub struct SignedToken { /// The token in CBOR format pub token_cbor: Vec, /// Base64-encoded signature pub signature_base64: String, /// Key ID used for signing pub key_id: String, /// Algorithm pub algorithm: String } ``` Source line: `278`. ## token\_signer::SignedToken::from\_token [#token_signersignedtokenfrom_token] Create from a signed token # Errors [#errors-3] Returns an error if the token is not signed ```rust pub fn from_token(token: &AgentCapabilityToken) -> ArsenalResult; ``` Source line: `294`. ## token\_signer::SignedToken::to\_token [#token_signersignedtokento_token] Restore the token # Errors [#errors-4] Returns an error if deserialization fails ```rust pub fn to_token(&self) -> ArsenalResult; ``` Source line: `316`. ## token\_signer::SignedToken::to\_compact [#token_signersignedtokento_compact] Encode as compact string (base64 CBOR) ```rust #[must_use] pub fn to_compact(&self) -> String; ``` Source line: `322`. ## token\_signer::SignedToken::from\_compact [#token_signersignedtokenfrom_compact] Decode from compact string # Errors [#errors-5] Returns an error if decoding fails ```rust pub fn from_compact(compact: &str) -> ArsenalResult; ``` Source line: `331`. # arsenal-core · act URL: https://docs.openagent.id/reference/rust/arsenal-core/act Markdown: https://docs.openagent.id/reference/rust/arsenal-core/act.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/act.rs`. SHA-256: `d4c5be0a419cb65effe0176715bed4cb77511de0dfd2d985ecd0c8c7d9a016d4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## act::ext\_keys [#actext_keys] Keys under which Arsenal's issuer-specific claims travel in `ext`. Namespaced, because `ext` is a shared space: another issuer minting ACTs for the same audience must be able to add its own claims without colliding with Arsenal's. ```rust pub mod ext_keys; ``` Source line: `45`. ## act::ext\_keys::CONSTRAINTS [#actext_keysconstraints] Binding constraints (\[`crate::constraints::Constraints`]). ```rust pub const CONSTRAINTS: &str; ``` Source line: `47`. ## act::ext\_keys::LIMITS [#actext_keyslimits] Rate limits (\[`crate::limits::RateLimits`]). ```rust pub const LIMITS: &str; ``` Source line: `49`. ## act::ext\_keys::BUDGET [#actext_keysbudget] Usage budget (\[`crate::limits::UsageBudget`]). ```rust pub const BUDGET: &str; ``` Source line: `51`. ## act::ext\_keys::TRACE [#actext_keystrace] Audit trace (\[`crate::token::TokenTrace`]). ```rust pub const TRACE: &str; ``` Source line: `53`. ## act::ext\_keys::DELEGATED\_VARIABLES [#actext_keysdelegated_variables] Credential variables reachable through the proxy. ```rust pub const DELEGATED_VARIABLES: &str; ``` Source line: `55`. ## act::ext\_keys::MAX\_DELEGATION\_DEPTH [#actext_keysmax_delegation_depth] Delegation depth ceiling for credential tokens. ```rust pub const MAX_DELEGATION_DEPTH: &str; ``` Source line: `57`. ## act::ext\_keys::DELEGATION\_REQUIRE\_APPROVAL [#actext_keysdelegation_require_approval] Whether onward delegation needs explicit human approval. Part of Arsenal's delegation constraints with no canonical counterpart: the wire format governs whether delegation is *permitted*, while approval is a workflow Arsenal runs. ```rust pub const DELEGATION_REQUIRE_APPROVAL: &str; ``` Source line: `63`. # arsenal-core · audit URL: https://docs.openagent.id/reference/rust/arsenal-core/audit Markdown: https://docs.openagent.id/reference/rust/arsenal-core/audit.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/audit.rs`. SHA-256: `2ab608239c5af9cc3d66b8ddefc3d5559f66b2d108b566125c05190dee89a546`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit::AuditEvent [#auditauditevent] Audit event - a single auditable occurrence ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuditEvent { /// Unique event ID pub id: AuditEventId, /// When the event occurred pub timestamp: chrono::DateTime, /// Event kind pub kind: AuditEventKind, /// Severity level pub severity: AuditSeverity, /// Tenant context pub tenant_id: TenantId, /// Agent involved (if any) #[serde(skip_serializing_if = "Option::is_none")] pub agent_id: Option, /// Session involved (if any) #[serde(skip_serializing_if = "Option::is_none")] pub session_id: Option, /// Token involved (if any) #[serde(skip_serializing_if = "Option::is_none")] pub token_id: Option, /// Outcome of the operation pub outcome: AuditOutcome, /// Human-readable description pub description: String, /// Additional structured data #[serde(default)] pub metadata: HashMap, /// Client IP address (if available) #[serde(skip_serializing_if = "Option::is_none")] pub client_ip: Option, /// User agent (if available) #[serde(skip_serializing_if = "Option::is_none")] pub user_agent: Option, /// Request ID for correlation #[serde(skip_serializing_if = "Option::is_none")] pub request_id: Option, /// Hash of the previous event (for chain integrity) #[serde(skip_serializing_if = "Option::is_none")] pub previous_hash: Option<[u8; 32]>, /// Hash of this event #[serde(skip_serializing_if = "Option::is_none")] pub event_hash: Option<[u8; 32]> } ``` Source line: `20`. ## audit::AuditEvent::builder [#auditauditeventbuilder] Create a new audit event builder ```rust #[must_use] pub fn builder(kind: AuditEventKind, tenant_id: TenantId) -> AuditEventBuilder; ``` Source line: `67`. ## audit::AuditEvent::compute\_hash [#auditauditeventcompute_hash] Compute the hash of this event ```rust #[must_use] pub fn compute_hash(&self) -> [u8; 32]; ``` Source line: `73`. ## audit::AuditEvent::verify\_hash [#auditauditeventverify_hash] Verify the event hash ```rust #[must_use] pub fn verify_hash(&self) -> bool; ``` Source line: `95`. ## audit::AuditEvent::to\_json [#auditauditeventto_json] Serialize to JSON # Errors [#errors] Returns an error if serialization fails ```rust pub fn to_json(&self) -> Result; ``` Source line: `114`. ## audit::AuditEvent::to\_json\_pretty [#auditauditeventto_json_pretty] Serialize to JSON (pretty) # Errors [#errors-1] Returns an error if serialization fails ```rust pub fn to_json_pretty(&self) -> Result; ``` Source line: `122`. ## audit::AuditEventId [#auditauditeventid] Audit event ID ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct AuditEventId(Uuid); ``` Source line: `130`. ## audit::AuditEventId::generate [#auditauditeventidgenerate] Generate a new event ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `135`. ## audit::AuditEventId::as\_uuid [#auditauditeventidas_uuid] Get the inner UUID ```rust #[must_use] pub const fn as_uuid(&self) -> &Uuid; ``` Source line: `141`. ## audit::AuditEventKind [#auditauditeventkind] Categories of audit events ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AuditEventKind { // Authentication events /// Agent authentication attempt AgentAuthentication, /// Session started SessionStarted, /// Session ended SessionEnded, /// Session renewed SessionRenewed, /// Session revoked SessionRevoked, // Token events /// Token issued TokenIssued, /// Token verified TokenVerified, /// Token rejected TokenRejected, /// Token revoked TokenRevoked, /// Token expired TokenExpired, // Capability events /// Capability requested CapabilityRequested, /// Capability granted CapabilityGranted, /// Capability denied CapabilityDenied, /// Capability delegated CapabilityDelegated, // Secret events /// Secret created SecretCreated, /// Secret accessed SecretAccessed, /// Secret rotated SecretRotated, /// Secret deleted SecretDeleted, /// Secret unwrapped SecretUnwrapped, // Policy events /// Policy created PolicyCreated, /// Policy updated PolicyUpdated, /// Policy deleted PolicyDeleted, /// Policy evaluated PolicyEvaluated, // Administrative events /// Agent created AgentCreated, /// Agent updated AgentUpdated, /// Agent deactivated AgentDeactivated, /// Tenant created TenantCreated, /// Tenant updated TenantUpdated, /// Tenant suspended TenantSuspended, // Security events /// Rate limit exceeded RateLimitExceeded, /// Budget exhausted BudgetExhausted, /// Constraint violated ConstraintViolated, /// Suspicious activity detected SuspiciousActivity, /// Security alert SecurityAlert, // System events /// System startup SystemStartup, /// System shutdown SystemShutdown, /// Configuration changed ConfigurationChanged, /// Key rotation KeyRotation, // Proxy events /// Proxy request processed ProxyRequest, /// Proxy request denied by policy or binding ProxyRequestDenied, /// Proxy destination binding violated ProxyDestinationViolation, /// Proxy resolved credential variables for a request ProxyCredentialResolved, // Fingerprint events /// Agent fingerprint verified successfully FingerprintVerified, /// Agent fingerprint mismatch detected (potential key theft) FingerprintMismatch, /// Agent fingerprint state was reset FingerprintReset, // Consent events /// Consent was requested from a human ConsentRequested, /// Consent was granted by a human ConsentGranted, /// Consent was denied by a human ConsentDenied, /// Consent was revoked ConsentRevoked, // Delegated credential token events /// Delegated credential token was issued DctIssued, /// Delegated credential token was used in a proxy request DctUsed, } ``` Source line: `161`. ## audit::AuditEventKind::default\_severity [#auditauditeventkinddefault_severity] Get the default severity for this event kind ```rust #[must_use] pub const fn default_severity(&self) -> AuditSeverity; ``` Source line: `292`. ## audit::AuditEventKind::is\_security\_relevant [#auditauditeventkindis_security_relevant] Check if this is a security-relevant event ```rust #[must_use] pub const fn is_security_relevant(&self) -> bool; ``` Source line: `329`. ## audit::AuditSeverity [#auditauditseverity] Severity levels for audit events ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AuditSeverity { /// Informational - routine operations Low, /// Medium - notable but expected operations Medium, /// High - significant security events High, /// Critical - requires immediate attention Critical, } ``` Source line: `356`. ## audit::AuditSeverity::as\_str [#auditauditseverityas_str] Get string representation ```rust #[must_use] pub const fn as_str(&self) -> &'static str; ``` Source line: `370`. ## audit::AuditOutcome [#auditauditoutcome] Outcome of an audited operation ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AuditOutcome { /// Operation succeeded Success, /// Operation failed Failure, /// Operation was denied by policy Denied, /// Operation timed out Timeout, /// Operation had an error Error, } ``` Source line: `389`. ## audit::AuditOutcome::is\_success [#auditauditoutcomeis_success] Check if the outcome indicates success ```rust #[must_use] pub const fn is_success(&self) -> bool; ``` Source line: `405`. ## audit::AuditEventBuilder [#auditauditeventbuilder-1] Builder for audit events ```rust #[derive(Debug)] pub struct AuditEventBuilder { } ``` Source line: `412`. ## audit::AuditEventBuilder::new [#auditauditeventbuildernew] Create a new builder ```rust #[must_use] pub fn new(kind: AuditEventKind, tenant_id: TenantId) -> Self; ``` Source line: `431`. ## audit::AuditEventBuilder::severity [#auditauditeventbuilderseverity] Set severity ```rust #[must_use] pub fn severity(mut self, severity: AuditSeverity) -> Self; ``` Source line: `451`. ## audit::AuditEventBuilder::agent [#auditauditeventbuilderagent] Set agent ID ```rust #[must_use] pub fn agent(mut self, agent_id: AgentId) -> Self; ``` Source line: `458`. ## audit::AuditEventBuilder::session [#auditauditeventbuildersession] Set session ID ```rust #[must_use] pub fn session(mut self, session_id: SessionId) -> Self; ``` Source line: `465`. ## audit::AuditEventBuilder::token [#auditauditeventbuildertoken] Set token ID ```rust #[must_use] pub fn token(mut self, token_id: TokenId) -> Self; ``` Source line: `472`. ## audit::AuditEventBuilder::outcome [#auditauditeventbuilderoutcome] Set outcome ```rust #[must_use] pub fn outcome(mut self, outcome: AuditOutcome) -> Self; ``` Source line: `479`. ## audit::AuditEventBuilder::description [#auditauditeventbuilderdescription] Set description ```rust #[must_use] pub fn description(mut self, description: impl Into) -> Self; ``` Source line: `486`. ## audit::AuditEventBuilder::metadata [#auditauditeventbuildermetadata] Add metadata ```rust #[must_use] pub fn metadata(mut self, key: impl Into, value: impl Serialize) -> Self; ``` Source line: `493`. ## audit::AuditEventBuilder::client\_ip [#auditauditeventbuilderclient_ip] Set client IP ```rust #[must_use] pub fn client_ip(mut self, ip: impl Into) -> Self; ``` Source line: `502`. ## audit::AuditEventBuilder::user\_agent [#auditauditeventbuilderuser_agent] Set user agent ```rust #[must_use] pub fn user_agent(mut self, ua: impl Into) -> Self; ``` Source line: `509`. ## audit::AuditEventBuilder::request\_id [#auditauditeventbuilderrequest_id] Set request ID ```rust #[must_use] pub fn request_id(mut self, id: Uuid) -> Self; ``` Source line: `516`. ## audit::AuditEventBuilder::previous\_hash [#auditauditeventbuilderprevious_hash] Set previous hash for chain integrity ```rust #[must_use] pub fn previous_hash(mut self, hash: [u8; 32]) -> Self; ``` Source line: `523`. ## audit::AuditEventBuilder::build [#auditauditeventbuilderbuild] Build the audit event ```rust #[must_use] pub fn build(self) -> AuditEvent; ``` Source line: `530`. ## audit::AuditLog [#auditauditlog] Audit log for collecting events ```rust #[derive(Debug, Default)] pub struct AuditLog { } ``` Source line: `563`. ## audit::AuditLog::new [#auditauditlognew] Create a new audit log ```rust #[must_use] pub fn new() -> Self; ``` Source line: `573`. ## audit::AuditLog::append [#auditauditlogappend] Add an event to the log ```rust pub fn append(&mut self, mut event: AuditEvent); ``` Source line: `578`. ## audit::AuditLog::events [#auditauditlogevents] Get all events ```rust #[must_use] pub fn events(&self) -> &[AuditEvent]; ``` Source line: `589`. ## audit::AuditLog::events\_by\_kind [#auditauditlogevents_by_kind] Get events by kind ```rust #[must_use] pub fn events_by_kind(&self, kind: AuditEventKind) -> Vec<&AuditEvent>; ``` Source line: `595`. ## audit::AuditLog::events\_by\_severity [#auditauditlogevents_by_severity] Get events by severity ```rust #[must_use] pub fn events_by_severity(&self, min_severity: AuditSeverity) -> Vec<&AuditEvent>; ``` Source line: `601`. ## audit::AuditLog::verify\_chain [#auditauditlogverify_chain] Verify chain integrity ```rust #[must_use] pub fn verify_chain(&self) -> bool; ``` Source line: `610`. ## audit::AuditLog::len [#auditauditloglen] Get the number of events ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `632`. ## audit::AuditLog::is\_empty [#auditauditlogis_empty] Check if the log is empty ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `638`. # arsenal-core · consent URL: https://docs.openagent.id/reference/rust/arsenal-core/consent Markdown: https://docs.openagent.id/reference/rust/arsenal-core/consent.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/consent.rs`. SHA-256: `7e190e9a4d86a5cd1177f2673c7134f73806ae4a4816fd658f564d477e7db94f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## consent::ConsentId [#consentconsentid] Unique identifier for a consent record ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct ConsentId(Uuid); ``` Source line: `38`. ## consent::ConsentId::generate [#consentconsentidgenerate] Generate a new consent ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `43`. ## consent::ConsentId::from\_uuid [#consentconsentidfrom_uuid] Create from an existing UUID ```rust #[must_use] pub const fn from_uuid(uuid: Uuid) -> Self; ``` Source line: `49`. ## consent::ConsentId::as\_uuid [#consentconsentidas_uuid] Get the inner UUID ```rust #[must_use] pub const fn as_uuid(&self) -> &Uuid; ``` Source line: `55`. ## consent::ConsentRecord [#consentconsentrecord] A signed consent record authorizing agent credential access. Consent records are immutable once created. They can be revoked but never modified. The `signature` field contains an Ed25519 signature over the canonical CBOR encoding of the record (excluding the signature and revocation fields). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConsentRecord { /// Unique consent record ID pub consent_id: ConsentId, /// Tenant this consent record belongs to (multi-tenant isolation) pub tenant_id: TenantId, /// DID of the agent granted access pub agent_did: String, /// DID of the human who granted consent pub human_root_did: String, /// Template variable names the agent may access pub variables: Vec, /// Target domains the agent may reach with these credentials pub destination_domains: Vec, /// Scopes the consent covers pub scopes: Vec, /// Human-readable identifier of who granted consent pub granted_by: String, /// When consent was granted pub granted_at: chrono::DateTime, /// When this consent expires pub expires_at: chrono::DateTime, /// Ed25519 signature by the human over canonical record bytes pub signature: Vec, /// Whether this consent can be revoked (always true) #[serde(default = "default_revocable")] pub revocable: bool, /// Whether this consent has been revoked #[serde(default)] pub revoked: bool, /// When this consent was revoked, if applicable #[serde(default, skip_serializing_if = "Option::is_none")] pub revoked_at: Option> } ``` Source line: `79`. ## consent::ConsentRecord::is\_valid [#consentconsentrecordis_valid] Check if this consent record is currently valid. A record is valid if it is not revoked and has not expired. ```rust #[must_use] pub fn is_valid(&self) -> bool; ``` Source line: `123`. ## consent::ConsentRecord::covers\_variable [#consentconsentrecordcovers_variable] Check if this consent covers a specific variable. ```rust #[must_use] pub fn covers_variable(&self, variable: &str) -> bool; ``` Source line: `129`. ## consent::ConsentRecord::covers\_domain [#consentconsentrecordcovers_domain] Check if this consent covers a specific domain. ```rust #[must_use] pub fn covers_domain(&self, domain: &str) -> bool; ``` Source line: `135`. ## consent::ConsentRecord::revoke [#consentconsentrecordrevoke] Revoke this consent record. ```rust pub fn revoke(&mut self); ``` Source line: `143`. ## consent::ConsentRecord::signing\_bytes [#consentconsentrecordsigning_bytes] Get the canonical bytes for signing/verification. Serializes all fields except `signature`, `revoked`, and `revoked_at` to a deterministic CBOR representation. # Errors [#errors] Returns an error if serialization fails. ```rust pub fn signing_bytes(&self) -> ArsenalResult>; ``` Source line: `156`. ## consent::ConsentPolicy [#consentconsentpolicy] Consent policy determining the granularity of consent checks. ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ConsentPolicy { /// Consent required for each individual variable #[default] PerVariable, /// Consent required per provider/service PerProvider, /// Consent required per agent (blanket consent) PerAgent, } ``` Source line: `199`. ## consent::ConsentPolicy::as\_str [#consentconsentpolicyas_str] Get the string representation ```rust #[must_use] pub const fn as_str(&self) -> &'static str; ``` Source line: `212`. ## consent::ConsentStatus [#consentconsentstatus] Status of consent for a credential operation. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ConsentStatus { /// Consent was pre-approved (e.g., by policy) PreApproved, /// Consent has been explicitly approved by a human Approved, /// Consent is pending human review Pending, /// Consent was explicitly denied Denied, /// Consent was previously granted but has been revoked Revoked, /// Consent is not required for this operation NotRequired, } ``` Source line: `232`. ## consent::ConsentStatus::allows\_operation [#consentconsentstatusallows_operation] Check if this status allows the operation to proceed. ```rust #[must_use] pub const fn allows_operation(&self) -> bool; ``` Source line: `250`. ## consent::ConsentStatus::as\_str [#consentconsentstatusas_str] Get the string representation ```rust #[must_use] pub const fn as_str(&self) -> &'static str; ``` Source line: `256`. ## consent::ConsentRequest [#consentconsentrequest] A request for consent from an agent. Created when an agent attempts to access credentials that require human consent. The broker holds the proxy request until consent is granted or denied. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConsentRequest { /// Unique request ID pub request_id: Uuid, /// DID of the requesting agent pub agent_did: String, /// DID of the human who must approve pub human_root_did: String, /// Variables the agent wants to access pub variables: Vec, /// Destination domains the agent wants to reach pub destination_domains: Vec, /// Scopes being requested pub scopes: Vec, /// When this request was created pub created_at: chrono::DateTime, /// When this request expires if not acted upon pub expires_at: chrono::DateTime } ``` Source line: `280`. ## consent::ConsentRequest::new [#consentconsentrequestnew] Create a new consent request. # Errors [#errors-1] Returns an error if validation fails. ```rust pub fn new( agent_did: impl Into, human_root_did: impl Into, variables: Vec, destination_domains: Vec, scopes: Vec, ) -> ArsenalResult; ``` Source line: `305`. ## consent::ConsentRequest::is\_expired [#consentconsentrequestis_expired] Check if this consent request has expired. ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `350`. # arsenal-core · constraints URL: https://docs.openagent.id/reference/rust/arsenal-core/constraints Markdown: https://docs.openagent.id/reference/rust/arsenal-core/constraints.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/constraints.rs`. SHA-256: `1d21f4bb1d751b9f986249d128ad97ed164d9f21534029f2cd3c715e61265bda`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## constraints::Constraints [#constraintsconstraints] Constraints that must be satisfied for a token to be valid ```rust #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Constraints { /// Device binding - token only valid from specific device #[serde(skip_serializing_if = "Option::is_none")] pub device_binding: Option, /// Session binding - token bound to a specific session #[serde(skip_serializing_if = "Option::is_none")] pub session_binding: Option, /// Browser/origin binding - token only valid from specific origins #[serde(skip_serializing_if = "Option::is_none")] pub origin_binding: Option, /// Network constraints - IP allowlist/denylist #[serde(skip_serializing_if = "Option::is_none")] pub network_constraints: Option, /// Time-based constraints #[serde(skip_serializing_if = "Option::is_none")] pub time_constraints: Option, /// Environment constraints #[serde(skip_serializing_if = "Option::is_none")] pub environment_constraints: Option, /// Proof-of-possession required #[serde(default)] pub require_pop: bool } ``` Source line: `15`. ## constraints::Constraints::none [#constraintsconstraintsnone] Create empty constraints (no restrictions) ```rust #[must_use] pub fn none() -> Self; ``` Source line: `48`. ## constraints::Constraints::with\_pop [#constraintsconstraintswith_pop] Create constraints requiring proof-of-possession ```rust #[must_use] pub fn with_pop() -> Self; ``` Source line: `54`. ## constraints::Constraints::with\_device [#constraintsconstraintswith_device] Add device binding ```rust #[must_use] pub fn with_device(mut self, device_id: DeviceId) -> Self; ``` Source line: `63`. ## constraints::Constraints::with\_origins [#constraintsconstraintswith_origins] Add origin binding ```rust #[must_use] pub fn with_origins(mut self, origins: Vec) -> Self; ``` Source line: `73`. ## constraints::Constraints::with\_time\_window [#constraintsconstraintswith_time_window] Add time constraints ```rust #[must_use] pub fn with_time_window( mut self, not_before: chrono::DateTime, not_after: chrono::DateTime, ) -> Self; ``` Source line: `82`. ## constraints::Constraints::validate [#constraintsconstraintsvalidate] Check if all constraints are satisfied # Errors [#errors] Returns an error if any constraint is violated. ```rust pub fn validate(&self, context: &ConstraintContext) -> ArsenalResult<()>; ``` Source line: `101`. ## constraints::DeviceBinding [#constraintsdevicebinding] Device binding configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DeviceBinding { /// The device this token is bound to pub device_id: DeviceId, /// Type of binding pub binding_type: BindingType } ``` Source line: `126`. ## constraints::SessionBinding [#constraintssessionbinding] Session binding configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionBinding { /// The session ID this token is bound to pub session_id: String, /// Hash of the session key for verification pub session_key_hash: Option<[u8; 32]> } ``` Source line: `155`. ## constraints::OriginBinding [#constraintsoriginbinding] Origin binding configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OriginBinding { /// Allowed origins pub allowed_origins: HashSet } ``` Source line: `192`. ## constraints::NetworkConstraints [#constraintsnetworkconstraints] Network constraints ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct NetworkConstraints { /// Allowed IP addresses #[serde(default)] pub allowed_ips: HashSet, /// Denied IP addresses #[serde(default)] pub denied_ips: HashSet, /// Allowed CIDR ranges #[serde(default)] pub allowed_cidrs: Vec, /// Allowed ASNs #[serde(default)] pub allowed_asns: HashSet } ``` Source line: `217`. ## constraints::TimeConstraints [#constraintstimeconstraints] Time-based constraints ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TimeConstraints { /// Token not valid before this time #[serde(skip_serializing_if = "Option::is_none")] pub not_before: Option>, /// Token not valid after this time #[serde(skip_serializing_if = "Option::is_none")] pub not_after: Option>, /// Allowed hours of day (0-23) #[serde(skip_serializing_if = "Option::is_none")] pub allowed_hours: Option>, /// Allowed days of week (0=Sunday, 6=Saturday) #[serde(skip_serializing_if = "Option::is_none")] pub allowed_days: Option> } ``` Source line: `267`. ## constraints::EnvironmentConstraint [#constraintsenvironmentconstraint] Environment constraints ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EnvironmentConstraint { /// Required environment #[serde(skip_serializing_if = "Option::is_none")] pub required_environment: Option, /// Required tags that must be present #[serde(default)] pub required_tags: HashSet, /// Forbidden tags that must not be present #[serde(default)] pub forbidden_tags: HashSet } ``` Source line: `307`. ## constraints::BindingType [#constraintsbindingtype] Type of binding enforcement ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum BindingType { /// Binding must be satisfied Required, /// Binding is preferred but not required Preferred, } ``` Source line: `358`. ## constraints::ConstraintContext [#constraintsconstraintcontext] Context for constraint validation ```rust #[derive(Debug, Clone, Default)] pub struct ConstraintContext { /// Current time for time-based checks pub current_time: chrono::DateTime, /// Device ID if available pub device_id: Option, /// Session ID if available pub session_id: Option, /// Session key hash if available pub session_key_hash: Option<[u8; 32]>, /// Request origin if available pub origin: Option, /// Client IP address if available pub client_ip: Option, /// Current environment pub environment: Option, /// Current tags pub tags: HashSet } ``` Source line: `367`. ## constraints::ConstraintContext::now [#constraintsconstraintcontextnow] Create a new context with current time ```rust #[must_use] pub fn now() -> Self; ``` Source line: `389`. ## constraints::ConstraintContext::with\_device [#constraintsconstraintcontextwith_device] Set device ID ```rust #[must_use] pub fn with_device(mut self, device_id: DeviceId) -> Self; ``` Source line: `398`. ## constraints::ConstraintContext::with\_session [#constraintsconstraintcontextwith_session] Set session ID ```rust #[must_use] pub fn with_session(mut self, session_id: impl Into) -> Self; ``` Source line: `405`. ## constraints::ConstraintContext::with\_origin [#constraintsconstraintcontextwith_origin] Set origin ```rust #[must_use] pub fn with_origin(mut self, origin: impl Into) -> Self; ``` Source line: `412`. ## constraints::ConstraintContext::with\_client\_ip [#constraintsconstraintcontextwith_client_ip] Set client IP ```rust #[must_use] pub fn with_client_ip(mut self, ip: IpAddr) -> Self; ``` Source line: `419`. ## constraints::ConstraintContext::with\_environment [#constraintsconstraintcontextwith_environment] Set environment ```rust #[must_use] pub fn with_environment(mut self, env: impl Into) -> Self; ``` Source line: `426`. ## constraints::ConstraintContext::with\_tag [#constraintsconstraintcontextwith_tag] Add a tag ```rust #[must_use] pub fn with_tag(mut self, tag: impl Into) -> Self; ``` Source line: `433`. # arsenal-core · crate URL: https://docs.openagent.id/reference/rust/arsenal-core/crate Markdown: https://docs.openagent.id/reference/rust/arsenal-core/crate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/lib.rs`. SHA-256: `13dfa8779257ee1a963ab68ee6489a3bda7f79157240c782eb47e7493c93d52f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## act [#act] ```rust pub mod act; ``` Source line: `24`. ## audit [#audit] ```rust pub mod audit; ``` Source line: `25`. ## consent [#consent] ```rust pub mod consent; ``` Source line: `26`. ## constraints [#constraints] ```rust pub mod constraints; ``` Source line: `27`. ## delegation [#delegation] ```rust pub mod delegation; ``` Source line: `28`. ## error [#error] ```rust pub mod error; ``` Source line: `29`. ## fingerprint [#fingerprint] ```rust pub mod fingerprint; ``` Source line: `30`. ## identity [#identity] ```rust pub mod identity; ``` Source line: `31`. ## limits [#limits] ```rust pub mod limits; ``` Source line: `32`. ## policy [#policy] ```rust pub mod policy; ``` Source line: `33`. ## proxy [#proxy] ```rust pub mod proxy; ``` Source line: `34`. ## scope [#scope] ```rust pub mod scope; ``` Source line: `35`. ## secret [#secret] ```rust pub mod secret; ``` Source line: `36`. ## session [#session] ```rust pub mod session; ``` Source line: `37`. ## token [#token] ```rust pub mod token; ``` Source line: `38`. ## pub use audit::\{AuditEvent, AuditEventKind, AuditSeverity}; [#pub-use-auditauditevent-auditeventkind-auditseverity] ```rust pub use audit::{AuditEvent, AuditEventKind, AuditSeverity}; ``` Source line: `40`. ## pub use consent::\{ConsentId, ConsentPolicy, ConsentRecord, ConsentRequest, ConsentStatus}; [#pub-use-consentconsentid-consentpolicy-consentrecord-consentrequest-consentstatus] ```rust pub use consent::{ConsentId, ConsentPolicy, ConsentRecord, ConsentRequest, ConsentStatus}; ``` Source line: `41`. ## pub use constraints::\{BindingType, Constraints, EnvironmentConstraint}; [#pub-use-constraintsbindingtype-constraints-environmentconstraint] ```rust pub use constraints::{BindingType, Constraints, EnvironmentConstraint}; ``` Source line: `42`. ## pub use delegation::\{DelegationChain, DelegationConstraints}; [#pub-use-delegationdelegationchain-delegationconstraints] ```rust pub use delegation::{DelegationChain, DelegationConstraints}; ``` Source line: `43`. ## pub use error::\{ArsenalError, ArsenalResult}; [#pub-use-errorarsenalerror-arsenalresult] ```rust pub use error::{ArsenalError, ArsenalResult}; ``` Source line: `44`. ## pub use fingerprint::\{FingerprintState, FingerprintVerification}; [#pub-use-fingerprintfingerprintstate-fingerprintverification] ```rust pub use fingerprint::{FingerprintState, FingerprintVerification}; ``` Source line: `45`. ## pub use identity::\{AgentIdentity, PrincipalId, TenantId}; [#pub-use-identityagentidentity-principalid-tenantid] ```rust pub use identity::{AgentIdentity, PrincipalId, TenantId}; ``` Source line: `46`. ## pub use limits::\{RateLimits, UsageBudget}; [#pub-use-limitsratelimits-usagebudget] ```rust pub use limits::{RateLimits, UsageBudget}; ``` Source line: `47`. ## pub use policy::\{PolicyDocument, PolicyEffect, PolicyId}; [#pub-use-policypolicydocument-policyeffect-policyid] ```rust pub use policy::{PolicyDocument, PolicyEffect, PolicyId}; ``` Source line: `48`. ## pub use proxy::\{ [#pub-use-proxy] DestinationBinding, ProxyMetadata, ProxyRequest, ProxyResponse, TemplateVariable, VariablePrefix, VariableResolutionTable, }; ```rust pub use proxy::{ DestinationBinding, ProxyMetadata, ProxyRequest, ProxyResponse, TemplateVariable, VariablePrefix, VariableResolutionTable, }; ``` Source line: `49`. ## pub use scope::\{Permission, Scope, ScopeSet}; [#pub-use-scopepermission-scope-scopeset] ```rust pub use scope::{Permission, Scope, ScopeSet}; ``` Source line: `53`. ## pub use secret::\{SecretId, SecretMetadata, SecretVersion}; [#pub-use-secretsecretid-secretmetadata-secretversion] ```rust pub use secret::{SecretId, SecretMetadata, SecretVersion}; ``` Source line: `54`. ## pub use session::\{AgentSession, SessionId, SessionState}; [#pub-use-sessionagentsession-sessionid-sessionstate] ```rust pub use session::{AgentSession, SessionId, SessionState}; ``` Source line: `55`. ## pub use token::\{AgentCapabilityToken, TokenClaims, TokenId}; [#pub-use-tokenagentcapabilitytoken-tokenclaims-tokenid] ```rust pub use token::{AgentCapabilityToken, TokenClaims, TokenId}; ``` Source line: `56`. ## prelude [#prelude] Re-export commonly used external types ```rust pub mod prelude; ``` Source line: `59`. ## pub use super::consent::\{ConsentRecord, ConsentStatus}; [#pub-use-superconsentconsentrecord-consentstatus] ```rust pub use super::consent::{ConsentRecord, ConsentStatus}; ``` Source line: `60`. ## pub use super::error::\{ArsenalError, ArsenalResult}; [#pub-use-supererrorarsenalerror-arsenalresult] ```rust pub use super::error::{ArsenalError, ArsenalResult}; ``` Source line: `61`. ## pub use super::fingerprint::\{FingerprintState, FingerprintVerification}; [#pub-use-superfingerprintfingerprintstate-fingerprintverification] ```rust pub use super::fingerprint::{FingerprintState, FingerprintVerification}; ``` Source line: `62`. ## pub use super::identity::\{AgentIdentity, PrincipalId, TenantId}; [#pub-use-superidentityagentidentity-principalid-tenantid] ```rust pub use super::identity::{AgentIdentity, PrincipalId, TenantId}; ``` Source line: `63`. ## pub use super::proxy::\{DestinationBinding, ProxyRequest, ProxyResponse, TemplateVariable}; [#pub-use-superproxydestinationbinding-proxyrequest-proxyresponse-templatevariable] ```rust pub use super::proxy::{DestinationBinding, ProxyRequest, ProxyResponse, TemplateVariable}; ``` Source line: `64`. ## pub use super::scope::\{Permission, Scope, ScopeSet}; [#pub-use-superscopepermission-scope-scopeset] ```rust pub use super::scope::{Permission, Scope, ScopeSet}; ``` Source line: `65`. ## pub use super::secret::\{SecretId, SecretVersion}; [#pub-use-supersecretsecretid-secretversion] ```rust pub use super::secret::{SecretId, SecretVersion}; ``` Source line: `66`. ## pub use super::session::\{SessionId, SessionState}; [#pub-use-supersessionsessionid-sessionstate] ```rust pub use super::session::{SessionId, SessionState}; ``` Source line: `67`. ## pub use super::token::\{AgentCapabilityToken, TokenId}; [#pub-use-supertokenagentcapabilitytoken-tokenid] ```rust pub use super::token::{AgentCapabilityToken, TokenId}; ``` Source line: `68`. # arsenal-core · delegation URL: https://docs.openagent.id/reference/rust/arsenal-core/delegation Markdown: https://docs.openagent.id/reference/rust/arsenal-core/delegation.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/delegation.rs`. SHA-256: `496b1578b6c1df82d7a5daeb80af45a1debdcf1d398fcac40c4963105d8969e7`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## delegation::DelegationConstraints [#delegationdelegationconstraints] Delegation constraints - what can be delegated ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationConstraints { /// Whether delegation is allowed at all pub allow_delegation: bool, /// Maximum depth of delegation (0 = no further delegation) pub max_depth: u8, /// Scopes that can be delegated (must be subset of parent) #[serde(skip_serializing_if = "Option::is_none")] pub delegatable_scopes: Option, /// Agents that can receive delegation, named by OAS DID /// /// A DID rather than a local key, because this constraint is a token claim: /// whoever verifies the delegated token must be able to resolve the identity /// it names. #[serde(default)] pub allowed_delegates: Vec, /// Whether any agent can receive delegation pub allow_any_delegate: bool, /// Maximum TTL reduction required (seconds) pub min_ttl_reduction: i64, /// Require explicit approval for delegation pub require_approval: bool } ``` Source line: `23`. ## delegation::DelegationConstraints::allow [#delegationdelegationconstraintsallow] Create constraints that allow delegation ```rust #[must_use] pub fn allow(max_depth: u8) -> Self; ``` Source line: `63`. ## delegation::DelegationConstraints::deny [#delegationdelegationconstraintsdeny] Create constraints that deny delegation ```rust #[must_use] pub fn deny() -> Self; ``` Source line: `77`. ## delegation::DelegationConstraints::can\_delegate\_to [#delegationdelegationconstraintscan_delegate_to] Check if delegation to a specific agent is allowed ```rust #[must_use] pub fn can_delegate_to(&self, agent_did: &OasDid) -> bool; ``` Source line: `83`. ## delegation::DelegationConstraints::can\_delegate\_scope [#delegationdelegationconstraintscan_delegate_scope] Check if a scope can be delegated ```rust #[must_use] pub fn can_delegate_scope(&self, scope: &ScopeSet) -> bool; ``` Source line: `95`. ## delegation::DelegationConstraints::validate\_delegation [#delegationdelegationconstraintsvalidate_delegation] Validate a delegation request # Errors [#errors] Returns an error if the delegation is not allowed ```rust pub fn validate_delegation( &self, target_agent: &OasDid, requested_scopes: &ScopeSet, current_depth: u8, parent_ttl: i64, requested_ttl: i64, ) -> ArsenalResult<()>; ``` Source line: `109`. ## delegation::DelegationLink [#delegationdelegationlink] A link in the delegation chain ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationLink { /// Token ID of the delegating token pub parent_token_id: TokenId, /// Agent that delegated pub delegator: AgentId, /// Agent that received delegation pub delegate: AgentId, /// Scopes that were delegated pub delegated_scopes: ScopeSet, /// When the delegation occurred pub delegated_at: chrono::DateTime, /// Depth in the chain (0 = first delegation) pub depth: u8 } ``` Source line: `159`. ## delegation::DelegationChain [#delegationdelegationchain] Complete delegation chain for audit and validation ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationChain { } ``` Source line: `176`. ## delegation::DelegationChain::new [#delegationdelegationchainnew] Create a new delegation chain starting from a root token ```rust #[must_use] pub fn new(root_token_id: TokenId, root_agent: AgentId) -> Self; ``` Source line: `188`. ## delegation::DelegationChain::add\_link [#delegationdelegationchainadd_link] Add a delegation link to the chain # Errors [#errors-1] Returns an error if the chain would be too long ```rust pub fn add_link(&mut self, link: DelegationLink) -> ArsenalResult<()>; ``` Source line: `200`. ## delegation::DelegationChain::depth [#delegationdelegationchaindepth] Get the current depth of the chain ```rust #[must_use] pub fn depth(&self) -> u8; ``` Source line: `219`. ## delegation::DelegationChain::root\_token\_id [#delegationdelegationchainroot_token_id] Get the root token ID ```rust #[must_use] pub fn root_token_id(&self) -> &TokenId; ``` Source line: `225`. ## delegation::DelegationChain::root\_agent [#delegationdelegationchainroot_agent] Get the root agent ```rust #[must_use] pub fn root_agent(&self) -> &AgentId; ``` Source line: `231`. ## delegation::DelegationChain::current\_delegate [#delegationdelegationchaincurrent_delegate] Get the current (most recent) delegate ```rust #[must_use] pub fn current_delegate(&self) -> &AgentId; ``` Source line: `237`. ## delegation::DelegationChain::links [#delegationdelegationchainlinks] Get all links in the chain ```rust #[must_use] pub fn links(&self) -> &[DelegationLink]; ``` Source line: `243`. ## delegation::DelegationChain::validate [#delegationdelegationchainvalidate] Validate the entire chain # Errors [#errors-2] Returns an error if the chain is invalid ```rust pub fn validate(&self) -> ArsenalResult<()>; ``` Source line: `251`. ## delegation::DelegationChain::contains\_agent [#delegationdelegationchaincontains_agent] Check if an agent is in the chain (as delegator or delegate) ```rust #[must_use] pub fn contains_agent(&self, agent_id: &AgentId) -> bool; ``` Source line: `278`. ## delegation::DelegationChain::effective\_scopes [#delegationdelegationchaineffective_scopes] Get the effective scopes at the end of the chain This is the intersection of all delegated scopes ```rust #[must_use] pub fn effective_scopes(&self) -> Option; ``` Source line: `291`. ## delegation::DelegationChain::to\_cbor [#delegationdelegationchainto_cbor] Serialize to CBOR # Errors [#errors-3] Returns an error if serialization fails ```rust pub fn to_cbor(&self) -> ArsenalResult>; ``` Source line: `307`. ## delegation::DelegationChain::from\_cbor [#delegationdelegationchainfrom_cbor] Deserialize from CBOR # Errors [#errors-4] Returns an error if deserialization fails ```rust pub fn from_cbor(bytes: &[u8]) -> ArsenalResult; ``` Source line: `322`. ## delegation::DelegationRequest [#delegationdelegationrequest] Delegation request for creating a new delegated token ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationRequest { /// Agent requesting delegation pub delegator: AgentId, /// Target agent to delegate to pub delegate: AgentId, /// Scopes to delegate pub scopes: ScopeSet, /// Requested TTL in seconds pub ttl_seconds: i64, /// Parent token ID pub parent_token_id: TokenId, /// Current delegation chain (if any) #[serde(skip_serializing_if = "Option::is_none")] pub chain: Option } ``` Source line: `346`. ## delegation::DelegationResult [#delegationdelegationresult] Result of a delegation request ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationResult { /// Whether delegation was approved pub approved: bool, /// New token ID (if approved) #[serde(skip_serializing_if = "Option::is_none")] pub token_id: Option, /// Updated delegation chain #[serde(skip_serializing_if = "Option::is_none")] pub chain: Option, /// Reason for denial (if not approved) #[serde(skip_serializing_if = "Option::is_none")] pub denial_reason: Option } ``` Source line: `364`. # arsenal-core · error URL: https://docs.openagent.id/reference/rust/arsenal-core/error Markdown: https://docs.openagent.id/reference/rust/arsenal-core/error.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/error.rs`. SHA-256: `8bdb49267bc6aecdbc280e3249509568c2de55bf309da38e91d5aef60c209130`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::ArsenalResult [#errorarsenalresult] Result type alias for ARSENAL operations ```rust pub type ArsenalResult = Result; ``` Source line: `14`. ## error::ErrorCode [#errorerrorcode] Error codes for programmatic handling ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ErrorCode { // Authentication errors (1xxx) /// Invalid or missing credentials AuthenticationFailed = 1001, /// Token expired TokenExpired = 1002, /// Token signature verification failed TokenSignatureInvalid = 1003, /// Proof-of-possession verification failed PopVerificationFailed = 1004, /// Identity not found or invalid IdentityInvalid = 1005, /// Session has expired or been revoked SessionExpired = 1006, // Authorization errors (2xxx) /// Insufficient permissions for requested operation InsufficientPermissions = 2001, /// Requested scope exceeds granted scope ScopeExceeded = 2002, /// Policy evaluation denied the request PolicyDenied = 2003, /// Delegation chain is invalid or broken DelegationInvalid = 2004, /// Rate limit exceeded RateLimitExceeded = 2005, /// Usage budget exhausted BudgetExhausted = 2006, // Constraint violations (3xxx) /// Request violates time-based constraints TimeConstraintViolation = 3001, /// Request violates environment binding EnvironmentBindingViolation = 3002, /// Request violates IP/network constraints NetworkConstraintViolation = 3003, /// Request violates device binding DeviceBindingViolation = 3004, /// Request violates origin binding OriginBindingViolation = 3005, // Secret management errors (4xxx) /// Secret not found SecretNotFound = 4001, /// Secret version not found SecretVersionNotFound = 4002, /// Secret has been revoked SecretRevoked = 4003, /// Secret rotation in progress SecretRotationInProgress = 4004, /// Secret unwrap limit exceeded SecretUnwrapLimitExceeded = 4005, /// Encryption/decryption failed CryptoOperationFailed = 4006, // Validation errors (5xxx) /// Input validation failed ValidationFailed = 5001, /// Malformed request MalformedRequest = 5002, /// Invalid token format InvalidTokenFormat = 5003, /// Invalid scope format InvalidScopeFormat = 5004, /// Invalid constraint specification InvalidConstraint = 5005, // Internal errors (6xxx) /// Internal service error InternalError = 6001, /// Storage backend error StorageError = 6002, /// Configuration error ConfigurationError = 6003, /// Cryptographic subsystem error CryptoSubsystemError = 6004, /// Audit subsystem error AuditError = 6005, /// Serialization failed SerializationFailed = 6006, // Revocation errors (7xxx) /// Token has been explicitly revoked TokenRevoked = 7001, /// Agent has been deactivated AgentDeactivated = 7002, /// Tenant has been suspended TenantSuspended = 7003, /// Revocation status could not be determined (fail-closed policy path) RevocationStatusUnknown = 7004, // Proxy errors (8xxx) /// Request violates destination binding for the credential ProxyDestinationViolation = 8001, /// Proxy request to target API failed ProxyRequestFailed = 8002, /// Proxy request timed out ProxyTimeout = 8003, /// Request blocked by SSRF protection SsrfBlocked = 8004, /// Referenced template variable not found in resolution table TemplateVariableNotFound = 8005, /// Agent does not have permission to access the template variable TemplateVariableAccessDenied = 8006, /// Template variable name is malformed InvalidTemplateVariable = 8007, /// OAuth token requires re-authentication OAuthReauthRequired = 8008, // Consent errors (9xxx) /// Human consent is required before accessing the credential ConsentRequired = 9001, /// Consent was explicitly denied ConsentDenied = 9002, /// Consent record has expired ConsentExpired = 9003, /// Consent was previously granted but has been revoked ConsentRevoked = 9004, // Fingerprint errors (10xxx) /// Agent fingerprint does not match expected hash chain state FingerprintMismatch = 10001, /// Agent fingerprint state not found (agent not initialized) FingerprintStateNotFound = 10002, // Delegation errors (11xxx) /// Delegated credential token attempts scope amplification DctScopeAmplification = 11001, /// Delegation depth exceeds maximum allowed DctDepthExceeded = 11002, } ``` Source line: `19`. ## error::ErrorCode::as\_u32 [#errorerrorcodeas_u32] Returns the numeric code ```rust #[must_use] pub const fn as_u32(self) -> u32; ``` Source line: `154`. ## error::ErrorCode::is\_client\_error [#errorerrorcodeis_client_error] Returns true if this is a client error (retrying won't help) ```rust #[must_use] pub const fn is_client_error(self) -> bool; ``` Source line: `160`. ## error::ErrorCode::is\_server\_error [#errorerrorcodeis_server_error] Returns true if this is a server error (may be transient) ```rust #[must_use] pub const fn is_server_error(self) -> bool; ``` Source line: `167`. ## error::ErrorCode::is\_proxy\_error [#errorerrorcodeis_proxy_error] Returns true if this is a proxy-related error ```rust #[must_use] pub const fn is_proxy_error(self) -> bool; ``` Source line: `174`. ## error::ErrorCode::is\_consent\_error [#errorerrorcodeis_consent_error] Returns true if this is a consent-related error ```rust #[must_use] pub const fn is_consent_error(self) -> bool; ``` Source line: `181`. ## error::ErrorCode::is\_fingerprint\_error [#errorerrorcodeis_fingerprint_error] Returns true if this is a fingerprint-related error ```rust #[must_use] pub const fn is_fingerprint_error(self) -> bool; ``` Source line: `188`. ## error::ErrorCode::is\_permanent [#errorerrorcodeis_permanent] Returns true if the error indicates the request should not be retried ```rust #[must_use] pub const fn is_permanent(self) -> bool; ``` Source line: `195`. ## error::ArsenalError [#errorarsenalerror] Main error type for ARSENAL operations ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ArsenalError { } ``` Source line: `213`. ## error::ErrorContext [#errorerrorcontext] Additional error context (all fields are sanitized) ```rust #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct ErrorContext { /// The operation that failed #[serde(skip_serializing_if = "Option::is_none")] pub operation: Option, /// Resource identifier (sanitized - no full paths or keys) #[serde(skip_serializing_if = "Option::is_none")] pub resource: Option, /// Constraint that was violated #[serde(skip_serializing_if = "Option::is_none")] pub constraint: Option, /// Timestamp of the error #[serde(skip_serializing_if = "Option::is_none")] pub timestamp: Option> } ``` Source line: `228`. ## error::ArsenalError::new [#errorarsenalerrornew] Create a new error with the given code and message ```rust #[must_use] pub fn new(code: ErrorCode, message: impl Into) -> Self; ``` Source line: `246`. ## error::ArsenalError::with\_correlation\_id [#errorarsenalerrorwith_correlation_id] Add a correlation ID for audit trail ```rust #[must_use] pub fn with_correlation_id(mut self, id: Uuid) -> Self; ``` Source line: `257`. ## error::ArsenalError::with\_context [#errorarsenalerrorwith_context] Add context to the error ```rust #[must_use] pub fn with_context(mut self, context: ErrorContext) -> Self; ``` Source line: `264`. ## error::ArsenalError::with\_operation [#errorarsenalerrorwith_operation] Add operation context ```rust #[must_use] pub fn with_operation(mut self, operation: impl Into) -> Self; ``` Source line: `271`. ## error::ArsenalError::with\_resource [#errorarsenalerrorwith_resource] Add resource context (will be sanitized) ```rust #[must_use] pub fn with_resource(mut self, resource: impl Into) -> Self; ``` Source line: `279`. ## error::ArsenalError::code [#errorarsenalerrorcode] Get the error code ```rust #[must_use] pub const fn code(&self) -> ErrorCode; ``` Source line: `288`. ## error::ArsenalError::message [#errorarsenalerrormessage] Get the error message ```rust #[must_use] pub fn message(&self) -> &str; ``` Source line: `294`. ## error::ArsenalError::correlation\_id [#errorarsenalerrorcorrelation_id] Get the correlation ID if set ```rust #[must_use] pub const fn correlation_id(&self) -> Option; ``` Source line: `300`. ## error::ArsenalError::context [#errorarsenalerrorcontext] Get the error context if set ```rust #[must_use] pub fn context(&self) -> Option<&ErrorContext>; ``` Source line: `306`. ## error::ArsenalError::authentication\_failed [#errorarsenalerrorauthentication_failed] Authentication failed ```rust #[must_use] pub fn authentication_failed() -> Self; ``` Source line: `314`. ## error::ArsenalError::token\_expired [#errorarsenalerrortoken_expired] Token expired ```rust #[must_use] pub fn token_expired() -> Self; ``` Source line: `320`. ## error::ArsenalError::token\_signature\_invalid [#errorarsenalerrortoken_signature_invalid] Token signature invalid ```rust #[must_use] pub fn token_signature_invalid() -> Self; ``` Source line: `326`. ## error::ArsenalError::pop\_verification\_failed [#errorarsenalerrorpop_verification_failed] Proof-of-possession failed ```rust #[must_use] pub fn pop_verification_failed() -> Self; ``` Source line: `335`. ## error::ArsenalError::insufficient\_permissions [#errorarsenalerrorinsufficient_permissions] Insufficient permissions ```rust #[must_use] pub fn insufficient_permissions(required_scope: &str) -> Self; ``` Source line: `344`. ## error::ArsenalError::scope\_exceeded [#errorarsenalerrorscope_exceeded] Scope exceeded ```rust #[must_use] pub fn scope_exceeded() -> Self; ``` Source line: `356`. ## error::ArsenalError::policy\_denied [#errorarsenalerrorpolicy_denied] Policy denied ```rust #[must_use] pub fn policy_denied(policy_id: &str) -> Self; ``` Source line: `365`. ## error::ArsenalError::rate\_limit\_exceeded [#errorarsenalerrorrate_limit_exceeded] Rate limit exceeded ```rust #[must_use] pub fn rate_limit_exceeded(retry_after_secs: Option) -> Self; ``` Source line: `377`. ## error::ArsenalError::secret\_not\_found [#errorarsenalerrorsecret_not_found] Secret not found ```rust #[must_use] pub fn secret_not_found() -> Self; ``` Source line: `387`. ## error::ArsenalError::secret\_revoked [#errorarsenalerrorsecret_revoked] Secret revoked ```rust #[must_use] pub fn secret_revoked() -> Self; ``` Source line: `393`. ## error::ArsenalError::validation\_failed [#errorarsenalerrorvalidation_failed] Validation failed ```rust #[must_use] pub fn validation_failed(field: &str, reason: &str) -> Self; ``` Source line: `399`. ## error::ArsenalError::internal [#errorarsenalerrorinternal] Internal error (generic, no details leaked) ```rust #[must_use] pub fn internal() -> Self; ``` Source line: `412`. ## error::ArsenalError::token\_revoked [#errorarsenalerrortoken_revoked] Token revoked ```rust #[must_use] pub fn token_revoked() -> Self; ``` Source line: `421`. ## error::ArsenalError::revocation\_status\_unknown [#errorarsenalerrorrevocation_status_unknown] Revocation status could not be determined (fail-closed) ```rust #[must_use] pub fn revocation_status_unknown() -> Self; ``` Source line: `427`. ## error::ArsenalError::session\_expired [#errorarsenalerrorsession_expired] Session expired ```rust #[must_use] pub fn session_expired() -> Self; ``` Source line: `436`. ## error::ArsenalError::proxy\_destination\_violation [#errorarsenalerrorproxy_destination_violation] Proxy destination binding violation ```rust #[must_use] pub fn proxy_destination_violation(domain: &str) -> Self; ``` Source line: `445`. ## error::ArsenalError::proxy\_request\_failed [#errorarsenalerrorproxy_request_failed] Proxy request to target failed ```rust #[must_use] pub fn proxy_request_failed(status: u16) -> Self; ``` Source line: `457`. ## error::ArsenalError::ssrf\_blocked [#errorarsenalerrorssrf_blocked] SSRF protection blocked the request ```rust #[must_use] pub fn ssrf_blocked() -> Self; ``` Source line: `466`. ## error::ArsenalError::template\_variable\_not\_found [#errorarsenalerrortemplate_variable_not_found] Template variable not found ```rust #[must_use] pub fn template_variable_not_found(variable: &str) -> Self; ``` Source line: `475`. ## error::ArsenalError::template\_variable\_access\_denied [#errorarsenalerrortemplate_variable_access_denied] Template variable access denied ```rust #[must_use] pub fn template_variable_access_denied(variable: &str) -> Self; ``` Source line: `487`. ## error::ArsenalError::invalid\_template\_variable [#errorarsenalerrorinvalid_template_variable] Invalid template variable name ```rust #[must_use] pub fn invalid_template_variable(name: &str) -> Self; ``` Source line: `499`. ## error::ArsenalError::oauth\_reauth\_required [#errorarsenalerroroauth_reauth_required] OAuth re-authentication required ```rust #[must_use] pub fn oauth_reauth_required() -> Self; ``` Source line: `508`. ## error::ArsenalError::consent\_required [#errorarsenalerrorconsent_required] Consent required ```rust #[must_use] pub fn consent_required() -> Self; ``` Source line: `517`. ## error::ArsenalError::consent\_denied [#errorarsenalerrorconsent_denied] Consent denied ```rust #[must_use] pub fn consent_denied() -> Self; ``` Source line: `526`. ## error::ArsenalError::consent\_expired [#errorarsenalerrorconsent_expired] Consent expired ```rust #[must_use] pub fn consent_expired() -> Self; ``` Source line: `535`. ## error::ArsenalError::consent\_revoked [#errorarsenalerrorconsent_revoked] Consent revoked ```rust #[must_use] pub fn consent_revoked() -> Self; ``` Source line: `541`. ## error::ArsenalError::fingerprint\_mismatch [#errorarsenalerrorfingerprint_mismatch] Fingerprint mismatch — potential key theft ```rust #[must_use] pub fn fingerprint_mismatch() -> Self; ``` Source line: `550`. ## error::ArsenalError::fingerprint\_state\_not\_found [#errorarsenalerrorfingerprint_state_not_found] Fingerprint state not found ```rust #[must_use] pub fn fingerprint_state_not_found() -> Self; ``` Source line: `559`. ## error::ArsenalError::dct\_scope\_amplification [#errorarsenalerrordct_scope_amplification] DCT scope amplification attempt ```rust #[must_use] pub fn dct_scope_amplification(variable: &str) -> Self; ``` Source line: `568`. ## error::ArsenalError::dct\_depth\_exceeded [#errorarsenalerrordct_depth_exceeded] DCT depth exceeded ```rust #[must_use] pub fn dct_depth_exceeded() -> Self; ``` Source line: `580`. ## error::ArsenalError::crypto\_operation\_failed [#errorarsenalerrorcrypto_operation_failed] Crypto operation failed (generic message to avoid oracle attacks) ```rust #[must_use] pub fn crypto_operation_failed() -> Self; ``` Source line: `589`. ## error::ArsenalError::storage\_error [#errorarsenalerrorstorage_error] Storage error (generic message) ```rust #[must_use] pub fn storage_error() -> Self; ``` Source line: `598`. ## error::ArsenalError::configuration\_error [#errorarsenalerrorconfiguration_error] Configuration error ```rust #[must_use] pub fn configuration_error(component: &str) -> Self; ``` Source line: `604`. ## error::ArsenalError::invalid\_state\_transition [#errorarsenalerrorinvalid_state_transition] Invalid state transition ```rust #[must_use] pub fn invalid_state_transition(from: impl Into, to: impl Into) -> Self; ``` Source line: `616`. # arsenal-core · fingerprint URL: https://docs.openagent.id/reference/rust/arsenal-core/fingerprint Markdown: https://docs.openagent.id/reference/rust/arsenal-core/fingerprint.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/fingerprint.rs`. SHA-256: `a300fa13494b16c90c849360b645f68426e398d2a2ad8dc28c3a03ef15000c60`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## fingerprint::FingerprintState [#fingerprintfingerprintstate] Stateful fingerprint for an agent's hash chain. The fingerprint tracks a BLAKE3 hash chain that is advanced with each proxy request. The broker verifies the agent's presented fingerprint against the expected chain state. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FingerprintState { /// Current hash chain state (BLAKE3 output) pub current_state: [u8; 32], /// Monotonically increasing sequence number pub sequence_number: u64, /// When the chain was last advanced pub last_advanced_at: chrono::DateTime, /// Window size for out-of-order tolerance (Strategy A) pub window_size: u8 } ``` Source line: `29`. ## fingerprint::FingerprintState::init [#fingerprintfingerprintstateinit] Initialize a new fingerprint chain. The initial state is computed as: `BLAKE3("arsenal.fingerprint.init" || agent_did || timestamp || nonce)` ```rust #[must_use] pub fn init( agent_did: &str, timestamp: &chrono::DateTime, nonce: &[u8; 32], ) -> Self; ``` Source line: `46`. ## fingerprint::FingerprintState::advance [#fingerprintfingerprintstateadvance] Advance the hash chain by one step. New state is computed as: `BLAKE3("arsenal.fingerprint.advance" || current_state || request_id || timestamp)` ```rust pub fn advance(&mut self, request_id: &Uuid, timestamp: &chrono::DateTime); ``` Source line: `70`. ## fingerprint::FingerprintState::compute\_fingerprint [#fingerprintfingerprintstatecompute_fingerprint] Compute the fingerprint to send as a header. The fingerprint is `BLAKE3(current_state)` — the raw state is never transmitted, only its hash. This prevents state reconstruction if the fingerprint header is intercepted. ```rust #[must_use] pub fn compute_fingerprint(&self) -> [u8; 32]; ``` Source line: `82`. ## fingerprint::FingerprintState::verify\_fingerprint [#fingerprintfingerprintstateverify_fingerprint] Verify a received fingerprint against the expected chain state. Uses Strategy A (sliding window): tries the current state and up to `window_size` future states to accommodate out-of-order delivery. ```rust #[must_use] pub fn verify_fingerprint( &self, received: &[u8; 32], request_id: &Uuid, timestamp: &chrono::DateTime, ) -> FingerprintVerification; ``` Source line: `91`. ## fingerprint::FingerprintState::set\_window\_size [#fingerprintfingerprintstateset_window_size] Set the window size (clamped to valid range). ```rust pub fn set_window_size(&mut self, size: u8); ``` Source line: `125`. ## fingerprint::FingerprintState::sequence\_number [#fingerprintfingerprintstatesequence_number] Get the current sequence number. ```rust #[must_use] pub const fn sequence_number(&self) -> u64; ``` Source line: `131`. ## fingerprint::FingerprintState::window\_size [#fingerprintfingerprintstatewindow_size] Get the window size. ```rust #[must_use] pub const fn window_size(&self) -> u8; ``` Source line: `137`. ## fingerprint::FingerprintVerification [#fingerprintfingerprintverification] Result of fingerprint verification. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum FingerprintVerification { /// Fingerprint matches the expected current state. Match { /// Sequence number to advance to advance_to: u64, }, /// Fingerprint matches a state within the sliding window. WindowMatch { /// Sequence number to advance to advance_to: u64, /// Number of states skipped skipped: u64, }, /// Fingerprint does not match any expected state — potential key theft. Mismatch, } ``` Source line: `144`. ## fingerprint::FingerprintVerification::is\_valid [#fingerprintfingerprintverificationis_valid] Check if verification succeeded (`Match` or `WindowMatch`). ```rust #[must_use] pub const fn is_valid(&self) -> bool; ``` Source line: `164`. ## fingerprint::FingerprintVerification::is\_mismatch [#fingerprintfingerprintverificationis_mismatch] Check if verification failed. ```rust #[must_use] pub const fn is_mismatch(&self) -> bool; ``` Source line: `170`. # arsenal-core · identity URL: https://docs.openagent.id/reference/rust/arsenal-core/identity Markdown: https://docs.openagent.id/reference/rust/arsenal-core/identity.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/identity.rs`. SHA-256: `ca80b7b23505b8d44b0fac716fa7e24e1f8ae1e1cdba46ec112dccb14014b8ea`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## identity::TenantId [#identitytenantid] Tenant identifier - represents an organization or customer ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct TenantId(String); ``` Source line: `21`. ## identity::TenantId::new [#identitytenantidnew] Create a new tenant ID with validation # Errors [#errors] Returns an error if the ID is empty, too long, or contains invalid characters ```rust pub fn new(id: impl Into) -> ArsenalResult; ``` Source line: `28`. ## identity::TenantId::generate [#identitytenantidgenerate] Create a new random tenant ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `36`. ## identity::TenantId::as\_str [#identitytenantidas_str] Get the inner string value ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `42`. ## identity::PrincipalId [#identityprincipalid] Principal identifier - represents a user, service account, or system principal ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct PrincipalId(String); ``` Source line: `101`. ## identity::PrincipalId::new [#identityprincipalidnew] Create a new principal ID with validation # Errors [#errors-1] Returns an error if the ID is empty, too long, or contains invalid characters ```rust pub fn new(id: impl Into) -> ArsenalResult; ``` Source line: `108`. ## identity::PrincipalId::generate [#identityprincipalidgenerate] Create a new random principal ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `116`. ## identity::PrincipalId::system [#identityprincipalidsystem] Create a system principal ```rust #[must_use] pub fn system() -> Self; ``` Source line: `122`. ## identity::PrincipalId::is\_system [#identityprincipalidis_system] Check if this is the system principal ```rust #[must_use] pub fn is_system(&self) -> bool; ``` Source line: `128`. ## identity::PrincipalId::as\_str [#identityprincipalidas_str] Get the inner string value ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `134`. ## identity::AgentIdentity [#identityagentidentity] Agent identity - the cryptographic identity of an agent This contains the agent's public key fingerprint and associated metadata. The actual private key is never stored here - only the public identity. # Two identifiers, two purposes [#two-identifiers-two-purposes] \[`AgentIdentity::did`] is the agent's identity: an OAS DID, assigned by OAS genesis under a human or organizational root, resolvable by any party, and the value that appears as `sub` in a capability token. Arsenal does not mint DIDs; it requires one as input, because a capability granted to an identity nobody can resolve is not auditable. \[`AgentIdentity::id`] is a local surrogate key. It orders records and keys storage rows. It is deliberately never used as the subject of a token. ```rust #[derive(Clone, Serialize, Deserialize)] pub struct AgentIdentity { } ``` Source line: `204`. ## identity::AgentIdentity::new [#identityagentidentitynew] Create a new agent identity `did` must be an OAS DID of kind `agent`. Arsenal issues capability tokens to agents, so a DID naming a human root, an organization, or a tool is rejected here rather than producing a token whose subject cannot exercise it. # Errors [#errors-2] Returns an error if the name length is invalid, or if `did` is not of entity kind `agent`. ```rust pub fn new( did: OasDid, tenant_id: TenantId, name: impl Into, public_key_fingerprint: KeyFingerprint, ) -> ArsenalResult; ``` Source line: `237`. ## identity::AgentIdentity::did [#identityagentidentitydid] Get the agent's OAS DID This is the identity to use as a token subject or in an audit record. ```rust #[must_use] pub fn did(&self) -> &OasDid; ``` Source line: `272`. ## identity::AgentIdentity::id [#identityagentidentityid] Get the local surrogate key For storage and ordering only. Use \[`AgentIdentity::did`] when naming this agent to anything outside Arsenal. ```rust #[must_use] pub fn id(&self) -> &AgentId; ``` Source line: `281`. ## identity::AgentIdentity::public\_key\_fingerprint [#identityagentidentitypublic_key_fingerprint] Get the public key fingerprint ```rust #[must_use] pub fn public_key_fingerprint(&self) -> &KeyFingerprint; ``` Source line: `287`. ## identity::AgentIdentity::tenant\_id [#identityagentidentitytenant_id] Get the tenant ID ```rust #[must_use] pub fn tenant_id(&self) -> &TenantId; ``` Source line: `293`. ## identity::AgentIdentity::name [#identityagentidentityname] Get the agent name ```rust #[must_use] pub fn name(&self) -> &str; ``` Source line: `299`. ## identity::AgentIdentity::is\_valid [#identityagentidentityis_valid] Check if the agent is currently valid (active and not expired) ```rust #[must_use] pub fn is_valid(&self) -> bool; ``` Source line: `305`. ## identity::AgentIdentity::is\_active [#identityagentidentityis_active] Check if the agent is active ```rust #[must_use] pub fn is_active(&self) -> bool; ``` Source line: `319`. ## identity::AgentIdentity::deactivate [#identityagentidentitydeactivate] Deactivate this agent ```rust pub fn deactivate(&mut self); ``` Source line: `324`. ## identity::AgentIdentity::set\_expires\_at [#identityagentidentityset_expires_at] Set expiration time ```rust pub fn set_expires_at(&mut self, expires_at: chrono::DateTime); ``` Source line: `329`. ## identity::AgentIdentity::add\_tag [#identityagentidentityadd_tag] Add a tag ```rust pub fn add_tag(&mut self, tag: impl Into); ``` Source line: `334`. ## identity::AgentIdentity::tags [#identityagentidentitytags] Get tags ```rust #[must_use] pub fn tags(&self) -> &[String]; ``` Source line: `343`. ## identity::AgentId [#identityagentid] Agent identifier ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct AgentId(Uuid); ``` Source line: `362`. ## identity::AgentId::from\_uuid [#identityagentidfrom_uuid] Create a new agent ID from a UUID ```rust #[must_use] pub const fn from_uuid(uuid: Uuid) -> Self; ``` Source line: `367`. ## identity::AgentId::generate [#identityagentidgenerate] Generate a new random agent ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `373`. ## identity::AgentId::as\_uuid [#identityagentidas_uuid] Get the inner UUID ```rust #[must_use] pub const fn as_uuid(&self) -> &Uuid; ``` Source line: `379`. ## identity::KeyFingerprint [#identitykeyfingerprint] Public key fingerprint - BLAKE3 hash of the public key bytes ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Zeroize)] #[zeroize(drop)] pub struct KeyFingerprint([u8; 32]); ``` Source line: `409`. ## identity::KeyFingerprint::from\_bytes [#identitykeyfingerprintfrom_bytes] Create a fingerprint from raw bytes ```rust #[must_use] pub const fn from_bytes(bytes: [u8; 32]) -> Self; ``` Source line: `414`. ## identity::KeyFingerprint::from\_public\_key [#identitykeyfingerprintfrom_public_key] Create a fingerprint from a public key ```rust #[must_use] pub fn from_public_key(public_key: &[u8]) -> Self; ``` Source line: `420`. ## identity::KeyFingerprint::as\_bytes [#identitykeyfingerprintas_bytes] Get the raw bytes ```rust #[must_use] pub const fn as_bytes(&self) -> &[u8; 32]; ``` Source line: `427`. ## identity::KeyFingerprint::to\_hex [#identitykeyfingerprintto_hex] Encode as hex string ```rust #[must_use] pub fn to_hex(&self) -> String; ``` Source line: `433`. ## identity::KeyFingerprint::from\_hex [#identitykeyfingerprintfrom_hex] Parse from hex string # Errors [#errors-3] Returns an error if the hex string is invalid ```rust pub fn from_hex(hex_str: &str) -> ArsenalResult; ``` Source line: `441`. ## identity::KeyFingerprint::ct\_eq [#identitykeyfingerprintct_eq] Constant-time comparison ```rust #[must_use] pub fn ct_eq(&self, other: &Self) -> bool; ``` Source line: `457`. ## identity::DeviceId [#identitydeviceid] Device identifier for device binding ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct DeviceId(String); ``` Source line: `482`. ## identity::DeviceId::new [#identitydeviceidnew] Create a new device ID # Errors [#errors-4] Returns an error if validation fails ```rust pub fn new(id: impl Into) -> ArsenalResult; ``` Source line: `489`. ## identity::DeviceId::as\_str [#identitydeviceidas_str] Get the inner string ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `511`. # arsenal-core modules URL: https://docs.openagent.id/reference/rust/arsenal-core Markdown: https://docs.openagent.id/reference/rust/arsenal-core.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/arsenal-crates-arsenal-core). [Focused integration guide](/arsenal/overview). ## Modules [#modules] * [crate](/reference/rust/arsenal-core/crate) — 39 declarations * [act](/reference/rust/arsenal-core/act) — 8 declarations * [audit](/reference/rust/arsenal-core/audit) — 39 declarations * [consent](/reference/rust/arsenal-core/consent) — 18 declarations * [constraints](/reference/rust/arsenal-core/constraints) — 22 declarations * [delegation](/reference/rust/arsenal-core/delegation) — 22 declarations * [error](/reference/rust/arsenal-core/error) — 54 declarations * [fingerprint](/reference/rust/arsenal-core/fingerprint) — 11 declarations * [identity](/reference/rust/arsenal-core/identity) — 37 declarations * [limits](/reference/rust/arsenal-core/limits) — 29 declarations * [policy](/reference/rust/arsenal-core/policy) — 29 declarations * [proxy](/reference/rust/arsenal-core/proxy) — 32 declarations * [scope](/reference/rust/arsenal-core/scope) — 29 declarations * [secret](/reference/rust/arsenal-core/secret) — 37 declarations * [session](/reference/rust/arsenal-core/session) — 35 declarations * [token](/reference/rust/arsenal-core/token) — 52 declarations # arsenal-core · limits URL: https://docs.openagent.id/reference/rust/arsenal-core/limits Markdown: https://docs.openagent.id/reference/rust/arsenal-core/limits.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/limits.rs`. SHA-256: `e6e5774acca5a12d8950c25c74538fd483f78dc775f91008537bf9cd3f8561d9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## limits::RateLimits [#limitsratelimits] Rate limiting configuration Equality is derived so that a round trip through the canonical ACT encoding can be checked for loss: these limits cross the wire as an issuer-defined extension claim, and a silently dropped ceiling is the failure mode that matters. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RateLimits { /// Maximum requests per second #[serde(skip_serializing_if = "Option::is_none")] pub requests_per_second: Option, /// Maximum requests per minute #[serde(skip_serializing_if = "Option::is_none")] pub requests_per_minute: Option, /// Maximum requests per hour #[serde(skip_serializing_if = "Option::is_none")] pub requests_per_hour: Option, /// Maximum concurrent requests #[serde(skip_serializing_if = "Option::is_none")] pub max_concurrent: Option, /// Maximum request body size in bytes #[serde(skip_serializing_if = "Option::is_none")] pub max_request_size: Option, /// Maximum response size in bytes #[serde(skip_serializing_if = "Option::is_none")] pub max_response_size: Option } ``` Source line: `19`. ## limits::RateLimits::unlimited [#limitsratelimitsunlimited] Create unlimited rate limits (use with caution) ```rust #[must_use] pub fn unlimited() -> Self; ``` Source line: `56`. ## limits::RateLimits::strict [#limitsratelimitsstrict] Create strict rate limits ```rust #[must_use] pub fn strict() -> Self; ``` Source line: `69`. ## limits::RateLimits::merge [#limitsratelimitsmerge] Merge with another rate limit configuration (take the more restrictive) ```rust #[must_use] pub fn merge(&self, other: &RateLimits) -> RateLimits; ``` Source line: `82`. ## limits::UsageBudget [#limitsusagebudget] Usage budget for a capability token ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UsageBudget { /// Maximum total requests allowed #[serde(skip_serializing_if = "Option::is_none")] pub max_requests: Option, /// Maximum total bytes transferred #[serde(skip_serializing_if = "Option::is_none")] pub max_bytes: Option, /// Maximum total cost units (for metered APIs) #[serde(skip_serializing_if = "Option::is_none")] pub max_cost_units: Option, /// Maximum secret unwrap operations #[serde(skip_serializing_if = "Option::is_none")] pub max_secret_unwraps: Option, /// Maximum delegation depth #[serde(skip_serializing_if = "Option::is_none")] pub max_delegation_depth: Option } ``` Source line: `102`. ## limits::UsageBudget::unlimited [#limitsusagebudgetunlimited] Create unlimited budget (use with caution) ```rust #[must_use] pub fn unlimited() -> Self; ``` Source line: `135`. ## limits::UsageBudget::minimal [#limitsusagebudgetminimal] Create a minimal budget for testing ```rust #[must_use] pub fn minimal() -> Self; ``` Source line: `147`. ## limits::UsageBudget::merge [#limitsusagebudgetmerge] Merge with another budget (take the more restrictive) ```rust #[must_use] pub fn merge(&self, other: &UsageBudget) -> UsageBudget; ``` Source line: `159`. ## limits::UsageTracker [#limitsusagetracker] Runtime usage tracker for enforcing limits ```rust #[derive(Debug)] pub struct UsageTracker { } ``` Source line: `175`. ## limits::UsageTracker::new [#limitsusagetrackernew] Create a new usage tracker with the given budget ```rust #[must_use] pub fn new(budget: UsageBudget) -> Self; ``` Source line: `193`. ## limits::UsageTracker::record\_request [#limitsusagetrackerrecord_request] Record a request and check if within budget # Errors [#errors] Returns an error if the budget would be exceeded ```rust pub fn record_request(&self) -> ArsenalResult<()>; ``` Source line: `208`. ## limits::UsageTracker::record\_bytes [#limitsusagetrackerrecord_bytes] Record bytes transferred and check if within budget # Errors [#errors-1] Returns an error if the budget would be exceeded ```rust pub fn record_bytes(&self, bytes: u64) -> ArsenalResult<()>; ``` Source line: `226`. ## limits::UsageTracker::record\_cost [#limitsusagetrackerrecord_cost] Record cost units and check if within budget # Errors [#errors-2] Returns an error if the budget would be exceeded ```rust pub fn record_cost(&self, units: u64) -> ArsenalResult<()>; ``` Source line: `244`. ## limits::UsageTracker::record\_secret\_unwrap [#limitsusagetrackerrecord_secret_unwrap] Record a secret unwrap and check if within budget # Errors [#errors-3] Returns an error if the budget would be exceeded ```rust pub fn record_secret_unwrap(&self) -> ArsenalResult<()>; ``` Source line: `262`. ## limits::UsageTracker::get\_stats [#limitsusagetrackerget_stats] Get current usage statistics ```rust #[must_use] pub fn get_stats(&self) -> UsageStats; ``` Source line: `278`. ## limits::UsageTracker::remaining [#limitsusagetrackerremaining] Get remaining budget ```rust #[must_use] pub fn remaining(&self) -> RemainingBudget; ``` Source line: `290`. ## limits::UsageStats [#limitsusagestats] Current usage statistics ```rust #[derive(Debug, Clone)] pub struct UsageStats { /// Total requests made pub request_count: u64, /// Total bytes transferred pub bytes_transferred: u64, /// Total cost units consumed pub cost_units: u64, /// Total secret unwraps pub secret_unwraps: u64, /// Time elapsed since tracking started pub elapsed: Duration } ``` Source line: `315`. ## limits::RemainingBudget [#limitsremainingbudget] Remaining budget ```rust #[derive(Debug, Clone)] pub struct RemainingBudget { /// Remaining requests (None if unlimited) pub requests: Option, /// Remaining bytes (None if unlimited) pub bytes: Option, /// Remaining cost units (None if unlimited) pub cost_units: Option, /// Remaining secret unwraps (None if unlimited) pub secret_unwraps: Option } ``` Source line: `330`. ## limits::TokenBucketLimiter [#limitstokenbucketlimiter] Token bucket rate limiter for per-second/minute/hour limits ```rust #[derive(Debug)] pub struct TokenBucketLimiter { } ``` Source line: `343`. ## limits::TokenBucketLimiter::new [#limitstokenbucketlimiternew] Create a new token bucket limiter ```rust #[must_use] pub fn new(max_tokens: u64, refill_amount: u64, refill_interval: Duration) -> Self; ``` Source line: `361`. ## limits::TokenBucketLimiter::per\_second [#limitstokenbucketlimiterper_second] Create a limiter for requests per second ```rust #[must_use] pub fn per_second(rate: u32) -> Self; ``` Source line: `374`. ## limits::TokenBucketLimiter::per\_minute [#limitstokenbucketlimiterper_minute] Create a limiter for requests per minute ```rust #[must_use] pub fn per_minute(rate: u32) -> Self; ``` Source line: `380`. ## limits::TokenBucketLimiter::per\_hour [#limitstokenbucketlimiterper_hour] Create a limiter for requests per hour ```rust #[must_use] pub fn per_hour(rate: u32) -> Self; ``` Source line: `386`. ## limits::TokenBucketLimiter::try\_acquire [#limitstokenbucketlimitertry_acquire] Try to acquire a token # Errors [#errors-4] Returns an error if rate limited ```rust pub fn try_acquire(&self) -> ArsenalResult<()>; ``` Source line: `394`. ## limits::TokenBucketLimiter::available [#limitstokenbucketlimiteravailable] Get current available tokens ```rust #[must_use] pub fn available(&self) -> u64; ``` Source line: `450`. ## limits::CompositeRateLimiter [#limitscompositeratelimiter] Composite rate limiter combining multiple time windows ```rust #[derive(Debug)] pub struct CompositeRateLimiter { } ``` Source line: `457`. ## limits::CompositeRateLimiter::from\_limits [#limitscompositeratelimiterfrom_limits] Create from rate limits configuration ```rust #[must_use] pub fn from_limits(limits: &RateLimits) -> Self; ``` Source line: `473`. ## limits::CompositeRateLimiter::try\_acquire [#limitscompositeratelimitertry_acquire] Try to acquire permission for a request # Errors [#errors-5] Returns an error if any rate limit is exceeded ```rust pub fn try_acquire(&self) -> ArsenalResult; ``` Source line: `491`. ## limits::RateLimitGuard [#limitsratelimitguard] Guard that releases concurrent slot on drop ```rust #[derive(Debug)] pub struct RateLimitGuard { } ``` Source line: `537`. # arsenal-core · policy URL: https://docs.openagent.id/reference/rust/arsenal-core/policy Markdown: https://docs.openagent.id/reference/rust/arsenal-core/policy.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/policy.rs`. SHA-256: `83a040bdc4d7f6631dfce58a3d61ba40b22723f7c77fa42497d76a247537f813`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## policy::PolicyId [#policypolicyid] Policy identifier ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct PolicyId(String); ``` Source line: `29`. ## policy::PolicyId::new [#policypolicyidnew] Create a new policy ID # Errors [#errors] Returns an error if the ID is invalid ```rust pub fn new(id: impl Into) -> ArsenalResult; ``` Source line: `36`. ## policy::PolicyId::generate [#policypolicyidgenerate] Generate a new random policy ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `58`. ## policy::PolicyId::as\_str [#policypolicyidas_str] Get the inner string ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `64`. ## policy::PolicyDocument [#policypolicydocument] Policy document - the complete policy definition ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PolicyDocument { /// Policy ID pub id: PolicyId, /// Policy version (for updates) pub version: u32, /// Tenant this policy belongs to pub tenant_id: TenantId, /// Human-readable name pub name: String, /// Description #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, /// Policy rules pub rules: Vec, /// Default effect when no rules match pub default_effect: PolicyEffect, /// Whether this policy is active pub is_active: bool, /// Priority (higher = evaluated first) pub priority: i32, /// When the policy was created pub created_at: chrono::DateTime, /// When the policy was last modified pub updated_at: chrono::DateTime, /// Policy signature (if signed) #[serde(skip_serializing_if = "Option::is_none")] pub signature: Option, /// Custom labels #[serde(default)] pub labels: HashMap } ``` Source line: `83`. ## policy::PolicyDocument::new [#policypolicydocumentnew] Create a new policy document # Errors [#errors-1] Returns an error if validation fails ```rust pub fn new(tenant_id: TenantId, name: impl Into) -> ArsenalResult; ``` Source line: `120`. ## policy::PolicyDocument::add\_rule [#policypolicydocumentadd_rule] Add a rule to the policy # Errors [#errors-2] Returns an error if too many rules ```rust pub fn add_rule(&mut self, rule: PolicyRule) -> ArsenalResult<()>; ``` Source line: `148`. ## policy::PolicyDocument::evaluate [#policypolicydocumentevaluate] Evaluate the policy for a given request ```rust #[must_use] pub fn evaluate(&self, request: &PolicyRequest) -> PolicyDecision; ``` Source line: `159`. ## policy::PolicyDocument::to\_cbor [#policypolicydocumentto_cbor] Serialize to CBOR bytes # Errors [#errors-3] Returns an error if serialization fails ```rust pub fn to_cbor(&self) -> ArsenalResult>; ``` Source line: `191`. ## policy::PolicyDocument::from\_cbor [#policypolicydocumentfrom_cbor] Deserialize from CBOR bytes # Errors [#errors-4] Returns an error if deserialization fails ```rust pub fn from_cbor(bytes: &[u8]) -> ArsenalResult; ``` Source line: `206`. ## policy::PolicyRule [#policypolicyrule] A single policy rule ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PolicyRule { /// Rule ID (unique within policy) pub id: String, /// Rule description #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, /// Effect when rule matches pub effect: PolicyEffect, /// Conditions that must be met pub conditions: Vec, /// Scopes this rule applies to #[serde(skip_serializing_if = "Option::is_none")] pub scopes: Option, /// Constraints to apply #[serde(skip_serializing_if = "Option::is_none")] pub constraints: Option, /// Rate limits to apply #[serde(skip_serializing_if = "Option::is_none")] pub rate_limits: Option, /// Usage budget to apply #[serde(skip_serializing_if = "Option::is_none")] pub budget: Option } ``` Source line: `218`. ## policy::PolicyRule::new [#policypolicyrulenew] Create a new rule ```rust #[must_use] pub fn new(id: impl Into, effect: PolicyEffect) -> Self; ``` Source line: `245`. ## policy::PolicyRule::with\_condition [#policypolicyrulewith_condition] Add a condition ```rust #[must_use] pub fn with_condition(mut self, condition: PolicyCondition) -> Self; ``` Source line: `260`. ## policy::PolicyRule::with\_scopes [#policypolicyrulewith_scopes] Set scopes ```rust #[must_use] pub fn with_scopes(mut self, scopes: ScopeSet) -> Self; ``` Source line: `267`. ## policy::PolicyRule::matches [#policypolicyrulematches] Check if this rule matches the request ```rust #[must_use] pub fn matches(&self, request: &PolicyRequest) -> bool; ``` Source line: `274`. ## policy::PolicyCondition [#policypolicycondition] Policy condition for rule evaluation ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum PolicyCondition { /// Match on agent ID AgentId { /// Operator for comparison operator: ConditionOperator, /// Value to compare against value: String, }, /// Match on tenant ID TenantId { /// Operator for comparison operator: ConditionOperator, /// Value to compare against value: String, }, /// Match on requested scope Scope { /// Operator for comparison operator: ConditionOperator, /// Value to compare against value: String, }, /// Match on environment Environment { /// Operator for comparison operator: ConditionOperator, /// Value to compare against value: String, }, /// Match on time of day TimeOfDay { /// Allowed hours (0-23) allowed_hours: Vec, }, /// Match on day of week DayOfWeek { /// Allowed days (0=Sunday, 6=Saturday) allowed_days: Vec, }, /// Match on IP address IpAddress { /// Allowed CIDRs allowed_cidrs: Vec, }, /// Match on custom attribute Attribute { /// Attribute key key: String, /// Operator for comparison operator: ConditionOperator, /// Value to compare against value: String, }, /// Boolean AND of conditions And { /// Conditions to AND together conditions: Vec, }, /// Boolean OR of conditions Or { /// Conditions to OR together conditions: Vec, }, /// Boolean NOT of condition Not { /// Condition to negate condition: Box, }, } ``` Source line: `283`. ## policy::PolicyCondition::evaluate [#policypolicyconditionevaluate] Evaluate the condition against a request ```rust #[must_use] pub fn evaluate(&self, request: &PolicyRequest) -> bool; ``` Source line: `356`. ## policy::ConditionOperator [#policyconditionoperator] Comparison operator for conditions ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ConditionOperator { /// Exact equality Equals, /// Not equal NotEquals, /// String contains Contains, /// String starts with StartsWith, /// String ends with EndsWith, /// Regex match Matches, /// In list In, /// Not in list NotIn, } ``` Source line: `419`. ## policy::ConditionOperator::compare [#policyconditionoperatorcompare] two strings using this operator ```rust #[must_use] pub fn compare(&self, actual: &str, expected: &str) -> bool; ``` Source line: `441`. ## policy::PolicyEffect [#policypolicyeffect] Policy effect (allow or deny) ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PolicyEffect { /// Allow the action Allow, /// Deny the action Deny, } ``` Source line: `482`. ## policy::PolicyRequest [#policypolicyrequest] Request context for policy evaluation ```rust #[derive(Debug, Clone)] pub struct PolicyRequest { /// Agent ID making the request pub agent_id: String, /// Tenant ID pub tenant_id: String, /// Requested scope pub requested_scope: String, /// Request timestamp pub timestamp: chrono::DateTime, /// Environment (e.g., "production", "staging") pub environment: Option, /// Client IP address pub client_ip: Option, /// Custom attributes pub attributes: HashMap } ``` Source line: `491`. ## policy::PolicyRequest::new [#policypolicyrequestnew] Create a new policy request ```rust #[must_use] pub fn new(agent_id: String, tenant_id: String, requested_scope: String) -> Self; ``` Source line: `511`. ## policy::PolicyRequest::with\_environment [#policypolicyrequestwith_environment] Set environment ```rust #[must_use] pub fn with_environment(mut self, env: impl Into) -> Self; ``` Source line: `525`. ## policy::PolicyRequest::with\_client\_ip [#policypolicyrequestwith_client_ip] Set client IP ```rust #[must_use] pub fn with_client_ip(mut self, ip: impl Into) -> Self; ``` Source line: `532`. ## policy::PolicyRequest::with\_attribute [#policypolicyrequestwith_attribute] Add an attribute ```rust #[must_use] pub fn with_attribute(mut self, key: impl Into, value: impl Into) -> Self; ``` Source line: `539`. ## policy::PolicyDecision [#policypolicydecision] Result of policy evaluation ```rust #[derive(Debug, Clone)] pub struct PolicyDecision { /// The effect (allow/deny) pub effect: PolicyEffect, /// ID of the rule that matched (if any) pub matched_rule: Option, /// Reason for the decision pub reason: Option } ``` Source line: `547`. ## policy::PolicyDecision::is\_allowed [#policypolicydecisionis_allowed] Check if the decision allows the action ```rust #[must_use] pub fn is_allowed(&self) -> bool; ``` Source line: `559`. ## policy::PolicyDecision::is\_denied [#policypolicydecisionis_denied] Check if the decision denies the action ```rust #[must_use] pub fn is_denied(&self) -> bool; ``` Source line: `565`. ## policy::PolicySignature [#policypolicysignature] Policy signature for tamper-resistance ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PolicySignature { /// Signature bytes pub bytes: Vec, /// Algorithm used pub algorithm: String, /// Key ID used for signing pub key_id: String, /// When the signature was created pub signed_at: chrono::DateTime } ``` Source line: `572`. # arsenal-core · proxy URL: https://docs.openagent.id/reference/rust/arsenal-core/proxy Markdown: https://docs.openagent.id/reference/rust/arsenal-core/proxy.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/proxy.rs`. SHA-256: `90e751496306a0bbe03e31e36b1f8df51ed69fa0c85d22a103c6f590e0e15319`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proxy::DestinationBinding [#proxydestinationbinding] Destination binding restricts which endpoints a credential can reach. When a secret has a destination binding, proxy requests using that secret are validated against the binding before credential injection. This prevents credential misuse even if an agent's capability token is compromised. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DestinationBinding { /// Allowed target domains (e.g., `["api.stripe.com"]`). /// At least one domain must be specified. pub allowed_domains: Vec, /// Optional allowed path patterns. Supports `*` (single segment) and `**` (multi-segment). #[serde(default, skip_serializing_if = "Option::is_none")] pub allowed_paths: Option>, /// Optional allowed HTTP methods (e.g., `["GET", "POST"]`). /// If `None`, all methods are allowed. #[serde(default, skip_serializing_if = "Option::is_none")] pub allowed_methods: Option>, /// Optional allowed ports. Defaults to `[443]` if not specified. #[serde(default, skip_serializing_if = "Option::is_none")] pub allowed_ports: Option>, /// Whether TLS is required. Defaults to `true`. #[serde(default = "default_true")] pub require_tls: bool, /// Whether subdomains of allowed domains are also allowed. Defaults to `false`. #[serde(default)] pub allow_subdomains: bool } ``` Source line: `73`. ## proxy::DestinationBinding::new [#proxydestinationbindingnew] Create a new destination binding for the given domains. # Errors [#errors] Returns an error if no domains are provided or validation fails. ```rust pub fn new(allowed_domains: Vec) -> ArsenalResult; ``` Source line: `106`. ## proxy::DestinationBinding::validate [#proxydestinationbindingvalidate] Validate the destination binding configuration. # Errors [#errors-1] Returns an error if the configuration is invalid. ```rust pub fn validate(&self) -> ArsenalResult<()>; ``` Source line: `124`. ## proxy::DestinationBinding::is\_domain\_allowed [#proxydestinationbindingis_domain_allowed] Check if a given domain is allowed by this binding. ```rust #[must_use] pub fn is_domain_allowed(&self, domain: &str) -> bool; ``` Source line: `179`. ## proxy::DestinationBinding::is\_method\_allowed [#proxydestinationbindingis_method_allowed] Check if a given HTTP method is allowed by this binding. ```rust #[must_use] pub fn is_method_allowed(&self, method: &str) -> bool; ``` Source line: `195`. ## proxy::DestinationBinding::is\_port\_allowed [#proxydestinationbindingis_port_allowed] Check if a given port is allowed by this binding. ```rust #[must_use] pub fn is_port_allowed(&self, port: u16) -> bool; ``` Source line: `204`. ## proxy::DestinationBinding::is\_path\_allowed [#proxydestinationbindingis_path_allowed] Check if a given path matches the allowed path patterns. Supports `*` (matches a single path segment) and `**` (matches any number of segments). ```rust #[must_use] pub fn is_path_allowed(&self, path: &str) -> bool; ``` Source line: `216`. ## proxy::VariablePrefix [#proxyvariableprefix] Variable prefix indicating the credential type. Template variables follow the pattern `{{PREFIX_NAME}}`, where the prefix indicates the credential type and helps the proxy resolve the correct secret. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum VariablePrefix { /// OAuth 2.0 token OAuth2, /// OAuth 1.0 token OAuth1, /// API key ApiKey, /// HTTP Basic authentication Basic, /// Bearer token Bearer, /// Client certificate Cert, /// Custom credential type Custom, } ``` Source line: `232`. ## proxy::VariablePrefix::as\_str [#proxyvariableprefixas_str] Get the string representation of this prefix. ```rust #[must_use] pub const fn as_str(&self) -> &'static str; ``` Source line: `252`. ## proxy::VariablePrefix::from\_str\_prefix [#proxyvariableprefixfrom_str_prefix] Parse a prefix from a string. # Errors [#errors-2] Returns an error if the string does not match a known prefix. ```rust pub fn from_str_prefix(s: &str) -> ArsenalResult; ``` Source line: `269`. ## proxy::TemplateVariable [#proxytemplatevariable] A parsed template variable from a proxy request. Template variables are placeholders in proxy request URLs, headers, or bodies that the proxy replaces with actual credential values. Agents see only the placeholder name, never the resolved value. ```rust #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct TemplateVariable { /// Full variable name (e.g., `OAUTH2_STRIPE_TOKEN`). /// Must match `[A-Z][A-Z0-9_]{1,63}`. pub name: String, /// The credential type prefix parsed from the name. pub prefix: VariablePrefix } ``` Source line: `292`. ## proxy::TemplateVariable::new [#proxytemplatevariablenew] Create a new template variable with validation. # Errors [#errors-3] Returns an error if the variable name is invalid. ```rust pub fn new(name: impl Into) -> ArsenalResult; ``` Source line: `306`. ## proxy::TemplateVariable::name [#proxytemplatevariablename] Get the variable name. ```rust #[must_use] pub fn name(&self) -> &str; ``` Source line: `315`. ## proxy::TemplateVariable::prefix [#proxytemplatevariableprefix] Get the credential type prefix. ```rust #[must_use] pub const fn prefix(&self) -> VariablePrefix; ``` Source line: `321`. ## proxy::parse\_template\_variables [#proxyparse_template_variables] Parse all template variables from a string containing `{{VARIABLE}}` placeholders. Scans the input for `{{...}}` patterns and returns all valid template variables found. Invalid variable names inside `{{}}` are silently skipped. ```rust #[must_use] pub fn parse_template_variables(input: &str) -> Vec; ``` Source line: `331`. ## proxy::validate\_variable\_name [#proxyvalidate_variable_name] Validate a template variable name. Variable names must match `[A-Z][A-Z0-9_]{1,63}`. # Errors [#errors-4] Returns an error if the name is invalid. ```rust pub fn validate_variable_name(name: &str) -> ArsenalResult<()>; ``` Source line: `360`. ## proxy::ProxyRequest [#proxyproxyrequest] A proxy request from an agent to the broker. The agent constructs this request using template variables instead of actual credentials. The broker resolves the variables, validates destination bindings, and forwards the assembled request. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProxyRequest { /// HTTP method (GET, POST, PUT, DELETE, etc.) pub method: String, /// Target URL (may contain `{{VARIABLE}}` placeholders) pub url: String, /// Optional HTTP headers (may contain `{{VARIABLE}}` placeholders) #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option>, /// Optional request body bytes #[serde(default, skip_serializing_if = "Option::is_none")] pub body: Option>, /// Base64-encoded capability token authorizing this request pub capability_token: String, /// Optional timeout in milliseconds (default: 30000, max: 300000) #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout_ms: Option } ``` Source line: `408`. ## proxy::ProxyRequest::validate [#proxyproxyrequestvalidate] Validate the proxy request structure. # Errors [#errors-5] Returns an error if the request is malformed. ```rust pub fn validate(&self) -> ArsenalResult<()>; ``` Source line: `432`. ## proxy::ProxyRequest::effective\_timeout\_ms [#proxyproxyrequesteffective_timeout_ms] Get the effective timeout in milliseconds. ```rust #[must_use] pub fn effective_timeout_ms(&self) -> u64; ``` Source line: `481`. ## proxy::ProxyRequest::extract\_variables [#proxyproxyrequestextract_variables] Extract all template variables from the URL, headers, and body. ```rust #[must_use] pub fn extract_variables(&self) -> Vec; ``` Source line: `489`. ## proxy::ProxyResponse [#proxyproxyresponse] Response from the broker after proxying an API call. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProxyResponse { /// HTTP status code from the target API pub status: u16, /// Response headers (sanitized — credential headers stripped) pub headers: BTreeMap, /// Response body bytes pub body: Vec, /// Metadata about how the proxy processed the request pub proxy_metadata: ProxyMetadata } ``` Source line: `518`. ## proxy::ProxyMetadata [#proxyproxymetadata] Metadata about proxy request processing. Included in every proxy response to give agents visibility into what happened without revealing credential values. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProxyMetadata { /// Names of variables that were resolved (never values) pub variables_resolved: Vec, /// Whether the destination binding was verified pub destination_verified: bool, /// Whether the agent fingerprint was verified pub fingerprint_verified: bool, /// Status of human consent for credential usage pub consent_status: ConsentStatus, /// End-to-end proxy latency in milliseconds pub latency_ms: u64, /// Unique request ID for audit correlation pub request_id: Uuid } ``` Source line: `534`. ## proxy::ProxyMetadata::new [#proxyproxymetadatanew] Create new proxy metadata for a request. ```rust #[must_use] pub fn new(request_id: Uuid) -> Self; ``` Source line: `552`. ## proxy::VariableResolutionTable [#proxyvariableresolutiontable] Maps template variable names to secret references. The variable resolution table is maintained per-tenant and maps agent-visible variable names to the actual secrets they represent. This table is the bridge between the agent's view (template variables) and the broker's view (encrypted secrets). ```rust #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct VariableResolutionTable { } ``` Source line: `573`. ## proxy::VariableResolutionTable::new [#proxyvariableresolutiontablenew] Create an empty resolution table. ```rust #[must_use] pub fn new() -> Self; ``` Source line: `581`. ## proxy::VariableResolutionTable::register [#proxyvariableresolutiontableregister] Register a variable-to-secret mapping. # Errors [#errors-6] Returns an error if the variable name is invalid or the table is full. ```rust pub fn register( &mut self, variable_name: impl Into, secret_ref: SecretRef, ) -> ArsenalResult<()>; ``` Source line: `590`. ## proxy::VariableResolutionTable::unregister [#proxyvariableresolutiontableunregister] Remove a variable mapping. Returns `true` if the variable existed. ```rust pub fn unregister(&mut self, variable_name: &str) -> bool; ``` Source line: `612`. ## proxy::VariableResolutionTable::resolve [#proxyvariableresolutiontableresolve] Resolve a variable name to its secret reference. ```rust #[must_use] pub fn resolve(&self, variable_name: &str) -> Option<&SecretRef>; ``` Source line: `618`. ## proxy::VariableResolutionTable::variable\_names [#proxyvariableresolutiontablevariable_names] List all registered variable names. ```rust #[must_use] pub fn variable_names(&self) -> Vec<&str>; ``` Source line: `624`. ## proxy::VariableResolutionTable::len [#proxyvariableresolutiontablelen] Get the number of registered variables. ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `630`. ## proxy::VariableResolutionTable::is\_empty [#proxyvariableresolutiontableis_empty] Check if the table is empty. ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `636`. ## proxy::VariableResolutionTable::entries [#proxyvariableresolutiontableentries] Get a reference to the underlying entries. ```rust #[must_use] pub fn entries(&self) -> &BTreeMap; ``` Source line: `642`. # arsenal-core · scope URL: https://docs.openagent.id/reference/rust/arsenal-core/scope Markdown: https://docs.openagent.id/reference/rust/arsenal-core/scope.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/scope.rs`. SHA-256: `539edaf85c4dd36b2b1c51fd72109798df47809c623318a4b6370e71dab7f46e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## scope::Scope [#scopescope] A single permission scope Format: `service:resource:action` or `service:resource:*` for wildcards Examples: * `stripe:charges:read` * `stripe:charges:write` * `github:repos:*` * `*:*:read` (read access to everything) ```rust #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(transparent)] pub struct Scope(String); ``` Source line: `29`. ## scope::Scope::new [#scopescopenew] Create a new scope with validation # Errors [#errors] Returns an error if the scope format is invalid ```rust pub fn new(scope: impl Into) -> ArsenalResult; ``` Source line: `36`. ## scope::Scope::wildcard [#scopescopewildcard] Create a wildcard scope that matches everything ```rust #[must_use] pub fn wildcard() -> Self; ``` Source line: `44`. ## scope::Scope::read\_only [#scopescoperead_only] Create a read-only scope for a service ```rust #[must_use] pub fn read_only(service: &str) -> Self; ``` Source line: `50`. ## scope::Scope::full\_access [#scopescopefull_access] Create a full access scope for a service ```rust #[must_use] pub fn full_access(service: &str) -> Self; ``` Source line: `56`. ## scope::Scope::service [#scopescopeservice] Get the service component ```rust #[must_use] pub fn service(&self) -> &str; ``` Source line: `62`. ## scope::Scope::resource [#scopescoperesource] Get the resource component ```rust #[must_use] pub fn resource(&self) -> &str; ``` Source line: `68`. ## scope::Scope::action [#scopescopeaction] Get the action component ```rust #[must_use] pub fn action(&self) -> &str; ``` Source line: `75`. ## scope::Scope::is\_wildcard [#scopescopeis_wildcard] Check if this scope is a wildcard (matches everything) ```rust #[must_use] pub fn is_wildcard(&self) -> bool; ``` Source line: `82`. ## scope::Scope::implies [#scopescopeimplies] Check if this scope implies (covers) another scope A scope implies another if it grants equal or greater permissions. Wildcards (`*`) match any value at that position. ```rust #[must_use] pub fn implies(&self, other: &Scope) -> bool; ``` Source line: `91`. ## scope::Scope::as\_str [#scopescopeas_str] Get the raw scope string ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `113`. ## scope::ScopeSet [#scopescopeset] A set of scopes representing granted permissions ```rust #[derive(Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct ScopeSet { } ``` Source line: `186`. ## scope::ScopeSet::new [#scopescopesetnew] Create an empty scope set ```rust #[must_use] pub fn new() -> Self; ``` Source line: `193`. ## scope::ScopeSet::single [#scopescopesetsingle] Create a scope set with a single scope ```rust #[must_use] pub fn single(scope: Scope) -> Self; ``` Source line: `201`. ## scope::ScopeSet::add [#scopescopesetadd] Add a scope to the set # Errors [#errors-1] Returns an error if the maximum number of scopes would be exceeded ```rust pub fn add(&mut self, scope: Scope) -> ArsenalResult<()>; ``` Source line: `211`. ## scope::ScopeSet::remove [#scopescopesetremove] Remove a scope from the set ```rust pub fn remove(&mut self, scope: &Scope) -> bool; ``` Source line: `223`. ## scope::ScopeSet::contains [#scopescopesetcontains] Check if the set contains a specific scope ```rust #[must_use] pub fn contains(&self, scope: &Scope) -> bool; ``` Source line: `229`. ## scope::ScopeSet::allows [#scopescopesetallows] Check scope set allows the given scope Returns true if any scope in the set implies the requested scope ```rust #[must_use] pub fn allows(&self, requested: &Scope) -> bool; ``` Source line: `237`. ## scope::ScopeSet::is\_superset\_of [#scopescopesetis_superset_of] Check if this scope set is a superset of another Returns true if all scopes in `other` are allowed by this set ```rust #[must_use] pub fn is_superset_of(&self, other: &ScopeSet) -> bool; ``` Source line: `245`. ## scope::ScopeSet::intersection [#scopescopesetintersection] Get the intersection of two scope sets ```rust #[must_use] pub fn intersection(&self, other: &ScopeSet) -> ScopeSet; ``` Source line: `251`. ## scope::ScopeSet::union [#scopescopesetunion] Get the union of two scope sets ```rust #[must_use] pub fn union(&self, other: &ScopeSet) -> ScopeSet; ``` Source line: `259`. ## scope::ScopeSet::is\_empty [#scopescopesetis_empty] Check if the set is empty ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `267`. ## scope::ScopeSet::len [#scopescopesetlen] Get the number of scopes in the set ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `273`. ## scope::ScopeSet::iter [#scopescopesetiter] Iterate over the scopes ```rust pub fn iter(&self) -> impl Iterator; ``` Source line: `278`. ## scope::ScopeSet::to\_strings [#scopescopesetto_strings] Convert to a vector of scope strings ```rust #[must_use] pub fn to_strings(&self) -> Vec; ``` Source line: `284`. ## scope::ScopeSet::from\_strings [#scopescopesetfrom_strings] Create from a vector of scope strings # Errors [#errors-2] Returns an error if any scope is invalid or too many scopes are provided ```rust pub fn from_strings(scopes: Vec) -> ArsenalResult; ``` Source line: `292`. ## scope::Permission [#scopepermission] Permission type for CRUD operations ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Permission { /// Read/view access Read, /// Create new resources Create, /// Update existing resources Update, /// Delete resources Delete, /// Full access (all permissions) Admin, } ``` Source line: `339`. ## scope::Permission::as\_str [#scopepermissionas_str] Get the string representation ```rust #[must_use] pub const fn as_str(&self) -> &'static str; ``` Source line: `355`. ## scope::Permission::implies [#scopepermissionimplies] Check if this permission implies another ```rust #[must_use] pub const fn implies(&self, other: &Permission) -> bool; ``` Source line: `367`. # arsenal-core · secret URL: https://docs.openagent.id/reference/rust/arsenal-core/secret Markdown: https://docs.openagent.id/reference/rust/arsenal-core/secret.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/secret.rs`. SHA-256: `b680d13ed794de37fa2a5d6719c3b4051d95e8019669cc69eb38a5f340187c34`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## secret::SecretId [#secretsecretid] Secret identifier ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct SecretId(Uuid); ``` Source line: `24`. ## secret::SecretId::generate [#secretsecretidgenerate] Generate a new secret ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `29`. ## secret::SecretId::from\_uuid [#secretsecretidfrom_uuid] Create from an existing UUID ```rust #[must_use] pub const fn from_uuid(uuid: Uuid) -> Self; ``` Source line: `35`. ## secret::SecretId::as\_uuid [#secretsecretidas_uuid] Get the inner UUID ```rust #[must_use] pub const fn as_uuid(&self) -> &Uuid; ``` Source line: `41`. ## secret::SecretVersion [#secretsecretversion] Secret version identifier ```rust #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(transparent)] pub struct SecretVersion(u64); ``` Source line: `61`. ## secret::SecretVersion::initial [#secretsecretversioninitial] Create version 1 (initial version) ```rust #[must_use] pub const fn initial() -> Self; ``` Source line: `66`. ## secret::SecretVersion::new [#secretsecretversionnew] Create from a version number ```rust #[must_use] pub const fn new(version: u64) -> Self; ``` Source line: `72`. ## secret::SecretVersion::as\_u64 [#secretsecretversionas_u64] Get the version number ```rust #[must_use] pub const fn as_u64(&self) -> u64; ``` Source line: `78`. ## secret::SecretVersion::next [#secretsecretversionnext] Get the next version ```rust #[must_use] pub const fn next(&self) -> Self; ``` Source line: `84`. ## secret::SecretVersion::is\_initial [#secretsecretversionis_initial] Check if this is the initial version ```rust #[must_use] pub const fn is_initial(&self) -> bool; ``` Source line: `90`. ## secret::SecretType [#secretsecrettype] Secret type classification ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SecretType { /// API key (e.g., `OpenAI`, Stripe) ApiKey, /// `OAuth2` client credentials OAuthClientCredentials, /// `OAuth2` access token OAuthAccessToken, /// `OAuth2` refresh token OAuthRefreshToken, /// Database connection string DatabaseCredentials, /// SSH private key SshKey, /// TLS/SSL private key and certificate TlsCertificate, /// Signing key (e.g., JWT, webhook) SigningKey, /// Encryption key EncryptionKey, /// Generic secret Generic, } ``` Source line: `110`. ## secret::SecretType::should\_auto\_rotate [#secretsecrettypeshould_auto_rotate] Check if this secret type should be automatically rotated ```rust #[must_use] pub const fn should_auto_rotate(&self) -> bool; ``` Source line: `136`. ## secret::SecretType::recommended\_rotation\_days [#secretsecrettyperecommended_rotation_days] Get recommended rotation period in days ```rust #[must_use] pub const fn recommended_rotation_days(&self) -> Option; ``` Source line: `145`. ## secret::SecretMetadata [#secretsecretmetadata] Secret metadata (does not contain the actual secret value) ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SecretMetadata { /// Secret ID pub id: SecretId, /// Tenant this secret belongs to pub tenant_id: TenantId, /// Human-readable name pub name: String, /// Description #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, /// Secret type pub secret_type: SecretType, /// Current version pub current_version: SecretVersion, /// All versions pub versions: Vec, /// When the secret was created pub created_at: chrono::DateTime, /// When the secret was last modified pub updated_at: chrono::DateTime, /// When the secret expires (if ever) #[serde(skip_serializing_if = "Option::is_none")] pub expires_at: Option>, /// When the secret was last rotated #[serde(skip_serializing_if = "Option::is_none")] pub last_rotated_at: Option>, /// Next scheduled rotation #[serde(skip_serializing_if = "Option::is_none")] pub next_rotation_at: Option>, /// Whether the secret is currently active pub is_active: bool, /// Custom labels #[serde(default)] pub labels: HashMap, /// Associated service (e.g., "stripe", "openai") #[serde(skip_serializing_if = "Option::is_none")] pub service: Option, /// Destination binding restricting where this credential can be used #[serde(default, skip_serializing_if = "Option::is_none")] pub destination_binding: Option } ``` Source line: `158`. ## secret::SecretMetadata::new [#secretsecretmetadatanew] Create new secret metadata # Errors [#errors] Returns an error if validation fails ```rust pub fn new( tenant_id: TenantId, name: impl Into, secret_type: SecretType, ) -> ArsenalResult; ``` Source line: `205`. ## secret::SecretMetadata::is\_expired [#secretsecretmetadatais_expired] Check if secret is expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `243`. ## secret::SecretMetadata::needs\_rotation [#secretsecretmetadataneeds_rotation] Check if the secret needs rotation ```rust #[must_use] pub fn needs_rotation(&self) -> bool; ``` Source line: `253`. ## secret::SecretMetadata::add\_version [#secretsecretmetadataadd_version] Add a new version ```rust pub fn add_version(&mut self, created_by: Option) -> SecretVersion; ``` Source line: `262`. ## secret::SecretMetadata::disable\_version [#secretsecretmetadatadisable_version] Disable a specific version ```rust pub fn disable_version(&mut self, version: SecretVersion); ``` Source line: `288`. ## secret::SecretMetadata::deactivate [#secretsecretmetadatadeactivate] Deactivate the entire secret ```rust pub fn deactivate(&mut self); ``` Source line: `298`. ## secret::SecretMetadata::set\_label [#secretsecretmetadataset_label] Set a label ```rust pub fn set_label(&mut self, key: impl Into, value: impl Into); ``` Source line: `304`. ## secret::SecretVersionInfo [#secretsecretversioninfo] Information about a specific secret version ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SecretVersionInfo { /// Version number pub version: SecretVersion, /// When this version was created pub created_at: chrono::DateTime, /// Who created this version #[serde(skip_serializing_if = "Option::is_none")] pub created_by: Option, /// Current state of this version pub state: SecretVersionState } ``` Source line: `312`. ## secret::SecretVersionState [#secretsecretversionstate] State of a secret version ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SecretVersionState { /// Currently active version Active, /// Previous version (still valid for grace period) Previous, /// Disabled (cannot be used) Disabled, /// Scheduled for deletion PendingDeletion, } ``` Source line: `327`. ## secret::SecretRef [#secretsecretref] Secret reference - used to reference a secret without containing it ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SecretRef { /// Secret ID pub id: SecretId, /// Specific version (None = latest) #[serde(skip_serializing_if = "Option::is_none")] pub version: Option } ``` Source line: `340`. ## secret::SecretRef::latest [#secretsecretreflatest] Create a reference to the latest version ```rust #[must_use] pub fn latest(id: SecretId) -> Self; ``` Source line: `351`. ## secret::SecretRef::specific [#secretsecretrefspecific] Create a reference to a specific version ```rust #[must_use] pub fn specific(id: SecretId, version: SecretVersion) -> Self; ``` Source line: `357`. ## secret::WrappedSecret [#secretwrappedsecret] Wrapped secret - encrypted secret value for transport ```rust #[derive(Clone, Serialize, Deserialize)] pub struct WrappedSecret { /// Secret ID pub id: SecretId, /// Version pub version: SecretVersion, /// Encrypted secret bytes pub ciphertext: Vec, /// Nonce used for encryption pub nonce: [u8; 12], /// Key ID used for wrapping pub wrap_key_id: String, /// Algorithm used pub algorithm: String, /// When this wrapped secret expires pub expires_at: chrono::DateTime } ``` Source line: `367`. ## secret::WrappedSecret::is\_expired [#secretwrappedsecretis_expired] Check if this wrapped secret has expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `387`. ## secret::SecretValue [#secretsecretvalue] Secret value - holds the actual decrypted secret This type is zeroized on drop for security. ```rust #[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)] pub struct SecretValue { } ``` Source line: `409`. ## secret::SecretValue::new [#secretsecretvaluenew] Create from bytes # Errors [#errors-1] Returns an error if the secret is too large ```rust pub fn new(bytes: Vec) -> ArsenalResult; ``` Source line: `419`. ## secret::SecretValue::from\_string [#secretsecretvaluefrom_string] Create from a string # Errors [#errors-2] Returns an error if the secret is too large ```rust pub fn from_string(s: impl Into) -> ArsenalResult; ``` Source line: `433`. ## secret::SecretValue::as\_bytes [#secretsecretvalueas_bytes] Get the secret bytes ```rust #[must_use] pub fn as_bytes(&self) -> &[u8]; ``` Source line: `439`. ## secret::SecretValue::as\_str [#secretsecretvalueas_str] Get as UTF-8 string if valid ```rust #[must_use] pub fn as_str(&self) -> Option<&str>; ``` Source line: `445`. ## secret::SecretValue::len [#secretsecretvaluelen] Get the length ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `451`. ## secret::SecretValue::is\_empty [#secretsecretvalueis_empty] Check if empty ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `457`. ## secret::RotationPolicy [#secretrotationpolicy] Rotation policy for secrets ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RotationPolicy { /// Enable automatic rotation pub auto_rotate: bool, /// Rotation interval in days pub rotation_days: u32, /// Grace period for old versions in hours pub grace_period_hours: u32, /// Maximum number of versions to keep pub max_versions: u32, /// Notification settings #[serde(skip_serializing_if = "Option::is_none")] pub notification: Option } ``` Source line: `470`. ## secret::RotationNotification [#secretrotationnotification] Rotation notification settings ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RotationNotification { /// Days before rotation to send warning pub warn_days_before: Vec, /// Webhook URL for notifications #[serde(skip_serializing_if = "Option::is_none")] pub webhook_url: Option, /// Email addresses for notifications #[serde(default)] pub email_addresses: Vec } ``` Source line: `498`. # arsenal-core · session URL: https://docs.openagent.id/reference/rust/arsenal-core/session Markdown: https://docs.openagent.id/reference/rust/arsenal-core/session.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/session.rs`. SHA-256: `f774575cf6008b05bafb52312b9d92083e0dd30d55e00b467702c72c613f17eb`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session::SessionId [#sessionsessionid] Session identifier ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct SessionId(Uuid); ``` Source line: `20`. ## session::SessionId::generate [#sessionsessionidgenerate] Generate a new session ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `25`. ## session::SessionId::from\_uuid [#sessionsessionidfrom_uuid] Create from an existing UUID ```rust #[must_use] pub const fn from_uuid(uuid: Uuid) -> Self; ``` Source line: `31`. ## session::SessionId::as\_uuid [#sessionsessionidas_uuid] Get the inner UUID ```rust #[must_use] pub const fn as_uuid(&self) -> &Uuid; ``` Source line: `37`. ## session::SessionState [#sessionsessionstate] Session state machine states Represents the lifecycle of an agent session: 1. `AgentBootstrapped` - Agent has proven identity 2. `SessionStarted` - Session is active 3. `CapabilitiesGranted` - Agent has received capabilities 4. `ToolUse` - Agent is actively using tools 5. `Renewal` - Session/tokens being renewed 6. `Escalation` - Privilege escalation requested 7. `SessionEnded` - Session terminated ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SessionState { /// Agent has completed identity verification AgentBootstrapped, /// Session has been established SessionStarted, /// Capabilities have been granted to the agent CapabilitiesGranted, /// Agent is actively using tools ToolUse, /// Session or tokens are being renewed Renewal, /// Privilege escalation is in progress Escalation, /// Session has ended SessionEnded, } ``` Source line: `66`. ## session::SessionState::can\_use\_tools [#sessionsessionstatecan_use_tools] Check if this state allows tool usage ```rust #[must_use] pub const fn can_use_tools(&self) -> bool; ``` Source line: `86`. ## session::SessionState::can\_request\_capabilities [#sessionsessionstatecan_request_capabilities] Check if this state allows capability requests ```rust #[must_use] pub const fn can_request_capabilities(&self) -> bool; ``` Source line: `92`. ## session::SessionState::is\_terminal [#sessionsessionstateis_terminal] Check if this is a terminal state ```rust #[must_use] pub const fn is_terminal(&self) -> bool; ``` Source line: `101`. ## session::SessionState::is\_active [#sessionsessionstateis_active] Check if the session is active ```rust #[must_use] pub const fn is_active(&self) -> bool; ``` Source line: `107`. ## session::SessionState::valid\_transitions [#sessionsessionstatevalid_transitions] Get valid transitions from this state ```rust #[must_use] pub fn valid_transitions(&self) -> &'static [SessionState]; ``` Source line: `113`. ## session::SessionState::can\_transition\_to [#sessionsessionstatecan_transition_to] Check if a transition to the target state is valid ```rust #[must_use] pub fn can_transition_to(&self, target: SessionState) -> bool; ``` Source line: `137`. ## session::SessionEndReason [#sessionsessionendreason] Reason for session termination ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SessionEndReason { /// Normal completion Completed, /// Explicit logout Logout, /// Session timeout Timeout, /// Token expired TokenExpired, /// Revoked by administrator Revoked, /// Security violation detected SecurityViolation, /// Policy violation PolicyViolation, /// System shutdown SystemShutdown, /// Error during session Error(String), } ``` Source line: `160`. ## session::AgentSession [#sessionagentsession] Agent session - represents an authenticated agent's session ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AgentSession { /// Unique session identifier pub id: SessionId, /// Tenant this session belongs to pub tenant_id: TenantId, /// Agent identity pub agent_id: AgentId, /// Principal (user/service) that initiated the session #[serde(skip_serializing_if = "Option::is_none")] pub principal_id: Option, /// Current state pub state: SessionState, /// When the session was created pub created_at: chrono::DateTime, /// When the session was last active pub last_activity_at: chrono::DateTime, /// When the session expires pub expires_at: chrono::DateTime, /// Session metadata #[serde(default)] pub metadata: std::collections::HashMap, /// Reason for session end (if ended) #[serde(skip_serializing_if = "Option::is_none")] pub end_reason: Option } ``` Source line: `199`. ## session::AgentSession::new [#sessionagentsessionnew] Create a new session ```rust #[must_use] pub fn new(tenant_id: TenantId, agent_id: AgentId, ttl_seconds: u64) -> Self; ``` Source line: `248`. ## session::AgentSession::with\_principal [#sessionagentsessionwith_principal] Set the principal ID ```rust #[must_use] pub fn with_principal(mut self, principal_id: PrincipalId) -> Self; ``` Source line: `272`. ## session::AgentSession::transition\_to [#sessionagentsessiontransition_to] Transition to a new state # Errors [#errors] Returns an error if the transition is invalid ```rust pub fn transition_to( &mut self, new_state: SessionState, reason: Option, ) -> ArsenalResult<()>; ``` Source line: `281`. ## session::AgentSession::start [#sessionagentsessionstart] Start the session # Errors [#errors-1] Returns an error if the session cannot be started ```rust pub fn start(&mut self) -> ArsenalResult<()>; ``` Source line: `311`. ## session::AgentSession::grant\_capabilities [#sessionagentsessiongrant_capabilities] Grant capabilities # Errors [#errors-2] Returns an error if capabilities cannot be granted ```rust pub fn grant_capabilities(&mut self, scopes: &ScopeSet) -> ArsenalResult<()>; ``` Source line: `322`. ## session::AgentSession::begin\_tool\_use [#sessionagentsessionbegin_tool_use] Begin tool use # Errors [#errors-3] Returns an error if tool use cannot begin ```rust pub fn begin_tool_use(&mut self) -> ArsenalResult<()>; ``` Source line: `335`. ## session::AgentSession::begin\_renewal [#sessionagentsessionbegin_renewal] Begin renewal # Errors [#errors-4] Returns an error if renewal cannot begin ```rust pub fn begin_renewal(&mut self) -> ArsenalResult<()>; ``` Source line: `343`. ## session::AgentSession::complete\_renewal [#sessionagentsessioncomplete_renewal] Complete renewal # Errors [#errors-5] Returns an error if renewal cannot be completed ```rust pub fn complete_renewal( &mut self, new_expires_at: chrono::DateTime, ) -> ArsenalResult<()>; ``` Source line: `351`. ## session::AgentSession::begin\_escalation [#sessionagentsessionbegin_escalation] Begin escalation # Errors [#errors-6] Returns an error if escalation cannot begin ```rust pub fn begin_escalation(&mut self) -> ArsenalResult<()>; ``` Source line: `367`. ## session::AgentSession::end [#sessionagentsessionend] End the session # Errors [#errors-7] Returns an error if the session cannot be ended ```rust pub fn end(&mut self, reason: SessionEndReason) -> ArsenalResult<()>; ``` Source line: `378`. ## session::AgentSession::add\_token [#sessionagentsessionadd_token] Add an active token ```rust pub fn add_token(&mut self, token_id: TokenId); ``` Source line: `388`. ## session::AgentSession::remove\_token [#sessionagentsessionremove_token] Remove an active token ```rust pub fn remove_token(&mut self, token_id: &TokenId); ``` Source line: `394`. ## session::AgentSession::active\_tokens [#sessionagentsessionactive_tokens] Get active token IDs ```rust #[must_use] pub fn active_tokens(&self) -> &HashSet; ``` Source line: `401`. ## session::AgentSession::granted\_scopes [#sessionagentsessiongranted_scopes] Get granted scopes ```rust #[must_use] pub fn granted_scopes(&self) -> &ScopeSet; ``` Source line: `407`. ## session::AgentSession::is\_expired [#sessionagentsessionis_expired] Check if the session is expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `413`. ## session::AgentSession::is\_active [#sessionagentsessionis_active] Check if the session is active ```rust #[must_use] pub fn is_active(&self) -> bool; ``` Source line: `419`. ## session::AgentSession::touch [#sessionagentsessiontouch] Update last activity timestamp ```rust pub fn touch(&mut self); ``` Source line: `424`. ## session::AgentSession::state\_history\_len [#sessionagentsessionstate_history_len] Get state history ```rust #[must_use] pub fn state_history_len(&self) -> usize; ``` Source line: `430`. ## session::AgentSession::extend [#sessionagentsessionextend] Extend session expiration ```rust pub fn extend(&mut self, additional_seconds: u64); ``` Source line: `435`. ## session::AgentSession::set\_metadata [#sessionagentsessionset_metadata] Set metadata ```rust pub fn set_metadata(&mut self, key: impl Into, value: impl Into); ``` Source line: `442`. ## session::AgentSession::get\_metadata [#sessionagentsessionget_metadata] Get metadata ```rust #[must_use] pub fn get_metadata(&self, key: &str) -> Option<&String>; ``` Source line: `448`. ## session::SessionConfig [#sessionsessionconfig] Session configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionConfig { /// Default session TTL in seconds pub default_ttl_seconds: u64, /// Maximum session TTL in seconds pub max_ttl_seconds: u64, /// Idle timeout in seconds pub idle_timeout_seconds: u64, /// Maximum concurrent sessions per agent pub max_concurrent_sessions: u32, /// Allow session extension pub allow_extension: bool, /// Maximum extensions allowed pub max_extensions: u32 } ``` Source line: `455`. # arsenal-core · token URL: https://docs.openagent.id/reference/rust/arsenal-core/token Markdown: https://docs.openagent.id/reference/rust/arsenal-core/token.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-core/src/token.rs`. SHA-256: `704152225e610b62f9b811548b7cd899d23bedee7514d8222e8073bd31044202`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## token::TokenId [#tokentokenid] Token identifier - unique ID for each token instance ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct TokenId(Uuid); ``` Source line: `35`. ## token::TokenId::generate [#tokentokenidgenerate] Generate a new random token ID ```rust #[must_use] pub fn generate() -> Self; ``` Source line: `40`. ## token::TokenId::from\_uuid [#tokentokenidfrom_uuid] Create from an existing UUID ```rust #[must_use] pub const fn from_uuid(uuid: Uuid) -> Self; ``` Source line: `47`. ## token::TokenId::as\_uuid [#tokentokenidas_uuid] Get the inner UUID ```rust #[must_use] pub const fn as_uuid(&self) -> &Uuid; ``` Source line: `53`. ## token::AgentCapabilityToken [#tokenagentcapabilitytoken] Agent Capability Token - the main credential type This struct represents the claims within a token. The actual signed token is produced by the crypto layer. ```rust #[derive(Clone, Serialize, Deserialize)] pub struct AgentCapabilityToken { } ``` Source line: `75`. ## token::AgentCapabilityToken::new [#tokenagentcapabilitytokennew] Create a new unsigned token with the given claims ```rust #[must_use] pub fn new(claims: TokenClaims) -> Self; ``` Source line: `86`. ## token::AgentCapabilityToken::claims [#tokenagentcapabilitytokenclaims] Get the token claims ```rust #[must_use] pub fn claims(&self) -> &TokenClaims; ``` Source line: `95`. ## token::AgentCapabilityToken::id [#tokenagentcapabilitytokenid] Get the token ID ```rust #[must_use] pub fn id(&self) -> &TokenId; ``` Source line: `101`. ## token::AgentCapabilityToken::subject [#tokenagentcapabilitytokensubject] Get the subject (the agent's OAS DID) ```rust #[must_use] pub fn subject(&self) -> &OasDid; ``` Source line: `107`. ## token::AgentCapabilityToken::audience [#tokenagentcapabilitytokenaudience] Get the audience ```rust #[must_use] pub fn audience(&self) -> &str; ``` Source line: `113`. ## token::AgentCapabilityToken::scopes [#tokenagentcapabilitytokenscopes] Get the scopes ```rust #[must_use] pub fn scopes(&self) -> &ScopeSet; ``` Source line: `119`. ## token::AgentCapabilityToken::is\_expired [#tokenagentcapabilitytokenis_expired] Check if the token is expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `125`. ## token::AgentCapabilityToken::is\_not\_yet\_valid [#tokenagentcapabilitytokenis_not_yet_valid] Check if the token is not yet valid ```rust #[must_use] pub fn is_not_yet_valid(&self) -> bool; ``` Source line: `131`. ## token::AgentCapabilityToken::is\_time\_valid [#tokenagentcapabilitytokenis_time_valid] Check if the token is currently valid (time-wise) ```rust #[must_use] pub fn is_time_valid(&self) -> bool; ``` Source line: `137`. ## token::AgentCapabilityToken::remaining\_ttl [#tokenagentcapabilitytokenremaining_ttl] Get remaining TTL ```rust #[must_use] pub fn remaining_ttl(&self) -> chrono::Duration; ``` Source line: `144`. ## token::AgentCapabilityToken::is\_signed [#tokenagentcapabilitytokenis_signed] Check if token has a valid signature ```rust #[must_use] pub fn is_signed(&self) -> bool; ``` Source line: `150`. ## token::AgentCapabilityToken::set\_signature [#tokenagentcapabilitytokenset_signature] Set the signature (called by the crypto layer after signing) ```rust pub fn set_signature(&mut self, signature: TokenSignature); ``` Source line: `155`. ## token::AgentCapabilityToken::signature [#tokenagentcapabilitytokensignature] Get the signature if present ```rust #[must_use] pub fn signature(&self) -> Option<&TokenSignature>; ``` Source line: `161`. ## token::AgentCapabilityToken::validate\_structure [#tokenagentcapabilitytokenvalidate_structure] Validate token structure (not cryptographic verification) # Errors [#errors] Returns an error if the token structure is invalid ```rust pub fn validate_structure(&self) -> ArsenalResult<()>; ``` Source line: `169`. ## token::AgentCapabilityToken::to\_cbor [#tokenagentcapabilitytokento_cbor] Serialize to the canonical ACT envelope The bytes produced here are the interoperable form defined by `agent-capability-token`, not Arsenal's internal struct layout. A token leaving this process is a standard ACT, so a verifier that has never seen Arsenal can validate it. # Errors [#errors-1] Returns an error if the token is unsigned, if the claims cannot be represented canonically, or if the encoded token exceeds the size limit. An unsigned token has no envelope form: the envelope carries a signature by construction. ```rust pub fn to_cbor(&self) -> ArsenalResult>; ``` Source line: `214`. ## token::AgentCapabilityToken::claims\_to\_cbor [#tokenagentcapabilitytokenclaims_to_cbor] Serialize just the claims to CBOR bytes (for signing/verification) Produces the canonical claim encoding, so a signature computed here is a signature over the standard ACT payload. Signing and verification both route through this method, which is what keeps them in agreement. # Errors [#errors-2] Returns an error if the claims cannot be represented canonically. ```rust pub fn claims_to_cbor(&self) -> ArsenalResult>; ``` Source line: `242`. ## token::AgentCapabilityToken::from\_cbor [#tokenagentcapabilitytokenfrom_cbor] Deserialize from the canonical ACT envelope Decoding does not verify the signature; that is the verifier's job. The signature is carried through so a verifier can check it. # Errors [#errors-3] Returns an error if the envelope is malformed, exceeds the size limit, or carries claims Arsenal cannot represent - a multi-audience token, for instance. ```rust pub fn from_cbor(bytes: &[u8]) -> ArsenalResult; ``` Source line: `258`. ## token::TokenClaims [#tokentokenclaims] Token claims - the payload of an ACT ```rust #[derive(Clone, Serialize, Deserialize)] pub struct TokenClaims { /// Token ID (unique identifier) pub jti: TokenId, /// Subject - the OAS DID of the agent this token is for /// /// A DID rather than a local key, so that a verifier outside Arsenal can /// resolve the identity a capability was granted to. ANVIL section 5.2 /// requires this binding. pub sub: OasDid, /// Issuer - who issued this token pub iss: String, /// Audience - intended recipient/service pub aud: String, /// Issued at timestamp pub iat: chrono::DateTime, /// Not before timestamp pub nbf: chrono::DateTime, /// Expiration timestamp pub exp: chrono::DateTime, /// Tenant ID pub tenant_id: TenantId, /// Granted scopes pub scope: ScopeSet, /// Binding constraints #[serde(default, skip_serializing_if = "Option::is_none")] pub constraints: Option, /// Rate limits #[serde(default, skip_serializing_if = "Option::is_none")] pub limits: Option, /// Usage budget #[serde(default, skip_serializing_if = "Option::is_none")] pub budget: Option, /// Delegation constraints (if this token can be delegated) #[serde(default, skip_serializing_if = "Option::is_none")] pub delegation: Option, /// Trace information #[serde(default, skip_serializing_if = "Option::is_none")] pub trace: Option, /// Proof-of-possession key fingerprint #[serde(default, skip_serializing_if = "Option::is_none")] pub cnf: Option, /// Delegated credential variables accessible via proxy (DCT extension) #[serde(default, skip_serializing_if = "Option::is_none")] pub delegated_variables: Option>, /// Maximum delegation depth for credential tokens (DCT extension) #[serde(default, skip_serializing_if = "Option::is_none")] pub max_delegation_depth: Option } ``` Source line: `319`. ## token::TokenClaims::builder [#tokentokenclaimsbuilder] Create a new token claims builder ```rust #[must_use] pub fn builder() -> TokenClaimsBuilder; ``` Source line: `371`. ## token::TokenClaimsBuilder [#tokentokenclaimsbuilder-1] Builder for token claims ```rust #[derive(Debug)] pub struct TokenClaimsBuilder { } ``` Source line: `390`. ## token::TokenClaimsBuilder::new [#tokentokenclaimsbuildernew] Create a new builder ```rust #[must_use] pub fn new() -> Self; ``` Source line: `410`. ## token::TokenClaimsBuilder::subject [#tokentokenclaimsbuildersubject] Set the subject - the agent's OAS DID ```rust #[must_use] pub fn subject(mut self, sub: OasDid) -> Self; ``` Source line: `431`. ## token::TokenClaimsBuilder::issuer [#tokentokenclaimsbuilderissuer] Set the issuer ```rust #[must_use] pub fn issuer(mut self, iss: impl Into) -> Self; ``` Source line: `438`. ## token::TokenClaimsBuilder::audience [#tokentokenclaimsbuilderaudience] Set the audience ```rust #[must_use] pub fn audience(mut self, aud: impl Into) -> Self; ``` Source line: `445`. ## token::TokenClaimsBuilder::tenant [#tokentokenclaimsbuildertenant] Set the tenant ID ```rust #[must_use] pub fn tenant(mut self, tenant_id: TenantId) -> Self; ``` Source line: `452`. ## token::TokenClaimsBuilder::scopes [#tokentokenclaimsbuilderscopes] Set the scopes ```rust #[must_use] pub fn scopes(mut self, scope: ScopeSet) -> Self; ``` Source line: `459`. ## token::TokenClaimsBuilder::ttl\_seconds [#tokentokenclaimsbuilderttl_seconds] Set the TTL in seconds ```rust #[must_use] pub fn ttl_seconds(mut self, ttl: i64) -> Self; ``` Source line: `466`. ## token::TokenClaimsBuilder::constraints [#tokentokenclaimsbuilderconstraints] Set constraints ```rust #[must_use] pub fn constraints(mut self, constraints: Constraints) -> Self; ``` Source line: `473`. ## token::TokenClaimsBuilder::limits [#tokentokenclaimsbuilderlimits] Set rate limits ```rust #[must_use] pub fn limits(mut self, limits: RateLimits) -> Self; ``` Source line: `480`. ## token::TokenClaimsBuilder::budget [#tokentokenclaimsbuilderbudget] Set usage budget ```rust #[must_use] pub fn budget(mut self, budget: UsageBudget) -> Self; ``` Source line: `487`. ## token::TokenClaimsBuilder::delegation [#tokentokenclaimsbuilderdelegation] Set delegation constraints ```rust #[must_use] pub fn delegation(mut self, delegation: DelegationConstraints) -> Self; ``` Source line: `494`. ## token::TokenClaimsBuilder::parent\_token [#tokentokenclaimsbuilderparent_token] Set parent token ID (for delegation chain) ```rust #[must_use] pub fn parent_token(mut self, parent_id: TokenId) -> Self; ``` Source line: `501`. ## token::TokenClaimsBuilder::proof\_of\_possession [#tokentokenclaimsbuilderproof_of_possession] Set proof-of-possession key ```rust #[must_use] pub fn proof_of_possession(mut self, cnf: ProofOfPossession) -> Self; ``` Source line: `508`. ## token::TokenClaimsBuilder::delegated\_variables [#tokentokenclaimsbuilderdelegated_variables] Set delegated credential variables accessible via proxy ```rust #[must_use] pub fn delegated_variables(mut self, vars: Vec) -> Self; ``` Source line: `515`. ## token::TokenClaimsBuilder::max\_delegation\_depth [#tokentokenclaimsbuildermax_delegation_depth] Set maximum delegation depth for credential tokens ```rust #[must_use] pub fn max_delegation_depth(mut self, depth: u8) -> Self; ``` Source line: `522`. ## token::TokenClaimsBuilder::build [#tokentokenclaimsbuilderbuild] Build the token claims # Errors [#errors-4] Returns an error if required fields are missing ```rust pub fn build(self) -> ArsenalResult; ``` Source line: `531`. ## token::TokenTrace [#tokentokentrace] Token trace information for audit trail ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TokenTrace { /// Unique issuance ID pub issuance_id: Uuid, /// Parent token ID (if delegated) #[serde(skip_serializing_if = "Option::is_none")] pub parent_token_id: Option, /// Policy ID that authorized this token #[serde(skip_serializing_if = "Option::is_none")] pub policy_id: Option, /// Delegation depth (0 = original token) pub delegation_depth: u8 } ``` Source line: `599`. ## token::ProofOfPossession [#tokenproofofpossession] Proof-of-possession confirmation ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProofOfPossession { /// Key fingerprint for `PoP` verification pub key_fingerprint: KeyFingerprint, /// Algorithm used for `PoP` (e.g., "Ed25519") pub alg: String } ``` Source line: `614`. ## token::ProofOfPossession::ed25519 [#tokenproofofpossessioned25519] Create a new `PoP` confirmation with Ed25519 ```rust #[must_use] pub fn ed25519(key_fingerprint: KeyFingerprint) -> Self; ``` Source line: `624`. ## token::TokenSignature [#tokentokensignature] Token signature ```rust #[derive(Clone, Serialize, Deserialize)] pub struct TokenSignature { } ``` Source line: `634`. ## token::TokenSignature::new [#tokentokensignaturenew] Create a new signature ```rust #[must_use] pub fn new(bytes: Vec, algorithm: SignatureAlgorithm) -> Self; ``` Source line: `646`. ## token::TokenSignature::with\_key\_id [#tokentokensignaturewith_key_id] Set the key ID ```rust #[must_use] pub fn with_key_id(mut self, key_id: impl Into) -> Self; ``` Source line: `656`. ## token::TokenSignature::bytes [#tokentokensignaturebytes] Get the signature bytes ```rust #[must_use] pub fn bytes(&self) -> &[u8]; ``` Source line: `663`. ## token::TokenSignature::algorithm [#tokentokensignaturealgorithm] Get the algorithm ```rust #[must_use] pub const fn algorithm(&self) -> &SignatureAlgorithm; ``` Source line: `669`. ## token::TokenSignature::key\_id [#tokentokensignaturekey_id] Get the key ID ```rust #[must_use] pub fn key_id(&self) -> Option<&str>; ``` Source line: `675`. ## token::SignatureAlgorithm [#tokensignaturealgorithm] Signature algorithms supported ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "UPPERCASE")] pub enum SignatureAlgorithm { /// Ed25519 signature Ed25519, /// ECDSA with P-256 Es256, /// ECDSA with P-384 Es384, } ``` Source line: `693`. ## token::SignatureAlgorithm::signature\_length [#tokensignaturealgorithmsignature_length] Get the expected signature length ```rust #[must_use] pub const fn signature_length(&self) -> usize; ``` Source line: `705`. # arsenal-sdk · broker_client URL: https://docs.openagent.id/reference/rust/arsenal-sdk/broker_client Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/broker_client.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/broker_client.rs`. SHA-256: `31f8a91c90e0c4af3a52b899bd085073fb13ca70a5f34780bda2c3d5220cb17d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## broker\_client::BrokerClient [#broker_clientbrokerclient] HTTP client for broker communication ```rust pub struct BrokerClient { } ``` Source line: `15`. ## broker\_client::CapabilityRequestPayload [#broker_clientcapabilityrequestpayload] Request payload for capability requests ```rust #[derive(Debug, Clone, Serialize)] pub struct CapabilityRequestPayload { /// Requested scopes pub scopes: Vec, /// Requested TTL in seconds #[serde(skip_serializing_if = "Option::is_none")] pub ttl_seconds: Option, /// Target audience (service) pub audience: String, /// Constraints to apply #[serde(skip_serializing_if = "Option::is_none")] pub constraints: Option, /// `PoP` key fingerprint (hex encoded) #[serde(skip_serializing_if = "Option::is_none")] pub pop_key_fingerprint: Option } ``` Source line: `26`. ## broker\_client::ConstraintsPayload [#broker_clientconstraintspayload] Constraints payload for API ```rust #[derive(Debug, Clone, Default, Serialize)] pub struct ConstraintsPayload { /// Require proof-of-possession #[serde(skip_serializing_if = "std::ops::Not::not")] pub require_pop: bool, /// Allowed origins #[serde(skip_serializing_if = "Option::is_none")] pub allowed_origins: Option>, /// Device ID binding #[serde(skip_serializing_if = "Option::is_none")] pub device_id: Option } ``` Source line: `44`. ## broker\_client::CapabilityResponsePayload [#broker_clientcapabilityresponsepayload] Response payload from capability requests ```rust #[derive(Debug, Deserialize)] pub struct CapabilityResponsePayload { /// Token ID pub token_id: String, /// Encoded token (base64) pub token: String, /// Expiration timestamp (ISO 8601) pub expires_at: String, /// Granted scopes pub granted_scopes: Vec } ``` Source line: `58`. ## broker\_client::SecretRequestPayload [#broker_clientsecretrequestpayload] Request payload for secret requests ```rust #[derive(Debug, Serialize)] pub struct SecretRequestPayload { /// Secret ID pub secret_id: String, /// Version (optional, defaults to latest) #[serde(skip_serializing_if = "Option::is_none")] pub version: Option, /// Capability token authorizing access pub capability_token: String } ``` Source line: `71`. ## broker\_client::SecretResponsePayload [#broker_clientsecretresponsepayload] Response payload from secret requests ```rust #[derive(Debug, Deserialize)] pub struct SecretResponsePayload { /// Secret ID pub secret_id: String, /// Version pub version: u64, /// Wrapped (encrypted) secret value (base64) pub wrapped_value: String, /// Wrapping key ID pub wrap_key_id: String, /// Ephemeral public key for unwrapping (base64) pub ephemeral_public_key: String, /// Expiration timestamp (ISO 8601) pub expires_at: String } ``` Source line: `83`. ## broker\_client::RevokeTokenPayload [#broker_clientrevoketokenpayload] Request payload for token revocation ```rust #[derive(Debug, Serialize)] pub struct RevokeTokenPayload { /// Token ID to revoke pub token_id: String, /// Reason for revocation #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option } ``` Source line: `100`. ## broker\_client::RevokeTokenResponse [#broker_clientrevoketokenresponse] Response from token revocation ```rust #[derive(Debug, Deserialize)] pub struct RevokeTokenResponse { /// Whether revocation succeeded pub success: bool, /// Message pub message: String } ``` Source line: `110`. ## broker\_client::ApiErrorResponse [#broker_clientapierrorresponse] API error response from broker ```rust #[derive(Debug, Deserialize)] pub struct ApiErrorResponse { /// Error code pub code: u32, /// Error message pub message: String, /// Correlation ID #[serde(default)] pub correlation_id: Option, /// Retry after (seconds) #[serde(default)] pub retry_after: Option } ``` Source line: `119`. ## broker\_client::HealthResponse [#broker_clienthealthresponse] Health check response ```rust #[derive(Debug, Deserialize)] pub struct HealthResponse { /// Service status pub status: String, /// Service version pub version: String } ``` Source line: `134`. ## broker\_client::BrokerClient::new [#broker_clientbrokerclientnew] Create a new broker client # Arguments [#arguments] * `base_url` - Base URL of the broker (e.g., `https://broker.example.com`) * `client` - Preconfigured HTTP client (must include mTLS identity for production) # Errors [#errors] Returns an error if the broker URL is invalid ```rust pub fn new(base_url: impl Into, client: reqwest::Client) -> ArsenalResult; ``` Source line: `150`. ## broker\_client::BrokerClient::with\_timeout [#broker_clientbrokerclientwith_timeout] Create with custom timeout ```rust #[must_use] pub fn with_timeout(mut self, timeout: Duration) -> Self; ``` Source line: `160`. ## broker\_client::BrokerClient::health [#broker_clientbrokerclienthealth] Check broker health # Errors [#errors-1] Returns an error if the health check fails # Returns [#returns] The health response ```rust pub async fn health(&self) -> ArsenalResult; ``` Source line: `172`. ## broker\_client::BrokerClient::request\_capability [#broker_clientbrokerclientrequest_capability] Request a capability token from the broker # Arguments [#arguments-1] * `payload` - The capability request payload # Errors [#errors-2] Returns an error if the request fails or is denied ```rust pub async fn request_capability( &self, payload: CapabilityRequestPayload, ) -> ArsenalResult; ``` Source line: `210`. ## broker\_client::BrokerClient::request\_secret [#broker_clientbrokerclientrequest_secret] Request a secret from the broker # Arguments [#arguments-2] * `payload` - The secret request payload # Errors [#errors-3] Returns an error if the request fails or is denied ```rust pub async fn request_secret( &self, payload: SecretRequestPayload, ) -> ArsenalResult; ``` Source line: `241`. ## broker\_client::BrokerClient::revoke\_token [#broker_clientbrokerclientrevoke_token] Revoke a token # Arguments [#arguments-3] * `token_id` - The token ID to revoke * `reason` - Optional reason for revocation # Errors [#errors-4] Returns an error if revocation fails ```rust pub async fn revoke_token( &self, token_id: &str, reason: Option<&str>, ) -> ArsenalResult; ``` Source line: `273`. ## broker\_client::BrokerClient::proxy\_request [#broker_clientbrokerclientproxy_request] Send a proxy request through the broker. # Arguments [#arguments-4] * `request` - The proxy request * `fingerprint_hex` - Optional hex-encoded fingerprint for chain verification # Errors [#errors-5] Returns an error if the request fails or is rejected. ```rust pub async fn proxy_request( &self, request: arsenal_core::proxy::ProxyRequest, fingerprint_hex: Option<&str>, ) -> ArsenalResult; ``` Source line: `311`. ## broker\_client::BrokerClient::approve\_consent [#broker_clientbrokerclientapprove_consent] Approve a consent request. # Errors [#errors-6] Returns an error if the approval fails. ```rust pub async fn approve_consent( &self, payload: ConsentApprovalPayload, ) -> ArsenalResult; ``` Source line: `385`. ## broker\_client::BrokerClient::list\_consents [#broker_clientbrokerclientlist_consents] List consent records for an agent. # Errors [#errors-7] Returns an error if the request fails. ```rust pub async fn list_consents(&self, agent_did: &str) -> ArsenalResult>; ``` Source line: `413`. ## broker\_client::ProxyRequestPayload [#broker_clientproxyrequestpayload] Request payload for proxy requests ```rust #[derive(Debug, Serialize)] pub struct ProxyRequestPayload { /// HTTP method pub method: String, /// Target URL (may contain `{{VARIABLE}}` placeholders) pub url: String, /// Optional HTTP headers #[serde(skip_serializing_if = "Option::is_none")] pub headers: Option>, /// Optional request body (base64-encoded) #[serde(skip_serializing_if = "Option::is_none")] pub body: Option, /// Capability token authorizing this request pub capability_token: String, /// Optional timeout in milliseconds #[serde(skip_serializing_if = "Option::is_none")] pub timeout_ms: Option } ``` Source line: `489`. ## broker\_client::ProxyResponsePayload [#broker_clientproxyresponsepayload] Response payload from proxy requests ```rust #[derive(Debug, Deserialize)] pub struct ProxyResponsePayload { /// HTTP status code from target API pub status: u16, /// Response headers (sanitized) pub headers: std::collections::BTreeMap, /// Response body (base64-encoded) pub body: String, /// Proxy processing metadata pub proxy_metadata: ProxyMetadataPayload } ``` Source line: `509`. ## broker\_client::ProxyMetadataPayload [#broker_clientproxymetadatapayload] Metadata about proxy processing ```rust #[derive(Debug, Deserialize)] pub struct ProxyMetadataPayload { /// Variable names that were resolved pub variables_resolved: Vec, /// Whether destination binding was verified pub destination_verified: bool, /// Whether agent fingerprint was verified pub fingerprint_verified: bool, /// Consent status pub consent_status: String, /// End-to-end latency in milliseconds pub latency_ms: u64, /// Request ID for audit correlation pub request_id: String } ``` Source line: `522`. ## broker\_client::ConsentApprovalPayload [#broker_clientconsentapprovalpayload] Request payload for consent approval ```rust #[derive(Debug, Serialize)] pub struct ConsentApprovalPayload { /// Agent DID pub agent_did: String, /// Human root DID pub human_root_did: String, /// Variables to authorize pub variables: Vec, /// Destination domains pub destination_domains: Vec, /// Scopes pub scopes: Vec, /// TTL in seconds pub ttl_seconds: u64, /// Ed25519 signature (base64) pub signature: String } ``` Source line: `539`. ## broker\_client::ConsentRecordPayload [#broker_clientconsentrecordpayload] Response payload from consent approval ```rust #[derive(Debug, Deserialize)] pub struct ConsentRecordPayload { /// Consent record ID pub consent_id: String, /// Agent DID pub agent_did: String, /// Granted at timestamp (ISO 8601) pub granted_at: String, /// Expires at timestamp (ISO 8601) pub expires_at: String, /// Variables authorized pub variables: Vec } ``` Source line: `558`. ## broker\_client::ConsentListPayload [#broker_clientconsentlistpayload] Summary payload for consent listing ```rust #[derive(Debug, Deserialize)] pub struct ConsentListPayload { /// List of consent records pub consents: Vec } ``` Source line: `573`. ## broker\_client::decode\_capability\_token [#broker_clientdecode_capability_token] Decode a capability token from the broker response # Arguments [#arguments-5] * `response` - The capability response from the broker # Errors [#errors-8] Returns an error if the token cannot be decoded ```rust pub fn decode_capability_token( response: &CapabilityResponsePayload, ) -> ArsenalResult; ``` Source line: `597`. # arsenal-sdk · capability URL: https://docs.openagent.id/reference/rust/arsenal-sdk/capability Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/capability.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/capability.rs`. SHA-256: `b7881bbba9b47c3c8eff9d4396c08c7615331729b09d6caf7e11c9ffeac6723b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## capability::CapabilityRequest [#capabilitycapabilityrequest] Builder for capability requests ```rust #[derive(Debug)] pub struct CapabilityRequest { } ``` Source line: `18`. ## capability::CapabilityRequest::new [#capabilitycapabilityrequestnew] Create a new capability request ```rust #[must_use] pub fn new() -> Self; ``` Source line: `36`. ## capability::CapabilityRequest::scope [#capabilitycapabilityrequestscope] Add a scope to the request # Errors [#errors] Returns an error if the scope is invalid ```rust pub fn scope(mut self, scope: &str) -> ArsenalResult; ``` Source line: `51`. ## capability::CapabilityRequest::scopes [#capabilitycapabilityrequestscopes] Add multiple scopes # Errors [#errors-1] Returns an error if any scope is invalid ```rust pub fn scopes(mut self, scopes: &[&str]) -> ArsenalResult; ``` Source line: `61`. ## capability::CapabilityRequest::ttl\_seconds [#capabilitycapabilityrequestttl_seconds] Set the TTL ```rust #[must_use] pub fn ttl_seconds(mut self, ttl: i64) -> Self; ``` Source line: `71`. ## capability::CapabilityRequest::audience [#capabilitycapabilityrequestaudience] Set the audience (target service identifier) ```rust #[must_use] pub fn audience(mut self, audience: impl Into) -> Self; ``` Source line: `78`. ## capability::CapabilityRequest::constraints [#capabilitycapabilityrequestconstraints] Set constraints ```rust #[must_use] pub fn constraints(mut self, constraints: Constraints) -> Self; ``` Source line: `85`. ## capability::CapabilityRequest::require\_pop [#capabilitycapabilityrequestrequire_pop] Require proof-of-possession ```rust #[must_use] pub fn require_pop(mut self) -> Self; ``` Source line: `92`. ## capability::CapabilityRequest::rate\_limits [#capabilitycapabilityrequestrate_limits] Set rate limits ```rust #[must_use] pub fn rate_limits(mut self, limits: RateLimits) -> Self; ``` Source line: `100`. ## capability::CapabilityRequest::budget [#capabilitycapabilityrequestbudget] Set usage budget ```rust #[must_use] pub fn budget(mut self, budget: UsageBudget) -> Self; ``` Source line: `107`. ## capability::CapabilityRequest::get\_scopes [#capabilitycapabilityrequestget_scopes] Get the requested scopes ```rust #[must_use] pub fn get_scopes(&self) -> &ScopeSet; ``` Source line: `114`. ## capability::CapabilityRequest::get\_ttl [#capabilitycapabilityrequestget_ttl] Get the requested TTL ```rust #[must_use] pub fn get_ttl(&self) -> i64; ``` Source line: `120`. ## capability::CapabilityRequest::get\_audience [#capabilitycapabilityrequestget_audience] Get the requested audience ```rust #[must_use] pub fn get_audience(&self) -> &str; ``` Source line: `126`. ## capability::CapabilityRequest::constraints\_ref [#capabilitycapabilityrequestconstraints_ref] Get constraints ```rust #[must_use] pub fn constraints_ref(&self) -> Option<&Constraints>; ``` Source line: `132`. ## capability::CapabilityRequest::build\_claims [#capabilitycapabilityrequestbuild_claims] Build token claims (for local use - normally the broker does this) # Errors [#errors-2] Returns an error if the request is invalid ```rust pub fn build_claims( self, agent_did: OasDid, tenant_id: TenantId, issuer: &str, audience: &str, ) -> ArsenalResult; ``` Source line: `140`. ## capability::CapabilityHandle [#capabilitycapabilityhandle] Handle for using a granted capability ```rust pub struct CapabilityHandle { } ``` Source line: `175`. ## capability::CapabilityHandle::new [#capabilitycapabilityhandlenew] Create a new capability handle ```rust #[must_use] pub fn new(token: AgentCapabilityToken) -> Self; ``` Source line: `187`. ## capability::CapabilityHandle::token\_id [#capabilitycapabilityhandletoken_id] Get the token ID ```rust #[must_use] pub fn token_id(&self) -> &TokenId; ``` Source line: `198`. ## capability::CapabilityHandle::token [#capabilitycapabilityhandletoken] Get the token ```rust #[must_use] pub fn token(&self) -> &AgentCapabilityToken; ``` Source line: `204`. ## capability::CapabilityHandle::is\_valid [#capabilitycapabilityhandleis_valid] Check if the capability is valid ```rust pub async fn is_valid(&self) -> bool; ``` Source line: `209`. ## capability::CapabilityHandle::is\_expired [#capabilitycapabilityhandleis_expired] Check if the capability is expired ```rust #[must_use] pub fn is_expired(&self) -> bool; ``` Source line: `215`. ## capability::CapabilityHandle::remaining\_ttl [#capabilitycapabilityhandleremaining_ttl] Get remaining TTL ```rust #[must_use] pub fn remaining_ttl(&self) -> chrono::Duration; ``` Source line: `221`. ## capability::CapabilityHandle::allows\_scope [#capabilitycapabilityhandleallows_scope] Check if a scope is allowed ```rust #[must_use] pub fn allows_scope(&self, scope: &Scope) -> bool; ``` Source line: `227`. ## capability::CapabilityHandle::record\_request [#capabilitycapabilityhandlerecord_request] Record a request (for budget tracking) # Errors [#errors-3] Returns an error if the budget is exceeded ```rust pub fn record_request(&self) -> ArsenalResult<()>; ``` Source line: `235`. ## capability::CapabilityHandle::record\_bytes [#capabilitycapabilityhandlerecord_bytes] Record bytes transferred # Errors [#errors-4] Returns an error if the budget is exceeded ```rust pub fn record_bytes(&self, bytes: u64) -> ArsenalResult<()>; ``` Source line: `243`. ## capability::CapabilityHandle::record\_cost [#capabilitycapabilityhandlerecord_cost] Record cost units # Errors [#errors-5] Returns an error if the budget is exceeded ```rust pub fn record_cost(&self, units: u64) -> ArsenalResult<()>; ``` Source line: `251`. ## capability::CapabilityHandle::usage\_stats [#capabilitycapabilityhandleusage_stats] Get usage statistics ```rust #[must_use] pub fn usage_stats(&self) -> arsenal_core::limits::UsageStats; ``` Source line: `257`. ## capability::CapabilityHandle::remaining\_budget [#capabilitycapabilityhandleremaining_budget] Get remaining budget ```rust #[must_use] pub fn remaining_budget(&self) -> arsenal_core::limits::RemainingBudget; ``` Source line: `263`. ## capability::CapabilityHandle::revoke [#capabilitycapabilityhandlerevoke] Revoke this capability ```rust pub async fn revoke(&self); ``` Source line: `268`. ## capability::CapabilityValidator [#capabilitycapabilityvalidator] Capability validator for checking requests ```rust pub struct CapabilityValidator { } ``` Source line: `284`. ## capability::CapabilityValidator::new [#capabilitycapabilityvalidatornew] Create a new validator ```rust #[must_use] pub fn new() -> Self; ``` Source line: `296`. ## capability::CapabilityValidator::with\_allowed\_scopes [#capabilitycapabilityvalidatorwith_allowed_scopes] Set allowed scopes ```rust #[must_use] pub fn with_allowed_scopes(mut self, scopes: ScopeSet) -> Self; ``` Source line: `306`. ## capability::CapabilityValidator::with\_max\_ttl [#capabilitycapabilityvalidatorwith_max_ttl] Set maximum TTL ```rust #[must_use] pub fn with_max_ttl(mut self, seconds: i64) -> Self; ``` Source line: `313`. ## capability::CapabilityValidator::require\_pop [#capabilitycapabilityvalidatorrequire_pop] Require proof-of-possession ```rust #[must_use] pub fn require_pop(mut self) -> Self; ``` Source line: `320`. ## capability::CapabilityValidator::validate [#capabilitycapabilityvalidatorvalidate] Validate a capability request # Errors [#errors-6] Returns an error if the request is invalid ```rust pub fn validate(&self, request: &CapabilityRequest) -> ArsenalResult<()>; ``` Source line: `329`. # arsenal-sdk · client URL: https://docs.openagent.id/reference/rust/arsenal-sdk/client Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/client.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/client.rs`. SHA-256: `777c7783f6c127277d54e40c822d1b5b3916608a3306affde415af33ac66626c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client::ArsenalClient [#clientarsenalclient] Arsenal client for agent key management ```rust pub struct ArsenalClient { } ``` Source line: `26`. ## client::ClientConfig [#clientclientconfig] Client configuration ```rust #[derive(Debug, Clone)] pub struct ClientConfig { /// Broker URL (for remote broker) pub broker_url: Option, /// Broker TLS configuration (required when `broker_url` is set) pub broker_tls: Option, /// Session configuration pub session_config: SessionConfig, /// Auto-renew tokens pub auto_renew: bool, /// Issuer pub issuer: String, /// Default audience for broker-issued tokens pub default_audience: String } ``` Source line: `45`. ## client::BrokerTlsConfig [#clientbrokertlsconfig] Broker TLS configuration for mTLS + custom trust roots. ```rust #[derive(Debug, Clone)] pub struct BrokerTlsConfig { /// PEM-encoded client certificate chain pub client_cert_path: PathBuf, /// PEM-encoded client private key pub client_key_path: PathBuf, /// Optional PEM-encoded CA certificate to trust for the broker server pub ca_cert_path: Option } ``` Source line: `62`. ## client::ArsenalClientBuilder [#clientarsenalclientbuilder] Builder for Arsenal client ```rust pub struct ArsenalClientBuilder { } ``` Source line: `85`. ## client::ArsenalClientBuilder::new [#clientarsenalclientbuildernew] Create a new Arsenal client builder # Returns [#returns] A new Arsenal client builder ```rust #[must_use] pub fn new() -> Self; ``` Source line: `96`. ## client::ArsenalClientBuilder::identity [#clientarsenalclientbuilderidentity] Set the agent identity # Parameters [#parameters] * `identity` - The agent identity # Returns [#returns-1] A new Arsenal client builder ```rust #[must_use] pub fn identity(mut self, identity: AgentIdentityLoader) -> Self; ``` Source line: `111`. ## client::ArsenalClientBuilder::broker\_url [#clientarsenalclientbuilderbroker_url] Set the broker URL # Parameters [#parameters-1] * `url` - The broker URL # Returns [#returns-2] A new Arsenal client builder ```rust #[must_use] pub fn broker_url(mut self, url: impl Into) -> Self; ``` Source line: `124`. ## client::ArsenalClientBuilder::broker\_mtls [#clientarsenalclientbuilderbroker_mtls] Configure mTLS for broker communication (required when using a broker). ```rust #[must_use] pub fn broker_mtls( mut self, client_cert_path: impl Into, client_key_path: impl Into, ) -> Self; ``` Source line: `131`. ## client::ArsenalClientBuilder::broker\_ca\_cert\_path [#clientarsenalclientbuilderbroker_ca_cert_path] Configure a custom CA bundle for broker server validation. ```rust #[must_use] pub fn broker_ca_cert_path(mut self, ca_cert_path: impl Into) -> Self; ``` Source line: `153`. ## client::ArsenalClientBuilder::default\_audience [#clientarsenalclientbuilderdefault_audience] Set the default audience for broker-issued tokens. ```rust #[must_use] pub fn default_audience(mut self, audience: impl Into) -> Self; ``` Source line: `169`. ## client::ArsenalClientBuilder::session\_config [#clientarsenalclientbuildersession_config] Set session configuration # Parameters [#parameters-2] * `config` - The session configuration # Returns [#returns-3] A new Arsenal client builder ```rust #[must_use] pub fn session_config(mut self, config: SessionConfig) -> Self; ``` Source line: `182`. ## client::ArsenalClientBuilder::auto\_renew [#clientarsenalclientbuilderauto_renew] Set auto-renew # Parameters [#parameters-3] * `auto_renew` - Whether to auto-renew tokens # Returns [#returns-4] A new Arsenal client builder ```rust #[must_use] pub fn auto_renew(mut self, auto_renew: bool) -> Self; ``` Source line: `195`. ## client::ArsenalClientBuilder::issuer [#clientarsenalclientbuilderissuer] Set issuer # Parameters [#parameters-4] * `issuer` - The issuer # Returns [#returns-5] A new Arsenal client builder ```rust #[must_use] pub fn issuer(mut self, issuer: impl Into) -> Self; ``` Source line: `208`. ## client::ArsenalClientBuilder::build [#clientarsenalclientbuilderbuild] Build the client # Errors [#errors] Returns an error if identity is not set # Returns [#returns-6] The Arsenal client ```rust pub fn build(self) -> ArsenalResult; ``` Source line: `220`. ## client::ArsenalClient::builder [#clientarsenalclientbuilder-1] Create a new Arsenal client builder # Returns [#returns-7] A new Arsenal client builder ```rust #[must_use] pub fn builder() -> ArsenalClientBuilder; ``` Source line: `319`. ## client::ArsenalClient::identity [#clientarsenalclientidentity] Get the agent identity # Returns [#returns-8] The agent identity ```rust #[must_use] pub fn identity(&self) -> &AgentIdentityLoader; ``` Source line: `328`. ## client::ArsenalClient::tenant\_id [#clientarsenalclienttenant_id] Get the tenant ID # Returns [#returns-9] The tenant ID ```rust #[must_use] pub fn tenant_id(&self) -> &TenantId; ``` Source line: `337`. ## client::ArsenalClient::start\_session [#clientarsenalclientstart_session] Start a new session # Errors [#errors-1] Returns an error if session creation fails # Returns [#returns-10] The session ID ```rust pub async fn start_session(&self) -> ArsenalResult; ``` Source line: `348`. ## client::ArsenalClient::session\_id [#clientarsenalclientsession_id] Get current session ID # Errors [#errors-2] Returns an error if no session is active # Returns [#returns-11] The session ID ```rust pub async fn session_id(&self) -> ArsenalResult; ``` Source line: `359`. ## client::ArsenalClient::has\_active\_session [#clientarsenalclienthas_active_session] Check if a session is active # Returns [#returns-12] Whether a session is active ```rust pub async fn has_active_session(&self) -> bool; ``` Source line: `367`. ## client::ArsenalClient::session\_stats [#clientarsenalclientsession_stats] Get session statistics # Returns [#returns-13] The session statistics ```rust pub async fn session_stats(&self) -> SessionStats; ``` Source line: `375`. ## client::ArsenalClient::request\_capability [#clientarsenalclientrequest_capability] Request a capability # Errors [#errors-3] Returns an error if the request fails # Returns [#returns-14] The capability handle ```rust pub async fn request_capability( &self, request: CapabilityRequest, ) -> ArsenalResult; ``` Source line: `386`. ## client::ArsenalClient::request\_capability\_for\_scopes [#clientarsenalclientrequest_capability_for_scopes] Request a capability with scope strings # Errors [#errors-4] Returns an error if the request fails # Parameters [#parameters-5] * `scopes` - The scopes * `ttl_seconds` - The TTL in seconds # Returns [#returns-15] The capability handle ```rust pub async fn request_capability_for_scopes( &self, scopes: &[&str], ttl_seconds: i64, ) -> ArsenalResult; ``` Source line: `485`. ## client::ArsenalClient::current\_token [#clientarsenalclientcurrent_token] Get current capability token # Returns [#returns-16] The current capability token ```rust pub async fn current_token(&self) -> Option; ``` Source line: `501`. ## client::ArsenalClient::register\_tool [#clientarsenalclientregister_tool] Register a tool # Parameters [#parameters-6] * `tool` - The tool to register ```rust pub fn register_tool(&mut self, tool: Arc); ``` Source line: `509`. ## client::ArsenalClient::call\_tool [#clientarsenalclientcall_tool] Call a tool # Errors [#errors-5] Returns an error if the call fails # Parameters [#parameters-7] * `request` - The tool call request # Returns [#returns-17] The tool call response ```rust pub async fn call_tool( &mut self, request: &ToolCallRequest, ) -> ArsenalResult; ``` Source line: `523`. ## client::ArsenalClient::unwrap\_secret\_response [#clientarsenalclientunwrap_secret_response] Unwrap a broker-wrapped secret using this agent's encryption key. The broker encrypts secrets to the agent's derived X25519 public key and includes an ephemeral public key for DH key agreement. This helper performs the full decrypt locally. # Errors [#errors-6] Returns an error if decoding or decryption fails. ```rust pub fn unwrap_secret_response( &self, wrapped: &SecretResponsePayload, ) -> ArsenalResult>; ``` Source line: `554`. ## client::ArsenalClient::call\_tool\_simple [#clientarsenalclientcall_tool_simple] Call a tool with simple interface # Errors [#errors-7] Returns an error if the call fails ```rust pub async fn call_tool_simple( &mut self, tool_id: &str, method: &str, params: serde_json::Value, ) -> ArsenalResult; ``` Source line: `645`. ## client::ArsenalClient::proxy\_http [#clientarsenalclientproxy_http] Send a proxy request through the broker's credential proxy. The proxy resolves `{{VARIABLE}}` placeholders server-side, so agents never see raw credentials. Requires a valid capability token with appropriate proxy scopes. # Errors [#errors-8] Returns an error if no proxy client is configured, the request is invalid, or the broker rejects it. ```rust pub async fn proxy_http( &self, request: arsenal_core::proxy::ProxyRequest, ) -> ArsenalResult; ``` Source line: `675`. ## client::ArsenalClient::proxy\_client [#clientarsenalclientproxy_client] Get a reference to the proxy client (if configured). ```rust #[must_use] pub fn proxy_client(&self) -> Option<&Arc>; ``` Source line: `691`. ## client::ArsenalClient::approve\_consent [#clientarsenalclientapprove_consent] Approve a consent request for credential access. # Errors [#errors-9] Returns an error if no broker is configured or the approval fails. ```rust pub async fn approve_consent( &self, payload: ConsentApprovalPayload, ) -> ArsenalResult; ``` Source line: `699`. ## client::ArsenalClient::list\_consents [#clientarsenalclientlist_consents] List consent records for this agent. # Errors [#errors-10] Returns an error if no broker is configured or the request fails. ```rust pub async fn list_consents(&self) -> ArsenalResult>; ``` Source line: `717`. ## client::ArsenalClient::end\_session [#clientarsenalclientend_session] End the current session # Errors [#errors-11] Returns an error if ending fails ```rust pub async fn end_session(&self) -> ArsenalResult<()>; ``` Source line: `733`. ## client::ArsenalClient::revoke\_session [#clientarsenalclientrevoke_session] Revoke the current session ```rust pub async fn revoke_session(&self); ``` Source line: `738`. # arsenal-sdk · crate URL: https://docs.openagent.id/reference/rust/arsenal-sdk/crate Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/crate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/lib.rs`. SHA-256: `bf2efb4b5fed418cbe33f6e12e01871a7227603aed6223a69a5ca287e797d37e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## broker\_client [#broker_client] ```rust pub mod broker_client; ``` Source line: `43`. ## capability [#capability] ```rust pub mod capability; ``` Source line: `44`. ## client [#client] ```rust pub mod client; ``` Source line: `45`. ## identity\_loader [#identity_loader] ```rust pub mod identity_loader; ``` Source line: `46`. ## proxy\_client [#proxy_client] ```rust pub mod proxy_client; ``` Source line: `47`. ## session\_manager [#session_manager] ```rust pub mod session_manager; ``` Source line: `48`. ## tool\_caller [#tool_caller] ```rust pub mod tool_caller; ``` Source line: `49`. ## pub use broker\_client::BrokerClient; [#pub-use-broker_clientbrokerclient] ```rust pub use broker_client::BrokerClient; ``` Source line: `51`. ## pub use capability::\{CapabilityHandle, CapabilityRequest}; [#pub-use-capabilitycapabilityhandle-capabilityrequest] ```rust pub use capability::{CapabilityHandle, CapabilityRequest}; ``` Source line: `52`. ## pub use client::\{ArsenalClient, ArsenalClientBuilder}; [#pub-use-clientarsenalclient-arsenalclientbuilder] ```rust pub use client::{ArsenalClient, ArsenalClientBuilder}; ``` Source line: `53`. ## pub use identity\_loader::AgentIdentityLoader; [#pub-use-identity_loaderagentidentityloader] ```rust pub use identity_loader::AgentIdentityLoader; ``` Source line: `54`. ## pub use proxy\_client::ProxyClient; [#pub-use-proxy_clientproxyclient] ```rust pub use proxy_client::ProxyClient; ``` Source line: `55`. ## pub use session\_manager::SessionManager; [#pub-use-session_managersessionmanager] ```rust pub use session_manager::SessionManager; ``` Source line: `56`. ## pub use tool\_caller::\{Tool, ToolCallRequest, ToolCallResponse, ToolCaller}; [#pub-use-tool_callertool-toolcallrequest-toolcallresponse-toolcaller] ```rust pub use tool_caller::{Tool, ToolCallRequest, ToolCallResponse, ToolCaller}; ``` Source line: `57`. ## prelude [#prelude] Re-export common types ```rust pub mod prelude; ``` Source line: `60`. ## pub use super::capability::\{CapabilityHandle, CapabilityRequest}; [#pub-use-supercapabilitycapabilityhandle-capabilityrequest] ```rust pub use super::capability::{CapabilityHandle, CapabilityRequest}; ``` Source line: `61`. ## pub use super::client::\{ArsenalClient, ArsenalClientBuilder}; [#pub-use-superclientarsenalclient-arsenalclientbuilder] ```rust pub use super::client::{ArsenalClient, ArsenalClientBuilder}; ``` Source line: `62`. ## pub use super::identity\_loader::AgentIdentityLoader; [#pub-use-superidentity_loaderagentidentityloader] ```rust pub use super::identity_loader::AgentIdentityLoader; ``` Source line: `63`. ## pub use super::proxy\_client::ProxyClient; [#pub-use-superproxy_clientproxyclient] ```rust pub use super::proxy_client::ProxyClient; ``` Source line: `64`. ## pub use super::session\_manager::SessionManager; [#pub-use-supersession_managersessionmanager] ```rust pub use super::session_manager::SessionManager; ``` Source line: `65`. ## pub use arsenal\_core::prelude::\*; [#pub-use-arsenal_coreprelude] ```rust pub use arsenal_core::prelude::*; ``` Source line: `68`. # arsenal-sdk · identity_loader URL: https://docs.openagent.id/reference/rust/arsenal-sdk/identity_loader Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/identity_loader.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/identity_loader.rs`. SHA-256: `882083d9db10928df481928cbebf1f27555436a15f8e30f00f5977c265cdefcb`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## identity\_loader::AgentIdentityLoader [#identity_loaderagentidentityloader] Loaded agent identity with signing capability ```rust pub struct AgentIdentityLoader { } ``` Source line: `15`. ## identity\_loader::AgentIdentityLoader::generate [#identity_loaderagentidentityloadergenerate] Create a new agent identity with a fresh key pair `did` is the agent's OAS DID, issued by OAS genesis. This loader mints key material, not identity: a DID must already exist for the agent whose keys these are. # Errors [#errors] Returns an error if key generation fails, or if `did` is not of entity kind `agent`. ```rust pub fn generate( did: OasDid, tenant_id: TenantId, name: impl Into, ) -> ArsenalResult; ``` Source line: `43`. ## identity\_loader::AgentIdentityLoader::from\_seed\_file [#identity_loaderagentidentityloaderfrom_seed_file] Load from a seed file The file should contain 32 bytes of seed material. # Errors [#errors-1] Returns an error if the file cannot be read or the seed is invalid ```rust pub async fn from_seed_file( path: impl AsRef, did: OasDid, tenant_id: TenantId, name: impl Into, ) -> ArsenalResult; ``` Source line: `79`. ## identity\_loader::AgentIdentityLoader::from\_env [#identity_loaderagentidentityloaderfrom_env] Load from environment variable The environment variable should contain hex-encoded 32-byte seed. # Errors [#errors-2] Returns an error if the environment variable is not set or invalid ```rust pub fn from_env( env_var: &str, did: OasDid, tenant_id: TenantId, name: impl Into, ) -> ArsenalResult; ``` Source line: `140`. ## identity\_loader::AgentIdentityLoader::identity [#identity_loaderagentidentityloaderidentity] Get the agent identity ```rust #[must_use] pub fn identity(&self) -> &AgentIdentity; ``` Source line: `200`. ## identity\_loader::AgentIdentityLoader::fingerprint [#identity_loaderagentidentityloaderfingerprint] Get the public key fingerprint ```rust #[must_use] pub fn fingerprint(&self) -> KeyFingerprint; ``` Source line: `206`. ## identity\_loader::AgentIdentityLoader::public\_key\_bytes [#identity_loaderagentidentityloaderpublic_key_bytes] Get the public key bytes ```rust #[must_use] pub fn public_key_bytes(&self) -> [u8; 32]; ``` Source line: `212`. ## identity\_loader::AgentIdentityLoader::encryption\_public\_key\_bytes [#identity_loaderagentidentityloaderencryption_public_key_bytes] Get the encryption public key bytes (X25519) ```rust #[must_use] pub fn encryption_public_key_bytes(&self) -> [u8; 32]; ``` Source line: `218`. ## identity\_loader::AgentIdentityLoader::encryption\_key\_pair [#identity_loaderagentidentityloaderencryption_key_pair] Get the encryption key pair (X25519) ```rust #[must_use] pub fn encryption_key_pair(&self) -> &EncryptionKeyPair; ``` Source line: `224`. ## identity\_loader::AgentIdentityLoader::sign [#identity_loaderagentidentityloadersign] Sign a message ```rust #[must_use] pub fn sign(&self, message: &[u8]) -> [u8; 64]; ``` Source line: `230`. ## identity\_loader::AgentIdentityLoader::export\_seed [#identity_loaderagentidentityloaderexport_seed] Export the seed for backup (handle with extreme care!) This returns the private key material. ```rust #[must_use] pub fn export_seed(&self) -> [u8; 32]; ``` Source line: `238`. ## identity\_loader::AgentIdentityLoader::save\_seed [#identity_loaderagentidentityloadersave_seed] Save the seed to a file # Errors [#errors-3] Returns an error if the file cannot be written ```rust pub async fn save_seed(&self, path: impl AsRef) -> ArsenalResult<()>; ``` Source line: `246`. # arsenal-sdk modules URL: https://docs.openagent.id/reference/rust/arsenal-sdk Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/arsenal-crates-arsenal-sdk). [Focused integration guide](/arsenal/overview). ## Modules [#modules] * [crate](/reference/rust/arsenal-sdk/crate) — 21 declarations * [broker\_client](/reference/rust/arsenal-sdk/broker_client) — 26 declarations * [capability](/reference/rust/arsenal-sdk/capability) — 35 declarations * [client](/reference/rust/arsenal-sdk/client) — 34 declarations * [identity\_loader](/reference/rust/arsenal-sdk/identity_loader) — 12 declarations * [proxy\_client](/reference/rust/arsenal-sdk/proxy_client) — 7 declarations * [session\_manager](/reference/rust/arsenal-sdk/session_manager) — 18 declarations * [tool\_caller](/reference/rust/arsenal-sdk/tool_caller) — 18 declarations # arsenal-sdk · proxy_client URL: https://docs.openagent.id/reference/rust/arsenal-sdk/proxy_client Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/proxy_client.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/proxy_client.rs`. SHA-256: `853d49b5c3ae77fd8c4c12fbab3a36a6eacaecc65a611e6de85fd3e4b1577b83`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proxy\_client::ProxyClient [#proxy_clientproxyclient] Client-side proxy integration with automatic fingerprint management. ```rust pub struct ProxyClient { } ``` Source line: `38`. ## proxy\_client::ProxyClient::new [#proxy_clientproxyclientnew] Create a new proxy client. ```rust #[must_use] pub fn new(broker_client: Arc) -> Self; ``` Source line: `50`. ## proxy\_client::ProxyClient::with\_persistence [#proxy_clientproxyclientwith_persistence] Create a new proxy client with fingerprint persistence. ```rust #[must_use] pub fn with_persistence(broker_client: Arc, path: PathBuf) -> Self; ``` Source line: `60`. ## proxy\_client::ProxyClient::init\_fingerprint [#proxy_clientproxyclientinit_fingerprint] Initialize fingerprint state for an agent. This should be called once when the agent starts. If a persistence path was configured and a saved state exists, it will be loaded instead of creating a new chain. # Errors [#errors] Returns an error if loading persisted state fails. ```rust pub async fn init_fingerprint(&self, agent_did: &str) -> ArsenalResult<()>; ``` Source line: `77`. ## proxy\_client::ProxyClient::proxy\_request [#proxy_clientproxyclientproxy_request] Send a proxy request through the broker. Automatically attaches the current fingerprint and advances the chain on success. # Errors [#errors-1] Returns an error if the proxy request fails or the broker rejects it. ```rust pub async fn proxy_request(&self, request: ProxyRequest) -> ArsenalResult; ``` Source line: `108`. ## proxy\_client::ProxyClient::fingerprint\_sequence [#proxy_clientproxyclientfingerprint_sequence] Get the current fingerprint state sequence number. ```rust pub async fn fingerprint_sequence(&self) -> Option; ``` Source line: `148`. ## proxy\_client::ProxyClient::save\_fingerprint\_state [#proxy_clientproxyclientsave_fingerprint_state] Save fingerprint state to disk (if persistence path is configured). # Errors [#errors-2] Returns an error if serialization or file write fails. ```rust pub async fn save_fingerprint_state(&self) -> ArsenalResult<()>; ``` Source line: `158`. # arsenal-sdk · session_manager URL: https://docs.openagent.id/reference/rust/arsenal-sdk/session_manager Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/session_manager.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/session_manager.rs`. SHA-256: `2689b01839e16765db0e6c17b6ef8bb0e4624fb3816e56a4104578b0d5576e2c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session\_manager::SessionManager [#session_managersessionmanager] Session manager for handling agent sessions ```rust pub struct SessionManager { } ``` Source line: `18`. ## session\_manager::SessionConfig [#session_managersessionconfig] Session configuration ```rust #[derive(Debug, Clone)] pub struct SessionConfig { /// Default session TTL in seconds pub session_ttl_seconds: u64, /// Token TTL in seconds pub token_ttl_seconds: i64, /// Renewal threshold in permille (renew when this fraction of TTL remains). /// /// Example: `200` = renew when 20% of TTL remains. pub renewal_threshold_permille: u16, /// Maximum renewal attempts pub max_renewal_attempts: u32, /// Renewal backoff base in milliseconds pub renewal_backoff_ms: u64 } ``` Source line: `43`. ## session\_manager::SessionManager::new [#session_managersessionmanagernew] Create a new session manager ```rust #[must_use] pub fn new(identity: Arc, config: SessionConfig) -> Self; ``` Source line: `73`. ## session\_manager::SessionManager::with\_defaults [#session_managersessionmanagerwith_defaults] Create with default configuration ```rust #[must_use] pub fn with_defaults(identity: Arc) -> Self; ``` Source line: `83`. ## session\_manager::SessionManager::start\_session [#session_managersessionmanagerstart_session] Start a new session # Errors [#errors] Returns an error if session creation fails ```rust pub async fn start_session(&self) -> ArsenalResult; ``` Source line: `91`. ## session\_manager::SessionManager::session\_id [#session_managersessionmanagersession_id] Get the current session ID # Errors [#errors-1] Returns an error if no session is active ```rust pub async fn session_id(&self) -> ArsenalResult; ``` Source line: `132`. ## session\_manager::SessionManager::has\_active\_session [#session_managersessionmanagerhas_active_session] Check if a session is active ```rust pub async fn has_active_session(&self) -> bool; ``` Source line: `141`. ## session\_manager::SessionManager::session\_state [#session_managersessionmanagersession_state] Get session state ```rust pub async fn session_state(&self) -> Option; ``` Source line: `149`. ## session\_manager::SessionManager::record\_activity [#session_managersessionmanagerrecord_activity] Record activity (updates last activity time) ```rust pub async fn record_activity(&self); ``` Source line: `155`. ## session\_manager::SessionManager::set\_current\_token [#session_managersessionmanagerset_current_token] Set the current capability token # Errors [#errors-2] Returns an error if no session is active ```rust pub async fn set_current_token(&self, token: AgentCapabilityToken) -> ArsenalResult<()>; ``` Source line: `167`. ## session\_manager::SessionManager::current\_token [#session_managersessionmanagercurrent_token] Get the current capability token ```rust pub async fn current_token(&self) -> Option; ``` Source line: `187`. ## session\_manager::SessionManager::needs\_token\_renewal [#session_managersessionmanagerneeds_token_renewal] Check if the current token needs renewal ```rust pub async fn needs_token_renewal(&self) -> bool; ``` Source line: `193`. ## session\_manager::SessionManager::needs\_session\_renewal [#session_managersessionmanagerneeds_session_renewal] Check if the session needs renewal ```rust pub async fn needs_session_renewal(&self) -> bool; ``` Source line: `212`. ## session\_manager::SessionManager::sign\_with\_session\_key [#session_managersessionmanagersign_with_session_key] Sign a message with the session key (for `PoP`) # Errors [#errors-3] Returns an error if no session is active ```rust pub async fn sign_with_session_key(&self, message: &[u8]) -> ArsenalResult<[u8; 64]>; ``` Source line: `231`. ## session\_manager::SessionManager::end\_session [#session_managersessionmanagerend_session] End the current session # Errors [#errors-4] Returns an error if ending fails ```rust pub async fn end_session(&self) -> ArsenalResult<()>; ``` Source line: `244`. ## session\_manager::SessionManager::revoke\_session [#session_managersessionmanagerrevoke_session] Revoke the current session (immediate termination) ```rust pub async fn revoke_session(&self); ``` Source line: `257`. ## session\_manager::SessionManager::stats [#session_managersessionmanagerstats] Get session statistics ```rust pub async fn stats(&self) -> SessionStats; ``` Source line: `269`. ## session\_manager::SessionStats [#session_managersessionstats] Session statistics ```rust #[derive(Debug, Clone)] pub struct SessionStats { /// Current session ID pub session_id: Option, /// Session state pub state: SessionState, /// Number of active tokens pub active_tokens: u64, /// Session age in seconds pub session_age_secs: u64, /// Seconds since last activity pub idle_secs: u64, /// Whether there's a valid token pub has_valid_token: bool } ``` Source line: `291`. # arsenal-sdk · tool_caller URL: https://docs.openagent.id/reference/rust/arsenal-sdk/tool_caller Markdown: https://docs.openagent.id/reference/rust/arsenal-sdk/tool_caller.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-sdk/src/tool_caller.rs`. SHA-256: `20def8c456e3c475caa03ec679b3be2c1055286604feb2c92095814f67a34d10`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## tool\_caller::Tool [#tool_callertool] Tool trait for implementing callable tools ```rust pub trait Tool: Send + Sync { /// Get the tool's unique identifier fn id(&self) -> &str; /// Get the tool's description fn description(&self) -> &str; /// Get the required scope pattern for this tool fn required_scope(&self) -> &str; /// Get available methods fn methods(&self) -> &[&str]; /// Execute a method on this tool /// /// # Errors /// Returns an error if the method is not found or execution fails fn execute(&self, method: &str, params: serde_json::Value) -> ArsenalResult; } ``` Source line: `16`. ## tool\_caller::ToolCallRequest [#tool_callertoolcallrequest] Request to call a tool ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ToolCallRequest { /// Tool identifier pub tool_id: String, /// Method to call pub method: String, /// Parameters pub params: serde_json::Value, /// Request ID for tracing pub request_id: Option } ``` Source line: `38`. ## tool\_caller::ToolCallRequest::new [#tool_callertoolcallrequestnew] Create a new tool call request ```rust #[must_use] pub fn new(tool_id: impl Into, method: impl Into) -> Self; ``` Source line: `52`. ## tool\_caller::ToolCallRequest::with\_params [#tool_callertoolcallrequestwith_params] Set parameters ```rust #[must_use] pub fn with_params(mut self, params: serde_json::Value) -> Self; ``` Source line: `63`. ## tool\_caller::ToolCallRequest::with\_request\_id [#tool_callertoolcallrequestwith_request_id] Set request ID ```rust #[must_use] pub fn with_request_id(mut self, request_id: impl Into) -> Self; ``` Source line: `70`. ## tool\_caller::ToolCallResponse [#tool_callertoolcallresponse] Response from a tool call ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ToolCallResponse { /// Whether the call succeeded pub success: bool, /// Response data pub data: serde_json::Value, /// Error message if failed pub error: Option, /// Request ID if provided pub request_id: Option } ``` Source line: `78`. ## tool\_caller::ToolCallResponse::success [#tool_callertoolcallresponsesuccess] Create a successful response ```rust #[must_use] pub fn success(data: serde_json::Value) -> Self; ``` Source line: `92`. ## tool\_caller::ToolCallResponse::error [#tool_callertoolcallresponseerror] Create an error response ```rust #[must_use] pub fn error(message: impl Into) -> Self; ``` Source line: `103`. ## tool\_caller::ToolCallResponse::with\_request\_id [#tool_callertoolcallresponsewith_request_id] Set request ID ```rust #[must_use] pub fn with_request_id(mut self, request_id: impl Into) -> Self; ``` Source line: `114`. ## tool\_caller::ToolCaller [#tool_callertoolcaller] Tool caller for invoking tools with capability checking ```rust pub struct ToolCaller { } ``` Source line: `121`. ## tool\_caller::ToolCaller::new [#tool_callertoolcallernew] Create a new tool caller ```rust #[must_use] pub fn new() -> Self; ``` Source line: `131`. ## tool\_caller::ToolCaller::register\_tool [#tool_callertoolcallerregister_tool] Register a tool ```rust pub fn register_tool(&mut self, tool: Arc); ``` Source line: `139`. ## tool\_caller::ToolCaller::unregister\_tool [#tool_callertoolcallerunregister_tool] Unregister a tool ```rust pub fn unregister_tool(&mut self, tool_id: &str); ``` Source line: `144`. ## tool\_caller::ToolCaller::get\_tool [#tool_callertoolcallerget_tool] Get a registered tool ```rust #[must_use] pub fn get_tool(&self, tool_id: &str) -> Option>; ``` Source line: `150`. ## tool\_caller::ToolCaller::tool\_ids [#tool_callertoolcallertool_ids] List registered tool IDs ```rust #[must_use] pub fn tool_ids(&self) -> Vec; ``` Source line: `156`. ## tool\_caller::ToolCaller::set\_capability [#tool_callertoolcallerset_capability] Set the current capability ```rust pub fn set_capability(&mut self, capability: Arc); ``` Source line: `161`. ## tool\_caller::ToolCaller::clear\_capability [#tool_callertoolcallerclear_capability] Clear the current capability ```rust pub fn clear_capability(&mut self); ``` Source line: `166`. ## tool\_caller::ToolCaller::call [#tool_callertoolcallercall] Call a tool # Errors [#errors] Returns an error if the tool is not found, capability is missing, or the call fails ```rust pub fn call(&self, request: &ToolCallRequest) -> ArsenalResult; ``` Source line: `175`. # arsenal-broker · audit_sink URL: https://docs.openagent.id/reference/rust/arsenal-broker/audit_sink Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/audit_sink.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/audit_sink.rs`. SHA-256: `eadf9c8a5735b18817d1a2389c227dd0ae30fc7a73e5869a3039aedb3b1c3e75`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit\_sink::AuditSinkResult [#audit_sinkauditsinkresult] Result type for audit sink operations ```rust pub type AuditSinkResult = Result; ``` Source line: `19`. ## audit\_sink::AuditSinkError [#audit_sinkauditsinkerror] Errors from audit sinks ```rust #[derive(Debug, thiserror::Error)] pub enum AuditSinkError { /// I/O error #[error("I/O error: {0}")] IoError(#[from] std::io::Error), /// Serialization error #[error("Serialization error: {0}")] SerializationError(String), /// Connection error #[error("Connection error: {0}")] ConnectionError(String), /// Sink is closed #[error("Sink is closed")] Closed, /// Buffer overflow #[error("Buffer overflow")] BufferOverflow, } ``` Source line: `23`. ## audit\_sink::AuditSink [#audit_sinkauditsink] Trait for audit event sinks (object-safe version) ```rust pub trait AuditSink: Send + Sync { /// Emit an audit event fn emit(&self, event: AuditEvent) -> BoxFuture<'_, AuditSinkResult<()>>; /// Flush any buffered events fn flush(&self) -> BoxFuture<'_, AuditSinkResult<()>>; /// Close the sink fn close(&self) -> BoxFuture<'_, AuditSinkResult<()>>; } ``` Source line: `49`. ## audit\_sink::NoOpAuditSink [#audit_sinknoopauditsink] No-op audit sink (for testing or when auditing is disabled) ```rust pub struct NoOpAuditSink; ``` Source line: `61`. ## audit\_sink::TracingAuditSink [#audit_sinktracingauditsink] Tracing-based audit sink (logs to tracing framework) ```rust pub struct TracingAuditSink { } ``` Source line: `78`. ## audit\_sink::TracingAuditSink::new [#audit_sinktracingauditsinknew] Create a new tracing audit sink # Returns [#returns] A new tracing audit sink ```rust #[must_use] pub fn new() -> Self; ``` Source line: `88`. ## audit\_sink::TracingAuditSink::with\_full\_event [#audit_sinktracingauditsinkwith_full_event] Enable full event logging ```rust #[must_use] pub fn with_full_event(mut self) -> Self; ``` Source line: `96`. ## audit\_sink::FileAuditSink [#audit_sinkfileauditsink] File-based audit sink with append-only logging ```rust pub struct FileAuditSink { } ``` Source line: `148`. ## audit\_sink::FileAuditSink::new [#audit_sinkfileauditsinknew] Create a new file audit sink # Parameters [#parameters] * `path` - The path to the audit log file # Errors [#errors] Returns an error if the log file cannot be created or opened. # Returns [#returns-1] A new file audit sink ```rust pub fn new(path: impl AsRef) -> Result; ``` Source line: `169`. ## audit\_sink::FileAuditSink::with\_buffer\_size [#audit_sinkfileauditsinkwith_buffer_size] Set the buffer size for the file audit sink # Parameters [#parameters-1] * `size` - The buffer size # Returns [#returns-2] A new file audit sink ```rust #[must_use] pub fn with_buffer_size(mut self, size: usize) -> Self; ``` Source line: `198`. ## audit\_sink::FileAuditSink::without\_hash\_chain [#audit_sinkfileauditsinkwithout_hash_chain] Disable hash chain for the file audit sink # Returns [#returns-3] A new file audit sink ```rust #[must_use] pub fn without_hash_chain(mut self) -> Self; ``` Source line: `208`. ## audit\_sink::FileAuditSink::rotate [#audit_sinkfileauditsinkrotate] Rotate the audit log file # Errors [#errors-1] Returns an error if the file cannot be flushed, renamed, or recreated. # Returns [#returns-4] The path to the rotated audit log file ```rust pub async fn rotate(&self) -> Result; ``` Source line: `221`. ## audit\_sink::CompositeAuditSink [#audit_sinkcompositeauditsink] Composite audit sink that writes to multiple sinks ```rust pub struct CompositeAuditSink { } ``` Source line: `316`. ## audit\_sink::CompositeAuditSink::new [#audit_sinkcompositeauditsinknew] Create a new composite audit sink # Returns [#returns-5] A new composite audit sink ```rust #[must_use] pub fn new() -> Self; ``` Source line: `327`. ## audit\_sink::CompositeAuditSink::with\_sink [#audit_sinkcompositeauditsinkwith_sink] Add a sink to the composite audit sink # Parameters [#parameters-2] * `sink` - The sink to add # Returns [#returns-6] A new composite audit sink ```rust #[must_use] pub fn with_sink(mut self, sink: Arc) -> Self; ``` Source line: `342`. ## audit\_sink::CompositeAuditSink::fail\_fast [#audit_sinkcompositeauditsinkfail_fast] Set the fail fast flag for the composite audit sink # Returns [#returns-7] A new composite audit sink ```rust #[must_use] pub fn fail_fast(mut self) -> Self; ``` Source line: `352`. ## audit\_sink::AsyncBufferedSink [#audit_sinkasyncbufferedsink] Async buffered sink with background flushing ```rust pub struct AsyncBufferedSink { } ``` Source line: `413`. ## audit\_sink::AsyncBufferedSink::new [#audit_sinkasyncbufferedsinknew] Create a new async buffered audit sink # Parameters [#parameters-3] * `inner` - The inner audit sink * `buffer_size` - The buffer size # Returns [#returns-8] A new async buffered audit sink ```rust pub fn new(inner: Arc, buffer_size: usize) -> Self; ``` Source line: `428`. # arsenal-broker · config URL: https://docs.openagent.id/reference/rust/arsenal-broker/config Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/config.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/config.rs`. SHA-256: `2db572d12b603005b5072a055012e88c8a2824075307b48b2b83b81a6e84d120`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::BrokerConfig [#configbrokerconfig] Broker configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BrokerConfig { /// Server configuration #[serde(default)] pub server: ServerConfig, /// TLS configuration #[serde(default)] pub tls: TlsConfig, /// Token configuration #[serde(default)] pub token: TokenConfig, /// Rate limiting configuration #[serde(default)] pub rate_limit: RateLimitConfig, /// Authentication / trust boundary configuration #[serde(default)] pub auth: AuthConfig, /// Audit configuration #[serde(default)] pub audit: AuditConfig, /// Revocation storage configuration #[serde(default)] pub revocation: RevocationConfig, /// Credential proxy configuration #[serde(default)] pub proxy: ProxyConfig, /// Consent service configuration #[serde(default)] pub consent: ConsentConfig, /// Issuer identifier #[serde(default = "default_issuer")] pub issuer: String } ``` Source line: `13`. ## config::BrokerConfig::listen\_addr [#configbrokerconfiglisten_addr] Default listen address ```rust #[must_use] pub fn listen_addr(&self) -> &str; ``` Source line: `62`. ## config::BrokerConfig::default\_token\_ttl [#configbrokerconfigdefault_token_ttl] Default token TTL ```rust #[must_use] pub fn default_token_ttl(&self) -> i64; ``` Source line: `68`. ## config::BrokerConfig::max\_token\_ttl [#configbrokerconfigmax_token_ttl] Maximum token TTL ```rust #[must_use] pub fn max_token_ttl(&self) -> i64; ``` Source line: `74`. ## config::AuthConfig [#configauthconfig] Authentication configuration Production defaults are **strict**: * Protected endpoints require a verified client identity (mTLS-derived fingerprint) * The broker does **not** trust client fingerprint headers unless explicitly configured ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuthConfig { /// Require a verified client identity on protected endpoints. /// /// Protected endpoints include: /// - `/v1/capabilities` /// - `/v1/secrets` /// - `/v1/tokens/revoke` #[serde(default = "default_require_verified_client_identity")] pub require_verified_client_identity: bool, /// Trust `X-Client-Cert-Fingerprint` header **only** when requests come from an explicitly /// allowlisted internal proxy. /// /// This is intended for deployments where TLS is terminated by an internal, verified proxy /// that injects the fingerprint header after mutual authentication. #[serde(default)] pub trust_fingerprint_header: bool, /// Allowlisted proxy IPs permitted to inject `X-Client-Cert-Fingerprint`. /// /// When `trust_fingerprint_header` is `true`, requests with a remote IP in this list may /// supply `X-Client-Cert-Fingerprint`. Requests from other IPs will have the header ignored. #[serde(default)] pub trusted_proxy_ips: Vec } ``` Source line: `102`. ## config::ServerConfig [#configserverconfig] Server configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ServerConfig { /// Listen address #[serde(default = "default_listen_addr")] pub listen_addr: String, /// Request timeout #[serde(default = "default_request_timeout")] pub request_timeout_secs: u64, /// Maximum request body size #[serde(default = "default_max_body_size")] pub max_body_size: usize, /// Enable CORS #[serde(default)] pub enable_cors: bool, /// Allowed CORS origins #[serde(default)] pub cors_origins: Vec, /// Graceful shutdown timeout #[serde(default = "default_shutdown_timeout")] pub shutdown_timeout_secs: u64 } ``` Source line: `144`. ## config::TlsConfig [#configtlsconfig] TLS configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TlsConfig { /// Enable TLS #[serde(default = "default_tls_enabled")] pub enabled: bool, /// TLS certificate path #[serde(default = "default_cert_path")] pub cert_path: PathBuf, /// TLS key path #[serde(default = "default_key_path")] pub key_path: PathBuf, /// CA certificate path for client verification #[serde(default = "default_ca_path")] pub ca_cert_path: PathBuf, /// Require client certificates (mTLS) #[serde(default = "default_require_client_cert")] pub require_client_cert: bool, /// Minimum TLS version (1.2 or 1.3) #[serde(default = "default_min_tls_version")] pub min_tls_version: String } ``` Source line: `201`. ## config::TokenConfig [#configtokenconfig] Token configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TokenConfig { /// Default token seconds #[serde(default = "default_token_ttl")] pub default_ttl_seconds: i64, /// Maximum token TTL in seconds #[serde(default = "default_max_token_ttl")] pub max_ttl_seconds: i64, /// Minimum token TTL in seconds #[serde(default = "default_min_token_ttl")] pub min_ttl_seconds: i64, /// Require proof-of-possession by default #[serde(default)] pub require_pop_by_default: bool, /// Token signing algorithm #[serde(default = "default_signing_algorithm")] pub signing_algorithm: String } ``` Source line: `266`. ## config::RateLimitConfig [#configratelimitconfig] Rate limiting configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RateLimitConfig { /// Enable rate limiting #[serde(default = "default_rate_limit_enabled")] pub enabled: bool, /// Requests per second per agent #[serde(default = "default_requests_per_second")] pub requests_per_second: u64, /// Burst size #[serde(default = "default_burst_size")] pub burst_size: u64, /// Capability request rate limit #[serde(default = "default_capability_rate")] pub capability_requests_per_minute: u64, /// Secret request rate limit #[serde(default = "default_secret_rate")] pub secret_requests_per_minute: u64 } ``` Source line: `318`. ## config::AuditConfig [#configauditconfig] Audit configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuditConfig { /// Enable audit logging #[serde(default = "default_audit_enabled")] pub enabled: bool, /// Audit log file path #[serde(default)] pub log_path: Option, /// Enable hash chain for audit integrity #[serde(default = "default_hash_chain")] pub enable_hash_chain: bool, /// Webhook URL for audit events #[serde(default)] pub webhook_url: Option, /// Webhook authorization header #[serde(default)] pub webhook_auth: Option, /// Buffer size for async #[serde(default = "default_audit_buffer")] pub buffer_size: usize } ``` Source line: `374`. ## config::RevocationConfig [#configrevocationconfig] Revocation storage configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RevocationConfig { /// Storage backend for revocations #[serde(default)] pub backend: RevocationBackend, /// File path for the file backend (JSONL log + snapshots) #[serde(default)] pub file_path: Option, /// SQL backend configuration #[serde(default)] pub sql: RevocationSqlConfig, /// HTTP backend configuration #[serde(default)] pub http: RevocationHttpConfig, /// Compaction interval in seconds (0 disables) #[serde(default = "default_revocation_compaction_interval_secs")] pub compaction_interval_secs: u64, /// Max entries to retain in memory before forcing cleanup #[serde(default = "default_revocation_max_entries")] pub max_entries: usize, /// fsync on revoke/unrevoke writes (stronger durability, higher latency) #[serde(default = "default_revocation_fsync_on_write")] pub fsync_on_write: bool } ``` Source line: `427`. ## config::RevocationBackend [#configrevocationbackend] Revocation storage backend. ```rust #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum RevocationBackend { /// In-memory only (restart loses revocations) #[default] Memory, /// File-backed (restart-safe on the same node) File, /// SQL-backed (Postgres/SQLite) revocation store Sql, /// HTTP-backed revocation store (external service) Http, } ``` Source line: `460`. ## config::RevocationSqlConfig [#configrevocationsqlconfig] SQL revocation backend configuration. Supports `PostgreSQL` and `SQLite` via `sqlx` and a single table. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RevocationSqlConfig { /// Database URL (e.g. `postgres://...` or `sqlite:///...`) #[serde(default)] pub database_url: Option, /// Table name to use for revocations #[serde(default = "default_revocation_sql_table")] pub table: String, /// Max database connections in the pool #[serde(default = "default_revocation_sql_max_connections")] pub max_connections: u32, /// Connection timeout (seconds) #[serde(default = "default_revocation_sql_connect_timeout_secs")] pub connect_timeout_secs: u64 } ``` Source line: `504`. ## config::RevocationHttpConfig [#configrevocationhttpconfig] HTTP revocation backend configuration. The broker will call an external revocation service for checks and writes. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RevocationHttpConfig { /// Base URL of the revocation service (e.g. `https://revocations.internal`) #[serde(default)] pub base_url: Option, /// Allow insecure `http://` base URLs (default: false). /// /// Production deployments should prefer mTLS/HTTPS for this integration. #[serde(default = "default_revocation_http_allow_insecure")] pub allow_insecure: bool, /// Optional Authorization header value to include (e.g. `Bearer ...`) #[serde(default)] pub auth_header: Option, /// Request timeout (seconds) #[serde(default = "default_revocation_http_timeout_secs")] pub timeout_secs: u64, /// Positive cache TTL (seconds) for `is_revoked`/`get` results #[serde(default = "default_revocation_http_cache_ttl_secs")] pub cache_ttl_secs: u64, /// Negative cache TTL (seconds) for not-revoked results #[serde(default = "default_revocation_http_negative_cache_ttl_secs")] pub negative_cache_ttl_secs: u64, /// Maximum TTL (seconds) for positive cache entries when token expiry is known. /// /// When the HTTP revocation service returns `original_expiry_ms`, the broker can safely cache /// a *revoked* result until (expiry + grace), capped by this maximum. #[serde(default = "default_revocation_http_positive_cache_max_ttl_secs")] pub positive_cache_max_ttl_secs: u64 } ``` Source line: `549`. ## config::BrokerConfig::from\_env [#configbrokerconfigfrom_env] Load configuration from environment variables ```rust #[allow(clippy::too_many_lines)] #[must_use] pub fn from_env() -> Self; ``` Source line: `624`. ## config::BrokerConfig::from\_file [#configbrokerconfigfrom_file] Load configuration from a TOML file # Errors [#errors] Returns an error if the file cannot be read or parsed ```rust pub fn from_file(path: impl AsRef) -> Result; ``` Source line: `794`. ## config::BrokerConfig::validate [#configbrokerconfigvalidate] Validate the configuration # Errors [#errors-1] Returns an error if the configuration is invalid ```rust #[allow(clippy::too_many_lines)] pub fn validate(&self) -> Result<(), ConfigError>; ``` Source line: `807`. ## config::ConfigError [#configconfigerror] Configuration errors ```rust #[derive(Debug, thiserror::Error)] pub enum ConfigError { /// I/O error #[error("I/O error: {0}")] IoError(String), /// Parse error #[error("Parse error: {0}")] ParseError(String), /// Validation error #[error("Validation error: {0}")] ValidationError(String), } ``` Source line: `947`. # arsenal-broker · consent_service URL: https://docs.openagent.id/reference/rust/arsenal-broker/consent_service Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/consent_service.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/consent_service.rs`. SHA-256: `d5bc3cfdbde82b3e2544445f990fce58684a28f34883bbf99c3b2e6ff7950a06`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## consent\_service::ConsentService [#consent_serviceconsentservice] Service for managing consent records. ```rust pub struct ConsentService { } ``` Source line: `32`. ## consent\_service::ConsentService::new [#consent_serviceconsentservicenew] Create a new consent service without signature verification. ```rust #[must_use] pub fn new( consent_store: Arc, audit_sink: Arc, config: ConsentConfig, ) -> Self; ``` Source line: `46`. ## consent\_service::ConsentService::with\_key\_resolver [#consent_serviceconsentservicewith_key_resolver] Create a consent service with signature verification enabled. ```rust #[must_use] pub fn with_key_resolver( consent_store: Arc, audit_sink: Arc, key_resolver: Arc, config: ConsentConfig, ) -> Self; ``` Source line: `61`. ## consent\_service::ConsentService::check\_consent [#consent_serviceconsentservicecheck_consent] Check if valid consent exists for an agent, variable, and tenant. Consent records are scoped to a tenant to prevent cross-tenant consent leakage in multi-tenant deployments. # Errors [#errors] Returns an error if the consent store lookup fails. ```rust pub async fn check_consent( &self, agent_did: &str, variable: &str, tenant_id: &TenantId, ) -> ArsenalResult; ``` Source line: `83`. ## consent\_service::ConsentService::approve\_consent [#consent_serviceconsentserviceapprove_consent] Store an approved consent record. # Errors [#errors-1] Returns an error if the record is invalid or storage fails. ```rust pub async fn approve_consent( &self, record: ConsentRecord, tenant_id: &TenantId, ctx: &RequestContext, ) -> ArsenalResult; ``` Source line: `114`. ## consent\_service::ConsentService::deny\_consent [#consent_serviceconsentservicedeny_consent] Deny a consent request. This is a no-store operation — denied requests are only audited, not persisted as records. ```rust pub async fn deny_consent( &self, request: &ConsentRequest, tenant_id: &TenantId, ctx: &RequestContext, ); ``` Source line: `175`. ## consent\_service::ConsentService::revoke\_consent [#consent_serviceconsentservicerevoke_consent] Revoke an existing consent record. # Errors [#errors-2] Returns an error if the consent ID is not found or storage fails. ```rust pub async fn revoke_consent( &self, consent_id: &ConsentId, tenant_id: &TenantId, ctx: &RequestContext, ) -> ArsenalResult<()>; ``` Source line: `200`. ## consent\_service::ConsentService::list\_consents [#consent_serviceconsentservicelist_consents] List consent records for an agent. # Errors [#errors-3] Returns an error if the consent store lookup fails. ```rust pub async fn list_consents(&self, agent_did: &str) -> ArsenalResult>; ``` Source line: `233`. ## consent\_service::ConsentService::get\_consent [#consent_serviceconsentserviceget_consent] Get a consent record by ID. # Errors [#errors-4] Returns an error if the consent store lookup fails. ```rust pub async fn get_consent( &self, consent_id: &ConsentId, ) -> ArsenalResult>; ``` Source line: `245`. ## consent\_service::ConsentService::cleanup\_expired [#consent_serviceconsentservicecleanup_expired] Run cleanup of expired consent records. Returns the number of records cleaned up. ```rust pub async fn cleanup_expired(&self) -> u64; ``` Source line: `258`. # arsenal-broker · crate URL: https://docs.openagent.id/reference/rust/arsenal-broker/crate Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/crate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/lib.rs`. SHA-256: `96b1bed6734958c5c5c0ce05651f84f2023928d166c7b91899604391a930a526`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit\_sink [#audit_sink] ```rust pub mod audit_sink; ``` Source line: `83`. ## config [#config] ```rust pub mod config; ``` Source line: `84`. ## consent\_service [#consent_service] ```rust pub mod consent_service; ``` Source line: `85`. ## handlers [#handlers] ```rust pub mod handlers; ``` Source line: `86`. ## metrics [#metrics] ```rust pub mod metrics; ``` Source line: `87`. ## middleware [#middleware] ```rust pub mod middleware; ``` Source line: `88`. ## proxy\_config [#proxy_config] ```rust pub mod proxy_config; ``` Source line: `89`. ## proxy\_service [#proxy_service] ```rust pub mod proxy_service; ``` Source line: `90`. ## rate [#rate] ```rust pub mod rate; ``` Source line: `91`. ## revocation [#revocation] ```rust pub mod revocation; ``` Source line: `92`. ## server [#server] ```rust pub mod server; ``` Source line: `93`. ## service [#service] ```rust pub mod service; ``` Source line: `94`. ## ssrf\_guard [#ssrf_guard] ```rust pub mod ssrf_guard; ``` Source line: `95`. ## pub use config::BrokerConfig; [#pub-use-configbrokerconfig] ```rust pub use config::BrokerConfig; ``` Source line: `98`. ## pub use consent\_service::ConsentService; [#pub-use-consent_serviceconsentservice] ```rust pub use consent_service::ConsentService; ``` Source line: `99`. ## pub use proxy\_config::\{ConsentConfig, ProxyConfig}; [#pub-use-proxy_configconsentconfig-proxyconfig] ```rust pub use proxy_config::{ConsentConfig, ProxyConfig}; ``` Source line: `100`. ## pub use proxy\_service::ProxyService; [#pub-use-proxy_serviceproxyservice] ```rust pub use proxy_service::ProxyService; ``` Source line: `101`. ## pub use server::BrokerServer; [#pub-use-serverbrokerserver] ```rust pub use server::BrokerServer; ``` Source line: `102`. ## pub use service::\{BrokerService, RegisteredAgent, RequestContext}; [#pub-use-servicebrokerservice-registeredagent-requestcontext] ```rust pub use service::{BrokerService, RegisteredAgent, RequestContext}; ``` Source line: `103`. ## pub use ssrf\_guard::SsrfGuard; [#pub-use-ssrf_guardssrfguard] ```rust pub use ssrf_guard::SsrfGuard; ``` Source line: `104`. ## prelude [#prelude] Prelude for common imports ```rust pub mod prelude; ``` Source line: `107`. ## pub use super::config::BrokerConfig; [#pub-use-superconfigbrokerconfig] ```rust pub use super::config::BrokerConfig; ``` Source line: `108`. ## pub use super::consent\_service::ConsentService; [#pub-use-superconsent_serviceconsentservice] ```rust pub use super::consent_service::ConsentService; ``` Source line: `109`. ## pub use super::proxy\_config::\{ConsentConfig, ProxyConfig}; [#pub-use-superproxy_configconsentconfig-proxyconfig] ```rust pub use super::proxy_config::{ConsentConfig, ProxyConfig}; ``` Source line: `110`. ## pub use super::proxy\_service::ProxyService; [#pub-use-superproxy_serviceproxyservice] ```rust pub use super::proxy_service::ProxyService; ``` Source line: `111`. ## pub use super::server::BrokerServer; [#pub-use-superserverbrokerserver] ```rust pub use super::server::BrokerServer; ``` Source line: `112`. ## pub use super::service::\{BrokerService, RegisteredAgent}; [#pub-use-superservicebrokerservice-registeredagent] ```rust pub use super::service::{BrokerService, RegisteredAgent}; ``` Source line: `113`. ## pub use super::ssrf\_guard::SsrfGuard; [#pub-use-superssrf_guardssrfguard] ```rust pub use super::ssrf_guard::SsrfGuard; ``` Source line: `114`. # arsenal-broker · handlers URL: https://docs.openagent.id/reference/rust/arsenal-broker/handlers Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/handlers.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/handlers.rs`. SHA-256: `63d254ec9f76e75e17827d465ba1452cbf72386508c7cbf9ca64eea98b5353d1`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## handlers::BrokerState [#handlersbrokerstate] Shared broker state ```rust pub struct BrokerState { /// The broker service pub service: Arc, /// Configuration pub config: BrokerConfig, /// Proxy service (optional, enabled via config) pub proxy_service: Option>, /// Consent service (optional, enabled via config) pub consent_service: Option> } ``` Source line: `41`. ## handlers::BrokerState::new [#handlersbrokerstatenew] Create new broker state ```rust #[must_use] pub fn new(service: Arc, config: BrokerConfig) -> Self; ``` Source line: `55`. ## handlers::BrokerState::with\_proxy [#handlersbrokerstatewith_proxy] Create broker state with proxy and consent services ```rust #[must_use] pub fn with_proxy( service: Arc, config: BrokerConfig, proxy_service: Option>, consent_service: Option>, ) -> Self; ``` Source line: `66`. ## handlers::ApiError [#handlersapierror] API error response ```rust #[derive(Debug, Serialize)] pub struct ApiError { /// Error code pub code: u32, /// Error message pub message: String, /// Correlation ID for tracing #[serde(skip_serializing_if = "Option::is_none")] pub correlation_id: Option, /// Retry after seconds (for rate limiting) #[serde(skip_serializing_if = "Option::is_none")] pub retry_after: Option } ``` Source line: `83`. ## handlers::HealthResponse [#handlershealthresponse] Health check response ```rust #[derive(Debug, Serialize)] pub struct HealthResponse { /// Service status pub status: String, /// Service version pub version: String, /// Number of registered agents pub registered_agents: usize, /// Number of revoked tokens pub revoked_tokens: usize } ``` Source line: `205`. ## handlers::health [#handlershealth] Health check handler ```rust pub async fn health(State(state): State>) -> Json; ``` Source line: `228`. ## handlers::metrics [#handlersmetrics] Prometheus metrics endpoint. ```rust pub async fn metrics() -> Response; ``` Source line: `234`. ## handlers::CapabilityRequestPayload [#handlerscapabilityrequestpayload] Capability request payload ```rust #[derive(Debug, Deserialize)] pub struct CapabilityRequestPayload { /// Requested scopes pub scopes: Vec, /// Requested TTL in seconds #[serde(default)] pub ttl_seconds: Option, /// Target audience (service) pub audience: String, /// Constraints to apply #[serde(default)] pub constraints: Option, /// `PoP` key fingerprint (hex encoded) #[serde(default)] pub pop_key_fingerprint: Option } ``` Source line: `253`. ## handlers::ConstraintsPayload [#handlersconstraintspayload] Constraints in API format ```rust #[derive(Debug, Default, Deserialize)] pub struct ConstraintsPayload { /// Require proof-of-possession #[serde(default)] pub require_pop: bool, /// Allowed origins #[serde(default)] pub allowed_origins: Option>, /// Device ID binding #[serde(default)] pub device_id: Option } ``` Source line: `271`. ## handlers::CapabilityResponsePayload [#handlerscapabilityresponsepayload] Capability response payload ```rust #[derive(Debug, Serialize)] pub struct CapabilityResponsePayload { /// Token ID pub token_id: String, /// Encoded token (base64) pub token: String, /// Expiration timestamp (ISO 8601) pub expires_at: String, /// Granted scopes pub granted_scopes: Vec } ``` Source line: `304`. ## handlers::request\_capability [#handlersrequest_capability] Request capability handler # Errors [#errors] Returns an `ApiError` if the capability request is denied or invalid. ```rust pub async fn request_capability( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result, ApiError>; ``` Source line: `331`. ## handlers::SecretRequestPayload [#handlerssecretrequestpayload] Secret request payload ```rust #[derive(Debug, Deserialize)] pub struct SecretRequestPayload { /// Secret ID pub secret_id: String, /// Version (optional, defaults to latest) #[serde(default)] pub version: Option, /// Capability token authorizing access pub capability_token: String } ``` Source line: `371`. ## handlers::WrappedSecretResponsePayload [#handlerswrappedsecretresponsepayload] Wrapped secret response payload ```rust #[derive(Debug, Serialize)] pub struct WrappedSecretResponsePayload { /// Secret ID pub secret_id: String, /// Version pub version: u64, /// Wrapped (encrypted) secret value (base64) pub wrapped_value: String, /// Wrapping key ID pub wrap_key_id: String, /// Ephemeral public key for unwrapping (base64) pub ephemeral_public_key: String, /// Expiration timestamp (ISO 8601) pub expires_at: String } ``` Source line: `383`. ## handlers::request\_secret [#handlersrequest_secret] Request secret handler # Errors [#errors-1] Returns an `ApiError` if the secret request is denied or the secret is not found. ```rust pub async fn request_secret( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result, ApiError>; ``` Source line: `416`. ## handlers::RevokeTokenPayload [#handlersrevoketokenpayload] Token revocation request ```rust #[derive(Debug, Deserialize)] pub struct RevokeTokenPayload { /// Token ID to revoke pub token_id: String, /// Reason for revocation #[serde(default)] pub reason: Option } ``` Source line: `480`. ## handlers::RevokeTokenResponse [#handlersrevoketokenresponse] Token revocation response ```rust #[derive(Debug, Serialize)] pub struct RevokeTokenResponse { /// Whether revocation succeeded pub success: bool, /// Message pub message: String } ``` Source line: `490`. ## handlers::revoke\_token [#handlersrevoke_token] Revoke token handler # Errors [#errors-2] Returns an `ApiError` if the token ID is invalid or revocation fails. ```rust pub async fn revoke_token( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result, ApiError>; ``` Source line: `502`. ## handlers::VerifyTokenPayload [#handlersverifytokenpayload] Token verification request ```rust #[derive(Debug, Deserialize)] pub struct VerifyTokenPayload { /// Token to verify (base64 encoded) pub token: String } ``` Source line: `547`. ## handlers::VerifyTokenResponse [#handlersverifytokenresponse] Token verification response ```rust #[derive(Debug, Serialize)] pub struct VerifyTokenResponse { /// Whether the token is valid pub valid: bool, /// Token ID #[serde(skip_serializing_if = "Option::is_none")] pub token_id: Option, /// Subject (agent ID) #[serde(skip_serializing_if = "Option::is_none")] pub subject: Option, /// Audience #[serde(skip_serializing_if = "Option::is_none")] pub audience: Option, /// Expiration timestamp #[serde(skip_serializing_if = "Option::is_none")] pub expires_at: Option, /// Granted scopes #[serde(skip_serializing_if = "Option::is_none")] pub scopes: Option>, /// Error message if invalid #[serde(skip_serializing_if = "Option::is_none")] pub error: Option } ``` Source line: `554`. ## handlers::verify\_token [#handlersverify_token] Verify token handler ```rust pub async fn verify_token( State(state): State>, Json(payload): Json, ) -> Json; ``` Source line: `578`. ## handlers::ProxyRequestPayload [#handlersproxyrequestpayload] Proxy request payload ```rust #[derive(Debug, Deserialize)] pub struct ProxyRequestPayload { /// HTTP method pub method: String, /// Target URL (with {{VARIABLE}} placeholders) pub url: String, /// Request headers (may contain {{VARIABLE}} placeholders) #[serde(default)] pub headers: Option>, /// Request body (base64 encoded, may contain {{VARIABLE}} placeholders) #[serde(default)] pub body: Option, /// Capability token (base64 encoded ACT) pub capability_token: String, /// Request timeout in milliseconds #[serde(default)] pub timeout_ms: Option } ``` Source line: `613`. ## handlers::ProxyResponsePayload [#handlersproxyresponsepayload] Proxy response payload ```rust #[derive(Debug, Serialize)] pub struct ProxyResponsePayload { /// HTTP status code pub status: u16, /// Response headers (sanitized) pub headers: std::collections::BTreeMap, /// Response body (base64 encoded) pub body: String, /// Proxy metadata pub metadata: ProxyMetadataPayload } ``` Source line: `633`. ## handlers::ProxyMetadataPayload [#handlersproxymetadatapayload] Proxy metadata payload ```rust #[derive(Debug, Serialize)] pub struct ProxyMetadataPayload { /// Variable names that were resolved (never values) pub variables_resolved: Vec, /// Whether destination binding was verified pub destination_verified: bool, /// Whether fingerprint was verified pub fingerprint_verified: bool, /// Consent status pub consent_status: String, /// Proxy latency in milliseconds pub latency_ms: u64 } ``` Source line: `646`. ## handlers::proxy\_request [#handlersproxy_request] Proxy request handler # Errors [#errors-3] Returns an `ApiError` if proxy is disabled, the agent is not registered, or the request fails. ```rust pub async fn proxy_request( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result, ApiError>; ``` Source line: `664`. ## handlers::ConsentApprovalPayload [#handlersconsentapprovalpayload] Consent approval payload ```rust #[derive(Debug, Deserialize)] pub struct ConsentApprovalPayload { /// Agent DID pub agent_did: String, /// Human root DID pub human_root_did: String, /// Variables to consent to pub variables: Vec, /// Destination domains pub destination_domains: Vec, /// Scopes pub scopes: Vec, /// Granted by (identifier of the approver) pub granted_by: String, /// Expiration in seconds from now #[serde(default)] pub expires_in_seconds: Option, /// Ed25519 signature (base64 encoded) pub signature: String } ``` Source line: `734`. ## handlers::ConsentRecordPayload [#handlersconsentrecordpayload] Consent record response payload ```rust #[derive(Debug, Serialize)] pub struct ConsentRecordPayload { /// Consent ID pub consent_id: String, /// Agent DID pub agent_did: String, /// Human root DID pub human_root_did: String, /// Variables pub variables: Vec, /// Destination domains pub destination_domains: Vec, /// Scopes pub scopes: Vec, /// Granted by pub granted_by: String, /// Granted at (ISO 8601) pub granted_at: String, /// Expires at (ISO 8601) pub expires_at: String, /// Whether revoked pub revoked: bool } ``` Source line: `756`. ## handlers::consent\_approve [#handlersconsent_approve] Approve consent handler # Errors [#errors-4] Returns an `ApiError` if the consent service is disabled, the agent is not found, or approval fails. ```rust pub async fn consent_approve( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result, ApiError>; ``` Source line: `801`. ## handlers::ConsentDenialPayload [#handlersconsentdenialpayload] Consent denial payload ```rust #[derive(Debug, Deserialize)] pub struct ConsentDenialPayload { /// Agent DID pub agent_did: String, /// Human root DID pub human_root_did: String, /// Variables being denied pub variables: Vec, /// Destination domains pub destination_domains: Vec, /// Scopes pub scopes: Vec } ``` Source line: `860`. ## handlers::consent\_deny [#handlersconsent_deny] Deny consent handler # Errors [#errors-5] Returns an `ApiError` if the consent service is disabled or the agent is not found. ```rust pub async fn consent_deny( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result; ``` Source line: `878`. ## handlers::ConsentRevocationPayload [#handlersconsentrevocationpayload] Consent revocation payload ```rust #[derive(Debug, Deserialize)] pub struct ConsentRevocationPayload { /// Consent ID to revoke pub consent_id: String } ``` Source line: `919`. ## handlers::consent\_revoke [#handlersconsent_revoke] Revoke consent handler # Errors [#errors-6] Returns an `ApiError` if the consent service is disabled, the agent is not found, or revocation fails. ```rust pub async fn consent_revoke( State(state): State>, ConnectInfo(addr): ConnectInfo, Extension(fingerprint): Extension, headers: HeaderMap, Json(payload): Json, ) -> Result; ``` Source line: `929`. ## handlers::ConsentListParams [#handlersconsentlistparams] Consent list query parameters ```rust #[derive(Debug, Deserialize)] pub struct ConsentListParams { /// Agent DID to list consents for pub agent_did: String } ``` Source line: `966`. ## handlers::consent\_list [#handlersconsent_list] List consents handler # Errors [#errors-7] Returns an `ApiError` if the consent service is disabled or the query fails. ```rust pub async fn consent_list( State(state): State>, axum::extract::Query(params): axum::extract::Query, ) -> Result>, ApiError>; ``` Source line: `976`. # arsenal-broker modules URL: https://docs.openagent.id/reference/rust/arsenal-broker Markdown: https://docs.openagent.id/reference/rust/arsenal-broker.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/arsenal-crates-arsenal-broker). [Focused integration guide](/arsenal/overview). ## Modules [#modules] * [crate](/reference/rust/arsenal-broker/crate) — 28 declarations * [audit\_sink](/reference/rust/arsenal-broker/audit_sink) — 18 declarations * [config](/reference/rust/arsenal-broker/config) — 18 declarations * [consent\_service](/reference/rust/arsenal-broker/consent_service) — 10 declarations * [handlers](/reference/rust/arsenal-broker/handlers) — 33 declarations * [metrics](/reference/rust/arsenal-broker/metrics) — 16 declarations * [middleware](/reference/rust/arsenal-broker/middleware) — 7 declarations * [proxy\_config](/reference/rust/arsenal-broker/proxy_config) — 2 declarations * [proxy\_service](/reference/rust/arsenal-broker/proxy_service) — 4 declarations * [rate](/reference/rust/arsenal-broker/rate) — 15 declarations * [revocation](/reference/rust/arsenal-broker/revocation) — 27 declarations * [server](/reference/rust/arsenal-broker/server) — 7 declarations * [service](/reference/rust/arsenal-broker/service) — 24 declarations * [ssrf\_guard](/reference/rust/arsenal-broker/ssrf_guard) — 7 declarations # arsenal-broker · metrics URL: https://docs.openagent.id/reference/rust/arsenal-broker/metrics Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/metrics.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/metrics.rs`. SHA-256: `ad03a2d1307a0ea3ecb52d8493a52aae62b1772d8e97ba9e61d905aa14df4d70`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## metrics::RevocationDecisionSource [#metricsrevocationdecisionsource] Revocation decision source (cache vs backend). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RevocationDecisionSource { /// Decision was computed by consulting the backend (SQL/file/memory/http). Backend, /// Decision came from a positive cache entry. CachePositive, /// Decision came from a negative cache entry. CacheNegative, } ``` Source line: `16`. ## metrics::RevocationDecisionSource::as\_str [#metricsrevocationdecisionsourceas_str] Convert to a stable label value. ```rust #[must_use] pub const fn as_str(self) -> &'static str; ``` Source line: `28`. ## metrics::RevocationDecision [#metricsrevocationdecision] One revocation check outcome (for metrics labeling). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RevocationDecision { /// Token is revoked. Revoked, /// Token is not revoked. NotRevoked, /// Revocation status could not be determined. Unknown, } ``` Source line: `39`. ## metrics::RevocationDecision::as\_str [#metricsrevocationdecisionas_str] Convert to a stable label value. ```rust #[must_use] pub const fn as_str(self) -> &'static str; ``` Source line: `51`. ## metrics::init [#metricsinit] Initialize metrics (Prometheus scrape endpoint). Safe to call multiple times; initialization occurs once. If the Prometheus exporter cannot be created, a fallback no-op provider is used and a warning is logged via `tracing`. ```rust pub fn init(); ``` Source line: `91`. ## metrics::render [#metricsrender] Render Prometheus text format. ```rust #[must_use] pub fn render() -> String; ``` Source line: `222`. ## metrics::record\_revocation\_check [#metricsrecord_revocation_check] Record a revocation check. ```rust pub fn record_revocation_check( backend: &'static str, endpoint: &'static str, result: &'static str, decision: RevocationDecision, source: RevocationDecisionSource, latency_seconds: f64, ); ``` Source line: `239`. ## metrics::record\_revocation\_cache\_hit [#metricsrecord_revocation_cache_hit] Record a revocation cache hit (HTTP backend). ```rust pub fn record_revocation_cache_hit(backend: &'static str, hit_type: &'static str); ``` Source line: `281`. ## metrics::record\_secret\_delivery\_denied [#metricsrecord_secret_delivery_denied] Record a secret delivery denial. ```rust pub fn record_secret_delivery_denied(reason: &'static str); ``` Source line: `295`. ## metrics::record\_secret\_request [#metricsrecord_secret_request] Record a secret delivery request. ```rust pub fn record_secret_request(result: &'static str); ``` Source line: `304`. ## metrics::record\_http\_request [#metricsrecord_http_request] Record an HTTP request (Google-safe labels: templated route + method + status). ```rust pub fn record_http_request(route: &'static str, method: &'static str, status: &'static str); ``` Source line: `313`. ## metrics::record\_proxy\_request [#metricsrecord_proxy_request] Record a proxy request. ```rust pub fn record_proxy_request( target_domain: &str, status: u16, result: &'static str, latency_ms: u64, ); ``` Source line: `328`. ## metrics::record\_fingerprint\_verification [#metricsrecord_fingerprint_verification] Record a fingerprint verification result. ```rust pub fn record_fingerprint_verification(result: &'static str); ``` Source line: `362`. ## metrics::record\_consent\_request [#metricsrecord_consent_request] Record a consent request. ```rust pub fn record_consent_request(status: &'static str); ``` Source line: `371`. ## metrics::record\_dct\_issued [#metricsrecord_dct_issued] Record a DCT issuance. ```rust pub fn record_dct_issued(); ``` Source line: `380`. ## metrics::record\_destination\_violation [#metricsrecord_destination_violation] Record a destination binding violation. ```rust pub fn record_destination_violation(domain: &str); ``` Source line: `388`. # arsenal-broker · middleware URL: https://docs.openagent.id/reference/rust/arsenal-broker/middleware Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/middleware.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/middleware.rs`. SHA-256: `4d2db1c3c9b5a9b3b3d6c7bce5a31f954b980e622b1a086bcacdf09d5d1ba94b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## middleware::auth\_middleware [#middlewareauth_middleware] Authentication middleware Extracts and validates information from mTLS. In production, this extracts the client cert fingerprint from the TLS layer. When behind a TLS-terminating proxy, it reads from X-Client-Cert-Fingerprint header. # Errors [#errors] Returns `StatusCode::UNAUTHORIZED` if a protected request has no verified client identity. ```rust pub async fn auth_middleware(mut request: Request, next: Next) -> Result; ``` Source line: `33`. ## middleware::audit\_middleware [#middlewareaudit_middleware] Audit logging middleware Logs all requests for security audit with timing information. ```rust pub async fn audit_middleware(request: Request, next: Next) -> Response; ``` Source line: `111`. ## middleware::rate\_limit\_middleware [#middlewarerate_limit_middleware] Rate limiting middleware Implements per-agent rate limiting using token bucket algorithm. Rate limits are enforced based on client certificate fingerprint. # Errors [#errors-1] Returns `StatusCode` errors if the inner handler returns one. ```rust pub async fn rate_limit_middleware(request: Request, next: Next) -> Result; ``` Source line: `182`. ## middleware::http\_metrics\_middleware [#middlewarehttp_metrics_middleware] HTTP request metrics middleware. Records a low-cardinality counter suitable for RED dashboards and SLO accounting: `arsenal_http_requests_total{route,method,status}`. ```rust pub async fn http_metrics_middleware(request: Request, next: Next) -> Response; ``` Source line: `232`. ## middleware::validation\_middleware [#middlewarevalidation_middleware] Request validation middleware Validates common request properties like content type and size. # Errors [#errors-2] Returns `StatusCode::UNSUPPORTED_MEDIA_TYPE` if the content type is missing or invalid. ```rust pub async fn validation_middleware(request: Request, next: Next) -> Result; ``` Source line: `301`. ## middleware::security\_headers\_middleware [#middlewaresecurity_headers_middleware] Security headers middleware Adds security-related headers to all responses. ```rust pub async fn security_headers_middleware(request: Request, next: Next) -> Response; ``` Source line: `337`. ## middleware::error\_handling\_middleware [#middlewareerror_handling_middleware] Error handling middleware Converts panics and errors to proper API responses. ```rust pub async fn error_handling_middleware(request: Request, next: Next) -> Response; ``` Source line: `384`. # arsenal-broker · proxy_config URL: https://docs.openagent.id/reference/rust/arsenal-broker/proxy_config Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/proxy_config.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/proxy_config.rs`. SHA-256: `813dfbd8c92accfae90736fb1f9d8d189007d05ec768d594407ef86644c34de9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proxy\_config::ProxyConfig [#proxy_configproxyconfig] Proxy service configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[allow(clippy::struct_excessive_bools)] pub struct ProxyConfig { /// Enable the credential proxy #[serde(default)] pub enabled: bool, /// Maximum request body size in bytes #[serde(default = "default_max_request_body_bytes")] pub max_request_body_bytes: usize, /// Default request timeout in milliseconds #[serde(default = "default_proxy_timeout_ms")] pub default_timeout_ms: u64, /// Maximum request timeout in milliseconds #[serde(default = "default_max_proxy_timeout_ms")] pub max_timeout_ms: u64, /// Additional blocked IP ranges in CIDR notation for SSRF protection. /// /// Private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, /// `::1`, `169.254.0.0/16`, etc.) are **always** blocked regardless of this list. #[serde(default)] pub blocked_domains: Vec, /// Require fingerprint verification on proxy requests #[serde(default = "default_require_fingerprinting")] pub require_fingerprinting: bool, /// Require human consent before proxy requests #[serde(default)] pub require_consent: bool, /// Consent policy granularity #[serde(default)] pub consent_policy: ConsentPolicy, /// Headers to strip from proxy responses (glob patterns). /// /// Common sensitive headers (Authorization, Cookie, Set-Cookie, X-Api-Key) /// are always stripped. #[serde(default)] pub additional_sanitize_headers: Vec, /// Strip cookies from proxy responses #[serde(default = "default_strip_cookies")] pub strip_cookies: bool, /// `OAuth2` proactive token refresh: refresh this many seconds before expiry #[serde(default = "default_oauth2_proactive_refresh")] pub oauth2_proactive_refresh_seconds: u64, /// Maximum concurrent connections per target domain #[serde(default = "default_max_connections_per_domain")] pub max_connections_per_domain: usize } ``` Source line: `13`. ## proxy\_config::ConsentConfig [#proxy_configconsentconfig] Consent service configuration ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConsentConfig { /// Enable the consent service endpoints #[serde(default)] pub enabled: bool, /// Default consent expiration in seconds #[serde(default = "default_consent_expiry_seconds")] pub default_expiry_seconds: u64, /// Maximum consent expiration in seconds #[serde(default = "default_max_consent_expiry_seconds")] pub max_expiry_seconds: u64, /// Cleanup interval for expired consent records (seconds) #[serde(default = "default_consent_cleanup_interval")] pub cleanup_interval_seconds: u64 } ``` Source line: `118`. # arsenal-broker · proxy_service URL: https://docs.openagent.id/reference/rust/arsenal-broker/proxy_service Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/proxy_service.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/proxy_service.rs`. SHA-256: `f371e74d538458acb8fd63bd137522e4febe0880749d8943757765d90898734e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proxy\_service::ProxyService [#proxy_serviceproxyservice] The credential proxy service. ```rust pub struct ProxyService { } ``` Source line: `53`. ## proxy\_service::ProxyService::new [#proxy_serviceproxyservicenew] Create a new proxy service. # Errors [#errors] Returns an error if the HTTP client cannot be created. ```rust pub fn new( config: ProxyConfig, secret_store: Arc, variable_resolver: Arc, fingerprint_store: Arc, consent_service: Arc, token_verifier: TokenVerifier, audit_sink: Arc, ) -> ArsenalResult; ``` Source line: `80`. ## proxy\_service::ProxyService::with\_ssrf\_guard [#proxy_serviceproxyservicewith_ssrf_guard] Create a new proxy service with a custom SSRF guard. Use `SsrfGuard::permissive()` in test environments where the proxy target is a local mock server. # Errors [#errors-1] Returns an error if the HTTP client cannot be created. ```rust #[allow(clippy::too_many_arguments)] pub fn with_ssrf_guard( config: ProxyConfig, secret_store: Arc, variable_resolver: Arc, fingerprint_store: Arc, consent_service: Arc, token_verifier: TokenVerifier, audit_sink: Arc, ssrf_guard: SsrfGuard, ) -> ArsenalResult; ``` Source line: `111`. ## proxy\_service::ProxyService::handle\_proxy\_request [#proxy_serviceproxyservicehandle_proxy_request] Handle a proxy request through the 11-step pipeline. # Errors [#errors-2] Returns an error at any pipeline step if validation fails. ```rust #[allow(clippy::similar_names)] #[allow(clippy::too_many_lines)] pub async fn handle_proxy_request( &self, _agent_fingerprint: &KeyFingerprint, agent_did: &OasDid, agent_id: &AgentId, tenant_id: &TenantId, request: ProxyRequest, ctx: &RequestContext, ) -> ArsenalResult; ``` Source line: `152`. # arsenal-broker · rate URL: https://docs.openagent.id/reference/rust/arsenal-broker/rate Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/rate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/rate.rs`. SHA-256: `acf9b257612b3e15bb618bf2c995edb440ab98f13f0d3403486c0a2104e242ec`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## rate::RateLimitResult [#rateratelimitresult] Result of a rate limit check ```rust #[derive(Debug, Clone)] pub enum RateLimitResult { /// Request is allowed Allowed { /// Remaining requests in the current window remaining: u64, }, /// Request is rate limited Limited { /// Seconds until the limit resets retry_after: u64, }, } ``` Source line: `13`. ## rate::RateLimiter [#rateratelimiter] Rate limiter with per-key token buckets ```rust pub struct RateLimiter { } ``` Source line: `99`. ## rate::RateLimitConfig [#rateratelimitconfig] Configuration for a specific rate limit key ```rust #[derive(Debug, Clone)] pub struct RateLimitConfig { /// Maximum tokens pub max_tokens: u64, /// Refill rate (tokens per second) pub refill_rate_tokens_per_second: u64 } ``` Source line: `112`. ## rate::RateLimiter::new [#rateratelimiternew] Create a new rate limiter # Arguments [#arguments] * `requests_per_second` - Base rate limit * `burst_size` - Maximum burst capacity ```rust #[must_use] pub fn new(requests_per_second: u64, burst_size: u64) -> Self; ``` Source line: `126`. ## rate::RateLimiter::set\_override [#rateratelimiterset_override] Set a rate limit override for a specific key pattern ```rust pub async fn set_override(&self, key_pattern: impl Into, config: RateLimitConfig); ``` Source line: `136`. ## rate::RateLimiter::check [#rateratelimitercheck] Check rate limit for a key ```rust pub async fn check(&self, key: &str) -> RateLimitResult; ``` Source line: `142`. ## rate::RateLimiter::peek [#rateratelimiterpeek] Check rate limit without consuming a token ```rust pub async fn peek(&self, key: &str) -> RateLimitResult; ``` Source line: `181`. ## rate::RateLimiter::reset [#rateratelimiterreset] Reset rate limit for a key ```rust pub async fn reset(&self, key: &str); ``` Source line: `204`. ## rate::RateLimiter::cleanup [#rateratelimitercleanup] Clean up expired buckets (call periodically) ```rust pub async fn cleanup(&self, max_age: Duration); ``` Source line: `210`. ## rate::RateLimiter::status [#rateratelimiterstatus] Get current status for a key ```rust pub async fn status(&self, key: &str) -> Option; ``` Source line: `221`. ## rate::RateLimitStatus [#rateratelimitstatus] Rate limit status for a key ```rust #[derive(Debug, Clone, serde::Serialize)] pub struct RateLimitStatus { /// Remaining requests pub remaining: u64, /// Total limit pub limit: u64, /// Seconds until full reset pub reset_in_seconds: u64 } ``` Source line: `238`. ## rate::SlidingWindowRateLimiter [#rateslidingwindowratelimiter] Sliding window rate limiter (alternative implementation) ```rust pub struct SlidingWindowRateLimiter { } ``` Source line: `248`. ## rate::SlidingWindowRateLimiter::new [#rateslidingwindowratelimiternew] Create a new sliding window rate limiter ```rust #[must_use] pub fn new(window_size: Duration, max_requests: u64) -> Self; ``` Source line: `260`. ## rate::SlidingWindowRateLimiter::check [#rateslidingwindowratelimitercheck] Check rate limit ```rust pub async fn check(&self, key: &str) -> RateLimitResult; ``` Source line: `269`. ## rate::SlidingWindowRateLimiter::cleanup [#rateslidingwindowratelimitercleanup] Clean up old entries ```rust pub async fn cleanup(&self); ``` Source line: `296`. # arsenal-broker · revocation URL: https://docs.openagent.id/reference/rust/arsenal-broker/revocation Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/revocation.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/revocation.rs`. SHA-256: `7098533bea972f1c4c2ff16eaf8d0126e95d9fe753270b092b31b52799d2a33f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## revocation::RevocationReason [#revocationrevocationreason] Reason for token revocation ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum RevocationReason { /// User/admin requested revocation UserRequested, /// Security incident SecurityIncident, /// Agent deactivated AgentDeactivated, /// Session ended SessionEnded, /// Policy violation PolicyViolation, /// Suspicious activity detected SuspiciousActivity, /// Key rotation KeyRotation, /// Other reason with description Other(String), } ``` Source line: `20`. ## revocation::RevokedToken [#revocationrevokedtoken] A revoked token entry ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RevokedToken { /// The token ID pub token_id: TokenId, /// When the token was revoked pub revoked_at: chrono::DateTime, /// Why the token was revoked pub reason: RevocationReason, /// Who revoked it (agent ID, admin ID, or "system") pub revoked_by: String, /// Original pub original_expiry: Option> } ``` Source line: `41`. ## revocation::RevocationList [#revocationrevocationlist] In-memory revocation list ```rust pub struct RevocationList { } ``` Source line: `55`. ## revocation::RevocationList::new [#revocationrevocationlistnew] Create a new revocation list ```rust #[must_use] pub fn new() -> Self; ``` Source line: `65`. ## revocation::RevocationList::with\_capacity [#revocationrevocationlistwith_capacity] Create with custom capacity ```rust #[must_use] pub fn with_capacity(max_entries: usize) -> Self; ``` Source line: `74`. ## revocation::RevocationList::revoke [#revocationrevocationlistrevoke] Revoke a token ```rust pub async fn revoke(&self, token_id: TokenId, reason: RevocationReason); ``` Source line: `82`. ## revocation::RevocationList::revoke\_with\_details [#revocationrevocationlistrevoke_with_details] Revoke a token with full details ```rust pub async fn revoke_with_details( &self, token_id: TokenId, reason: RevocationReason, revoked_by: String, original_expiry: Option>, ); ``` Source line: `88`. ## revocation::RevocationList::is\_revoked [#revocationrevocationlistis_revoked] Check if a token is revoked ```rust pub async fn is_revoked(&self, token_id: &TokenId) -> bool; ``` Source line: `114`. ## revocation::RevocationList::get\_revocation [#revocationrevocationlistget_revocation] Get revocation details ```rust pub async fn get_revocation(&self, token_id: &TokenId) -> Option; ``` Source line: `120`. ## revocation::RevocationList::unrevoke [#revocationrevocationlistunrevoke] Remove a revocation (unrevoke) ```rust pub async fn unrevoke(&self, token_id: &TokenId) -> Option; ``` Source line: `126`. ## revocation::RevocationList::count [#revocationrevocationlistcount] Get count of revoked tokens ```rust pub async fn count(&self) -> usize; ``` Source line: `132`. ## revocation::RevocationList::cleanup\_expired [#revocationrevocationlistcleanup_expired] Clean up entries for tokens that have naturally expired ```rust pub async fn cleanup_expired(&self); ``` Source line: `138`. ## revocation::RevocationList::all [#revocationrevocationlistall] Get all revoked tokens (for sync/backup) ```rust pub async fn all(&self) -> Vec; ``` Source line: `162`. ## revocation::RevocationList::revoke\_bulk [#revocationrevocationlistrevoke_bulk] Bulk revoke tokens ```rust pub async fn revoke_bulk(&self, token_ids: Vec, reason: RevocationReason); ``` Source line: `168`. ## revocation::RevocationList::load [#revocationrevocationlistload] Load revocations from a list (for initialization) ```rust pub async fn load(&self, entries: Vec); ``` Source line: `185`. ## revocation::RevocationDecisionDetailed [#revocationrevocationdecisiondetailed] Detailed revocation decision. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RevocationDecisionDetailed { /// Whether the token is revoked. pub revoked: bool, /// Where the decision came from. pub source: crate::metrics::RevocationDecisionSource } ``` Source line: `201`. ## revocation::RevocationStore [#revocationrevocationstore] Trait for persistent revocation storage (object-safe). ```rust pub trait RevocationStore: Send + Sync { /// Add a revocation fn add(&self, entry: RevokedToken) -> BoxFuture<'_, Result<(), RevocationStoreError>>; /// Remove a revocation fn remove<'a>( &'a self, token_id: &'a TokenId, ) -> BoxFuture<'a, Result, RevocationStoreError>>; /// Check if a token is revoked fn is_revoked<'a>( &'a self, token_id: &'a TokenId, ) -> BoxFuture<'a, Result>; /// Check if a token is revoked, with decision source detail. fn is_revoked_detailed<'a>( &'a self, token_id: &'a TokenId, ) -> BoxFuture<'a, Result> ; /// Get revocation details fn get<'a>( &'a self, token_id: &'a TokenId, ) -> BoxFuture<'a, Result, RevocationStoreError>>; /// List all revocations (paginated) fn list( &self, limit: usize, offset: usize, ) -> BoxFuture<'_, Result, RevocationStoreError>>; /// Clean up expired entries fn cleanup(&self) -> BoxFuture<'_, Result>; /// Compact any persistent storage (no-op for in-memory stores) fn compact(&self) -> BoxFuture<'_, Result<(), RevocationStoreError>>; /// Count current revocations fn count(&self) -> BoxFuture<'_, Result>; } ``` Source line: `212`. ## revocation::RevocationStoreError [#revocationrevocationstoreerror] Errors from revocation store ```rust #[derive(Debug, thiserror::Error)] pub enum RevocationStoreError { /// Storage backend error #[error("Storage error: {0}")] StorageError(String), /// Entry not found #[error("Revocation not found")] NotFound, } ``` Source line: `267`. ## revocation::InMemoryRevocationStore [#revocationinmemoryrevocationstore] In-memory implementation of `RevocationStore` ```rust pub struct InMemoryRevocationStore { } ``` Source line: `278`. ## revocation::InMemoryRevocationStore::new [#revocationinmemoryrevocationstorenew] Create a new in-memory store ```rust #[must_use] pub fn new() -> Self; ``` Source line: `285`. ## revocation::FileRevocationStore [#revocationfilerevocationstore] File-backed revocation store (restart-safe on a single node). This maintains an in-memory index for fast checks, and persists mutations to a JSONL file. A periodic compaction rewrites the file as a snapshot to avoid unbounded growth. ```rust pub struct FileRevocationStore { } ``` Source line: `379`. ## revocation::SqlRevocationStore [#revocationsqlrevocationstore] SQL-backed revocation store (Postgres/SQLite) using `sqlx`. ```rust pub struct SqlRevocationStore { } ``` Source line: `388`. ## revocation::SqlRevocationStore::connect [#revocationsqlrevocationstoreconnect] Create a new SQL-backed revocation store and ensure schema exists. # Errors [#errors] Returns an error if the database cannot be reached or schema init fails. ```rust pub async fn connect( database_url: &str, table: String, max_connections: u32, connect_timeout: std::time::Duration, ) -> Result; ``` Source line: `427`. ## revocation::HttpRevocationStore [#revocationhttprevocationstore] HTTP-backed revocation store (external service). The store supports: * read-through caching (positive + negative TTL) * bounded timeouts * basic retry on transient failures ```rust pub struct HttpRevocationStore { } ``` Source line: `859`. ## revocation::HttpRevocationStore::new [#revocationhttprevocationstorenew] Create a new HTTP-backed store. # Errors [#errors-1] Returns an error if the base URL is invalid or the HTTP client cannot be created. ```rust pub fn new( base_url: &str, auth_header: Option, timeout: std::time::Duration, cache_ttl: std::time::Duration, negative_cache_ttl: std::time::Duration, positive_cache_max_ttl: std::time::Duration, ) -> Result; ``` Source line: `884`. ## revocation::FileRevocationStore::new [#revocationfilerevocationstorenew] Create or load a file-backed revocation store. # Errors [#errors-2] Returns an error if the log cannot be read or opened. ```rust pub fn new( path: impl Into, max_entries: usize, fsync_on_write: bool, ) -> Result; ``` Source line: `1333`. ## revocation::FileRevocationStore::compact\_snapshot [#revocationfilerevocationstorecompact_snapshot] Compact the on-disk log into a snapshot of current revocations. # Errors [#errors-3] Returns an error if rewriting fails. ```rust pub async fn compact_snapshot(&self) -> Result<(), RevocationStoreError>; ``` Source line: `1430`. # arsenal-broker · server URL: https://docs.openagent.id/reference/rust/arsenal-broker/server Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/server.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/server.rs`. SHA-256: `c0f5d78e3eaf16bf215ea3ad3fd6bf0aa4d925aa785cebea43a33f79c601e8e8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## server::BrokerServer [#serverbrokerserver] Broker server ```rust pub struct BrokerServer { } ``` Source line: `44`. ## server::BrokerServer::new [#serverbrokerservernew] Create a new broker server # Errors [#errors] Returns an error if initialization fails ```rust pub async fn new( config: BrokerConfig, secret_store: Arc, ) -> Result>; ``` Source line: `58`. ## server::BrokerServer::with\_service [#serverbrokerserverwith_service] Create with an existing service ```rust #[must_use] pub fn with_service(config: BrokerConfig, service: Arc) -> Self; ``` Source line: `79`. ## server::BrokerServer::service [#serverbrokerserverservice] Get a reference to the broker service ```rust #[must_use] pub fn service(&self) -> &Arc; ``` Source line: `90`. ## server::BrokerServer::router [#serverbrokerserverrouter] Build the router ```rust pub fn router(&self) -> Router; ``` Source line: `95`. ## server::BrokerServer::run\_insecure [#serverbrokerserverrun_insecure] Run the server without TLS (for development/testing) # Errors [#errors-1] Returns an error if the server fails to start ```rust pub async fn run_insecure(&self) -> Result<(), Box>; ``` Source line: `183`. ## server::BrokerServer::run [#serverbrokerserverrun] Run the server with TLS # Errors [#errors-2] Returns an error if the server fails to start ```rust pub async fn run(&self) -> Result<(), Box>; ``` Source line: `208`. # arsenal-broker · service URL: https://docs.openagent.id/reference/rust/arsenal-broker/service Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/service.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/service.rs`. SHA-256: `fe130c951282730bd7e6bf3e94598bb2f4ce1b1343366db18147306a409479f1`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## service::RegisteredAgent [#serviceregisteredagent] Registered agent with its identity and metadata ```rust #[derive(Debug, Clone)] pub struct RegisteredAgent { /// Agent identity pub identity: AgentIdentity, /// Public key bytes for signature verification pub public_key: [u8; 32], /// Public key bytes for encryption (X25519) /// /// Used to encrypt secrets to the agent such that only the agent can unwrap them. pub encryption_public_key: [u8; 32], /// Maximum allowed scopes for this agent pub allowed_scopes: ScopeSet, /// Maximum token TTL in seconds pub max_ttl_seconds: i64, /// Whether `PoP` is required pub require_pop: bool } ``` Source line: `46`. ## service::RequestContext [#servicerequestcontext] Request context extracted from the incoming request ```rust #[derive(Debug, Clone)] pub struct RequestContext { /// Request ID for tracing pub request_id: uuid::Uuid, /// Client IP address pub client_ip: Option, /// User agent string pub user_agent: Option, /// Origin header pub origin: Option, /// Session ID if provided pub session_id: Option, /// Timestamp of the request pub timestamp: chrono::DateTime } ``` Source line: `65`. ## service::RequestContext::new [#servicerequestcontextnew] Create a new request context ```rust #[must_use] pub fn new() -> Self; ``` Source line: `83`. ## service::RequestContext::to\_constraint\_context [#servicerequestcontextto_constraint_context] Convert to constraint context for validation ```rust #[must_use] pub fn to_constraint_context(&self) -> ConstraintContext; ``` Source line: `96`. ## service::CapabilityRequest [#servicecapabilityrequest] Capability request from an agent ```rust #[derive(Debug, Clone)] pub struct CapabilityRequest { /// Requested scopes pub scopes: Vec, /// Requested TTL in seconds pub ttl_seconds: Option, /// Target audience (service) pub audience: String, /// Constraints to apply pub constraints: Option, /// `PoP` key fingerprint (if providing `PoP`) pub pop_key_fingerprint: Option } ``` Source line: `119`. ## service::CapabilityResponse [#servicecapabilityresponse] Capability response ```rust #[derive(Debug, Clone)] pub struct CapabilityResponse { /// The issued token ID pub token_id: TokenId, /// Serialized token (CBOR, base64 encoded) pub token: String, /// Expiration timestamp pub expires_at: chrono::DateTime, /// Granted scopes (may be narrower than requested) pub granted_scopes: Vec } ``` Source line: `134`. ## service::SecretRequest [#servicesecretrequest] Secret request from an agent ```rust #[derive(Debug, Clone)] pub struct SecretRequest { /// Secret ID pub secret_id: String, /// Version (optional, defaults to latest) pub version: Option, /// Capability token authorizing access pub capability_token: String, /// Proof-of-possession header (base64url JSON), if required by token binding pub pop_proof: Option } ``` Source line: `147`. ## service::WrappedSecretResponse [#servicewrappedsecretresponse] Wrapped secret response ```rust #[derive(Debug, Clone)] pub struct WrappedSecretResponse { /// Secret ID pub secret_id: String, /// Version pub version: u64, /// Wrapped (encrypted) secret value pub wrapped_value: String, /// Wrapping key ID pub wrap_key_id: String, /// Ephemeral public key for unwrapping pub ephemeral_public_key: String, /// Expiration pub expires_at: chrono::DateTime } ``` Source line: `160`. ## service::BrokerService [#servicebrokerservice] The core broker service ```rust pub struct BrokerService { } ``` Source line: `176`. ## service::BrokerService::new [#servicebrokerservicenew] Create a new broker service # Errors [#errors] Returns an error if initialization fails ```rust #[allow(clippy::too_many_lines)] pub async fn new( config: BrokerConfig, secret_store: Arc, audit_sink: Arc, ) -> ArsenalResult; ``` Source line: `218`. ## service::BrokerService::with\_signing\_key [#servicebrokerservicewith_signing_key] Create with an existing signing key # Errors [#errors-1] Returns an error if the key is invalid ```rust #[allow(clippy::too_many_lines)] pub async fn with_signing_key( config: BrokerConfig, signing_key_seed: [u8; 32], secret_store: Arc, audit_sink: Arc, ) -> ArsenalResult; ``` Source line: `345`. ## service::BrokerService::check\_http\_rate\_limit [#servicebrokerservicecheck_http_rate_limit] Coarse front-door rate limit for a caller key. Returns `Some(retry_after_seconds)` if limited. ```rust pub async fn check_http_rate_limit(&self, key: &str) -> Option; ``` Source line: `472`. ## service::BrokerService::register\_agent [#servicebrokerserviceregister_agent] Register an agent ```rust pub async fn register_agent(&self, agent: RegisteredAgent); ``` Source line: `483`. ## service::BrokerService::unregister\_agent [#servicebrokerserviceunregister_agent] Unregister an agent ```rust pub async fn unregister_agent(&self, fingerprint: &KeyFingerprint); ``` Source line: `490`. ## service::BrokerService::get\_agent [#servicebrokerserviceget_agent] Get a registered agent by fingerprint ```rust pub async fn get_agent(&self, fingerprint: &KeyFingerprint) -> Option; ``` Source line: `496`. ## service::BrokerService::add\_policy [#servicebrokerserviceadd_policy] Add a policy ```rust pub async fn add_policy(&self, policy: PolicyDocument); ``` Source line: `502`. ## service::BrokerService::request\_capability [#servicebrokerservicerequest_capability] Request a capability token # Errors [#errors-2] Returns an error if the request is denied or invalid ```rust #[allow(clippy::too_many_lines)] pub async fn request_capability( &self, agent_fingerprint: &KeyFingerprint, request: CapabilityRequest, ctx: &RequestContext, ) -> ArsenalResult; ``` Source line: `512`. ## service::BrokerService::request\_secret [#servicebrokerservicerequest_secret] Request a secret # Errors [#errors-3] Returns an error if access is denied or the secret doesn't exist ```rust #[allow(clippy::too_many_lines)] pub async fn request_secret( &self, agent_fingerprint: &KeyFingerprint, request: SecretRequest, ctx: &RequestContext, ) -> ArsenalResult; ``` Source line: `746`. ## service::BrokerService::revoke\_token [#servicebrokerservicerevoke_token] Revoke a token # Errors [#errors-4] Returns an error if revocation fails ```rust pub async fn revoke_token( &self, agent_fingerprint: &KeyFingerprint, token_id: &TokenId, reason: RevocationReason, ctx: &RequestContext, ) -> ArsenalResult<()>; ``` Source line: `991`. ## service::BrokerService::verify\_token [#servicebrokerserviceverify_token] Verify a token (for external validation) # Errors [#errors-5] Returns an error if the token is invalid ```rust pub async fn verify_token(&self, token_b64: &str) -> ArsenalResult; ``` Source line: `1037`. ## service::BrokerService::health [#servicebrokerservicehealth] Get broker health status ```rust pub async fn health(&self) -> BrokerHealth; ``` Source line: `1108`. ## service::BrokerService::issue\_dct [#servicebrokerserviceissue_dct] Issue a Delegated Credential Token (DCT). Creates a child ACT that grants proxy access to a subset of the parent's delegated variables. The child token inherits the parent's constraints but with narrower scope and shorter TTL. # Errors [#errors-6] Returns an error if: * The parent token is invalid or expired * The requested variables are not in the parent's delegated set * The delegation depth exceeds the maximum * The requested TTL exceeds the parent's remaining lifetime `child_agent_did` names the token subject; `child_agent_id` keys the audit record. Both are required because the audit trail is still keyed by local surrogate, which is tracked for migration to DIDs. ```rust #[allow(clippy::similar_names)] pub async fn issue_dct( &self, parent_token_b64: &str, delegated_variables: Vec, child_agent_did: &OasDid, child_agent_id: &AgentId, ttl_seconds: i64, ctx: &RequestContext, ) -> ArsenalResult<(String, chrono::DateTime)>; ``` Source line: `1136`. ## service::BrokerService::maintain\_revocations [#servicebrokerservicemaintain_revocations] Run revocation store maintenance (cleanup + optional compaction). This is safe to run periodically in the background. Compaction is a no-op for in-memory stores and will rewrite the on-disk snapshot for file-backed stores. ```rust pub async fn maintain_revocations(&self); ``` Source line: `1233`. ## service::BrokerHealth [#servicebrokerhealth] Broker health status ```rust #[derive(Debug, Clone, serde::Serialize)] pub struct BrokerHealth { /// Status string pub status: String, /// Version pub version: String, /// Number of registered agents pub registered_agents: usize, /// Number of revoked tokens pub revoked_tokens: usize } ``` Source line: `1481`. # arsenal-broker · ssrf_guard URL: https://docs.openagent.id/reference/rust/arsenal-broker/ssrf_guard Markdown: https://docs.openagent.id/reference/rust/arsenal-broker/ssrf_guard.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-broker/src/ssrf_guard.rs`. SHA-256: `e8f8c4e2155fa0b45c5066053b61ad07925c471104f651d43455a908a2ad8ce6`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## ssrf\_guard::SsrfGuard [#ssrf_guardssrfguard] SSRF guard for validating proxy request destinations. ```rust #[derive(Debug, Clone, Default)] pub struct SsrfGuard { } ``` Source line: `26`. ## ssrf\_guard::SsrfGuard::new [#ssrf_guardssrfguardnew] Create a new SSRF guard with additional blocked domains. ```rust #[must_use] pub fn new(blocked_domains: Vec) -> Self; ``` Source line: `36`. ## ssrf\_guard::SsrfGuard::permissive [#ssrf_guardssrfguardpermissive] Create an SSRF guard that allows ALL destinations. This completely disables SSRF protection including private IP blocking and HTTPS enforcement. Use ONLY in test environments with mock servers. ```rust #[must_use] pub fn permissive() -> Self; ``` Source line: `51`. ## ssrf\_guard::SsrfGuard::validate\_ip [#ssrf_guardssrfguardvalidate_ip] Check if an IP address is safe for proxy requests. Returns `Ok(())` if the IP is safe, or an error if it is blocked. # Errors [#errors] Returns `ArsenalError` with `SsrfBlocked` code if the address is unsafe. ```rust pub fn validate_ip(&self, ip: &IpAddr) -> ArsenalResult<()>; ``` Source line: `65`. ## ssrf\_guard::SsrfGuard::validate\_host [#ssrf_guardssrfguardvalidate_host] Check if a hostname is safe for proxy requests. Validates that the hostname is not in the blocklist and does not resolve to a private IP range. # Errors [#errors-1] Returns `ArsenalError` with `SsrfBlocked` code if the hostname is blocked. ```rust pub fn validate_host(&self, host: &str) -> ArsenalResult<()>; ``` Source line: `80`. ## ssrf\_guard::SsrfGuard::validate\_url [#ssrf_guardssrfguardvalidate_url] Full validation: validate a URL's host against SSRF protections. # Errors [#errors-2] Returns `ArsenalError` with `SsrfBlocked` if the URL targets a blocked destination. ```rust pub fn validate_url(&self, url: &str) -> ArsenalResult<()>; ``` Source line: `123`. ## ssrf\_guard::SsrfGuard::validate\_url\_resolved [#ssrf_guardssrfguardvalidate_url_resolved] Full validation with DNS resolution: validates a URL and resolves its hostname to ensure it does not point to private/internal IP addresses. Returns the validated resolved socket addresses so that the caller can **pin** outbound connections to these IPs, preventing DNS rebinding (TOCTOU) attacks where the hostname re-resolves to a different address between validation and the actual HTTP request. # Errors [#errors-3] Returns `ArsenalError` with `SsrfBlocked` if: * The URL is malformed or uses a non-HTTPS scheme * The hostname is in the blocklist * DNS resolution fails or returns no results * Any resolved IP is in a private/reserved range ```rust pub async fn validate_url_resolved( &self, url: &str, ) -> ArsenalResult>; ``` Source line: `156`. # arsenal-store · consent_store URL: https://docs.openagent.id/reference/rust/arsenal-store/consent_store Markdown: https://docs.openagent.id/reference/rust/arsenal-store/consent_store.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/consent_store.rs`. SHA-256: `3c5a1606ecd36ea252f54a56d288b95864e895588b58701a11e1cf06c22ed07c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## consent\_store::ConsentStoreResult [#consent_storeconsentstoreresult] Result type for consent store operations ```rust pub type ConsentStoreResult = Result; ``` Source line: `22`. ## consent\_store::ConsentStore [#consent_storeconsentstore] Trait for consent record storage backends ```rust pub trait ConsentStore: Send + Sync { /// Store a new consent record fn store_consent<'a>( &'a self, record: ConsentRecord, ) -> Pin> + Send + 'a>>; /// Get a consent record by ID fn get_consent<'a>( &'a self, consent_id: &'a ConsentId, ) -> Pin>> + Send + 'a>>; /// Find a valid consent record for an agent and variable fn find_consent<'a>( &'a self, agent_did: &'a str, variable: &'a str, ) -> Pin>> + Send + 'a>>; /// Revoke a consent record fn revoke_consent<'a>( &'a self, consent_id: &'a ConsentId, ) -> Pin> + Send + 'a>>; /// List all consent records for an agent fn list_consents<'a>( &'a self, agent_did: &'a str, ) -> Pin>> + Send + 'a>>; /// Remove expired consent records, returning the count removed fn cleanup_expired<'a>( &'a self, ) -> Pin> + Send + 'a>>; } ``` Source line: `25`. ## consent\_store::InMemoryConsentStore [#consent_storeinmemoryconsentstore] In-memory consent store for development and testing ```rust #[derive(Debug, Clone)] pub struct InMemoryConsentStore { } ``` Source line: `65`. ## consent\_store::InMemoryConsentStore::new [#consent_storeinmemoryconsentstorenew] Create a new empty in-memory consent store ```rust #[must_use] pub fn new() -> Self; ``` Source line: `72`. ## consent\_store::SqlConsentStore [#consent_storesqlconsentstore] SQL-backed consent store (Postgres/SQLite) using `sqlx`. ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub struct SqlConsentStore { } ``` Source line: `180`. ## consent\_store::SqlConsentStore::connect [#consent_storesqlconsentstoreconnect] Create a new SQL-backed consent store and ensure schema exists. # Errors [#errors] Returns an error if the database cannot be reached or schema init fails. ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub async fn connect( database_url: &str, table: String, max_connections: u32, connect_timeout: std::time::Duration, ) -> ConsentStoreResult; ``` Source line: `242`. # arsenal-store · crate URL: https://docs.openagent.id/reference/rust/arsenal-store/crate Markdown: https://docs.openagent.id/reference/rust/arsenal-store/crate.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/lib.rs`. SHA-256: `9eef468c92a9dc9b45700316aa160791082cc0d1e66682d9a61faead9a37b6dc`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## consent\_store [#consent_store] ```rust pub mod consent_store; ``` Source line: `21`. ## encrypted\_file [#encrypted_file] ```rust pub mod encrypted_file; ``` Source line: `22`. ## fingerprint\_store [#fingerprint_store] ```rust pub mod fingerprint_store; ``` Source line: `23`. ## key\_resolver [#key_resolver] ```rust pub mod key_resolver; ``` Source line: `24`. ## key\_wrapper [#key_wrapper] ```rust pub mod key_wrapper; ``` Source line: `25`. ## memory [#memory] ```rust pub mod memory; ``` Source line: `26`. ## traits [#traits] ```rust pub mod traits; ``` Source line: `27`. ## variable\_resolver [#variable_resolver] ```rust pub mod variable_resolver; ``` Source line: `28`. ## pub use consent\_store::\{ConsentStore, InMemoryConsentStore}; [#pub-use-consent_storeconsentstore-inmemoryconsentstore] ```rust pub use consent_store::{ConsentStore, InMemoryConsentStore}; ``` Source line: `30`. ## pub use encrypted\_file::EncryptedFileStore; [#pub-use-encrypted_fileencryptedfilestore] ```rust pub use encrypted_file::EncryptedFileStore; ``` Source line: `31`. ## pub use fingerprint\_store::\{FingerprintStore, InMemoryFingerprintStore}; [#pub-use-fingerprint_storefingerprintstore-inmemoryfingerprintstore] ```rust pub use fingerprint_store::{FingerprintStore, InMemoryFingerprintStore}; ``` Source line: `32`. ## pub use key\_resolver::\{InMemoryKeyResolver, PublicKeyResolver}; [#pub-use-key_resolverinmemorykeyresolver-publickeyresolver] ```rust pub use key_resolver::{InMemoryKeyResolver, PublicKeyResolver}; ``` Source line: `33`. ## pub use key\_wrapper::\{KeyWrapper, SoftwareKeyWrapper}; [#pub-use-key_wrapperkeywrapper-softwarekeywrapper] ```rust pub use key_wrapper::{KeyWrapper, SoftwareKeyWrapper}; ``` Source line: `34`. ## pub use memory::InMemorySecretStore; [#pub-use-memoryinmemorysecretstore] ```rust pub use memory::InMemorySecretStore; ``` Source line: `35`. ## pub use traits::\{SecretStore, SecretStoreError, SecretStoreResult}; [#pub-use-traitssecretstore-secretstoreerror-secretstoreresult] ```rust pub use traits::{SecretStore, SecretStoreError, SecretStoreResult}; ``` Source line: `36`. ## pub use variable\_resolver::\{InMemoryVariableResolver, VariableResolver}; [#pub-use-variable_resolverinmemoryvariableresolver-variableresolver] ```rust pub use variable_resolver::{InMemoryVariableResolver, VariableResolver}; ``` Source line: `37`. ## pub use consent\_store::SqlConsentStore; [#pub-use-consent_storesqlconsentstore] ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub use consent_store::SqlConsentStore; ``` Source line: `40`. ## pub use fingerprint\_store::SqlFingerprintStore; [#pub-use-fingerprint_storesqlfingerprintstore] ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub use fingerprint_store::SqlFingerprintStore; ``` Source line: `42`. ## pub use variable\_resolver::SqlVariableResolver; [#pub-use-variable_resolversqlvariableresolver] ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub use variable_resolver::SqlVariableResolver; ``` Source line: `44`. ## prelude [#prelude] Re-export common types ```rust pub mod prelude; ``` Source line: `47`. ## pub use super::consent\_store::\{ConsentStore, InMemoryConsentStore}; [#pub-use-superconsent_storeconsentstore-inmemoryconsentstore] ```rust pub use super::consent_store::{ConsentStore, InMemoryConsentStore}; ``` Source line: `48`. ## pub use super::fingerprint\_store::\{FingerprintStore, InMemoryFingerprintStore}; [#pub-use-superfingerprint_storefingerprintstore-inmemoryfingerprintstore] ```rust pub use super::fingerprint_store::{FingerprintStore, InMemoryFingerprintStore}; ``` Source line: `49`. ## pub use super::key\_resolver::\{InMemoryKeyResolver, PublicKeyResolver}; [#pub-use-superkey_resolverinmemorykeyresolver-publickeyresolver] ```rust pub use super::key_resolver::{InMemoryKeyResolver, PublicKeyResolver}; ``` Source line: `50`. ## pub use super::key\_wrapper::KeyWrapper; [#pub-use-superkey_wrapperkeywrapper] ```rust pub use super::key_wrapper::KeyWrapper; ``` Source line: `51`. ## pub use super::memory::InMemorySecretStore; [#pub-use-supermemoryinmemorysecretstore] ```rust pub use super::memory::InMemorySecretStore; ``` Source line: `52`. ## pub use super::traits::\{SecretStore, SecretStoreResult}; [#pub-use-supertraitssecretstore-secretstoreresult] ```rust pub use super::traits::{SecretStore, SecretStoreResult}; ``` Source line: `53`. ## pub use super::variable\_resolver::\{InMemoryVariableResolver, VariableResolver}; [#pub-use-supervariable_resolverinmemoryvariableresolver-variableresolver] ```rust pub use super::variable_resolver::{InMemoryVariableResolver, VariableResolver}; ``` Source line: `54`. # arsenal-store · encrypted_file URL: https://docs.openagent.id/reference/rust/arsenal-store/encrypted_file Markdown: https://docs.openagent.id/reference/rust/arsenal-store/encrypted_file.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/encrypted_file.rs`. SHA-256: `7f84dce81d01e01ff29bd839b8362ee2194ad47c3fa27557dc45e5ad7c9a09eb`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## encrypted\_file::EncryptedFileStore [#encrypted_fileencryptedfilestore] Encrypted file-based secret store ```rust pub struct EncryptedFileStore { } ``` Source line: `27`. ## encrypted\_file::EncryptedFileStore::new [#encrypted_fileencryptedfilestorenew] Create a new encrypted file store # Errors [#errors] Returns an error if the directory cannot be created ```rust pub async fn new( base_dir: impl AsRef, key_wrapper: Arc, ) -> SecretStoreResult; ``` Source line: `61`. ## encrypted\_file::EncryptedFileStore::without\_cache [#encrypted_fileencryptedfilestorewithout_cache] Disable caching (useful for testing) ```rust #[must_use] pub fn without_cache(mut self) -> Self; ``` Source line: `82`. ## encrypted\_file::EncryptedFileStore::load\_cache [#encrypted_fileencryptedfilestoreload_cache] Load metadata cache from disk # Errors [#errors-1] Returns an error if reading from disk fails ```rust pub async fn load_cache(&self, tenant_id: &TenantId) -> SecretStoreResult<()>; ``` Source line: `225`. # arsenal-store · fingerprint_store URL: https://docs.openagent.id/reference/rust/arsenal-store/fingerprint_store Markdown: https://docs.openagent.id/reference/rust/arsenal-store/fingerprint_store.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/fingerprint_store.rs`. SHA-256: `4aac1a706971c702a45d583a81089130863c80ba0a0614eb7b58d0dc6056959e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## fingerprint\_store::FingerprintStoreResult [#fingerprint_storefingerprintstoreresult] Result type for fingerprint store operations ```rust pub type FingerprintStoreResult = Result; ``` Source line: `19`. ## fingerprint\_store::FingerprintStore [#fingerprint_storefingerprintstore] Trait for fingerprint state storage backends ```rust pub trait FingerprintStore: Send + Sync { /// Get the fingerprint state for an agent fn get_state<'a>( &'a self, agent_did: &'a str, ) -> Pin>> + Send + 'a>>; /// Create or update the fingerprint state for an agent fn update_state<'a>( &'a self, agent_did: &'a str, state: FingerprintState, ) -> Pin> + Send + 'a>>; /// Delete the fingerprint state for an agent fn delete_state<'a>( &'a self, agent_did: &'a str, ) -> Pin> + Send + 'a>>; /// Reset the fingerprint state for an agent (delete and recreate) fn reset_state<'a>( &'a self, agent_did: &'a str, new_state: FingerprintState, ) -> Pin> + Send + 'a>>; } ``` Source line: `22`. ## fingerprint\_store::InMemoryFingerprintStore [#fingerprint_storeinmemoryfingerprintstore] In-memory fingerprint store for development and testing ```rust #[derive(Debug, Clone)] pub struct InMemoryFingerprintStore { } ``` Source line: `52`. ## fingerprint\_store::InMemoryFingerprintStore::new [#fingerprint_storeinmemoryfingerprintstorenew] Create a new empty in-memory fingerprint store ```rust #[must_use] pub fn new() -> Self; ``` Source line: `59`. ## fingerprint\_store::SqlFingerprintStore [#fingerprint_storesqlfingerprintstore] SQL-backed fingerprint state store (Postgres / `SQLite`) using `sqlx`. Mirrors the pattern established by `SqlRevocationStore` in `arsenal-broker`. ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub struct SqlFingerprintStore { } ``` Source line: `136`. ## fingerprint\_store::SqlFingerprintStore::connect [#fingerprint_storesqlfingerprintstoreconnect] Create a new SQL-backed fingerprint store and ensure the schema exists. # Errors [#errors] Returns an error if the database cannot be reached or schema creation fails. ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub async fn connect( database_url: &str, table: String, max_connections: u32, connect_timeout: std::time::Duration, ) -> Result; ``` Source line: `180`. # arsenal-store modules URL: https://docs.openagent.id/reference/rust/arsenal-store Markdown: https://docs.openagent.id/reference/rust/arsenal-store.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/arsenal-crates-arsenal-store). [Focused integration guide](/arsenal/overview). ## Modules [#modules] * [crate](/reference/rust/arsenal-store/crate) — 27 declarations * [consent\_store](/reference/rust/arsenal-store/consent_store) — 6 declarations * [encrypted\_file](/reference/rust/arsenal-store/encrypted_file) — 4 declarations * [fingerprint\_store](/reference/rust/arsenal-store/fingerprint_store) — 6 declarations * [key\_resolver](/reference/rust/arsenal-store/key_resolver) — 4 declarations * [key\_wrapper](/reference/rust/arsenal-store/key_wrapper) — 13 declarations * [memory](/reference/rust/arsenal-store/memory) — 5 declarations * [traits](/reference/rust/arsenal-store/traits) — 19 declarations * [variable\_resolver](/reference/rust/arsenal-store/variable_resolver) — 7 declarations # arsenal-store · key_resolver URL: https://docs.openagent.id/reference/rust/arsenal-store/key_resolver Markdown: https://docs.openagent.id/reference/rust/arsenal-store/key_resolver.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/key_resolver.rs`. SHA-256: `6fab98ceac09d802887f16520ce1f1d4c030124a181c530a2c17e11befef58a8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## key\_resolver::PublicKeyResolver [#key_resolverpublickeyresolver] Resolves a DID (Decentralized Identifier) to a public signing key. Implementations may resolve keys from local storage, DID documents, or remote key servers. ```rust pub trait PublicKeyResolver: Send + Sync { /// Look up the public signing key for a given DID. /// /// Returns `Ok(Some(key))` if found, `Ok(None)` if not found, /// or an error if the resolution process itself fails. fn resolve_public_key( &self, did: &str, ) -> Pin>> + Send + '_>>; } ``` Source line: `19`. ## key\_resolver::InMemoryKeyResolver [#key_resolverinmemorykeyresolver] In-memory public key resolver for testing and development. ```rust #[derive(Debug, Clone)] pub struct InMemoryKeyResolver { } ``` Source line: `32`. ## key\_resolver::InMemoryKeyResolver::new [#key_resolverinmemorykeyresolvernew] Create an empty resolver. ```rust #[must_use] pub fn new() -> Self; ``` Source line: `40`. ## key\_resolver::InMemoryKeyResolver::register [#key_resolverinmemorykeyresolverregister] Register a public key for a DID. ```rust pub async fn register(&self, did: &str, key: PublicSigningKey); ``` Source line: `47`. # arsenal-store · key_wrapper URL: https://docs.openagent.id/reference/rust/arsenal-store/key_wrapper Markdown: https://docs.openagent.id/reference/rust/arsenal-store/key_wrapper.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/key_wrapper.rs`. SHA-256: `dfd726b12e16e9c9fe04621c2784e80f7aa16ac08a0076fe2817c195ca0b6259`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## key\_wrapper::KeyWrapper [#key_wrapperkeywrapper] Trait for key wrapping operations Implementations can use software encryption, HSM, KMS, etc. ```rust pub trait KeyWrapper: Send + Sync { /// Wrap a key fn wrap<'a>( &'a self, key_id: &'a str, plaintext_key: &'a [u8], ) -> Pin> + Send + 'a>>; /// Unwrap a key fn unwrap<'a>( &'a self, wrapped: &'a WrappedKeyData, ) -> Pin, SecretStoreError>> + Send + 'a>>; /// Get the wrapper's key ID fn key_id(&self) -> &str; /// Check if this wrapper can unwrap data wrapped by the given key ID fn can_unwrap(&self, key_id: &str) -> bool ; } ``` Source line: `21`. ## key\_wrapper::WrappedKeyData [#key_wrapperwrappedkeydata] Wrapped key data ```rust #[derive(Clone, serde::Serialize, serde::Deserialize)] pub struct WrappedKeyData { /// The encrypted key pub ciphertext: Vec, /// Nonce used for encryption pub nonce: Vec, /// ID of the wrapping key pub wrapper_key_id: String, /// Algorithm used pub algorithm: String } ``` Source line: `46`. ## key\_wrapper::SoftwareKeyWrapper [#key_wrappersoftwarekeywrapper] Software-based key wrapper using XChaCha20-Poly1305 ```rust pub struct SoftwareKeyWrapper { } ``` Source line: `68`. ## key\_wrapper::SoftwareKeyWrapper::new [#key_wrappersoftwarekeywrappernew] Create a new software key wrapper ```rust pub fn new(kek_bytes: [u8; 32], key_id: impl Into) -> Self; ``` Source line: `77`. ## key\_wrapper::SoftwareKeyWrapper::generate [#key_wrappersoftwarekeywrappergenerate] Create with a randomly generated KEK # Errors [#errors] Returns an error if random generation fails ```rust pub fn generate(key_id: impl Into) -> Result; ``` Source line: `88`. ## key\_wrapper::SoftwareKeyWrapper::export\_kek [#key_wrappersoftwarekeywrapperexport_kek] Export the KEK (for backup - handle with extreme care!) ```rust #[must_use] pub fn export_kek(&self) -> [u8; 32]; ``` Source line: `95`. ## key\_wrapper::MultiKeyWrapper [#key_wrappermultikeywrapper] Multi-key wrapper that supports multiple KEKs for rotation ```rust pub struct MultiKeyWrapper { } ``` Source line: `148`. ## key\_wrapper::MultiKeyWrapper::new [#key_wrappermultikeywrappernew] Create a new multi-key wrapper ```rust pub fn new(current: Arc) -> Self; ``` Source line: `157`. ## key\_wrapper::MultiKeyWrapper::add\_previous [#key_wrappermultikeywrapperadd_previous] Add a previous wrapper (for key rotation) ```rust pub fn add_previous(&mut self, wrapper: Arc); ``` Source line: `165`. ## key\_wrapper::MultiKeyWrapper::rotate [#key_wrappermultikeywrapperrotate] Rotate to a new primary wrapper ```rust pub fn rotate(&mut self, new_wrapper: Arc); ``` Source line: `170`. ## key\_wrapper::MultiKeyWrapper::current\_key\_id [#key_wrappermultikeywrappercurrent_key_id] Get the current wrapper's key ID ```rust #[must_use] pub fn current_key_id(&self) -> &str; ``` Source line: `182`. ## key\_wrapper::DerivedKeyWrapper [#key_wrapperderivedkeywrapper] Derived key wrapper that derives KEKs from a master key ```rust pub struct DerivedKeyWrapper { } ``` Source line: `231`. ## key\_wrapper::DerivedKeyWrapper::new [#key_wrapperderivedkeywrappernew] Create a new derived key wrapper ```rust pub fn new(master_key: [u8; 32], key_id_prefix: impl Into) -> Self; ``` Source line: `240`. # arsenal-store · memory URL: https://docs.openagent.id/reference/rust/arsenal-store/memory Markdown: https://docs.openagent.id/reference/rust/arsenal-store/memory.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/memory.rs`. SHA-256: `c2c9de33edaacd6480db7b26b298e44a069345ddf0b89dab31e8d1e3cc511459`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## memory::InMemorySecretStore [#memoryinmemorysecretstore] In-memory secret store ```rust pub struct InMemorySecretStore { } ``` Source line: `22`. ## memory::InMemorySecretStore::new [#memoryinmemorysecretstorenew] Create a new in-memory store with a random encryption key # Errors [#errors] Returns an error if key generation fails ```rust pub fn new() -> SecretStoreResult; ``` Source line: `44`. ## memory::InMemorySecretStore::with\_key [#memoryinmemorysecretstorewith_key] Create with a specific encryption key ```rust #[must_use] pub fn with_key(key_bytes: [u8; 32]) -> Self; ``` Source line: `56`. ## memory::InMemorySecretStore::clear [#memoryinmemorysecretstoreclear] Clear all secrets (for testing) ```rust pub async fn clear(&self); ``` Source line: `96`. ## memory::InMemorySecretStore::count [#memoryinmemorysecretstorecount] Get count of secrets ```rust pub async fn count(&self, tenant_id: &TenantId) -> usize; ``` Source line: `102`. # arsenal-store · traits URL: https://docs.openagent.id/reference/rust/arsenal-store/traits Markdown: https://docs.openagent.id/reference/rust/arsenal-store/traits.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/traits.rs`. SHA-256: `f1e8cf49bdd881de6ca0f5bb1ae623cd2dbccf466665c1f375de947185c28ac3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## traits::SecretStoreResult [#traitssecretstoreresult] Result type for secret store operations ```rust pub type SecretStoreResult = Result; ``` Source line: `16`. ## traits::SecretStoreError [#traitssecretstoreerror] Errors specific to secret storage ```rust #[derive(Debug, thiserror::Error)] pub enum SecretStoreError { /// Secret not found #[error("Secret not found: {0}")] NotFound(String), /// Secret version not found #[error("Secret version not found: {0} v{1}")] VersionNotFound(String, u64), /// Secret already exists #[error("Secret already exists: {0}")] AlreadyExists(String), /// Access denied #[error("Access denied: {0}")] AccessDenied(String), /// Storage backend error #[error("Storage error: {0}")] StorageError(String), /// Encryption error #[error("Encryption error: {0}")] EncryptionError(String), /// Validation error #[error("Validation error: {0}")] ValidationError(String), /// Configuration error #[error("Configuration error: {0}")] ConfigurationError(String), /// Wrapped arsenal error #[error(transparent)] Arsenal(#[from] ArsenalError), } ``` Source line: `20`. ## traits::SecretStoreError::not\_found [#traitssecretstoreerrornot_found] Create a not found error ```rust pub fn not_found(id: impl Into) -> Self; ``` Source line: `60`. ## traits::SecretStoreError::storage [#traitssecretstoreerrorstorage] Create a storage error ```rust pub fn storage(msg: impl Into) -> Self; ``` Source line: `65`. ## traits::SecretStoreError::encryption [#traitssecretstoreerrorencryption] Create an encryption error ```rust pub fn encryption(msg: impl Into) -> Self; ``` Source line: `70`. ## traits::SecretStoreError::validation [#traitssecretstoreerrorvalidation] Create a validation error ```rust pub fn validation(msg: impl Into) -> Self; ``` Source line: `75`. ## traits::SecretStoreError::is\_not\_found [#traitssecretstoreerroris_not_found] Check if this is a not found error ```rust #[must_use] pub fn is_not_found(&self) -> bool; ``` Source line: `81`. ## traits::SecretStore [#traitssecretstore] Trait for secret storage backends All methods async to support both local and remote backends. ```rust pub trait SecretStore: Send + Sync { /// Create a new secret fn create<'a>( &'a self, tenant_id: &'a TenantId, name: &'a str, secret_type: SecretType, value: SecretValue, ) -> Pin> + Send + 'a>>; /// Get secret metadata (without the value) fn get_metadata<'a>( &'a self, tenant_id: &'a TenantId, secret_id: &'a SecretId, ) -> Pin> + Send + 'a>>; /// Get a secret value fn get_value<'a>( &'a self, tenant_id: &'a TenantId, secret_ref: &'a SecretRef, ) -> Pin> + Send + 'a>>; /// Update a secret (creates a new version) fn update<'a>( &'a self, tenant_id: &'a TenantId, secret_id: &'a SecretId, new_value: SecretValue, ) -> Pin> + Send + 'a>>; /// Delete a secret (all versions) fn delete<'a>( &'a self, tenant_id: &'a TenantId, secret_id: &'a SecretId, ) -> Pin> + Send + 'a>>; /// List secrets for a tenant fn list<'a>( &'a self, tenant_id: &'a TenantId, filter: Option<&'a SecretFilter>, ) -> Pin>> + Send + 'a>>; /// Disable a specific version fn disable_version<'a>( &'a self, tenant_id: &'a TenantId, secret_id: &'a SecretId, version: SecretVersion, ) -> Pin> + Send + 'a>>; /// Check if a secret exists fn exists<'a>( &'a self, tenant_id: &'a TenantId, secret_id: &'a SecretId, ) -> Pin> + Send + 'a>>; } ``` Source line: `89`. ## traits::SecretFilter [#traitssecretfilter] Filter for listing secrets ```rust #[derive(Debug, Clone, Default)] pub struct SecretFilter { /// Filter by secret type pub secret_type: Option, /// Filter by name prefix pub name_prefix: Option, /// Filter by service pub service: Option, /// Filter by label key pub label_key: Option, /// Filter by label value (requires `label_key`) pub label_value: Option, /// Only active secrets pub active_only: bool, /// Maximum results pub limit: Option, /// Offset for pagination pub offset: Option } ``` Source line: `153`. ## traits::SecretFilter::new [#traitssecretfilternew] Create a new filter ```rust #[must_use] pub fn new() -> Self; ``` Source line: `175`. ## traits::SecretFilter::with\_type [#traitssecretfilterwith_type] Filter by secret type ```rust #[must_use] pub fn with_type(mut self, secret_type: SecretType) -> Self; ``` Source line: `181`. ## traits::SecretFilter::with\_name\_prefix [#traitssecretfilterwith_name_prefix] Filter by name prefix ```rust #[must_use] pub fn with_name_prefix(mut self, prefix: impl Into) -> Self; ``` Source line: `188`. ## traits::SecretFilter::with\_service [#traitssecretfilterwith_service] Filter by service ```rust #[must_use] pub fn with_service(mut self, service: impl Into) -> Self; ``` Source line: `195`. ## traits::SecretFilter::active\_only [#traitssecretfilteractive_only] Only active secrets ```rust #[must_use] pub fn active_only(mut self) -> Self; ``` Source line: `202`. ## traits::SecretFilter::with\_limit [#traitssecretfilterwith_limit] Set limit ```rust #[must_use] pub fn with_limit(mut self, limit: usize) -> Self; ``` Source line: `209`. ## traits::SecretFilter::with\_offset [#traitssecretfilterwith_offset] Set offset ```rust #[must_use] pub fn with_offset(mut self, offset: usize) -> Self; ``` Source line: `216`. ## traits::SecretFilter::matches [#traitssecretfiltermatches] Check if a secret matches this filter ```rust #[must_use] pub fn matches(&self, metadata: &SecretMetadata) -> bool; ``` Source line: `223`. ## traits::SecretStoreStats [#traitssecretstorestats] Statistics about the secret store ```rust #[derive(Debug, Clone, Default)] pub struct SecretStoreStats { /// Total number of secrets pub total_secrets: u64, /// Number of active secrets pub active_secrets: u64, /// Total number of versions across all secrets pub total_versions: u64, /// Number of secrets needing rotation pub needs_rotation: u64, /// Storage size in bytes (if available) pub storage_bytes: Option } ``` Source line: `271`. ## traits::SecretStoreExt [#traitssecretstoreext] Extended secret store trait with additional operations ```rust pub trait SecretStoreExt: SecretStore { /// Get store statistics fn stats<'a>( &'a self, tenant_id: &'a TenantId, ) -> Pin> + Send + 'a>>; /// Find secrets by name fn find_by_name<'a>( &'a self, tenant_id: &'a TenantId, name: &'a str, ) -> Pin>> + Send + 'a>>; /// Rotate a secret (convenience method) fn rotate<'a>( &'a self, tenant_id: &'a TenantId, secret_id: &'a SecretId, new_value: SecretValue, ) -> Pin> + Send + 'a>> ; } ``` Source line: `285`. # arsenal-store · variable_resolver URL: https://docs.openagent.id/reference/rust/arsenal-store/variable_resolver Markdown: https://docs.openagent.id/reference/rust/arsenal-store/variable_resolver.md Declared module signatures, types, configuration, and source documentation. Source: `arsenal/crates/arsenal-store/src/variable_resolver.rs`. SHA-256: `d20f8680464033e18d84d462ef627d5ab542791643cc94740744a31f9016ebff`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## variable\_resolver::VariableResolverResult [#variable_resolvervariableresolverresult] Result type for variable resolver operations ```rust pub type VariableResolverResult = Result; ``` Source line: `21`. ## variable\_resolver::VariableMappings [#variable_resolvervariablemappings] Variable mappings (variable name -> secret reference) ```rust pub type VariableMappings = BTreeMap; ``` Source line: `24`. ## variable\_resolver::VariableResolver [#variable_resolvervariableresolver] Trait for template variable resolution backends ```rust pub trait VariableResolver: Send + Sync { /// Resolve a variable name to a secret reference fn resolve<'a>( &'a self, tenant_id: &'a TenantId, variable: &'a str, ) -> Pin>> + Send + 'a>>; /// Register a variable-to-secret mapping fn register<'a>( &'a self, tenant_id: &'a TenantId, variable: &'a str, secret_ref: SecretRef, ) -> Pin> + Send + 'a>>; /// Remove a variable mapping fn unregister<'a>( &'a self, tenant_id: &'a TenantId, variable: &'a str, ) -> Pin> + Send + 'a>>; /// List all variable mappings for a tenant fn list<'a>( &'a self, tenant_id: &'a TenantId, ) -> Pin> + Send + 'a>>; } ``` Source line: `27`. ## variable\_resolver::InMemoryVariableResolver [#variable_resolverinmemoryvariableresolver] In-memory variable resolver for development and testing ```rust #[derive(Debug, Clone)] pub struct InMemoryVariableResolver { } ``` Source line: `59`. ## variable\_resolver::InMemoryVariableResolver::new [#variable_resolverinmemoryvariableresolvernew] Create a new empty in-memory variable resolver ```rust #[must_use] pub fn new() -> Self; ``` Source line: `67`. ## variable\_resolver::SqlVariableResolver [#variable_resolversqlvariableresolver] SQL-backed variable resolver (Postgres / `SQLite`) using `sqlx`. Stores variable-to-secret mappings in a SQL table with the `SecretRef` serialized as JSON TEXT. Follows the same dual-pool pattern as `SqlRevocationStore` in arsenal-broker. ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub struct SqlVariableResolver { } ``` Source line: `157`. ## variable\_resolver::SqlVariableResolver::connect [#variable_resolversqlvariableresolverconnect] Create a new SQL-backed variable resolver and ensure the schema exists. # Errors [#errors] Returns an error if the database cannot be reached or schema init fails. ```rust #[cfg(any(feature = "sqlite", feature = "postgres"))] pub async fn connect( database_url: &str, table: String, max_connections: u32, connect_timeout: std::time::Duration, ) -> VariableResolverResult; ``` Source line: `201`. # oas-anchor-eas · abi URL: https://docs.openagent.id/reference/rust/oas-anchor-eas/abi Markdown: https://docs.openagent.id/reference/rust/oas-anchor-eas/abi.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-anchor-eas/src/abi.rs`. SHA-256: `26b9f9f5b77b3394ff5ee5889295e3b39445082cf2ac9d8652c97b23ad1ac7ff`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## abi::SCHEMA\_STRING [#abischema_string] ```rust pub const SCHEMA_STRING: &str; ``` Source line: `17`. ## abi::AnchorData [#abianchordata] The attestation's decoded data fields. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct AnchorData { pub did: String, pub kind: String, pub status: String, pub metadata_commitment: String, pub anchored_at_block: u64 } ``` Source line: `22`. ## abi::encode [#abiencode] ABI-encode the anchor data for an `attest` call. ```rust pub fn encode(data: &AnchorData) -> Vec; ``` Source line: `49`. ## abi::decode [#abidecode] ABI-decode an attestation's data field. ```rust pub fn decode(data: &[u8]) -> Result; ``` Source line: `125`. # oas-anchor-eas · crate URL: https://docs.openagent.id/reference/rust/oas-anchor-eas/crate Markdown: https://docs.openagent.id/reference/rust/oas-anchor-eas/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-anchor-eas/src/lib.rs`. SHA-256: `e7376745ce2cffd53d2c9f3cf749659adda88ebdb14f08c69180db258380d5f7`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## abi [#abi] `oas-anchor-eas` — Ethereum Attestation Service (EAS) adapter for the OAS \[`oas_resolve::LineageAnchor`] trait. # What this adapter is (and is not) [#what-this-adapter-is-and-is-not] This crate is the **resolver**: the verifier-side path that reads lineage authority from EAS. Root anchors are attestations under a dedicated OAS lineage schema; revocation and status changes are newer attestations superseding older ones for the same subject. Publishing (writing anchors) is the issuer-side path and lives in the TypeScript adapter (`@openagentid/anchor-eas`), which uses the maintained EAS SDK for transaction signing and submission. Writing transactions correctly — RLP encoding, EIP-1559 fees, replacement semantics — is a problem best left to the maintained SDK; this crate deliberately does not hand-roll it. # The anchoring model [#the-anchoring-model] * **Schema**: \[`abi::SCHEMA_STRING`] registered on EAS; its UID is configuration, not code, because a schema UID is per-chain. * **Recipient**: attestations are addressed to a deterministic address derived from the subject DID (`did_recipient`): BLAKE3 of the DID's UTF-8 bytes, first 20 bytes. That makes "all attestations about this DID" an exact-match GraphQL query without a server-side index. * **Supersession**: the latest attestation for a subject wins. A `status: "revoked"` attestation, or a revoked latest attestation, means the subject is revoked. * **Finality**: `current_finalized_block` is `eth_blockNumber` minus the configured confirmation depth, so "finalized" is a policy knob, not a hardcoded number. * **Org roots**: not modeled in v1. `get_org_root` returns `None`, so rule 7 (org Merkle inclusion) is skipped against this backend — the honest answer rather than a wrong one. ```rust pub mod abi; ``` Source line: `36`. ## eas [#eas] ```rust pub mod eas; ``` Source line: `37`. ## error [#error] ```rust pub mod error; ``` Source line: `38`. ## pub use eas::\{did\_recipient, EasAnchor, EasConfig}; [#pub-use-easdid_recipient-easanchor-easconfig] ```rust pub use eas::{did_recipient, EasAnchor, EasConfig}; ``` Source line: `40`. ## pub use error::EasError; [#pub-use-erroreaserror] ```rust pub use error::EasError; ``` Source line: `41`. # oas-anchor-eas · eas URL: https://docs.openagent.id/reference/rust/oas-anchor-eas/eas Markdown: https://docs.openagent.id/reference/rust/oas-anchor-eas/eas.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-anchor-eas/src/eas.rs`. SHA-256: `78657c38a52d183f2665b0c1ec30057c5f505bbd627f57fdbc62775a669efd50`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## eas::MAINNET\_GRAPHQL [#easmainnet_graphql] Default GraphQL endpoints by network name. ```rust pub const MAINNET_GRAPHQL: &str; ``` Source line: `10`. ## eas::SEPOLIA\_GRAPHQL [#eassepolia_graphql] Sepolia GraphQL endpoint. ```rust pub const SEPOLIA_GRAPHQL: &str; ``` Source line: `12`. ## eas::did\_recipient [#easdid_recipient] Derive the deterministic recipient address for a subject DID: the first 20 bytes of the BLAKE3 digest of the DID's UTF-8 bytes. Attestations about a DID are addressed to this recipient, which makes "every attestation about this subject" an exact-match GraphQL query without a server-side index. This mapping is normative: publishers and resolvers MUST use the same derivation. ```rust pub fn did_recipient(did: &str) -> String; ``` Source line: `21`. ## eas::EasConfig [#easeasconfig] Configuration for an \[`EasAnchor`]. ```rust #[derive(Debug, Clone)] pub struct EasConfig { /// The OAS lineage schema UID on this chain. Per-chain; never hardcoded /// as a global constant because schema registration is per deployment. pub schema_uid: String, /// EAS GraphQL endpoint. pub graphql_url: String, /// Chain JSON-RPC endpoint (for `eth_blockNumber`). pub rpc_url: String, /// Confirmations subtracted from the head to define "finalized". pub confirmation_depth: u64 } ``` Source line: `29`. ## eas::EasConfig::mainnet [#easeasconfigmainnet] A mainnet-shaped config (schema UID still required). ```rust pub fn mainnet(schema_uid: impl Into, rpc_url: impl Into) -> Self; ``` Source line: `43`. ## eas::EasConfig::sepolia [#easeasconfigsepolia] A Sepolia-shaped config. ```rust pub fn sepolia(schema_uid: impl Into, rpc_url: impl Into) -> Self; ``` Source line: `53`. ## eas::EasAnchor [#easeasanchor] The EAS adapter: implements \[`LineageAnchor`] over EAS GraphQL plus JSON-RPC finality. ```rust pub struct EasAnchor { } ``` Source line: `65`. ## eas::EasAnchor::new [#easeasanchornew] Build the adapter. # Errors [#errors] Returns an error if the HTTP client cannot be constructed, or if the schema UID is blank. ```rust pub fn new(config: EasConfig) -> Result; ``` Source line: `77`. ## eas::EasAnchor::config [#easeasanchorconfig] The configuration this anchor was built with. ```rust pub fn config(&self) -> &EasConfig; ``` Source line: `91`. # oas-anchor-eas · error URL: https://docs.openagent.id/reference/rust/oas-anchor-eas/error Markdown: https://docs.openagent.id/reference/rust/oas-anchor-eas/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-anchor-eas/src/error.rs`. SHA-256: `82d4d9420b8634bd02ed098d756ec061b168e538b67a44e38806665192875b4b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::EasError [#erroreaserror] Error types for the EAS anchor adapter. Errors returned by the EAS adapter. Mapped into `oas_resolve::AnchorError` at the trait boundary. ```rust #[derive(Debug, thiserror::Error)] pub enum EasError { /// GraphQL or JSON-RPC transport failure. #[error("eas transport error: {0}")] Transport(String), /// The backend returned a structurally invalid record or an unexpected /// response shape. #[error("invalid eas record: {0}")] InvalidRecord(String), /// ABI encode/decode failure for attestation data. #[error("eas abi error: {0}")] Abi(String), } ``` Source line: `6`. # oas-anchor-eas modules URL: https://docs.openagent.id/reference/rust/oas-anchor-eas Markdown: https://docs.openagent.id/reference/rust/oas-anchor-eas.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-anchor-eas). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-anchor-eas/crate) — 5 declarations * [abi](/reference/rust/oas-anchor-eas/abi) — 4 declarations * [eas](/reference/rust/oas-anchor-eas/eas) — 9 declarations * [error](/reference/rust/oas-anchor-eas/error) — 1 declarations # conformance-runner · handlers URL: https://docs.openagent.id/reference/rust/conformance-runner/handlers Markdown: https://docs.openagent.id/reference/rust/conformance-runner/handlers.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/conformance/runner-rust/src/handlers.rs`. SHA-256: `48534696f198c6051aa4beb4550a4a65c8f1c8c9a9e86fbdc8184b7fbf032b7c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## handlers::run\_vector [#handlersrun_vector] ```rust pub fn run_vector(category: &str, vector: &Vector) -> VectorResult; ``` Source line: `8`. ## handlers::crypto::run [#handlerscryptorun] ```rust pub fn run(v: &Vector) -> Result<(), String>; ``` Source line: `66`. ## handlers::oas::run [#handlersoasrun] ```rust pub fn run(v: &Vector) -> Result<(), String>; ``` Source line: `541`. ## handlers::arsenal::run [#handlersarsenalrun] ```rust pub fn run(v: &Vector) -> Result<(), String>; ``` Source line: `1083`. ## handlers::aegis::run [#handlersaegisrun] ```rust pub fn run(v: &Vector) -> Result<(), String>; ``` Source line: `1497`. ## handlers::openagent::run [#handlersopenagentrun] ```rust pub fn run(v: &Vector) -> Result<(), String>; ``` Source line: `2136`. ## handlers::helpers::op\_str [#handlershelpersop_str] ```rust pub fn op_str(v: &Vector) -> Result<&str, String>; ``` Source line: `2805`. ## handlers::helpers::input\_hex [#handlershelpersinput_hex] ```rust pub fn input_hex(v: &Vector, field: &str) -> Result, String>; ``` Source line: `2812`. ## handlers::helpers::expected\_hex [#handlershelpersexpected_hex] ```rust pub fn expected_hex(v: &Vector, field: &str) -> Result, String>; ``` Source line: `2821`. ## handlers::helpers::expected\_bool [#handlershelpersexpected_bool] ```rust pub fn expected_bool(v: &Vector, field: &str) -> Result; ``` Source line: `2830`. ## handlers::helpers::info\_bytes [#handlershelpersinfo_bytes] ```rust pub fn info_bytes(v: &Vector) -> Result, String>; ``` Source line: `2837`. # conformance-runner modules URL: https://docs.openagent.id/reference/rust/conformance-runner Markdown: https://docs.openagent.id/reference/rust/conformance-runner.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-conformance-runner-rust). [Focused integration guide](/features/conformance). ## Modules [#modules] * [handlers](/reference/rust/conformance-runner/handlers) — 11 declarations * [report](/reference/rust/conformance-runner/report) — 6 declarations * [types](/reference/rust/conformance-runner/types) — 3 declarations # conformance-runner · report URL: https://docs.openagent.id/reference/rust/conformance-runner/report Markdown: https://docs.openagent.id/reference/rust/conformance-runner/report.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/conformance/runner-rust/src/report.rs`. SHA-256: `1d57ff1ae3d961eec391b11f9627e2db13886125afafb326050114bad5b188e7`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## report::Summary [#reportsummary] ```rust #[derive(Debug, Default)] pub struct Summary { pub total_pass: usize, pub total_fail: usize, pub per_category: BTreeMap } ``` Source line: `8`. ## report::Summary::record\_pass [#reportsummaryrecord_pass] ```rust pub fn record_pass(&mut self, category: &str); ``` Source line: `15`. ## report::Summary::record\_fail [#reportsummaryrecord_fail] ```rust pub fn record_fail(&mut self, category: &str); ``` Source line: `23`. ## report::JunitReport [#reportjunitreport] ```rust pub struct JunitReport<'a> { } ``` Source line: `32`. ## report::JunitReport\<'a>::from\_results [#reportjunitreportafrom_results] ```rust pub fn from_results(suite_name: &'a str, results: &'a [VectorResult]) -> Self; ``` Source line: `38`. ## report::JunitReport\<'a>::render [#reportjunitreportarender] ```rust pub fn render(&self) -> String; ``` Source line: `45`. # conformance-runner · types URL: https://docs.openagent.id/reference/rust/conformance-runner/types Markdown: https://docs.openagent.id/reference/rust/conformance-runner/types.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/conformance/runner-rust/src/types.rs`. SHA-256: `909d50c14862d81e62708e0297a49bf0f34dbf3d94f38edd3eddb1c8cc3adb0c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## types::Vector [#typesvector] ```rust #[derive(Debug, Clone, Deserialize)] pub struct Vector { pub name: String, #[serde(default)] pub description: String, #[serde(default)] pub tags: Vec, pub input: serde_json::Value, pub expected_output: serde_json::Value } ``` Source line: `7`. ## types::VectorFile [#typesvectorfile] ```rust #[derive(Debug, Clone)] pub struct VectorFile { pub category: String, pub name: String, pub vectors: Vec, pub source: PathBuf } ``` Source line: `18`. ## types::VectorResult [#typesvectorresult] ```rust #[derive(Debug)] pub struct VectorResult { pub category: String, pub file_name: String, pub vector_name: String, pub outcome: Result<(), String>, pub duration_ms: u64 } ``` Source line: `26`. # oas-attestation · crate URL: https://docs.openagent.id/reference/rust/oas-attestation/crate Markdown: https://docs.openagent.id/reference/rust/oas-attestation/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/lib.rs`. SHA-256: `7effa9fd9902e4f2a6dfbb5e56081f02fd2f4eb2f75299648ce58a5cb9c64078`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## credential [#credential] # oas-attestation [#oas-attestation] W3C Verifiable Credential attestation support for the Open Agent Specification (OAS). This crate implements OAS Specification §13 — Attestation Integration, providing creation, signing, and verification of attestations about autonomous entities. ## Key Types [#key-types] * [`OasCredential`](credential::OasCredential) — W3C VC with OAS constraints * [`AttestationType`](types::AttestationType) — The six standard attestation types * [`CredentialProof`](credential::CredentialProof) — Ed25519Signature2020 proof * \[`AttestationError`] — Attestation-specific errors ## Attestation Types (§13.2) [#attestation-types-132] | Type | Description | | ------------------------ | ------------------------------- | | `SecurityAudit` | Results of security analysis | | `BehaviorAttestation` | Observed runtime behavior | | `CapabilityVerification` | Capability verification results | | `ComplianceAttestation` | Regulatory compliance | | `ExpertEndorsement` | Domain expert endorsement | | `CommunityReview` | Community-sourced review | ## Example [#example] ``` use oas_attestation::credential::OasCredential; use oas_attestation::types::AttestationType; use oas_attestation::sign::sign_credential; use oas_attestation::verify::verify_credential; use oas_crypto::keypair::OasKeyPair; // Build a credential let keypair = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .attestation_type(AttestationType::SecurityAudit) .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build() .unwrap(); // Sign it let signed = sign_credential( &cred, &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", ).unwrap(); // Verify it let result = verify_credential(&signed, &keypair.verifying_key_bytes()); assert!(result.is_ok()); ``` ```rust pub mod credential; ``` Source line: `62`. ## data\_integrity\_2025 [#data_integrity_2025] ```rust pub mod data_integrity_2025; ``` Source line: `63`. ## error [#error] ```rust pub mod error; ``` Source line: `64`. ## lineage\_vc [#lineage_vc] ```rust pub mod lineage_vc; ``` Source line: `65`. ## oid4vp [#oid4vp] ```rust pub mod oid4vp; ``` Source line: `66`. ## presentation [#presentation] ```rust pub mod presentation; ``` Source line: `67`. ## proof\_formats [#proof_formats] ```rust pub mod proof_formats; ``` Source line: `68`. ## sd\_jwt\_vc [#sd_jwt_vc] ```rust pub mod sd_jwt_vc; ``` Source line: `69`. ## sign [#sign] ```rust pub mod sign; ``` Source line: `70`. ## signer [#signer] ```rust pub mod signer; ``` Source line: `71`. ## types [#types] ```rust pub mod types; ``` Source line: `72`. ## vc\_jose [#vc_jose] ```rust pub mod vc_jose; ``` Source line: `73`. ## verify [#verify] ```rust pub mod verify; ``` Source line: `74`. ## pub use credential::ContextMode; [#pub-use-credentialcontextmode] ```rust pub use credential::ContextMode; ``` Source line: `76`. ## pub use data\_integrity\_2025::\{ [#pub-use-data_integrity_2025] algorithm\_to\_cryptosuite, cryptosuite\_to\_algorithm, sign\_credential\_data\_integrity, verify\_credential\_data\_integrity, CRYPTOSUITE\_BBS\_2023, CRYPTOSUITE\_ECDSA\_2019, CRYPTOSUITE\_EDDSA\_2022, DATA\_INTEGRITY\_PROOF\_TYPE, }; ```rust pub use data_integrity_2025::{ algorithm_to_cryptosuite, cryptosuite_to_algorithm, sign_credential_data_integrity, verify_credential_data_integrity, CRYPTOSUITE_BBS_2023, CRYPTOSUITE_ECDSA_2019, CRYPTOSUITE_EDDSA_2022, DATA_INTEGRITY_PROOF_TYPE, }; ``` Source line: `77`. ## pub use error::AttestationError; [#pub-use-errorattestationerror] ```rust pub use error::AttestationError; ``` Source line: `82`. ## pub use lineage\_vc::\{ [#pub-use-lineage_vc] lineage\_proof\_from\_credential, lineage\_proof\_to\_credential, LineageAttestationContext, LineageAttestationData, LineageRootKind, }; ```rust pub use lineage_vc::{ lineage_proof_from_credential, lineage_proof_to_credential, LineageAttestationContext, LineageAttestationData, LineageRootKind, }; ``` Source line: `83`. ## pub use oid4vp::\{ [#pub-use-oid4vp] create\_authorization\_request, create\_oid4vp\_response, verify\_oid4vp\_response, AuthorizationRequest, Constraints, DescriptorMap, InputDescriptor, InputField, Oid4vpResponse, PresentationDefinition, PresentationSubmission, }; ```rust pub use oid4vp::{ create_authorization_request, create_oid4vp_response, verify_oid4vp_response, AuthorizationRequest, Constraints, DescriptorMap, InputDescriptor, InputField, Oid4vpResponse, PresentationDefinition, PresentationSubmission, }; ``` Source line: `87`. ## pub use presentation::\{ [#pub-use-presentation] is\_authority\_bearing, sign\_presentation, verify\_presentation, verify\_presentation\_holder\_binding, verify\_presentation\_holder\_binding\_with\_lineage, verify\_presentation\_holder\_binding\_with\_resolved\_lineage, OasPresentation, PresentationProof, }; ```rust pub use presentation::{ is_authority_bearing, sign_presentation, verify_presentation, verify_presentation_holder_binding, verify_presentation_holder_binding_with_lineage, verify_presentation_holder_binding_with_resolved_lineage, OasPresentation, PresentationProof, }; ``` Source line: `92`. ## pub use proof\_formats::\{Ed25519Signature2020Format, ProofFormat, ProofFormatId}; [#pub-use-proof_formatsed25519signature2020format-proofformat-proofformatid] ```rust pub use proof_formats::{Ed25519Signature2020Format, ProofFormat, ProofFormatId}; ``` Source line: `97`. ## pub use sd\_jwt\_vc::\{ [#pub-use-sd_jwt_vc] present\_sd\_jwt\_vc, sign\_credential\_sd\_jwt\_vc, verify\_sd\_jwt\_vc, Disclosure, SdJwtVc, SdJwtVcHeader, SdJwtVcPayload, SdJwtVcSignOptions, }; ```rust pub use sd_jwt_vc::{ present_sd_jwt_vc, sign_credential_sd_jwt_vc, verify_sd_jwt_vc, Disclosure, SdJwtVc, SdJwtVcHeader, SdJwtVcPayload, SdJwtVcSignOptions, }; ``` Source line: `98`. ## pub use signer::\{OasKeyPairSigner, OasKeyPairVerifier, Signer, Verifier, ALG\_EDDSA}; [#pub-use-signeroaskeypairsigner-oaskeypairverifier-signer-verifier-alg_eddsa] ```rust pub use signer::{OasKeyPairSigner, OasKeyPairVerifier, Signer, Verifier, ALG_EDDSA}; ``` Source line: `102`. ## pub use vc\_jose::\{ [#pub-use-vc_jose] parse\_jwt\_vc, sign\_credential\_jwt\_vc, verify\_jwt\_vc, JwtVc, JwtVcHeader, JwtVcPayload, JwtVcSignOptions, }; ```rust pub use vc_jose::{ parse_jwt_vc, sign_credential_jwt_vc, verify_jwt_vc, JwtVc, JwtVcHeader, JwtVcPayload, JwtVcSignOptions, }; ``` Source line: `103`. # oas-attestation · credential URL: https://docs.openagent.id/reference/rust/oas-attestation/credential Markdown: https://docs.openagent.id/reference/rust/oas-attestation/credential.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/credential.rs`. SHA-256: `63826d2acf8654122b01fedcc8b64fb39e08923edb9fc1d741bbdfdb14ef16f9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## credential::VC\_CONTEXT [#credentialvc_context] The W3C Verifiable Credentials v1.1 context URI. Per OAS Specification §14.1 (v1.2.0), this context is **deprecated** and will be removed in OAS v2.0.0 or after 2027-04-06, whichever occurs first. New credentials SHOULD declare \[`VC_CONTEXT_V2`]; verifiers MUST accept either or both during the transition period. ```rust pub const VC_CONTEXT: &str; ``` Source line: `21`. ## credential::VC\_CONTEXT\_V2 [#credentialvc_context_v2] The W3C Verifiable Credentials Data Model v2.0 context URI. Per OAS Specification §14.1 (v1.2.0), credentials SHOULD declare this context. The legacy \[`VC_CONTEXT`] (v1.1) MAY be additionally declared during the deprecation transition period that ends 2027-04-06 or upon publication of OAS v2.0.0, whichever occurs first. ```rust pub const VC_CONTEXT_V2: &str; ``` Source line: `29`. ## credential::OAS\_ATTESTATION\_CONTEXT [#credentialoas_attestation_context] The OAS attestation context URI. ```rust pub const OAS_ATTESTATION_CONTEXT: &str; ``` Source line: `32`. ## credential::ATTESTATION\_PROOF\_TYPE [#credentialattestation_proof_type] The fixed proof type for `Ed25519Signature2020` (the OAS baseline). ```rust pub const ATTESTATION_PROOF_TYPE: &str; ``` Source line: `35`. ## credential::ContextMode [#credentialcontextmode] JSON-LD context declaration mode for an \[`OasCredential`]. Per OAS Specification §14.1 (v1.2.0), credentials SHOULD declare the W3C Verifiable Credentials v2.0 context. For backward compatibility, they MAY additionally declare the v1.1 context until **2027-04-06** or until publication of OAS v2.0.0, whichever occurs first. Verifiers MUST accept either or both during the transition period. The default is \[`ContextMode::Both`], which emits both v2.0 and v1.1 contexts. This is the safest choice during the transition period — v1.1-only verifiers still accept the credential and v2.0-aware verifiers see the preferred context. # Examples [#examples] ``` use oas_attestation::credential::{ContextMode, OasCredential, VC_CONTEXT, VC_CONTEXT_V2}; use oas_attestation::types::AttestationType; // Default mode (Both) emits the v2.0 context first, then v1.1 for back-compat. let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .issuance_date("2026-01-15T00:00:00Z") .attestation_type(AttestationType::SecurityAudit) .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build() .unwrap(); assert!(cred.context.contains(&VC_CONTEXT_V2.to_string())); assert!(cred.context.contains(&VC_CONTEXT.to_string())); ``` ```rust #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] pub enum ContextMode { /// Emit both v2.0 and v1.1 contexts in canonical order /// (v2.0 first, then v1.1, then the OAS attestation context). /// /// **Default during the transition period** per Spec §14.1. Maximizes /// interoperability with both v1.1-only and v2.0-aware verifiers. #[default] Both, /// Emit only the v2.0 context plus the OAS attestation context. /// /// Use this mode when targeting verifiers that explicitly require v2.0 /// or after the v1.1 deprecation period ends (2027-04-06). V2Only, /// Emit only the v1.1 context plus the OAS attestation context. /// /// **Deprecated.** Reserved for migration tooling and legacy verifier /// compatibility. New code SHOULD use [`ContextMode::Both`] or /// [`ContextMode::V2Only`]. This mode will be removed in OAS v2.0.0. V1Only, } ``` Source line: `74`. ## credential::ContextMode::context\_uris [#credentialcontextmodecontext_uris] Returns the JSON-LD context URIs this mode emits, in canonical order. The OAS attestation context is always appended last regardless of mode. The W3C VC context (v1.1, v2.0, or both) precedes it in the order defined by the variant. # Examples [#examples-1] ``` use oas_attestation::credential::{ ContextMode, OAS_ATTESTATION_CONTEXT, VC_CONTEXT, VC_CONTEXT_V2, }; assert_eq!( ContextMode::Both.context_uris(), vec![VC_CONTEXT_V2, VC_CONTEXT, OAS_ATTESTATION_CONTEXT] ); assert_eq!( ContextMode::V2Only.context_uris(), vec![VC_CONTEXT_V2, OAS_ATTESTATION_CONTEXT] ); assert_eq!( ContextMode::V1Only.context_uris(), vec![VC_CONTEXT, OAS_ATTESTATION_CONTEXT] ); ``` ```rust pub fn context_uris(self) -> Vec<&'static str>; ``` Source line: `122`. ## credential::OasCredential [#credentialoascredential] An OAS Verifiable Credential per Specification §13.1. Combines the W3C VC Data Model v2.0 structure with OAS-specific constraints including `did:oas` issuer/subject requirements and the `oasAttestationType` field. # Examples [#examples-2] ``` use oas_attestation::credential::OasCredential; use oas_attestation::types::AttestationType; let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .attestation_type(AttestationType::SecurityAudit) .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build(); assert!(cred.is_ok()); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OasCredential { /// The JSON-LD context array. #[serde(rename = "@context")] pub context: Vec, /// The credential types (always includes `"VerifiableCredential"`). #[serde(rename = "type")] pub credential_type: Vec, /// The issuer's `did:oas` identifier. pub issuer: String, /// ISO 8601 timestamp when the credential was issued. pub issuance_date: String, /// Optional ISO 8601 expiration timestamp. #[serde(skip_serializing_if = "Option::is_none")] pub expiration_date: Option, /// The credential subject containing the attestation claims. pub credential_subject: serde_json::Value, /// The OAS attestation type per §13.2. #[serde(skip_serializing_if = "Option::is_none")] pub oas_attestation_type: Option, /// The Ed25519Signature2020 proof (populated after signing). #[serde(skip_serializing_if = "Option::is_none")] pub proof: Option } ``` Source line: `157`. ## credential::CredentialProof [#credentialcredentialproof] A credential proof per OAS Specification §13.1 / §14.4. Carries either an `Ed25519Signature2020` proof (the OAS baseline) or a W3C `DataIntegrityProof` (the §14.4 `data-integrity-2025` registered format). The optional [`cryptosuite`](Self::cryptosuite) field distinguishes the two: `Ed25519Signature2020` proofs MUST omit it (so the on-wire JSON is byte-identical to v1.1.0), while `DataIntegrityProof` proofs MUST set it (e.g., `"eddsa-2022"`). See OAS Specification §14.4 for the proof format registry that enumerates the supported `(proof_type, cryptosuite)` pairs. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CredentialProof { /// Either `"Ed25519Signature2020"` (baseline) or `"DataIntegrityProof"` /// (Spec §14.4 `data-integrity-2025` format). #[serde(rename = "type")] pub proof_type: String, /// Cryptosuite identifier — REQUIRED for `DataIntegrityProof`, /// MUST be omitted for `Ed25519Signature2020`. Examples: `"eddsa-2022"`, /// `"ecdsa-2019"`, `"bbs-2023"`. #[serde(default, skip_serializing_if = "Option::is_none")] pub cryptosuite: Option, /// ISO 8601 timestamp when the proof was created. pub created: String, /// Reference to the verification method used. pub verification_method: String, /// The purpose of this proof (e.g., `"assertionMethod"`). pub proof_purpose: String, /// The multibase-encoded (base58btc, `z` prefix) signature bytes. pub proof_value: String } ``` Source line: `201`. ## credential::OasCredential::builder [#credentialoascredentialbuilder] Creates a new \[`CredentialBuilder`] for constructing credentials. # Returns [#returns] A builder with default context and type values pre-populated. ```rust pub fn builder() -> CredentialBuilder; ``` Source line: `232`. ## credential::OasCredential::subject\_id [#credentialoascredentialsubject_id] Returns the subject DID from the credential subject. # Returns [#returns-1] The `id` field value from `credentialSubject`, or `None` if absent. ```rust pub fn subject_id(&self) -> Option<&str>; ``` Source line: `241`. ## credential::OasCredential::to\_json\_without\_proof [#credentialoascredentialto_json_without_proof] Returns a JSON representation of this credential without the proof field. Used during proof generation and verification — the proof field must be absent from the canonical form. # Returns [#returns-2] A \[`serde_json::Value`] with the `proof` field removed. # Errors [#errors] Returns \[`AttestationError::Json`] if serialization fails. ```rust pub fn to_json_without_proof(&self) -> Result; ``` Source line: `260`. ## credential::OasCredential::validate [#credentialoascredentialvalidate] Validates this credential's structure per OAS §13.1 constraints. Checks: * Issuer is a valid `did:oas` identifier * Credential subject `id` is a valid `did:oas` identifier * Required attestation-type fields are present (if type is set) # Returns [#returns-3] `Ok(())` if the credential is structurally valid. # Errors [#errors-1] Returns an \[`AttestationError`] variant describing the validation failure. ```rust pub fn validate(&self) -> Result<(), AttestationError>; ``` Source line: `282`. ## credential::CredentialBuilder [#credentialcredentialbuilder] Builder for constructing \[`OasCredential`] instances. Provides a fluent API for setting credential fields, with validation performed at build time. # Examples [#examples-3] ``` use oas_attestation::credential::OasCredential; use oas_attestation::types::AttestationType; let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .attestation_type(AttestationType::SecurityAudit) .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build(); assert!(cred.is_ok()); ``` ```rust #[derive(Debug, Default)] pub struct CredentialBuilder { } ``` Source line: `336`. ## credential::CredentialBuilder::issuer [#credentialcredentialbuilderissuer] Sets the issuer DID. # Arguments [#arguments] * `issuer` - A `did:oas` identifier for the entity issuing this credential. ```rust pub fn issuer(mut self, issuer: &str) -> Self; ``` Source line: `352`. ## credential::CredentialBuilder::subject\_id [#credentialcredentialbuildersubject_id] Sets the credential subject DID. # Arguments [#arguments-1] * `subject_id` - A `did:oas` identifier for the entity this credential is about. ```rust pub fn subject_id(mut self, subject_id: &str) -> Self; ``` Source line: `362`. ## credential::CredentialBuilder::attestation\_type [#credentialcredentialbuilderattestation_type] Sets the attestation type. # Arguments [#arguments-2] * `attestation_type` - The OAS §13.2 attestation type. ```rust pub fn attestation_type(mut self, attestation_type: AttestationType) -> Self; ``` Source line: `372`. ## credential::CredentialBuilder::issuance\_date [#credentialcredentialbuilderissuance_date] Sets the issuance date. # Arguments [#arguments-3] * `date` - ISO 8601 timestamp. ```rust pub fn issuance_date(mut self, date: &str) -> Self; ``` Source line: `382`. ## credential::CredentialBuilder::expiration\_date [#credentialcredentialbuilderexpiration_date] Sets an optional expiration date. # Arguments [#arguments-4] * `date` - ISO 8601 timestamp. ```rust pub fn expiration_date(mut self, date: &str) -> Self; ``` Source line: `392`. ## credential::CredentialBuilder::subject\_claim [#credentialcredentialbuildersubject_claim] Adds a claim to the credential subject. # Arguments [#arguments-5] * `key` - The claim name. * `value` - The claim value. ```rust pub fn subject_claim(mut self, key: &str, value: serde_json::Value) -> Self; ``` Source line: `403`. ## credential::CredentialBuilder::context\_mode [#credentialcredentialbuildercontext_mode] Sets the JSON-LD context declaration mode per OAS Spec §14.1. The default is \[`ContextMode::Both`], which emits both the v2.0 and v1.1 W3C VC contexts during the deprecation transition period that ends 2027-04-06 or upon publication of OAS v2.0.0, whichever occurs first. # Arguments [#arguments-6] * `mode` - The \[`ContextMode`] to use for this credential. # Examples [#examples-4] ``` use oas_attestation::credential::{ContextMode, OasCredential, VC_CONTEXT, VC_CONTEXT_V2}; use oas_attestation::types::AttestationType; let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .issuance_date("2026-01-15T00:00:00Z") .context_mode(ContextMode::V2Only) .attestation_type(AttestationType::SecurityAudit) .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build() .unwrap(); assert!(cred.context.contains(&VC_CONTEXT_V2.to_string())); assert!(!cred.context.contains(&VC_CONTEXT.to_string())); ``` ```rust pub fn context_mode(mut self, mode: ContextMode) -> Self; ``` Source line: `442`. ## credential::CredentialBuilder::build [#credentialcredentialbuilderbuild] Builds the credential, validating all constraints. # Returns [#returns-4] A validated \[`OasCredential`] ready for signing. # Errors [#errors-2] Returns an \[`AttestationError`] if required fields are missing or invalid. ```rust pub fn build(self) -> Result; ``` Source line: `456`. # oas-attestation · data_integrity_2025 URL: https://docs.openagent.id/reference/rust/oas-attestation/data_integrity_2025 Markdown: https://docs.openagent.id/reference/rust/oas-attestation/data_integrity_2025.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/data_integrity_2025.rs`. SHA-256: `28cb729f15f34a8b2c6b569850b60134f9aba33eee273babf7a3e549089422f8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## data\_integrity\_2025::DATA\_INTEGRITY\_PROOF\_TYPE [#data_integrity_2025data_integrity_proof_type] Fixed proof type literal for W3C `DataIntegrityProof`. ```rust pub const DATA_INTEGRITY_PROOF_TYPE: &str; ``` Source line: `90`. ## data\_integrity\_2025::ASSERTION\_METHOD [#data_integrity_2025assertion_method] Fixed proof purpose literal for issuer assertions. ```rust pub const ASSERTION_METHOD: &str; ``` Source line: `93`. ## data\_integrity\_2025::CRYPTOSUITE\_EDDSA\_2022 [#data_integrity_2025cryptosuite_eddsa_2022] W3C cryptosuite identifier for Ed25519 over JCS canonicalization. ```rust pub const CRYPTOSUITE_EDDSA_2022: &str; ``` Source line: `100`. ## data\_integrity\_2025::CRYPTOSUITE\_ECDSA\_2019 [#data_integrity_2025cryptosuite_ecdsa_2019] W3C cryptosuite identifier for ECDSA P-256 over JCS canonicalization. ```rust pub const CRYPTOSUITE_ECDSA_2019: &str; ``` Source line: `103`. ## data\_integrity\_2025::CRYPTOSUITE\_BBS\_2023 [#data_integrity_2025cryptosuite_bbs_2023] W3C cryptosuite identifier for BBS+ (selective disclosure capable). ```rust pub const CRYPTOSUITE_BBS_2023: &str; ``` Source line: `106`. ## data\_integrity\_2025::algorithm\_to\_cryptosuite [#data_integrity_2025algorithm_to_cryptosuite] Maps a JOSE-style algorithm identifier (as returned by \[`Signer::algorithm`]) to its W3C Data Integrity cryptosuite identifier. # Examples [#examples] ``` use oas_attestation::data_integrity_2025::algorithm_to_cryptosuite; assert_eq!(algorithm_to_cryptosuite("EdDSA"), Some("eddsa-2022")); assert_eq!(algorithm_to_cryptosuite("ES256"), Some("ecdsa-2019")); assert_eq!(algorithm_to_cryptosuite("BBS"), Some("bbs-2023")); assert_eq!(algorithm_to_cryptosuite("RS256"), None); ``` ```rust pub fn algorithm_to_cryptosuite(algorithm: &str) -> Option<&'static str>; ``` Source line: `121`. ## data\_integrity\_2025::cryptosuite\_to\_algorithm [#data_integrity_2025cryptosuite_to_algorithm] Reverse mapping — given a W3C cryptosuite identifier, returns the expected JOSE-style algorithm identifier the verifier MUST report. ```rust pub fn cryptosuite_to_algorithm(cryptosuite: &str) -> Option<&'static str>; ``` Source line: `132`. ## data\_integrity\_2025::sign\_credential\_data\_integrity [#data_integrity_2025sign_credential_data_integrity] Signs an \[`OasCredential`] with a W3C `DataIntegrityProof` per OAS Spec §14.4 `data-integrity-2025`. The signing payload is the JCS canonicalization of the credential **without** the `proof` field — the same scheme used by \[`crate::sign::sign_credential`]. The cryptosuite identifier is derived from the signer's algorithm via \[`algorithm_to_cryptosuite`]. # Arguments [#arguments] * `credential` - The unsigned credential. * `signer` - Any \[`Signer`] implementation. * `verification_method_id` - The full verification method ID (e.g., `"did:oas:test:hmr:auditor#key-1"`). * `created` - ISO 8601 timestamp for the proof. # Errors [#errors] * \[`AttestationError::ProofGenerationFailed`] if canonicalization or signing fails. * \[`AttestationError::UnknownProofFormat`] if the signer's algorithm has no registered cryptosuite mapping. ```rust pub fn sign_credential_data_integrity( credential: &OasCredential, signer: &dyn Signer, verification_method_id: &str, created: &str, ) -> Result; ``` Source line: `167`. ## data\_integrity\_2025::verify\_credential\_data\_integrity [#data_integrity_2025verify_credential_data_integrity] Verifies an \[`OasCredential`] signed with a `DataIntegrityProof` per OAS Spec §14.4 `data-integrity-2025`. 1. Validates the credential structure. 2. Checks the proof exists and uses `DataIntegrityProof`. 3. Checks the proof has a `cryptosuite` field. 4. Cross-validates that the cryptosuite matches the verifier's `algorithm()` via \[`cryptosuite_to_algorithm`] — preventing the verifier from accidentally accepting a proof signed with the wrong suite. 5. Reconstructs the JCS canonical bytes (without proof) and verifies the signature. # Errors [#errors-1] * \[`AttestationError::MissingProof`] if no proof is present. * \[`AttestationError::InvalidProofSignature`] for any structural, suite-mismatch, or cryptographic failure. ```rust pub fn verify_credential_data_integrity( credential: &OasCredential, verifier: &dyn Verifier, ) -> Result<(), AttestationError>; ``` Source line: `234`. ## data\_integrity\_2025::format\_id [#data_integrity_2025format_id] Returns the registered OAS proof format ID for `data-integrity-2025`. ```rust pub const fn format_id() -> ProofFormatId; ``` Source line: `311`. ## data\_integrity\_2025::format\_url [#data_integrity_2025format_url] Returns the canonical OAS format identifier URL. ```rust pub const fn format_url() -> &'static str; ``` Source line: `316`. # oas-attestation · error URL: https://docs.openagent.id/reference/rust/oas-attestation/error Markdown: https://docs.openagent.id/reference/rust/oas-attestation/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/error.rs`. SHA-256: `ee13cdd8789399eec1bea08dfe05a8b1d5a9074549b2fa08c0d807b470697e30`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::AttestationError [#errorattestationerror] Errors that can occur during attestation operations. Covers credential creation, signing, and verification. ```rust #[derive(Debug, Error)] pub enum AttestationError { /// The issuer DID is not a valid `did:oas` identifier. #[error("invalid issuer DID: {issuer}")] InvalidIssuer { /// The invalid issuer DID. issuer: String, }, /// The credential subject DID is not a valid `did:oas` identifier. #[error("invalid credential subject DID: {subject}")] InvalidSubject { /// The invalid subject DID. subject: String, }, /// The attestation type is not recognized. #[error("unrecognized attestation type: '{found}'")] UnknownAttestationType { /// The unrecognized type. found: String, }, /// The credential proof is missing. #[error("credential proof is missing")] MissingProof, /// The credential proof signature is invalid. #[error("credential proof signature invalid: {reason}")] InvalidProofSignature { /// Details about the signature failure. reason: String, }, /// Proof generation failed. #[error("credential proof generation failed: {reason}")] ProofGenerationFailed { /// Details about the failure. reason: String, }, /// The credential has expired. #[error("credential expired at {expiration}")] Expired { /// The expiration timestamp. expiration: String, }, /// The credential is not yet valid. #[error("credential not valid until {valid_from}")] NotYetValid { /// The earliest valid timestamp. valid_from: String, }, /// A required field is missing from the credential subject. #[error("credential subject missing required field: '{field}'")] MissingField { /// The missing field name. field: String, }, /// The presentation's challenge (nonce) does not match the verifier's /// expected value. Per OAS Spec §14.5, replay protection requires the /// presentation proof to bind a verifier-supplied nonce; mismatches MUST /// cause rejection. #[error( "presentation challenge mismatch: expected '{expected}', got '{actual}' (replay \ protection per OAS Spec §14.5)" )] PresentationChallengeMismatch { /// The verifier-supplied nonce. expected: String, /// The nonce embedded in the presentation proof. actual: String, }, /// The presentation's domain (audience) does not match the verifier's /// identifier. Per OAS Spec §14.5, the audience prevents cross-verifier /// replay; mismatches MUST cause rejection. #[error( "presentation domain mismatch: expected '{expected}', got '{actual}' (audience \ binding per OAS Spec §14.5)" )] PresentationDomainMismatch { /// The verifier's identifier. expected: String, /// The domain embedded in the presentation proof. actual: String, }, /// A holder lineage chain submitted for §14.5.1 descendant-form holder /// binding check is structurally invalid: chain continuity is broken /// (a proof's `parent_did` does not match the next proof's `child_did`), /// the chain does not start at the presentation holder, or one of the /// proofs failed cryptographic verification. #[error("holder lineage chain invalid: {reason} (OAS Spec §14.5.1)")] LineageChainInvalid { /// Specific reason the chain failed validation. reason: String, }, /// The presentation violates the Holder Binding Rule from OAS Spec /// §14.5.1: an authority-bearing attestation (e.g., `CapabilityVerification`) /// is being presented by a holder whose DID is neither the credential /// subject nor a lineage descendant of the subject. #[error( "holder binding violation: holder '{holder}' is not the subject (or a lineage \ descendant of) authority-bearing credential subject '{subject}' for attestation \ type '{attestation_type}' (OAS Spec §14.5.1)" )] HolderBindingViolation { /// The presentation holder DID. holder: String, /// The authority-bearing credential subject DID. subject: String, /// The credential's attestation type (e.g., `CapabilityVerification`). attestation_type: String, }, /// The proof format identifier is not in the OAS proof format registry /// (Spec §14.4). Per spec, verifiers MUST reject credentials whose proof /// format is unrecognized; callers SHOULD propagate this error. #[error( "unknown proof format identifier: '{format_id}' is not in the OAS \ §14.4 registry; expected one of \ 'https://openagent.id/proof/ed25519-2020', \ 'https://openagent.id/proof/vc-jose', \ 'https://openagent.id/proof/sd-jwt-vc', \ 'https://openagent.id/proof/data-integrity-2025'" )] UnknownProofFormat { /// The unrecognized format identifier as presented on the wire. format_id: String, }, /// A JSON serialization error. #[error("JSON error: {0}")] Json(#[from] serde_json::Error), /// An underlying cryptographic error. #[error("cryptographic error: {0}")] Crypto(#[from] oas_crypto::CryptoError), } ``` Source line: `10`. # oas-attestation modules URL: https://docs.openagent.id/reference/rust/oas-attestation Markdown: https://docs.openagent.id/reference/rust/oas-attestation.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-attestation). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-attestation/crate) — 23 declarations * [credential](/reference/rust/oas-attestation/credential) — 21 declarations * [data\_integrity\_2025](/reference/rust/oas-attestation/data_integrity_2025) — 11 declarations * [error](/reference/rust/oas-attestation/error) — 1 declarations * [lineage\_vc](/reference/rust/oas-attestation/lineage_vc) — 6 declarations * [oid4vp](/reference/rust/oas-attestation/oid4vp) — 14 declarations * [presentation](/reference/rust/oas-attestation/presentation) — 18 declarations * [proof\_formats](/reference/rust/oas-attestation/proof_formats) — 13 declarations * [sd\_jwt\_vc](/reference/rust/oas-attestation/sd_jwt_vc) — 31 declarations * [sign](/reference/rust/oas-attestation/sign) — 1 declarations * [signer](/reference/rust/oas-attestation/signer) — 7 declarations * [types](/reference/rust/oas-attestation/types) — 4 declarations * [vc\_jose](/reference/rust/oas-attestation/vc_jose) — 21 declarations * [verify](/reference/rust/oas-attestation/verify) — 2 declarations # oas-attestation · lineage_vc URL: https://docs.openagent.id/reference/rust/oas-attestation/lineage_vc Markdown: https://docs.openagent.id/reference/rust/oas-attestation/lineage_vc.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/lineage_vc.rs`. SHA-256: `ad645c49dca7878d8e4a9e1c805951c07f48b18ef627edb4315b95a2fdb76e3a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## lineage\_vc::LineageRootKind [#lineage_vclineagerootkind] The kind of root anchor a lineage chain terminates at, per OAS Spec §14.7.1. On the wire, encoded as the lowercase string `"hmr"`, `"mhr"`, or `"enr"` to match the spec example in §14.7.1. # Examples [#examples] ``` use oas_attestation::lineage_vc::LineageRootKind; assert_eq!(LineageRootKind::Hmr.as_str(), "hmr"); assert_eq!(LineageRootKind::Mhr.as_str(), "mhr"); assert_eq!(LineageRootKind::Enr.as_str(), "enr"); assert_eq!("hmr".parse::().unwrap(), LineageRootKind::Hmr); assert!("invalid".parse::().is_err()); ``` ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LineageRootKind { /// Human Root (HMR) per OAS Spec §6 — single human accountability anchor. Hmr, /// Multi-Human Root (MHR) per OAS Spec §7 — threshold-signed multi-party anchor. Mhr, /// Enterprise Root (ENR) per OAS Spec §8 — MHR-governed enterprise anchor. Enr, } ``` Source line: `95`. ## lineage\_vc::LineageRootKind::as\_str [#lineage_vclineagerootkindas_str] Returns the canonical lowercase string form used on the wire. ```rust pub const fn as_str(self) -> &'static str; ``` Source line: `106`. ## lineage\_vc::LineageAttestationContext [#lineage_vclineageattestationcontext] Per-link metadata that \[`AgentLineageProof`] does not carry but the LineageAttestation credential subject schema requires. Per OAS Spec §14.7.1, the credential subject MUST contain `generationDepth`, `rootAnchor`, `rootKind`, and `derivedAt`. The native [`AgentLineageProof2025`](AgentLineageProof) does not encode these fields, so callers using the bridge MUST supply them. The values are typically derived from the lineage walking context: `generation_depth` from the chain walker's depth counter, `root_anchor` from the topmost ancestor's DID, `root_kind` from inspecting that ancestor's identity document, and `derived_at` from the parent's derivation log. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct LineageAttestationContext { /// Generation depth from the nearest root, where 1 is the first /// derivation from the root and increases by 1 per hop. Must be in /// the range `[1, MAX_GENERATION]` per OAS Spec §10 (`MAX_GENERATION = 16`). pub generation_depth: u32, /// Root anchor DID — the topmost ancestor in the lineage chain. MUST be /// a valid `did:oas` identifier of kind `hmr`, `mhr`, or `enr`. pub root_anchor: String, /// The root kind matching `root_anchor`'s entity kind. pub root_kind: LineageRootKind, /// ISO 8601 UTC timestamp marking when the derivation occurred. pub derived_at: String } ``` Source line: `158`. ## lineage\_vc::LineageAttestationData [#lineage_vclineageattestationdata] All lineage data extracted from a `LineageAttestation` credential by \[`lineage_proof_from_credential`]. This is the round-trip target type. Calling `lineage_proof_to_credential(proof, ctx)` then `lineage_proof_from_credential(...)` MUST produce a value where every field matches the original `proof` and `ctx` exactly. This guarantee is enforced by the round-trip property test in this module. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct LineageAttestationData { /// Parent DID (matches `AgentLineageProof::parent_did` and the credential /// `issuer`). pub parent_did: String, /// Child DID (matches `AgentLineageProof::child_did` and the credential /// `credentialSubject.id`). pub child_did: String, /// HKDF derivation path (matches `AgentLineageProof::derivation_path`). pub derivation_path: String, /// Generation depth from the root (caller-supplied, not in /// `AgentLineageProof`). pub generation_depth: u32, /// Root anchor DID (caller-supplied). pub root_anchor: String, /// Root kind (caller-supplied). pub root_kind: LineageRootKind, /// Derivation timestamp (caller-supplied). pub derived_at: String } ``` Source line: `185`. ## lineage\_vc::lineage\_proof\_to\_credential [#lineage_vclineage_proof_to_credential] Converts an [`AgentLineageProof2025`](AgentLineageProof) into an \[`OasCredential`] of type `LineageAttestation` per OAS Spec §14.7. The returned credential is **unsigned** — callers who need a signed VC MUST sign it separately using \[`crate::sign::sign_credential`] (or the equivalent \[`crate::proof_formats::Ed25519Signature2020Format`] trait dispatch). Per Spec §14.7.2, the signature MUST be produced by the parent's signing key, the same key authorized to produce the equivalent `AgentLineageProof2025`. The [`AttestationContext`](LineageAttestationContext) parameter supplies the four spec-required subject fields that \[`AgentLineageProof`] does not itself carry: `generation_depth`, `root_anchor`, `root_kind`, `derived_at`. # Arguments [#arguments] * `proof` - The native lineage proof to bridge. * `ctx` - The per-link metadata required by Spec §14.7.1. # Returns [#returns] An unsigned \[`OasCredential`] with `oasAttestationType: LineageAttestation` and all six required subject fields populated. # Errors [#errors] Returns \[`AttestationError`] if the resulting credential fails structural validation (e.g., parent or child DIDs are not valid `did:oas` identifiers). # Examples [#examples-1] ``` use oas_attestation::lineage_vc::{ lineage_proof_to_credential, LineageAttestationContext, LineageRootKind, }; use oas_attestation::types::AttestationType; use oas_crypto::keypair::OasKeyPair; use oas_crypto::proof::AgentLineageProof; let parent = OasKeyPair::generate(); let proof = AgentLineageProof::generate( &parent, "did:oas:test:hmr:alice", "did:oas:test:agent:bot", "/agent-bot", ).unwrap(); let ctx = LineageAttestationContext { generation_depth: 1, root_anchor: "did:oas:test:hmr:alice".to_string(), root_kind: LineageRootKind::Hmr, derived_at: "2026-04-06T00:00:00Z".to_string(), }; let cred = lineage_proof_to_credential(&proof, &ctx).unwrap(); assert_eq!(cred.issuer, "did:oas:test:hmr:alice"); assert_eq!(cred.oas_attestation_type, Some(AttestationType::LineageAttestation)); ``` ```rust pub fn lineage_proof_to_credential( proof: &AgentLineageProof, ctx: &LineageAttestationContext, ) -> Result; ``` Source line: `268`. ## lineage\_vc::lineage\_proof\_from\_credential [#lineage_vclineage_proof_from_credential] Extracts \[`LineageAttestationData`] from an \[`OasCredential`] previously produced by \[`lineage_proof_to_credential`] (or any other source that follows the OAS Spec §14.7.1 schema). This is the inverse of \[`lineage_proof_to_credential`]. Round-trip (`to_credential` → `from_credential`) is byte-equivalent in all shared fields and is enforced by the property test in this module. # Arguments [#arguments-1] * `credential` - A credential whose `oasAttestationType` is `LineageAttestation` and whose subject contains all six required fields. # Returns [#returns-1] A populated \[`LineageAttestationData`]. # Errors [#errors-1] * \[`AttestationError::UnknownAttestationType`] if the credential's `oasAttestationType` is not `LineageAttestation`. * \[`AttestationError::MissingField`] if any required subject field is missing or has the wrong JSON type. * \[`AttestationError::InvalidSubject`] if the subject `id` is missing or not a valid `did:oas` identifier. # Examples [#examples-2] ``` use oas_attestation::lineage_vc::{ lineage_proof_from_credential, lineage_proof_to_credential, LineageAttestationContext, LineageRootKind, }; use oas_crypto::keypair::OasKeyPair; use oas_crypto::proof::AgentLineageProof; let parent = OasKeyPair::generate(); let proof = AgentLineageProof::generate( &parent, "did:oas:test:hmr:alice", "did:oas:test:agent:bot", "/agent-bot", ).unwrap(); let ctx = LineageAttestationContext { generation_depth: 1, root_anchor: "did:oas:test:hmr:alice".to_string(), root_kind: LineageRootKind::Hmr, derived_at: "2026-04-06T00:00:00Z".to_string(), }; let cred = lineage_proof_to_credential(&proof, &ctx).unwrap(); let data = lineage_proof_from_credential(&cred).unwrap(); assert_eq!(data.parent_did, proof.parent_did); assert_eq!(data.child_did, proof.child_did); assert_eq!(data.derivation_path, proof.derivation_path); assert_eq!(data.generation_depth, ctx.generation_depth); ``` ```rust pub fn lineage_proof_from_credential( credential: &OasCredential, ) -> Result; ``` Source line: `363`. # oas-attestation · oid4vp URL: https://docs.openagent.id/reference/rust/oas-attestation/oid4vp Markdown: https://docs.openagent.id/reference/rust/oas-attestation/oid4vp.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/oid4vp.rs`. SHA-256: `93be1a5e1335c2ba0bd9657bc94547d8becc78be721afa638c2fc6722af37854`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## oid4vp::RESPONSE\_TYPE\_VP\_TOKEN [#oid4vpresponse_type_vp_token] Default OID4VP `response_type` value for verifiable presentations. ```rust pub const RESPONSE_TYPE_VP_TOKEN: &str; ``` Source line: `140`. ## oid4vp::RESPONSE\_MODE\_DIRECT\_POST [#oid4vpresponse_mode_direct_post] Default OID4VP `response_mode` value for direct POST responses. ```rust pub const RESPONSE_MODE_DIRECT_POST: &str; ``` Source line: `143`. ## oid4vp::PresentationDefinition [#oid4vppresentationdefinition] Verifier-side declaration of what credentials a holder must present. Per the OID4VP / DIF Presentation Exchange spec, a presentation definition is the contract between the verifier and the holder: it names a set of input descriptors, each describing one credential the verifier wants to see. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PresentationDefinition { /// Unique identifier for this definition. pub id: String, /// Optional human-readable name (shown to the holder during consent). #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// Optional human-readable purpose explaining why the verifier needs /// the credentials. #[serde(skip_serializing_if = "Option::is_none")] pub purpose: Option, /// One or more input descriptors, each describing a credential the /// verifier requires. pub input_descriptors: Vec } ``` Source line: `156`. ## oid4vp::InputDescriptor [#oid4vpinputdescriptor] A single credential requirement within a \[`PresentationDefinition`]. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct InputDescriptor { /// Unique identifier for this descriptor (the holder's /// [`DescriptorMap`] entries reference it by ID). pub id: String, /// Optional name shown to the holder. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// Optional human-readable purpose. #[serde(skip_serializing_if = "Option::is_none")] pub purpose: Option, /// Constraints — field path expressions and filters the credential /// must satisfy. #[serde(default, skip_serializing_if = "Constraints::is_empty")] pub constraints: Constraints } ``` Source line: `176`. ## oid4vp::Constraints [#oid4vpconstraints] Constraint set for an \[`InputDescriptor`]. ```rust #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Constraints { /// One or more required field path expressions and filters. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub fields: Vec } ``` Source line: `197`. ## oid4vp::Constraints::is\_empty [#oid4vpconstraintsis_empty] Returns `true` if no constraints are declared. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `205`. ## oid4vp::InputField [#oid4vpinputfield] A single field constraint within a \[`Constraints`] block. Per DIF Presentation Exchange, each field carries a list of JSONPath expressions identifying where the value should be found in the credential, plus an optional JSON Schema filter the value must satisfy. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct InputField { /// JSONPath expressions pointing to candidate locations in the credential. pub path: Vec, /// Optional human-readable purpose. #[serde(skip_serializing_if = "Option::is_none")] pub purpose: Option, /// Optional JSON Schema filter the resolved value must satisfy. #[serde(skip_serializing_if = "Option::is_none")] pub filter: Option } ``` Source line: `216`. ## oid4vp::AuthorizationRequest [#oid4vpauthorizationrequest] OID4VP Authorization Request — issued by the verifier and delivered to the holder over any transport (URL query string, custom messaging, QR code, deep link). ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AuthorizationRequest { /// OAuth 2.0 `response_type` — fixed to `"vp_token"` for OID4VP. pub response_type: String, /// OAuth 2.0 `response_mode` — typically `"direct_post"` for OID4VP. pub response_mode: String, /// Verifier identifier (audience). Becomes `proof.domain` on the /// holder's signed presentation. MUST be cross-checked at verify time. pub client_id: String, /// Verifier-supplied nonce. Becomes `proof.challenge` on the holder's /// signed presentation. MUST be cross-checked at verify time. pub nonce: String, /// Optional opaque state echoed back unchanged in the response. #[serde(skip_serializing_if = "Option::is_none")] pub state: Option, /// The presentation definition the holder must satisfy. pub presentation_definition: PresentationDefinition } ``` Source line: `237`. ## oid4vp::create\_authorization\_request [#oid4vpcreate_authorization_request] Constructs an \[`AuthorizationRequest`] with default `response_type` and `response_mode` values. ```rust pub fn create_authorization_request( definition: PresentationDefinition, nonce: impl Into, client_id: impl Into, ) -> AuthorizationRequest; ``` Source line: `262`. ## oid4vp::PresentationSubmission [#oid4vppresentationsubmission] Holder-side mapping from the credentials in `vp_token` back to the verifier's input descriptors. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PresentationSubmission { /// Unique identifier for this submission. pub id: String, /// Identifier of the presentation definition this submission satisfies. pub definition_id: String, /// One descriptor map entry per credential in `vp_token`. pub descriptor_map: Vec } ``` Source line: `284`. ## oid4vp::DescriptorMap [#oid4vpdescriptormap] A single entry in a \[`PresentationSubmission`]'s descriptor map. Tells the verifier where to find a credential within the `vp_token` and which proof format to use to verify it. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DescriptorMap { /// Identifier of the [`InputDescriptor`] this credential satisfies. pub id: String, /// Proof format identifier from the OAS Spec §14.4 registry. Verifiers /// route the credential to the matching verification routine based on /// this value. pub format: String, /// JSONPath expression pointing to the credential within the `vp_token`. /// `"$"` means the entire `vp_token` IS the credential (single-credential /// case). pub path: String } ``` Source line: `300`. ## oid4vp::Oid4vpResponse [#oid4vpoid4vpresponse] The holder's full OID4VP response carrying the signed presentation, the submission descriptor map, and the echoed state. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Oid4vpResponse { /// The signed [`OasPresentation`] (or, for non-OAS formats, an opaque /// JSON value). For OAS attestation flows this is the W3C VP from /// [`crate::presentation::sign_presentation`]. pub vp_token: serde_json::Value, /// Submission map — one entry per credential in `vp_token`. pub presentation_submission: PresentationSubmission, /// Echoed `state` from the request, if the request included one. #[serde(skip_serializing_if = "Option::is_none")] pub state: Option } ``` Source line: `322`. ## oid4vp::create\_oid4vp\_response [#oid4vpcreate_oid4vp_response] Constructs an \[`Oid4vpResponse`] from a verifier request and a holder-signed presentation. The function: 1. Cross-checks the presentation's `proof.challenge` against `request.nonce` so the response cannot be built with a stale or mismatched VP. 2. Cross-checks the presentation's `proof.domain` against `request.client_id` for the same reason. 3. Serializes the presentation as the `vp_token`. 4. Echoes the request's `state`. # Errors [#errors] * \[`AttestationError::PresentationChallengeMismatch`] if the VP's challenge doesn't match the request nonce. * \[`AttestationError::PresentationDomainMismatch`] if the VP's domain doesn't match the request client\_id. * \[`AttestationError::MissingProof`] if the VP is unsigned. ```rust pub fn create_oid4vp_response( request: &AuthorizationRequest, presentation: OasPresentation, descriptor_map: Vec, ) -> Result; ``` Source line: `355`. ## oid4vp::verify\_oid4vp\_response [#oid4vpverify_oid4vp_response] Validates an \[`Oid4vpResponse`] against an \[`AuthorizationRequest`] and the holder's public key. 1. Validates that `response.presentation_submission.definition_id` matches `request.presentation_definition.id`. 2. Parses `response.vp_token` as an \[`OasPresentation`]. 3. Calls \[`crate::presentation::verify_presentation`] with the request's nonce and client\_id, which enforces the cryptographic challenge + domain replay protection per Spec §14.5. 4. Confirms the descriptor map is non-empty (the verifier's input descriptors must be satisfied — a presentation with zero descriptors is rejected). On success, returns the parsed \[`OasPresentation`] for further inspection (e.g., to apply the holder binding rule from §14.5.1). # Errors [#errors-1] * \[`AttestationError::MissingField`] if the definition IDs don't match or the descriptor map is empty. * \[`AttestationError::Json`] if `vp_token` doesn't parse as a presentation. * Any error from \[`verify_presentation`] (signature, challenge, domain). ```rust pub fn verify_oid4vp_response( response: &Oid4vpResponse, request: &AuthorizationRequest, holder_public_key: &[u8], ) -> Result; ``` Source line: `416`. # oas-attestation · presentation URL: https://docs.openagent.id/reference/rust/oas-attestation/presentation Markdown: https://docs.openagent.id/reference/rust/oas-attestation/presentation.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/presentation.rs`. SHA-256: `b987664d14728ebd7f56f3d60db3ab60cc953031fa55d7a29ba0f0d2a8af7a7e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## presentation::PRESENTATION\_TYPE [#presentationpresentation_type] The credential / presentation type literal `"VerifiablePresentation"`. ```rust pub const PRESENTATION_TYPE: &str; ``` Source line: `108`. ## presentation::OAS\_PRESENTATION\_TYPE [#presentationoas_presentation_type] The credential / presentation type literal `"OasPresentation"`. ```rust pub const OAS_PRESENTATION_TYPE: &str; ``` Source line: `111`. ## presentation::AUTHENTICATION\_PURPOSE [#presentationauthentication_purpose] The fixed proof purpose for presentation proofs (per W3C VP spec). ```rust pub const AUTHENTICATION_PURPOSE: &str; ``` Source line: `114`. ## presentation::OasPresentation [#presentationoaspresentation] An OAS Verifiable Presentation per Spec §14.5. Wraps one or more \[`OasCredential`]s for transmission from a holder to a verifier. The presentation carries its own \[`PresentationProof`] (separate from the per-credential proofs) that binds the holder's signing key, the verifier-supplied challenge, and the verifier's domain — providing replay protection across sessions and verifiers. # Examples [#examples] ``` use oas_attestation::credential::OasCredential; use oas_attestation::presentation::OasPresentation; use oas_attestation::types::AttestationType; let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:bot") .attestation_type(AttestationType::SecurityAudit) .issuance_date("2026-04-06T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-04-06T00:00:00Z")) .build() .unwrap(); let vp = OasPresentation::builder() .holder("did:oas:test:agent:bot") .add_credential(cred) .build() .unwrap(); assert_eq!(vp.holder, "did:oas:test:agent:bot"); assert_eq!(vp.verifiable_credential.len(), 1); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OasPresentation { /// JSON-LD context array. #[serde(rename = "@context")] pub context: Vec, /// VP type array (always includes `"VerifiablePresentation"` and /// `"OasPresentation"`). #[serde(rename = "type")] pub presentation_type: Vec, /// The holder's `did:oas` identifier — the entity presenting this VP. pub holder: String, /// One or more verifiable credentials wrapped by this presentation. pub verifiable_credential: Vec, /// The presentation proof (populated by [`sign_presentation`]). #[serde(skip_serializing_if = "Option::is_none")] pub proof: Option } ``` Source line: `159`. ## presentation::PresentationProof [#presentationpresentationproof] An Ed25519Signature2020 proof on a \[`OasPresentation`]. Per Spec §14.5, the proof structure includes a `challenge` (verifier nonce) and `domain` (verifier audience identifier), both of which are part of the signed payload. Tampering with either invalidates the signature. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PresentationProof { /// Fixed: `"Ed25519Signature2020"` (the OAS baseline format). #[serde(rename = "type")] pub proof_type: String, /// ISO 8601 timestamp when the proof was created. pub created: String, /// Reference to the verification method used by the holder. pub verification_method: String, /// Fixed: `"authentication"` (W3C VP convention for VP proofs). pub proof_purpose: String, /// Verifier-supplied nonce — bound into the signature for replay /// protection across sessions. pub challenge: String, /// Verifier audience identifier — bound into the signature for replay /// protection across verifiers. pub domain: String, /// Multibase base58btc-encoded Ed25519 signature. pub proof_value: String } ``` Source line: `188`. ## presentation::OasPresentation::builder [#presentationoaspresentationbuilder] Creates a new \[`PresentationBuilder`] with sensible defaults. ```rust pub fn builder() -> PresentationBuilder; ``` Source line: `216`. ## presentation::OasPresentation::validate [#presentationoaspresentationvalidate] Validates the presentation's structural invariants per Spec §14.5. Checks: * `holder` is a valid `did:oas` identifier * At least one credential is present * Every contained credential individually validates per §14.1 # Errors [#errors] Returns \[`AttestationError`] on the first failure. ```rust pub fn validate(&self) -> Result<(), AttestationError>; ``` Source line: `230`. ## presentation::PresentationBuilder [#presentationpresentationbuilder] Builder for \[`OasPresentation`]. ```rust #[derive(Debug, Default)] pub struct PresentationBuilder { } ``` Source line: `260`. ## presentation::PresentationBuilder::holder [#presentationpresentationbuilderholder] Sets the holder DID — the `did:oas` identifier of the presenting entity. ```rust pub fn holder(mut self, holder: &str) -> Self; ``` Source line: `267`. ## presentation::PresentationBuilder::add\_credential [#presentationpresentationbuilderadd_credential] Adds a credential to the presentation. Multiple credentials may be included; all are covered by the single presentation proof. ```rust pub fn add_credential(mut self, credential: OasCredential) -> Self; ``` Source line: `274`. ## presentation::PresentationBuilder::add\_credentials [#presentationpresentationbuilderadd_credentials] Adds multiple credentials at once. ```rust pub fn add_credentials(mut self, credentials: impl IntoIterator) -> Self; ``` Source line: `280`. ## presentation::PresentationBuilder::build [#presentationpresentationbuilderbuild] Builds an unsigned \[`OasPresentation`]. # Errors [#errors-1] Returns \[`AttestationError`] if the holder is missing or invalid, or if no credentials were added. ```rust pub fn build(self) -> Result; ``` Source line: `291`. ## presentation::sign\_presentation [#presentationsign_presentation] Signs an \[`OasPresentation`], producing a new presentation with an attached \[`PresentationProof`]. Per OAS Spec §14.5: 1. Validates the presentation structure 2. Constructs the proof with the supplied challenge and domain 3. Sets `proof.proofValue` to empty string 4. JCS-canonicalizes the entire presentation 5. Signs the canonical bytes with the holder's Ed25519 key 6. Encodes the signature as multibase base58btc and stores it in `proof.proofValue` # Arguments [#arguments] * `presentation` - The unsigned presentation. * `holder_keypair` - The holder's signing keypair. * `verification_method_id` - Full verification method ID (e.g., `"did:oas:test:agent:bot#key-1"`). * `created` - ISO 8601 timestamp for the proof. * `challenge` - Verifier-supplied nonce (Spec §14.5 replay protection). * `domain` - Verifier audience identifier (Spec §14.5 replay protection). # Returns [#returns] A new \[`OasPresentation`] with the proof field populated. # Errors [#errors-2] Returns \[`AttestationError`] if validation, canonicalization, or signing fails. ```rust pub fn sign_presentation( mut presentation: OasPresentation, holder_keypair: &OasKeyPair, verification_method_id: &str, created: &str, challenge: &str, domain: &str, ) -> Result; ``` Source line: `373`. ## presentation::verify\_presentation [#presentationverify_presentation] Verifies an \[`OasPresentation`] against a holder public key, with challenge and domain replay protection. Per OAS Spec §14.5: 1. Validates the presentation structure 2. Checks the proof exists and uses Ed25519Signature2020 3. Checks the challenge matches the verifier's expected nonce 4. Checks the domain matches the verifier's expected audience 5. Reconstructs the canonical bytes (with proofValue set to empty) 6. Verifies the Ed25519 signature against the holder's public key This function does NOT enforce the §14.5.1 Holder Binding Rule. Use \[`verify_presentation_holder_binding`] for that check, or call this function followed by the binding check. # Arguments [#arguments-1] * `presentation` - The signed presentation to verify. * `holder_public_key` - The holder's 32-byte Ed25519 public key. * `expected_challenge` - The nonce the verifier originally issued. * `expected_domain` - The verifier's audience identifier. # Errors [#errors-3] * \[`AttestationError::MissingProof`] if the presentation has no proof. * \[`AttestationError::PresentationChallengeMismatch`] on nonce mismatch. * \[`AttestationError::PresentationDomainMismatch`] on audience mismatch. * \[`AttestationError::InvalidProofSignature`] on signature failure. ```rust pub fn verify_presentation( presentation: &OasPresentation, holder_public_key: &[u8], expected_challenge: &str, expected_domain: &str, ) -> Result<(), AttestationError>; ``` Source line: `435`. ## presentation::is\_authority\_bearing [#presentationis_authority_bearing] Returns `true` if the given attestation type is authority-bearing per Spec §14.5.1, meaning the strict-equality holder binding rule applies. Per Spec §14.5.1, only `CapabilityVerification` is authority-bearing among the standard types. Custom attestation types may opt in to authority- bearing classification via their registered schema; this function does not currently consult an external schema registry, so all `Custom` types default to factual. Callers needing custom-schema-aware classification should wrap this function and override for their custom types. ```rust pub fn is_authority_bearing(attestation_type: &AttestationType) -> bool; ``` Source line: `508`. ## presentation::verify\_presentation\_holder\_binding [#presentationverify_presentation_holder_binding] Enforces the §14.5.1 Holder Binding Rule (strict-equality form) on a presentation. Per Spec §14.5.1: * **Authority-bearing** attestations (`CapabilityVerification` and any custom type marked authority-bearing): the holder MUST be the credential subject, OR a lineage descendant of the subject. * **Factual** attestations (`SecurityAudit`, `BehaviorAttestation`, `ComplianceAttestation`, `ExpertEndorsement`, `CommunityReview`, `LineageAttestation`): any holder MAY present. This function enforces only the **strict-equality** branch (`holder == subject`). For the descendant branch, use \[`verify_presentation_holder_binding_with_lineage`], which accepts a holder lineage chain and accepts the binding when the credential subject is any ancestor of the holder. # Arguments [#arguments-2] * `presentation` - The presentation to check. # Returns [#returns-1] `Ok(())` if the rule is satisfied for every contained credential. # Errors [#errors-4] Returns \[`AttestationError::HolderBindingViolation`] on the first authority-bearing credential whose subject DID does not match the holder. ```rust pub fn verify_presentation_holder_binding( presentation: &OasPresentation, ) -> Result<(), AttestationError>; ``` Source line: `541`. ## presentation::verify\_presentation\_holder\_binding\_with\_lineage [#presentationverify_presentation_holder_binding_with_lineage] Legacy raw-proof entry point for the §14.5.1 Holder Binding Rule. Non-empty raw proof chains fail closed because they do not carry validated parent documents or verifier root policy. Use \[`verify_presentation_holder_binding_with_resolved_lineage`] for descendant-aware authorization. # Arguments [#arguments-3] * `presentation` - The signed presentation to check. * `holder_lineage_chain` - Legacy raw proofs. Only an empty slice is accepted, yielding strict-equality semantics. # Errors [#errors-5] * \[`AttestationError::LineageChainInvalid`] if any raw proof is supplied. * \[`AttestationError::HolderBindingViolation`] if any authority-bearing credential's subject is neither the holder nor any ancestor proven by the chain. # Examples [#examples-1] ``` use oas_attestation::credential::OasCredential; use oas_attestation::presentation::{ verify_presentation_holder_binding_with_lineage, OasPresentation, }; use oas_attestation::sign::sign_credential; use oas_attestation::types::AttestationType; use oas_crypto::keypair::OasKeyPair; use oas_crypto::proof::AgentLineageProof; // Parent issues a CapabilityVerification credential about itself. let parent_kp = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:parent") .subject_id("did:oas:test:hmr:parent") .attestation_type(AttestationType::CapabilityVerification) .issuance_date("2026-04-06T00:00:00Z") .subject_claim("capabilities", serde_json::json!(["data-extraction"])) .subject_claim("verificationMethod", serde_json::json!("benchmark")) .subject_claim("verificationDate", serde_json::json!("2026-04-06T00:00:00Z")) .build() .unwrap(); let signed = sign_credential( &cred, &parent_kp, "did:oas:test:hmr:parent#key-1", "2026-04-06T00:00:00Z", ).unwrap(); // Parent derives a child agent and the child holds the proof of descent. let lineage = AgentLineageProof::generate( &parent_kp, "did:oas:test:hmr:parent", "did:oas:test:agent:child", "/agent-child", ).unwrap(); // Child holds a presentation containing the parent's capability — this is // legitimate because the child is a lineage descendant of the parent. let vp = OasPresentation::builder() .holder("did:oas:test:agent:child") .add_credential(signed) .build() .unwrap(); // Raw proofs cannot select their own verification authority. assert!(verify_presentation_holder_binding_with_lineage(&vp, &[lineage]).is_err()); ``` ```rust pub fn verify_presentation_holder_binding_with_lineage( presentation: &OasPresentation, holder_lineage_chain: &[oas_crypto::proof::AgentLineageProof], ) -> Result<(), AttestationError>; ``` Source line: `668`. ## presentation::verify\_presentation\_holder\_binding\_with\_resolved\_lineage [#presentationverify_presentation_holder_binding_with_resolved_lineage] Verifies descendant holder binding through the strict lineage verifier. This is the authorizing descendant-aware API. It resolves and validates the complete holder lineage, including parent document keys, signed bindings, chain continuity, current status, and verifier-controlled root anchors, before considering any ancestor credential subject covered. # Errors [#errors-6] Returns \[`AttestationError::LineageChainInvalid`] if the holder document does not match the presentation or strict lineage verification fails. Returns \[`AttestationError::HolderBindingViolation`] when an authority-bearing credential subject is outside the verified chain. ```rust pub fn verify_presentation_holder_binding_with_resolved_lineage( presentation: &OasPresentation, holder_document: &oas_document::OasDocument, provider: &dyn oas_lineage::provider::DocumentProvider, config: &oas_lineage::config::VerifyConfig, ) -> Result<(), AttestationError>; ``` Source line: `689`. # oas-attestation · proof_formats URL: https://docs.openagent.id/reference/rust/oas-attestation/proof_formats Markdown: https://docs.openagent.id/reference/rust/oas-attestation/proof_formats.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/proof_formats.rs`. SHA-256: `958972941e10c17fae5359fed57dc1d21160a60a60bc1560f21a121015c423bb`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proof\_formats::ED25519\_2020 [#proof_formatsed25519_2020] Identifier for the `Ed25519Signature2020` proof format (baseline). This is the baseline format every conformant OAS implementation MUST support per Spec §14.4. JSON-LD encoded, no selective disclosure, no holder key binding. The signature is multibase base58btc encoded under the `proofValue` field of \[`crate::credential::CredentialProof`]. ```rust pub const ED25519_2020: &str; ``` Source line: `68`. ## proof\_formats::VC\_JOSE [#proof_formatsvc_jose] Identifier for the `vc-jose` (JWT-VC, VC-JOSE-COSE) proof format. Compact JWS encoding suitable for transports that prefer JWT. Holder key binding is provided via the `cnf` (confirmation) claim per \[RFC 7800]. Implementations supporting this format MUST decline selective disclosure requests on credentials encoded with it; use \[`SD_JWT_VC`] for selective disclosure. ```rust pub const VC_JOSE: &str; ``` Source line: `77`. ## proof\_formats::SD\_JWT\_VC [#proof_formatssd_jwt_vc] Identifier for the `sd-jwt-vc` (SD-JWT VC) proof format. Compact serialization with salted-hash selective disclosure. Holder key binding via the `cnf` claim per \[RFC 7800]. Implementations using this format MUST use a freshly generated salt per disclosable claim per issuance, per OAS Spec §14.6.2. The non-selective fields enumerated in Spec §14.6.1 (`issuer`, `credentialSubject.id`, `oasAttestationType`, `issuanceDate`, and any present `expirationDate`) MUST always be disclosed to preserve verifier policy enforcement. ```rust pub const SD_JWT_VC: &str; ``` Source line: `90`. ## proof\_formats::DATA\_INTEGRITY\_2025 [#proof_formatsdata_integrity_2025] Identifier for the `data-integrity-2025` (`DataIntegrityProof`) format. JSON-LD encoded with optional selective disclosure via BBS+ signature suites. Holder key binding via proof options. Implementations using BBS+ MAY produce unlinkable presentations that prevent correlation across multiple presentations of the same underlying credential. ```rust pub const DATA_INTEGRITY_2025: &str; ``` Source line: `98`. ## proof\_formats::ProofFormatId [#proof_formatsproofformatid] A registered OAS proof format identifier. Per OAS Specification §14.4, this enum enumerates the four format identifiers reserved by spec version 1.2.0. Implementations MAY register additional formats via the IANA registration procedure described in §18 or in a future spec version; future identifiers will be added as variants here. Verifiers MUST reject credentials whose proof format identifier is not in this registry. Implementations MUST NOT silently ignore unknown proof types. # Examples [#examples] ``` use oas_attestation::proof_formats::{ProofFormatId, ED25519_2020}; let id = ProofFormatId::Ed25519Signature2020; assert_eq!(id.url(), ED25519_2020); assert!(id.is_baseline()); assert!(!id.supports_selective_disclosure()); ``` ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ProofFormatId { /// `Ed25519Signature2020` — the OAS baseline. JSON-LD, no SD, no holder /// key binding. Identifier: [`ED25519_2020`]. Ed25519Signature2020, /// `vc-jose` — JWT-VC compact JWS encoding. Holder key binding via `cnf`. /// Identifier: [`VC_JOSE`]. VcJose, /// `sd-jwt-vc` — SD-JWT VC with salted-hash selective disclosure. /// Identifier: [`SD_JWT_VC`]. SdJwtVc, /// `data-integrity-2025` — JSON-LD `DataIntegrityProof` with optional BBS+ /// selective disclosure. Identifier: [`DATA_INTEGRITY_2025`]. DataIntegrity2025, } ``` Source line: `125`. ## proof\_formats::ProofFormatId::url [#proof_formatsproofformatidurl] Returns the dereferenceable HTTPS identifier URL for this format. Per OAS Spec §14.4, implementations MAY abbreviate format identifiers in code-level constants but MUST emit and accept the full HTTPS identifier on the wire. # Returns [#returns] A `&'static str` containing the canonical HTTPS URL. # Examples [#examples-1] ``` use oas_attestation::proof_formats::ProofFormatId; assert_eq!( ProofFormatId::Ed25519Signature2020.url(), "https://openagent.id/proof/ed25519-2020" ); ``` ```rust pub const fn url(self) -> &'static str; ``` Source line: `161`. ## proof\_formats::ProofFormatId::from\_url [#proof_formatsproofformatidfrom_url] Parses a \[`ProofFormatId`] from its dereferenceable HTTPS identifier. # Arguments [#arguments] * `url` - The HTTPS format identifier as published in OAS Spec §14.4. # Returns [#returns-1] `Ok(ProofFormatId)` if the URL matches a registered format. # Errors [#errors] Returns \[`AttestationError::UnknownProofFormat`] if the URL is not in the registry. Per Spec §14.4, verifiers encountering an unrecognized format MUST reject the credential — callers SHOULD propagate this error and refuse the credential. # Examples [#examples-2] ``` use oas_attestation::proof_formats::{ProofFormatId, SD_JWT_VC}; let parsed = ProofFormatId::from_url(SD_JWT_VC).unwrap(); assert_eq!(parsed, ProofFormatId::SdJwtVc); let unknown = ProofFormatId::from_url("https://example.com/unknown"); assert!(unknown.is_err()); ``` ```rust pub fn from_url(url: &str) -> Result; ``` Source line: `198`. ## proof\_formats::ProofFormatId::is\_baseline [#proof_formatsproofformatidis_baseline] Returns `true` if this format is the OAS baseline. Per Spec §14.4, every conformant implementation MUST support the baseline format. Currently only `Ed25519Signature2020` is the baseline. # Examples [#examples-3] ``` use oas_attestation::proof_formats::ProofFormatId; assert!(ProofFormatId::Ed25519Signature2020.is_baseline()); assert!(!ProofFormatId::SdJwtVc.is_baseline()); ``` ```rust pub const fn is_baseline(self) -> bool; ``` Source line: `231`. ## proof\_formats::ProofFormatId::supports\_selective\_disclosure [#proof_formatsproofformatidsupports_selective_disclosure] Returns `true` if this format supports selective disclosure. Per Spec §14.6, only formats with this capability flag set MAY be used to issue credentials whose claims will be selectively disclosed at presentation time. # Examples [#examples-4] ``` use oas_attestation::proof_formats::ProofFormatId; assert!(!ProofFormatId::Ed25519Signature2020.supports_selective_disclosure()); assert!(!ProofFormatId::VcJose.supports_selective_disclosure()); assert!(ProofFormatId::SdJwtVc.supports_selective_disclosure()); // data-integrity-2025 supports SD only when the BBS+ suite is used; // the registry flag indicates capability, not unconditional support. assert!(ProofFormatId::DataIntegrity2025.supports_selective_disclosure()); ``` ```rust pub const fn supports_selective_disclosure(self) -> bool; ``` Source line: `253`. ## proof\_formats::ProofFormatId::supports\_holder\_key\_binding [#proof_formatsproofformatidsupports_holder_key_binding] Returns `true` if this format supports holder key binding at presentation time. Per Spec §14.5, presentations of authority-bearing attestations (`CapabilityVerification` and any custom type that opts in) MUST be bound to the holder's key. Formats that do not support holder key binding cannot be used for authority-bearing attestations that may be presented by a descendant of the subject. # Examples [#examples-5] ``` use oas_attestation::proof_formats::ProofFormatId; assert!(!ProofFormatId::Ed25519Signature2020.supports_holder_key_binding()); assert!(ProofFormatId::VcJose.supports_holder_key_binding()); assert!(ProofFormatId::SdJwtVc.supports_holder_key_binding()); assert!(ProofFormatId::DataIntegrity2025.supports_holder_key_binding()); ``` ```rust pub const fn supports_holder_key_binding(self) -> bool; ``` Source line: `276`. ## proof\_formats::ProofFormatId::legacy\_proof\_type [#proof_formatsproofformatidlegacy_proof_type] Returns the legacy proof `type` string used in JSON-LD encoded credentials, if applicable. Only JSON-LD formats (`Ed25519Signature2020` and `data-integrity-2025`) carry a proof `type` field in the credential document. Compact-encoded formats (JWT-VC, SD-JWT VC) do not. # Returns [#returns-2] `Some(&str)` for JSON-LD formats, `None` for compact-encoded formats. # Examples [#examples-6] ``` use oas_attestation::proof_formats::ProofFormatId; assert_eq!( ProofFormatId::Ed25519Signature2020.legacy_proof_type(), Some("Ed25519Signature2020") ); assert_eq!( ProofFormatId::DataIntegrity2025.legacy_proof_type(), Some("DataIntegrityProof") ); assert_eq!(ProofFormatId::SdJwtVc.legacy_proof_type(), None); assert_eq!(ProofFormatId::VcJose.legacy_proof_type(), None); ``` ```rust pub const fn legacy_proof_type(self) -> Option<&'static str>; ``` Source line: `307`. ## proof\_formats::ProofFormat [#proof_formatsproofformat] Trait abstraction for OAS credential proof formats. Per OAS Specification §14.4 (v1.2.0), this trait is the dispatch surface every proof format implementation MUST satisfy. Implementations are stateless, reusable across many credentials, and `Send + Sync` so they can be stored in registry maps shared across threads or trait objects. The baseline implementation is \[`Ed25519Signature2020Format`], which every conformant OAS implementation MUST support per §14.4. # Future Format Implementations [#future-format-implementations] Additional proof formats (`vc-jose`, `sd-jwt-vc`, `data-integrity-2025`) will implement this trait in subsequent crate versions. Each new format will live in its own submodule behind a feature flag and will conform to the same `sign` / `verify` shape defined here. # Examples [#examples-7] ``` use oas_attestation::credential::OasCredential; use oas_attestation::proof_formats::{Ed25519Signature2020Format, ProofFormat}; use oas_attestation::types::AttestationType; use oas_crypto::keypair::OasKeyPair; let format = Ed25519Signature2020Format; let keypair = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .attestation_type(AttestationType::SecurityAudit) .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build() .unwrap(); let signed = format.sign( &cred, &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", ).unwrap(); assert!(format.verify(&signed, &keypair.verifying_key_bytes()).is_ok()); ``` ```rust pub trait ProofFormat: Send + Sync { /// Returns the registered format identifier per Spec §14.4. fn format_id(&self) -> ProofFormatId; /// Returns `true` if this format supports selective disclosure of claims /// per Spec §14.6. Default delegates to the format identifier's /// capability flag. fn supports_selective_disclosure(&self) -> bool ; /// Returns `true` if this format supports holder key binding at /// presentation time per Spec §14.5. Default delegates to the format /// identifier's capability flag. fn supports_holder_key_binding(&self) -> bool ; /// Signs an OAS credential with this proof format and returns a new /// credential with the proof field populated. /// /// # Arguments /// /// * `credential` - The unsigned credential to sign. /// * `keypair` - The issuer's signing keypair. /// * `verification_method_id` - Full ID of the verification method /// (e.g., `"did:oas:test:hmr:auditor#key-1"`). /// * `created` - ISO 8601 timestamp for the proof. /// /// # Returns /// /// A new [`OasCredential`] with the `proof` field populated. /// /// # Errors /// /// Returns [`AttestationError`] if validation, canonicalization, or /// signing fails. fn sign( &self, credential: &OasCredential, keypair: &OasKeyPair, verification_method_id: &str, created: &str, ) -> Result; /// Verifies a signed credential against a known issuer public key. /// /// # Arguments /// /// * `credential` - The signed credential to verify. /// * `issuer_public_key` - The 32-byte Ed25519 public key of the issuer. /// /// # Returns /// /// `Ok(())` if the credential is valid and the proof verifies. /// /// # Errors /// /// Returns [`AttestationError`] on any validation or signature failure. /// Per Spec §14.4, verifiers encountering an unrecognized format MUST /// reject the credential. fn verify( &self, credential: &OasCredential, issuer_public_key: &[u8], ) -> Result<(), AttestationError>; } ``` Source line: `378`. ## proof\_formats::Ed25519Signature2020Format [#proof_formatsed25519signature2020format] The baseline `Ed25519Signature2020` proof format implementation per Spec §14.4. This is the format every conformant OAS implementation MUST support. It uses JCS canonicalization (RFC 8785) and Ed25519 signatures with multibase base58btc encoding for the proof value, as defined in Spec §13.1. The implementation delegates to the existing module-level \[`crate::sign::sign_credential`] and \[`crate::verify::verify_credential`] functions, preserving the existing public API while adding trait-based dispatch for users who need to swap formats at runtime. # Examples [#examples-8] ``` use oas_attestation::credential::OasCredential; use oas_attestation::proof_formats::{Ed25519Signature2020Format, ProofFormat, ProofFormatId}; use oas_attestation::types::AttestationType; use oas_crypto::keypair::OasKeyPair; let format = Ed25519Signature2020Format; assert_eq!(format.format_id(), ProofFormatId::Ed25519Signature2020); assert!(format.format_id().is_baseline()); assert!(!format.supports_selective_disclosure()); assert!(!format.supports_holder_key_binding()); let keypair = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .attestation_type(AttestationType::SecurityAudit) .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build() .unwrap(); let signed = format.sign( &cred, &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", ).unwrap(); assert!(format.verify(&signed, &keypair.verifying_key_bytes()).is_ok()); ``` ```rust #[derive(Debug, Default, Clone, Copy)] pub struct Ed25519Signature2020Format; ``` Source line: `495`. # oas-attestation · sd_jwt_vc URL: https://docs.openagent.id/reference/rust/oas-attestation/sd_jwt_vc Markdown: https://docs.openagent.id/reference/rust/oas-attestation/sd_jwt_vc.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/sd_jwt_vc.rs`. SHA-256: `030aa958aaddddb462b84a41e56bec4b794538a7f12304be56759d3537fa1a9d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## sd\_jwt\_vc::SD\_JWT\_VC\_TYP [#sd_jwt_vcsd_jwt_vc_typ] SD-JWT VC media type per draft-ietf-oauth-sd-jwt-vc. ```rust pub const SD_JWT_VC_TYP: &str; ``` Source line: `125`. ## sd\_jwt\_vc::VC\_CLAIM [#sd_jwt_vcvc_claim] JWT payload claim name carrying the OAS credential body. ```rust pub const VC_CLAIM: &str; ``` Source line: `128`. ## sd\_jwt\_vc::SD\_CLAIM [#sd_jwt_vcsd_claim] JWT payload claim name carrying the array of disclosure hashes. ```rust pub const SD_CLAIM: &str; ``` Source line: `131`. ## sd\_jwt\_vc::SD\_ALG\_CLAIM [#sd_jwt_vcsd_alg_claim] JWT payload claim name declaring the hash algorithm used for `_sd`. ```rust pub const SD_ALG_CLAIM: &str; ``` Source line: `134`. ## sd\_jwt\_vc::SD\_ALG\_SHA256 [#sd_jwt_vcsd_alg_sha256] Hash algorithm used for `_sd` digests (`"sha-256"` per the IETF spec). ```rust pub const SD_ALG_SHA256: &str; ``` Source line: `137`. ## sd\_jwt\_vc::SALT\_BYTE\_LENGTH [#sd_jwt_vcsalt_byte_length] Salt length in bytes (16 bytes = 128 bits, matching the IETF reference). ```rust pub const SALT_BYTE_LENGTH: usize; ``` Source line: `140`. ## sd\_jwt\_vc::NON\_SELECTIVE\_SUBJECT\_FIELDS [#sd_jwt_vcnon_selective_subject_fields] Fields that MUST always be disclosed per OAS Spec §14.6.1. These are emitted as plain payload claims, not as `_sd` hashes, so they are visible to every verifier regardless of which disclosures the holder chooses to present. ```rust pub const NON_SELECTIVE_SUBJECT_FIELDS: &[&str]; ``` Source line: `147`. ## sd\_jwt\_vc::Disclosure [#sd_jwt_vcdisclosure] A single SD-JWT VC disclosure: a salted commitment to one credential claim, in the form `[salt, claim_name, claim_value]`. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct Disclosure { /// Base64url-encoded random salt (16 bytes raw). pub salt: String, /// The claim name being disclosed. pub claim_name: String, /// The claim value being disclosed. pub claim_value: serde_json::Value } ``` Source line: `156`. ## sd\_jwt\_vc::Disclosure::new\_with\_random\_salt [#sd_jwt_vcdisclosurenew_with_random_salt] Constructs a disclosure with a freshly generated 16-byte random salt via `OsRng`. Per Spec §14.6.2, implementations MUST use a fresh salt per claim per issuance. ```rust pub fn new_with_random_salt( claim_name: impl Into, claim_value: serde_json::Value, ) -> Self; ``` Source line: `169`. ## sd\_jwt\_vc::Disclosure::with\_salt [#sd_jwt_vcdisclosurewith_salt] Constructs a disclosure with a caller-supplied salt. Use this only for deterministic test fixtures; production code MUST use \[`Self::new_with_random_salt`]. ```rust pub fn with_salt( salt: impl Into, claim_name: impl Into, claim_value: serde_json::Value, ) -> Self; ``` Source line: `185`. ## sd\_jwt\_vc::Disclosure::to\_b64 [#sd_jwt_vcdisclosureto_b64] Encodes the disclosure as base64url(JSON(\[salt, claim\_name, claim\_value])). ```rust pub fn to_b64(&self) -> Result; ``` Source line: `198`. ## sd\_jwt\_vc::Disclosure::from\_b64 [#sd_jwt_vcdisclosurefrom_b64] Parses a disclosure from its base64url(JSON) form. ```rust pub fn from_b64(b64: &str) -> Result; ``` Source line: `209`. ## sd\_jwt\_vc::Disclosure::hash [#sd_jwt_vcdisclosurehash] Returns the base64url-encoded SHA-256 hash of the disclosure's base64url string. This is the value placed in the payload's `_sd` array per Spec §14.6 + draft-ietf-oauth-sd-jwt-vc. ```rust pub fn hash(&self) -> Result; ``` Source line: `252`. ## sd\_jwt\_vc::SdJwtVcPayload [#sd_jwt_vcsdjwtvcpayload] SD-JWT VC payload — JWT registered claims plus `_sd` (disclosure hashes), `_sd_alg` (hash algorithm), and the always-disclosed `vc` body. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SdJwtVcPayload { pub iss: String, pub sub: String, #[serde(skip_serializing_if = "Option::is_none")] pub nbf: Option, #[serde(skip_serializing_if = "Option::is_none")] pub exp: Option, #[serde(skip_serializing_if = "Option::is_none")] pub jti: Option, #[serde(skip_serializing_if = "Option::is_none")] pub cnf: Option, /// Hash algorithm declaration — fixed to `"sha-256"`. #[serde(rename = "_sd_alg")] pub sd_alg: String, /// Disclosure hash digests, in arbitrary order. #[serde(rename = "_sd")] pub sd: Vec, /// The OAS credential body, with selectively disclosable claims removed /// from `credentialSubject`. The non-selective fields per Spec §14.6.1 /// remain in place. pub vc: serde_json::Value } ``` Source line: `268`. ## sd\_jwt\_vc::SdJwtVcHeader [#sd_jwt_vcsdjwtvcheader] JOSE header for an SD-JWT VC. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SdJwtVcHeader { pub alg: String, pub typ: String, pub kid: String } ``` Source line: `297`. ## sd\_jwt\_vc::SdJwtVcHeader::new [#sd_jwt_vcsdjwtvcheadernew] ```rust pub fn new(alg: impl Into, kid: impl Into) -> Self; ``` Source line: `304`. ## sd\_jwt\_vc::SdJwtVcSignOptions [#sd_jwt_vcsdjwtvcsignoptions] Caller-supplied options for \[`sign_credential_sd_jwt_vc`]. ```rust #[derive(Debug, Clone)] pub struct SdJwtVcSignOptions { pub verification_method_id: String, pub issuance_unix_seconds: Option, pub jwt_id: Option, pub holder_public_key_jwk: Option } ``` Source line: `319`. ## sd\_jwt\_vc::SdJwtVc [#sd_jwt_vcsdjwtvc] An issuer-signed SD-JWT VC, including all original disclosures. At presentation time, the holder uses \[`present_sd_jwt_vc`] to produce a new compact form containing only a subset of disclosures. ```rust #[derive(Debug, Clone)] pub struct SdJwtVc { } ``` Source line: `335`. ## sd\_jwt\_vc::SdJwtVc::header [#sd_jwt_vcsdjwtvcheader-1] ```rust pub fn header(&self) -> &SdJwtVcHeader; ``` Source line: `348`. ## sd\_jwt\_vc::SdJwtVc::payload [#sd_jwt_vcsdjwtvcpayload-1] ```rust pub fn payload(&self) -> &SdJwtVcPayload; ``` Source line: `351`. ## sd\_jwt\_vc::SdJwtVc::disclosures [#sd_jwt_vcsdjwtvcdisclosures] ```rust pub fn disclosures(&self) -> &[Disclosure]; ``` Source line: `354`. ## sd\_jwt\_vc::SdJwtVc::as\_compact\_string [#sd_jwt_vcsdjwtvcas_compact_string] ```rust pub fn as_compact_string(&self) -> &str; ``` Source line: `357`. ## sd\_jwt\_vc::SdJwtVc::issuer [#sd_jwt_vcsdjwtvcissuer] ```rust pub fn issuer(&self) -> &str; ``` Source line: `360`. ## sd\_jwt\_vc::SdJwtVc::subject [#sd_jwt_vcsdjwtvcsubject] ```rust pub fn subject(&self) -> &str; ``` Source line: `363`. ## sd\_jwt\_vc::SdJwtVc::algorithm [#sd_jwt_vcsdjwtvcalgorithm] ```rust pub fn algorithm(&self) -> &str; ``` Source line: `366`. ## sd\_jwt\_vc::SdJwtVc::disclosed\_claim [#sd_jwt_vcsdjwtvcdisclosed_claim] Returns a disclosed claim by name, or `None` if it isn't included in the disclosures (either because the holder didn't include it or because it was never disclosable). ```rust pub fn disclosed_claim(&self, claim_name: &str) -> Option<&serde_json::Value>; ``` Source line: `373`. ## sd\_jwt\_vc::SdJwtVc::format\_id [#sd_jwt_vcsdjwtvcformat_id] ```rust pub const fn format_id() -> ProofFormatId; ``` Source line: `380`. ## sd\_jwt\_vc::SdJwtVc::format\_url [#sd_jwt_vcsdjwtvcformat_url] ```rust pub const fn format_url() -> &'static str; ``` Source line: `383`. ## sd\_jwt\_vc::sign\_credential\_sd\_jwt\_vc [#sd_jwt_vcsign_credential_sd_jwt_vc] Issues an SD-JWT VC for the given credential. Per Spec §14.6.1, the non-selective fields (`issuer`, `credentialSubject.id`, `oasAttestationType`, `issuanceDate`, `expirationDate`) remain in plain view. All other `credentialSubject` fields become selectively disclosable disclosures. The returned \[`SdJwtVc`] holds the full set of disclosures so the holder can later choose which subset to present via \[`present_sd_jwt_vc`]. ```rust pub fn sign_credential_sd_jwt_vc( credential: &OasCredential, signer: &dyn Signer, options: &SdJwtVcSignOptions, ) -> Result; ``` Source line: `426`. ## sd\_jwt\_vc::verify\_sd\_jwt\_vc [#sd_jwt_vcverify_sd_jwt_vc] Verifies an SD-JWT VC compact string against an issuer \[`Verifier`]. Per Spec §14.6 + draft-ietf-oauth-sd-jwt-vc: 1. Splits the compact form on `~` — first segment is the JWT, remaining are disclosures (with the trailing tilde producing an empty final element which is dropped). 2. Validates the JOSE header type is `vc+sd-jwt`. 3. Enforces algorithm match between header and verifier. 4. Verifies the JWT signature over `header.payload`. 5. For each presented disclosure, recomputes its hash and confirms the hash is in the payload's `_sd` array. **Disclosures whose hash is not in `_sd` cause rejection** — this is the integrity binding that prevents holders from injecting unrelated claims. On success, returns an \[`SdJwtVc`] populated with the disclosures included in the input. The verifier can then call `disclosed_claim` to inspect individual revealed claims. ```rust pub fn verify_sd_jwt_vc( compact: &str, verifier: &dyn Verifier, ) -> Result; ``` Source line: `544`. ## sd\_jwt\_vc::present\_sd\_jwt\_vc [#sd_jwt_vcpresent_sd_jwt_vc] Builds a derived SD-JWT VC presentation containing only the disclosures for the requested claim names. Per Spec §14.6, the holder can selectively reveal a subset of the originally disclosed claims at presentation time. The verifier still validates the JWT signature against the issuer key — the `_sd` hashes commit to all disclosures the issuer attached, so the holder cannot invent new claims, only choose which to hide. Claim names not present in the original disclosures are silently skipped (they may be non-selective fields that are already plain-view in the payload). ```rust pub fn present_sd_jwt_vc( issued: &SdJwtVc, claims_to_disclose: &[&str], ) -> Result; ``` Source line: `657`. # oas-attestation · sign URL: https://docs.openagent.id/reference/rust/oas-attestation/sign Markdown: https://docs.openagent.id/reference/rust/oas-attestation/sign.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/sign.rs`. SHA-256: `86ff420604f984017407bd53da44360939390bafb44649efcca0007c2c9bff30`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## sign::sign\_credential [#signsign_credential] Signs an OAS credential, producing a new credential with an attached proof. Implements the Ed25519Signature2020 proof suite per OAS Specification §13.1: 1. Validates the credential structure 2. Serializes to JSON without the `proof` field 3. Canonicalizes via JCS (RFC 8785) 4. Signs the canonical bytes with Ed25519 5. Encodes the signature as multibase base58btc (`z` prefix) # Arguments [#arguments] * `credential` - The unsigned credential to sign. * `keypair` - The issuer's Ed25519 keypair. * `verification_method_id` - Full ID of the verification method (e.g., `"did:oas:test:hmr:auditor#key-1"`). * `created` - ISO 8601 timestamp for the proof. # Returns [#returns] A new \[`OasCredential`] with the `proof` field populated. # Errors [#errors] Returns \[`AttestationError::ProofGenerationFailed`] if canonicalization or signing fails. Returns other \[`AttestationError`] variants if validation fails. # Examples [#examples] ``` use oas_attestation::credential::OasCredential; use oas_attestation::types::AttestationType; use oas_attestation::sign::sign_credential; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .attestation_type(AttestationType::SecurityAudit) .build() .unwrap(); let signed = sign_credential( &cred, &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", ); assert!(signed.is_ok()); assert!(signed.unwrap().proof.is_some()); ``` ```rust pub fn sign_credential( credential: &OasCredential, keypair: &OasKeyPair, verification_method_id: &str, created: &str, ) -> Result; ``` Source line: `73`. # oas-attestation · signer URL: https://docs.openagent.id/reference/rust/oas-attestation/signer Markdown: https://docs.openagent.id/reference/rust/oas-attestation/signer.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/signer.rs`. SHA-256: `d2a2ec0b3933204d3390bd7082e07d8f69c3dae636de1758df836561b09db857`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## signer::ALG\_EDDSA [#signeralg_eddsa] JOSE algorithm identifier for Ed25519 (`EdDSA`). ```rust pub const ALG_EDDSA: &str; ``` Source line: `58`. ## signer::Signer [#signersigner] A cryptographic signer for OAS attestation and presentation proofs. Implementations are stateless with respect to the message being signed: the same `Signer` instance can be reused across many sign calls. They are `Send + Sync` so they can be shared across threads and stored as `Box` trait objects in proof format dispatch tables. The trait is intentionally minimal — `algorithm()`, `sign()`, `public_key_bytes()` — so it can adapt to any of the algorithm families referenced by the OAS proof format registry (Ed25519 / ECDSA P-256 RSA / BBS+ / etc.). # Examples [#examples] ``` use oas_attestation::signer::{OasKeyPairSigner, Signer}; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let signer = OasKeyPairSigner::new(&keypair); let signature = signer.sign(b"hello").unwrap(); assert!(!signature.is_empty()); ``` ```rust pub trait Signer: Send + Sync { /// Returns the JOSE-style algorithm identifier for this signer /// (e.g., `"EdDSA"`, `"ES256"`, `"RS256"`). /// /// Verifiers consume this string to route the signature bytes to a /// matching verification routine. fn algorithm(&self) -> &'static str; /// Signs the given message and returns the raw signature bytes. /// /// # Arguments /// /// * `message` - The message bytes to sign. Typically this is the /// JCS-canonicalized credential or presentation payload. /// /// # Returns /// /// The signature bytes in the algorithm's natural binary form (not /// base-encoded). For Ed25519 this is 64 bytes. /// /// # Errors /// /// Returns [`AttestationError`] if the underlying signing operation /// fails. Pure-software signers typically do not fail; HSM-backed or /// remote signers may. fn sign(&self, message: &[u8]) -> Result, AttestationError>; /// Returns the public key bytes for this signer in the algorithm's /// canonical form. /// /// For Ed25519 this is the 32-byte verifying key. For ECDSA P-256 this /// is typically the SEC1 uncompressed point. The caller decides how to /// encode the bytes for transport. fn public_key_bytes(&self) -> Vec; } ``` Source line: `87`. ## signer::Verifier [#signerverifier] A cryptographic verifier for OAS attestation and presentation proofs. Like \[`Signer`], `Verifier` is stateless and `Send + Sync`. It exposes the same algorithm identifier so dispatch tables can match a credential's declared proof format against a registered verifier. ```rust pub trait Verifier: Send + Sync { /// Returns the JOSE-style algorithm identifier for this verifier. fn algorithm(&self) -> &'static str; /// Verifies that `signature` is a valid signature over `message` under /// this verifier's public key. /// /// # Arguments /// /// * `message` - The message bytes that were signed. /// * `signature` - The raw signature bytes. /// /// # Errors /// /// Returns [`AttestationError::InvalidProofSignature`] if the signature /// fails verification for any reason (wrong key, tampered message, /// malformed signature, etc.). fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), AttestationError>; } ``` Source line: `132`. ## signer::OasKeyPairSigner [#signeroaskeypairsigner] Adapter that implements \[`Signer`] for an existing \[`oas_crypto::keypair::OasKeyPair`]. This is the bridge between the existing Ed25519-only OAS APIs and the algorithm-agnostic `Signer` trait. It uses the `"EdDSA"` JOSE algorithm identifier and the existing `OasKeyPair::sign` routine, so producing a signature through this adapter is byte-equivalent to calling the keypair directly. The adapter borrows the keypair, so the signer's lifetime is tied to the keypair's lifetime. This avoids any clone or zeroize concerns for the secret key material. # Examples [#examples-1] ``` use oas_attestation::signer::{OasKeyPairSigner, Signer, ALG_EDDSA}; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let signer = OasKeyPairSigner::new(&keypair); assert_eq!(signer.algorithm(), ALG_EDDSA); let signature = signer.sign(b"hello").unwrap(); assert_eq!(signature.len(), 64); // Ed25519 signatures are 64 bytes ``` ```rust #[derive(Debug)] pub struct OasKeyPairSigner<'a> { } ``` Source line: `183`. ## signer::OasKeyPairSigner\<'a>::new [#signeroaskeypairsigneranew] Creates a new Ed25519 signer from an \[`OasKeyPair`] reference. ```rust pub fn new(keypair: &'a OasKeyPair) -> Self; ``` Source line: `189`. ## signer::OasKeyPairVerifier [#signeroaskeypairverifier] Adapter that implements \[`Verifier`] for a borrowed Ed25519 public key. Verification uses the existing \[`oas_crypto::keypair::OasKeyPair::verify_with_key`] routine, so accepting a signature through this adapter is byte-equivalent to calling the underlying function directly. # Examples [#examples-2] ``` use oas_attestation::signer::{OasKeyPairSigner, OasKeyPairVerifier, Signer, Verifier}; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let signer = OasKeyPairSigner::new(&keypair); let public_key = keypair.verifying_key_bytes(); let verifier = OasKeyPairVerifier::new(&public_key); let signature = signer.sign(b"important payload").unwrap(); assert!(verifier.verify(b"important payload", &signature).is_ok()); assert!(verifier.verify(b"tampered payload", &signature).is_err()); ``` ```rust #[derive(Debug)] pub struct OasKeyPairVerifier<'a> { } ``` Source line: `235`. ## signer::OasKeyPairVerifier\<'a>::new [#signeroaskeypairverifieranew] Creates a new Ed25519 verifier from a borrowed public key byte slice. The slice MUST be 32 bytes (the Ed25519 verifying key length). Verification will fail with `InvalidProofSignature` if it is not. ```rust pub fn new(public_key: &'a [u8]) -> Self; ``` Source line: `244`. # oas-attestation · types URL: https://docs.openagent.id/reference/rust/oas-attestation/types Markdown: https://docs.openagent.id/reference/rust/oas-attestation/types.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/types.rs`. SHA-256: `c1a59688117ef835c95ecb653755d55fe6ab510ead834be9d686a0d69ccd360b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## types::AttestationType [#typesattestationtype] An OAS attestation type per Specification §13.2. Six standard types are defined. Implementations MAY register custom attestation types by defining a new value and publishing its schema. # Examples [#examples] ``` use oas_attestation::types::AttestationType; let at = AttestationType::SecurityAudit; assert_eq!(at.as_str(), "SecurityAudit"); let parsed: AttestationType = "BehaviorAttestation".parse().unwrap(); assert_eq!(parsed, AttestationType::BehaviorAttestation); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum AttestationType { /// Results of a security analysis (vulnerability scan, code audit, penetration test). SecurityAudit, /// Attestation about observed runtime behavior over a period. BehaviorAttestation, /// Verification that an entity possesses claimed capabilities. CapabilityVerification, /// Attestation of compliance with a regulatory framework or standard. ComplianceAttestation, /// Endorsement by a verified domain expert. ExpertEndorsement, /// Community-sourced review with aggregated trust score. CommunityReview, /// Lineage Attestation Bridge per OAS Spec §14.7 — opt-in lossless export /// of an `AgentLineageProof2025` (§10) into W3C VC form for /// interoperability with VC-native verifiers. LineageAttestation, /// A custom attestation type not defined in the specification. /// /// The string value SHOULD be published at a well-known URI within /// the issuer's namespace. Custom(String), } ``` Source line: `30`. ## types::AttestationType::as\_str [#typesattestationtypeas_str] Returns the canonical string representation of this attestation type. # Returns [#returns] The OAS §13.2 type name (e.g., `"SecurityAudit"`) or the custom value. ```rust pub fn as_str(&self) -> &str; ``` Source line: `60`. ## types::AttestationType::required\_fields [#typesattestationtyperequired_fields] Returns the required `credentialSubject` fields for this attestation type. Per OAS Specification §13.2, each standard type defines a minimum set of fields. Implementations MAY extend these schemas. # Returns [#returns-1] A slice of field names that MUST be present in the credential subject. Does not include `"id"` and `"attestationType"` which are always required. ```rust pub fn required_fields(&self) -> &[&str]; ``` Source line: `82`. ## types::AttestationType::validate\_subject [#typesattestationtypevalidate_subject] Validates that a credential subject contains all required fields for this type. # Arguments [#arguments] * `subject` - The credential subject as a JSON object. # Returns [#returns-2] `Ok(())` if all required fields are present. # Errors [#errors] Returns \[`AttestationError::MissingField`] if a required field is absent. ```rust pub fn validate_subject(&self, subject: &serde_json::Value) -> Result<(), AttestationError>; ``` Source line: `129`. # oas-attestation · vc_jose URL: https://docs.openagent.id/reference/rust/oas-attestation/vc_jose Markdown: https://docs.openagent.id/reference/rust/oas-attestation/vc_jose.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/vc_jose.rs`. SHA-256: `bc53b9e6bf836e08e39faab3f7f89f73044baba653623da2e60db6d53fa8e70a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## vc\_jose::JWT\_VC\_TYP [#vc_josejwt_vc_typ] JWT-VC media type per W3C VC-JOSE-COSE. ```rust pub const JWT_VC_TYP: &str; ``` Source line: `92`. ## vc\_jose::VC\_CLAIM [#vc_josevc_claim] JWT-VC payload claim name carrying the OAS credential body. ```rust pub const VC_CLAIM: &str; ``` Source line: `95`. ## vc\_jose::JwtVcHeader [#vc_josejwtvcheader] JOSE header for a JWT-VC compact serialization. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct JwtVcHeader { /// Algorithm identifier (matches the [`Signer::algorithm`] used). pub alg: String, /// Media type — fixed to `"vc+jwt"`. pub typ: String, /// Verification method ID (the `did:oas:...#key-id` of the issuer key). pub kid: String } ``` Source line: `103`. ## vc\_jose::JwtVcHeader::new [#vc_josejwtvcheadernew] Constructs the canonical header for a given algorithm and verification method ID. ```rust pub fn new(alg: impl Into, kid: impl Into) -> Self; ``` Source line: `115`. ## vc\_jose::JwtVcPayload [#vc_josejwtvcpayload] JWT-VC payload — JWT registered claims plus the `vc` claim carrying the OAS credential body. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct JwtVcPayload { /// Issuer DID (RFC 7519 §4.1.1). pub iss: String, /// Subject DID (RFC 7519 §4.1.2). pub sub: String, /// "Not before" — Unix seconds, derived from credential issuance date. /// (RFC 7519 §4.1.5). #[serde(skip_serializing_if = "Option::is_none")] pub nbf: Option, /// JWT ID (RFC 7519 §4.1.7). #[serde(skip_serializing_if = "Option::is_none")] pub jti: Option, /// Holder confirmation key per RFC 7800 (`cnf.jwk`). #[serde(skip_serializing_if = "Option::is_none")] pub cnf: Option, /// The OAS credential body (without its native Ed25519Signature2020 /// proof — the JWT signature replaces it). pub vc: serde_json::Value } ``` Source line: `131`. ## vc\_jose::JwtVcSignOptions [#vc_josejwtvcsignoptions] Caller-supplied options for \[`sign_credential_jwt_vc`]. ```rust #[derive(Debug, Clone)] pub struct JwtVcSignOptions { /// Full verification method ID /// (e.g., `"did:oas:test:hmr:auditor#key-1"`). pub verification_method_id: String, /// Optional explicit `nbf` claim (Unix seconds). If `None`, the function /// attempts to parse the credential's `issuanceDate` (ISO 8601) and /// converts it to Unix seconds. If parsing fails, `nbf` is omitted. pub issuance_unix_seconds: Option, /// Optional JWT ID. If `None`, no `jti` claim is emitted. pub jwt_id: Option, /// Optional holder confirmation key per RFC 7800. If supplied, embedded /// under `payload.cnf.jwk`. Used by verifiers to enforce the §14.5.1 /// holder binding rule for authority-bearing credentials presented over /// JWT-VC. pub holder_public_key_jwk: Option } ``` Source line: `157`. ## vc\_jose::JwtVc [#vc_josejwtvc] A parsed JWT-VC ready for inspection. Returned by \[`verify_jwt_vc`] (after the signature has been validated) and by \[`parse_jwt_vc`] (without verification — for inspection only). ```rust #[derive(Debug, Clone)] pub struct JwtVc { } ``` Source line: `186`. ## vc\_jose::JwtVc::header [#vc_josejwtvcheader-1] Returns the JOSE header. ```rust pub fn header(&self) -> &JwtVcHeader; ``` Source line: `195`. ## vc\_jose::JwtVc::payload [#vc_josejwtvcpayload-1] Returns the JWT payload. ```rust pub fn payload(&self) -> &JwtVcPayload; ``` Source line: `200`. ## vc\_jose::JwtVc::as\_compact\_string [#vc_josejwtvcas_compact_string] Returns the compact serialization (`header.payload.signature`). ```rust pub fn as_compact_string(&self) -> &str; ``` Source line: `205`. ## vc\_jose::JwtVc::issuer [#vc_josejwtvcissuer] Returns the issuer DID from the payload. ```rust pub fn issuer(&self) -> &str; ``` Source line: `210`. ## vc\_jose::JwtVc::subject [#vc_josejwtvcsubject] Returns the subject DID from the payload. ```rust pub fn subject(&self) -> &str; ``` Source line: `215`. ## vc\_jose::JwtVc::algorithm [#vc_josejwtvcalgorithm] Returns the algorithm identifier from the JOSE header. ```rust pub fn algorithm(&self) -> &str; ``` Source line: `220`. ## vc\_jose::JwtVc::verification\_method\_id [#vc_josejwtvcverification_method_id] Returns the verification method ID (`kid`) from the JOSE header. ```rust pub fn verification_method_id(&self) -> &str; ``` Source line: `225`. ## vc\_jose::JwtVc::holder\_confirmation\_key [#vc_josejwtvcholder_confirmation_key] Returns the holder confirmation key (`cnf.jwk`) per RFC 7800, if the credential was signed with one. ```rust pub fn holder_confirmation_key(&self) -> Option<&serde_json::Value>; ``` Source line: `231`. ## vc\_jose::JwtVc::to\_credential [#vc_josejwtvcto_credential] Reconstructs the original \[`OasCredential`] body from the `vc` claim. The reconstructed credential will not carry an `Ed25519Signature2020` proof — the JWT signature replaces it. Verifying this credential structurally (via \[`OasCredential::validate`]) will succeed; verifying it cryptographically via \[`crate::verify::verify_credential`] will fail because there is no proof field. Use \[`verify_jwt_vc`] for cryptographic verification of JWT-VC credentials. ```rust pub fn to_credential(&self) -> Result; ``` Source line: `244`. ## vc\_jose::JwtVc::format\_id [#vc_josejwtvcformat_id] Returns the registered OAS proof format identifier this JWT-VC represents. ```rust pub const fn format_id() -> ProofFormatId; ``` Source line: `251`. ## vc\_jose::JwtVc::format\_url [#vc_josejwtvcformat_url] Returns the canonical OAS format identifier URL for this format. ```rust pub const fn format_url() -> &'static str; ``` Source line: `256`. ## vc\_jose::sign\_credential\_jwt\_vc [#vc_josesign_credential_jwt_vc] Signs an \[`OasCredential`] as a JWT-VC compact string per OAS Spec §14.4. The credential's existing proof (if any) is stripped before encoding — the JWT signature replaces it. The result is a \[`JwtVc`] wrapping the compact serialization, the parsed header, and the parsed payload. # Arguments [#arguments] * `credential` - The credential to sign. * `signer` - Any \[`Signer`] implementation. The signer's `algorithm()` is used as the `alg` JOSE header value. * `options` - Sign options (verification method ID, optional `nbf` `jti` / `cnf` claims). # Errors [#errors] Returns \[`AttestationError`] on JSON serialization or signing failure. ```rust pub fn sign_credential_jwt_vc( credential: &OasCredential, signer: &dyn Signer, options: &JwtVcSignOptions, ) -> Result; ``` Source line: `307`. ## vc\_jose::parse\_jwt\_vc [#vc_joseparse_jwt_vc] Parses a JWT-VC compact string **without** verifying its signature. Returns a \[`JwtVc`] for inspection. **Do not** trust any field returned by this function until \[`verify_jwt_vc`] has succeeded against a known issuer public key. ```rust pub fn parse_jwt_vc(compact: &str) -> Result; ``` Source line: `370`. ## vc\_jose::verify\_jwt\_vc [#vc_joseverify_jwt_vc] Verifies a JWT-VC compact string against a known issuer \[`Verifier`]. Per OAS Spec §14.4: 1. Parses the three-segment compact form. 2. Validates the JOSE header type and decodes the payload. 3. Decodes the base64url signature. 4. Routes the signature to the supplied verifier — the verifier's `algorithm()` MUST match the JOSE header `alg`, otherwise this function rejects with `InvalidProofSignature`. 5. Re-derives the signing input (`base64url(header).base64url(payload)`) and verifies the signature against the verifier's public key. On success, returns the parsed \[`JwtVc`] with all claims accessible. # Errors [#errors-1] * \[`AttestationError::InvalidProofSignature`] on any structural, parsing, algorithm-mismatch, or cryptographic failure. ```rust pub fn verify_jwt_vc(compact: &str, verifier: &dyn Verifier) -> Result; ``` Source line: `422`. # oas-attestation · verify URL: https://docs.openagent.id/reference/rust/oas-attestation/verify Markdown: https://docs.openagent.id/reference/rust/oas-attestation/verify.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-attestation/src/verify.rs`. SHA-256: `5bc06575da77ebb7e2a866752baca3b924e8d377a2019837c9e127e080569d69`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## verify::verify\_credential [#verifyverify_credential] Verifies an OAS credential's proof against a known issuer public key. Implements verification per OAS Specification §13.1: 1. Validates the credential structure (issuer/subject DIDs, required fields) 2. Checks that the proof exists and uses `Ed25519Signature2020` 3. Serializes the credential without proof 4. Canonicalizes via JCS (RFC 8785) 5. Decodes the multibase signature 6. Verifies the Ed25519 signature against the issuer's public key This function does NOT check expiration or temporal validity. Use \[`verify_credential_with_time`] for time-aware verification. # Arguments [#arguments] * `credential` - The signed credential to verify. * `issuer_public_key` - The 32-byte Ed25519 public key of the issuer. # Returns [#returns] `Ok(())` if the credential is valid and the proof verifies. # Errors [#errors] * \[`AttestationError::MissingProof`] if no proof is present. * \[`AttestationError::InvalidProofSignature`] if the proof type is wrong or signature is invalid. * \[`AttestationError::InvalidIssuer`] or \[`AttestationError::InvalidSubject`] for DID validation failures. # Examples [#examples] ``` use oas_attestation::credential::OasCredential; use oas_attestation::types::AttestationType; use oas_attestation::sign::sign_credential; use oas_attestation::verify::verify_credential; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .issuance_date("2026-01-15T00:00:00Z") .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .attestation_type(AttestationType::SecurityAudit) .build() .unwrap(); let signed = sign_credential( &cred, &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", ).unwrap(); let result = verify_credential(&signed, &keypair.verifying_key_bytes()); assert!(result.is_ok()); ``` ```rust pub fn verify_credential( credential: &OasCredential, issuer_public_key: &[u8], ) -> Result<(), AttestationError>; ``` Source line: `74`. ## verify::verify\_credential\_with\_time [#verifyverify_credential_with_time] Verifies an OAS credential with temporal checks. Performs all checks from \[`verify_credential`] plus: * Checks that `issuanceDate` is not in the future * Checks that `expirationDate` (if present) has not passed # Arguments [#arguments-1] * `credential` - The signed credential to verify. * `issuer_public_key` - The 32-byte Ed25519 public key of the issuer. * `now` - The current time as an ISO 8601 string for comparison. # Returns [#returns-1] `Ok(())` if the credential is valid, the proof verifies, and temporal constraints hold. # Errors [#errors-1] All errors from \[`verify_credential`], plus: * \[`AttestationError::NotYetValid`] if `issuanceDate` is in the future. * \[`AttestationError::Expired`] if `expirationDate` has passed. # Examples [#examples-1] ``` use oas_attestation::credential::OasCredential; use oas_attestation::types::AttestationType; use oas_attestation::sign::sign_credential; use oas_attestation::verify::verify_credential_with_time; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let cred = OasCredential::builder() .issuer("did:oas:test:hmr:auditor") .subject_id("did:oas:test:agent:target") .issuance_date("2026-01-15T00:00:00Z") .expiration_date("2027-01-15T00:00:00Z") .attestation_type(AttestationType::SecurityAudit) .subject_claim("auditType", serde_json::json!("codeAudit")) .subject_claim("result", serde_json::json!("pass")) .subject_claim("severityFindings", serde_json::json!({"critical": 0})) .subject_claim("toolOrMethodology", serde_json::json!("OWASP")) .subject_claim("auditDate", serde_json::json!("2026-01-15T00:00:00Z")) .build() .unwrap(); let signed = sign_credential( &cred, &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", ).unwrap(); // Verify at a time when the credential is valid let result = verify_credential_with_time( &signed, &keypair.verifying_key_bytes(), "2026-06-15T00:00:00Z", ); assert!(result.is_ok()); ``` ```rust pub fn verify_credential_with_time( credential: &OasCredential, issuer_public_key: &[u8], now: &str, ) -> Result<(), AttestationError>; ``` Source line: `180`. # oas-did · crate URL: https://docs.openagent.id/reference/rust/oas-did/crate Markdown: https://docs.openagent.id/reference/rust/oas-did/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-did/src/lib.rs`. SHA-256: `7d8654202dff400d34a4a1ee2e8293f14d046a389dd847b7781a7b627e945cf0`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## did [#did] # oas-did [#oas-did] DID parsing and validation for the Open Agent Specification (OAS). This crate provides the \[`OasDid`] type for parsing, validating, and representing `did:oas` decentralized identifiers as defined in OAS Specification §3. ## Format [#format] ```text did:oas::: ``` ## Entity Kinds [#entity-kinds] OAS defines 11 entity kinds (OAS Spec §4): `hmr`, `mhr`, `ao`, `agent`, `agent:instance`, `tool`, `skill`, `workflow`, `model`, `dataset`, `service` ## Example [#example] ``` use oas_did::OasDid; use std::str::FromStr; let did = OasDid::from_str("did:oas:acme:agent:support-bot-42").unwrap(); assert_eq!(did.namespace(), "acme"); assert_eq!(did.identifier(), "support-bot-42"); assert!(!did.is_root()); ``` ```rust pub mod did; ``` Source line: `32`. ## error [#error] ```rust pub mod error; ``` Source line: `33`. ## kind [#kind] ```rust pub mod kind; ``` Source line: `34`. ## namespace [#namespace] ```rust pub mod namespace; ``` Source line: `35`. ## validation [#validation] ```rust pub mod validation; ``` Source line: `36`. ## pub use did::OasDid; [#pub-use-didoasdid] ```rust pub use did::OasDid; ``` Source line: `38`. ## pub use error::DidError; [#pub-use-errordiderror] ```rust pub use error::DidError; ``` Source line: `39`. ## pub use kind::EntityKind; [#pub-use-kindentitykind] ```rust pub use kind::EntityKind; ``` Source line: `40`. # oas-did · did URL: https://docs.openagent.id/reference/rust/oas-did/did Markdown: https://docs.openagent.id/reference/rust/oas-did/did.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-did/src/did.rs`. SHA-256: `f25910f0bb7b9f5b506496b7757f690bd5c76826b61d953f1e50a6784d019022`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## did::OasDid [#didoasdid] A parsed and validated `did:oas` decentralized identifier. An \[`OasDid`] guarantees that the contained identifier conforms to the syntax rules in OAS Specification §3.1. It is the primary type for working with OAS identifiers throughout the SDK. # Format [#format] ```text did:oas::: ``` For the compound kind `agent:instance`: ```text did:oas::agent:instance: ``` # Examples [#examples] ``` use oas_did::OasDid; use std::str::FromStr; let did = OasDid::from_str("did:oas:acme:agent:support-bot-42").unwrap(); assert_eq!(did.namespace(), "acme"); assert_eq!(did.kind(), oas_did::kind::EntityKind::Agent); assert_eq!(did.identifier(), "support-bot-42"); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct OasDid { } ``` Source line: `43`. ## did::OasDid::new [#didoasdidnew] Creates a new \[`OasDid`] with validation. # Arguments [#arguments] * `namespace` - The organizational namespace. * `kind` - The entity kind. * `identifier` - The unique identifier within the namespace and kind. # Returns [#returns] A validated \[`OasDid`]. # Errors [#errors] Returns a \[`DidError`] if the namespace or identifier fails validation. # Examples [#examples-1] ``` use oas_did::OasDid; use oas_did::kind::EntityKind; let did = OasDid::new("acme", EntityKind::Agent, "my-bot").unwrap(); assert_eq!(did.to_string(), "did:oas:acme:agent:my-bot"); ``` ```rust pub fn new(namespace: &str, kind: EntityKind, identifier: &str) -> Result; ``` Source line: `75`. ## did::OasDid::namespace [#didoasdidnamespace] Returns the namespace component. ```rust pub fn namespace(&self) -> &str; ``` Source line: `86`. ## did::OasDid::kind [#didoasdidkind] Returns the entity kind. ```rust pub fn kind(&self) -> EntityKind; ``` Source line: `91`. ## did::OasDid::identifier [#didoasdididentifier] Returns the identifier component. ```rust pub fn identifier(&self) -> &str; ``` Source line: `96`. ## did::OasDid::is\_root [#didoasdidis_root] Returns `true` if this is a root entity (HMR, MHR, or ENR). Root entities have no parent and no lineage section. ```rust pub fn is_root(&self) -> bool; ``` Source line: `103`. ## did::OasDid::as\_str [#didoasdidas_str] Returns the full DID string representation. ```rust pub fn as_str(&self) -> String; ``` Source line: `108`. # oas-did · error URL: https://docs.openagent.id/reference/rust/oas-did/error Markdown: https://docs.openagent.id/reference/rust/oas-did/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-did/src/error.rs`. SHA-256: `7a732512f4c2b4698eba8e790e92162d2580d494df3e5af8b8afdd06cfadab74`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::DidError [#errordiderror] Errors arising from parsing or validating `did:oas` identifiers. ```rust #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum DidError { /// The DID string does not start with `did:oas:`. #[error("invalid DID prefix: expected 'did:oas:', got '{found}'")] InvalidPrefix { /// The prefix that was found. found: String, }, /// The DID does not have enough components. #[error("DID has {found} components, expected at least 5 (did:oas:namespace:kind:identifier)")] TooFewComponents { /// How many components were found. found: usize, }, /// The namespace is invalid per OAS Spec §3.1. #[error("invalid namespace '{namespace}': {reason}")] InvalidNamespace { /// The invalid namespace value. namespace: String, /// Why it's invalid. reason: String, }, /// The entity kind is not recognized. #[error("unknown entity kind '{found}'; expected one of: hmr, mhr, enr, ao, agent, agent:instance, tool, skill, workflow, model, dataset, service")] UnknownEntityKind { /// The unrecognized kind string. found: String, }, /// The identifier is invalid per OAS Spec §3.1. #[error("invalid identifier '{identifier}': {reason}")] InvalidIdentifier { /// The invalid identifier value. identifier: String, /// Why it's invalid. reason: String, }, /// The DID string is empty. #[error("DID string is empty")] Empty, } ``` Source line: `8`. # oas-did modules URL: https://docs.openagent.id/reference/rust/oas-did Markdown: https://docs.openagent.id/reference/rust/oas-did.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-did). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-did/crate) — 8 declarations * [did](/reference/rust/oas-did/did) — 7 declarations * [error](/reference/rust/oas-did/error) — 1 declarations * [kind](/reference/rust/oas-did/kind) — 4 declarations * [namespace](/reference/rust/oas-did/namespace) — 3 declarations * [validation](/reference/rust/oas-did/validation) — 2 declarations # oas-did · kind URL: https://docs.openagent.id/reference/rust/oas-did/kind Markdown: https://docs.openagent.id/reference/rust/oas-did/kind.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-did/src/kind.rs`. SHA-256: `e37dbf4c5e148ea633b4108909de20c3c0c59aa886bcb14fc4da2117758a717e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## kind::EntityKind [#kindentitykind] The 12 entity kinds defined in OAS Specification §4. Each kind represents a category of autonomous entity with distinct identity requirements and lineage constraints. # Examples [#examples] ``` use oas_did::kind::EntityKind; use std::str::FromStr; let kind = EntityKind::from_str("agent").unwrap(); assert_eq!(kind, EntityKind::Agent); assert_eq!(kind.as_str(), "agent"); ``` ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum EntityKind { /// Human Root — a single verified human being (OAS Spec §6). #[serde(rename = "hmr")] Hmr, /// Multi-Human Root — a threshold group of verified humans (OAS Spec §7). #[serde(rename = "mhr")] Mhr, /// Entity Name Record — a stable organizational identity governed by an MHR. #[serde(rename = "enr")] Enr, /// Autonomous Organization — a group of agents operating as a unit. #[serde(rename = "ao")] Ao, /// Agent — an autonomous software entity. #[serde(rename = "agent")] Agent, /// Agent Instance — a specific running instance of an agent, identified by UUID. #[serde(rename = "agent:instance")] AgentInstance, /// Tool — a capability that agents can invoke. #[serde(rename = "tool")] Tool, /// Skill — a composable unit of agent behavior. #[serde(rename = "skill")] Skill, /// Workflow — a defined process involving one or more agents. #[serde(rename = "workflow")] Workflow, /// Model — a machine learning model with verified provenance. #[serde(rename = "model")] Model, /// Dataset — a data collection with verified provenance and lineage. #[serde(rename = "dataset")] Dataset, /// Service — an infrastructure service with verified identity. #[serde(rename = "service")] Service, } ``` Source line: `30`. ## kind::EntityKind::as\_str [#kindentitykindas_str] Returns the string representation of this kind as it appears in a DID. # Examples [#examples-1] ``` use oas_did::kind::EntityKind; assert_eq!(EntityKind::AgentInstance.as_str(), "agent:instance"); assert_eq!(EntityKind::Hmr.as_str(), "hmr"); ``` ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `90`. ## kind::EntityKind::is\_root [#kindentitykindis_root] Returns `true` if this kind is a root entity (HMR, MHR, or ENR). Root entities have no parent and no lineage section. # Examples [#examples-2] ``` use oas_did::kind::EntityKind; assert!(EntityKind::Hmr.is_root()); assert!(EntityKind::Mhr.is_root()); assert!(!EntityKind::Agent.is_root()); ``` ```rust pub fn is_root(&self) -> bool; ``` Source line: `119`. ## kind::EntityKind::component\_count [#kindentitykindcomponent_count] Returns the number of DID components this kind consumes. Most kinds are a single component (e.g., `agent`), but `agent:instance` is a compound kind that consumes two components (`agent` + `instance`). ```rust pub fn component_count(&self) -> usize; ``` Source line: `127`. # oas-did · namespace URL: https://docs.openagent.id/reference/rust/oas-did/namespace Markdown: https://docs.openagent.id/reference/rust/oas-did/namespace.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-did/src/namespace.rs`. SHA-256: `e9dcb9c4b49416f6d558cc3d0d02dc5184b15dff3d170aef65655dae747cfb13`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## namespace::RESERVED\_NAMESPACES [#namespacereserved_namespaces] Reserved namespaces per OAS Spec §3.2. ```rust pub const RESERVED_NAMESPACES: &[&str]; ``` Source line: `7`. ## namespace::validate\_namespace [#namespacevalidate_namespace] Validates an OAS namespace string. Per OAS Specification §3.1, a namespace: * MUST be 1-63 characters long * MUST contain only lowercase alphanumeric characters and hyphens * MUST NOT begin or end with a hyphen # Arguments [#arguments] * `namespace` - The namespace string to validate. # Returns [#returns] `Ok(())` if the namespace is valid. # Errors [#errors] Returns \[`DidError::InvalidNamespace`] with a specific reason if validation fails. # Examples [#examples] ``` use oas_did::namespace::validate_namespace; assert!(validate_namespace("acme").is_ok()); assert!(validate_namespace("my-org-123").is_ok()); assert!(validate_namespace("-starts-with-hyphen").is_err()); ``` ```rust pub fn validate_namespace(namespace: &str) -> Result<(), DidError>; ``` Source line: `37`. ## namespace::is\_reserved [#namespaceis_reserved] Returns `true` if the namespace is reserved per OAS Spec §3.2. # Examples [#examples-1] ``` use oas_did::namespace::is_reserved; assert!(is_reserved("oas")); assert!(is_reserved("test")); assert!(!is_reserved("acme")); ``` ```rust pub fn is_reserved(namespace: &str) -> bool; ``` Source line: `95`. # oas-did · validation URL: https://docs.openagent.id/reference/rust/oas-did/validation Markdown: https://docs.openagent.id/reference/rust/oas-did/validation.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-did/src/validation.rs`. SHA-256: `a761dd2f3bf3afc274be57deddf282d8f0eab7e549324f0b76c709c775e1c900`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## validation::MAX\_IDENTIFIER\_LENGTH [#validationmax_identifier_length] Maximum length for an identifier per OAS Spec §3.1. ```rust pub const MAX_IDENTIFIER_LENGTH: usize; ``` Source line: `7`. ## validation::validate\_identifier [#validationvalidate_identifier] Validates an OAS identifier string. Per OAS Specification §3.1, an identifier: * MUST be 1-128 characters long * MUST contain only characters from the set `[a-zA-Z0-9._-]` # Arguments [#arguments] * `identifier` - The identifier string to validate. # Returns [#returns] `Ok(())` if the identifier is valid. # Errors [#errors] Returns \[`DidError::InvalidIdentifier`] with a specific reason if validation fails. # Examples [#examples] ``` use oas_did::validation::validate_identifier; assert!(validate_identifier("support-bot-42").is_ok()); assert!(validate_identifier("my.model_v2").is_ok()); assert!(validate_identifier("").is_err()); ``` ```rust pub fn validate_identifier(identifier: &str) -> Result<(), DidError>; ``` Source line: `36`. # oas-document · builder URL: https://docs.openagent.id/reference/rust/oas-document/builder Markdown: https://docs.openagent.id/reference/rust/oas-document/builder.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/builder.rs`. SHA-256: `4e2c69ae88dc0a619072d629a1b848631be7c9b191d768d3bcd3783d78860646`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## builder::DocumentBuilder [#builderdocumentbuilder] Builder for constructing \[`OasDocument`] instances. Provides an ergonomic API for building OAS Identity Documents with proper defaults and validation. # Examples [#examples] ``` use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .controller("did:oas:test:hmr:alice") .conformance_level(ConformanceLevel::L1) .add_verification_method(&keypair) .name("Alice") .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); assert_eq!(doc.kind, "hmr"); assert!(doc.proof.is_some()); ``` ```rust pub struct DocumentBuilder { } ``` Source line: `48`. ## builder::DocumentBuilder::new [#builderdocumentbuildernew] Creates a new builder with the given DID and kind. # Arguments [#arguments] * `id` - The `did:oas` identifier. * `kind` - The entity kind string (e.g., `"hmr"`, `"agent"`). ```rust pub fn new(id: &str, kind: &str) -> Self; ``` Source line: `84`. ## builder::DocumentBuilder::controller [#builderdocumentbuildercontroller] Sets the controller DID. ```rust pub fn controller(mut self, controller: &str) -> Self; ``` Source line: `115`. ## builder::DocumentBuilder::add\_verification\_method [#builderdocumentbuilderadd_verification_method] Adds a verification method from a keypair. Automatically adds the key to authentication, assertionMethod, capabilityInvocation, and capabilityDelegation relationships. ```rust pub fn add_verification_method(mut self, keypair: &OasKeyPair) -> Self; ``` Source line: `124`. ## builder::DocumentBuilder::conformance\_level [#builderdocumentbuilderconformance_level] Sets the conformance level. ```rust pub fn conformance_level(mut self, level: ConformanceLevel) -> Self; ``` Source line: `137`. ## builder::DocumentBuilder::name [#builderdocumentbuildername] Sets the human-readable name. ```rust pub fn name(mut self, name: &str) -> Self; ``` Source line: `143`. ## builder::DocumentBuilder::description [#builderdocumentbuilderdescription] Sets the human-readable description. ```rust pub fn description(mut self, description: &str) -> Self; ``` Source line: `149`. ## builder::DocumentBuilder::lineage [#builderdocumentbuilderlineage] Sets the lineage section. ```rust pub fn lineage(mut self, lineage: LineageSection) -> Self; ``` Source line: `155`. ## builder::DocumentBuilder::governance [#builderdocumentbuildergovernance] Sets the governance section (ENR entities only). ```rust pub fn governance(mut self, governance: GovernanceSection) -> Self; ``` Source line: `161`. ## builder::DocumentBuilder::lifecycle\_status [#builderdocumentbuilderlifecycle_status] Sets the lifecycle status. ```rust pub fn lifecycle_status(mut self, status: LifecycleStatus) -> Self; ``` Source line: `167`. ## builder::DocumentBuilder::sequence [#builderdocumentbuildersequence] Sets the sequence number. ```rust pub fn sequence(mut self, seq: u64) -> Self; ``` Source line: `173`. ## builder::DocumentBuilder::add\_service [#builderdocumentbuilderadd_service] Adds a service endpoint. ```rust pub fn add_service(mut self, service: ServiceEndpoint) -> Self; ``` Source line: `179`. ## builder::DocumentBuilder::profile [#builderdocumentbuilderprofile] Sets the profile section (§5.8). ```rust pub fn profile(mut self, profile: ProfileSection) -> Self; ``` Source line: `185`. ## builder::DocumentBuilder::contact [#builderdocumentbuildercontact] Sets the contact directory (§5.9). ```rust pub fn contact(mut self, contact: ContactSection) -> Self; ``` Source line: `191`. ## builder::DocumentBuilder::calendar [#builderdocumentbuildercalendar] Sets the calendar & scheduling section (§5.10). ```rust pub fn calendar(mut self, calendar: CalendarSection) -> Self; ``` Source line: `197`. ## builder::DocumentBuilder::operational [#builderdocumentbuilderoperational] Sets the operational specification (§5.11). ```rust pub fn operational(mut self, operational: OperationalSection) -> Self; ``` Source line: `203`. ## builder::DocumentBuilder::pricing [#builderdocumentbuilderpricing] Sets the pricing & economics section (§5.12). ```rust pub fn pricing(mut self, pricing: PricingSection) -> Self; ``` Source line: `209`. ## builder::DocumentBuilder::interoperability [#builderdocumentbuilderinteroperability] Sets the interoperability section (§5.13). ```rust pub fn interoperability(mut self, interop: InteroperabilitySection) -> Self; ``` Source line: `215`. ## builder::DocumentBuilder::reputation [#builderdocumentbuilderreputation] Sets the reputation summary (§5.14). ```rust pub fn reputation(mut self, reputation: ReputationSection) -> Self; ``` Source line: `221`. ## builder::DocumentBuilder::compliance [#builderdocumentbuildercompliance] Sets the compliance & jurisdiction section (§5.15). ```rust pub fn compliance(mut self, compliance: ComplianceSection) -> Self; ``` Source line: `227`. ## builder::DocumentBuilder::relationships [#builderdocumentbuilderrelationships] Sets the relationships & affiliations section (§5.16). ```rust pub fn relationships(mut self, relationships: RelationshipsSection) -> Self; ``` Source line: `233`. ## builder::DocumentBuilder::build\_and\_sign [#builderdocumentbuilderbuild_and_sign] Builds the document and signs it. # Arguments [#arguments-1] * `signing_keypair` - The keypair to sign the document with. * `created` - ISO 8601 timestamp for both document creation and proof. # Returns [#returns] A complete, signed \[`OasDocument`]. # Errors [#errors] Returns \[`DocumentError`] if signing fails. ```rust pub fn build_and_sign( self, signing_keypair: &OasKeyPair, created: &str, ) -> Result; ``` Source line: `252`. # oas-document · calendar URL: https://docs.openagent.id/reference/rust/oas-document/calendar Markdown: https://docs.openagent.id/reference/rust/oas-document/calendar.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/calendar.rs`. SHA-256: `a47a74b8f5b6ee89de670909f0e7440e59138bbfcf5445dbd729930b7df83c11`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## calendar::ScheduleWindow [#calendarschedulewindow] A recurring time window (e.g., office hours on a specific day). # Examples [#examples] ``` use oas_document::calendar::ScheduleWindow; let window = ScheduleWindow { day: "monday".to_string(), start: "09:00".to_string(), end: "17:00".to_string(), timezone: "America/New_York".to_string(), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScheduleWindow { /// Day of week: `"monday"` through `"sunday"`, or `"daily"` for every day. pub day: String, /// Start time in 24h format (e.g., `"09:00"`). pub start: String, /// End time in 24h format (e.g., `"17:00"`). pub end: String, /// IANA timezone for this window (e.g., `"America/New_York"`). pub timezone: String } ``` Source line: `29`. ## calendar::BookingEndpoint [#calendarbookingendpoint] A booking or scheduling endpoint. Each booking entry can have its own visibility — an agent might expose a public booking link for external clients but restrict an internal scheduling API to organization members only. # Examples [#examples-1] ``` use oas_document::calendar::BookingEndpoint; use oas_document::visibility::Visibility; let booking = BookingEndpoint { id: "booking-public".to_string(), url: "https://cal.com/agent42/30min".to_string(), label: Some("30-min consultation".to_string()), booking_type: Some("consultation".to_string()), visibility: Visibility::Public, }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BookingEndpoint { /// Fragment identifier (e.g., "booking-public", "booking-internal"). pub id: String, /// The booking URL (e.g., Calendly, Cal.com, custom API). pub url: String, /// Human-readable label (e.g., "30-min consultation", "Priority support"). #[serde(skip_serializing_if = "Option::is_none")] pub label: Option, /// Type of booking: `"consultation"`, `"support"`, `"meeting"`, `"task"`, `"custom"`. #[serde(skip_serializing_if = "Option::is_none")] pub booking_type: Option, /// Who can access this booking endpoint. #[serde(default)] pub visibility: Visibility } ``` Source line: `65`. ## calendar::CalendarSection [#calendarcalendarsection] Calendar and scheduling section of an OAS Identity Document. # Examples [#examples-2] ``` use oas_document::calendar::{CalendarSection, BookingEndpoint, ScheduleWindow}; use oas_document::visibility::Visibility; let calendar = CalendarSection { booking_endpoints: vec![ BookingEndpoint { id: "booking-external".to_string(), url: "https://cal.com/agent42/intro".to_string(), label: Some("Intro call".to_string()), booking_type: Some("consultation".to_string()), visibility: Visibility::Public, }, BookingEndpoint { id: "booking-internal".to_string(), url: "https://internal.acme.com/schedule/agent42".to_string(), label: Some("Internal sync".to_string()), booking_type: Some("meeting".to_string()), visibility: Visibility::Organization, }, ], availability_feed: Some("https://cal.com/agent42/availability.ics".to_string()), scheduling_protocol: Some("ical-invite".to_string()), office_hours: vec![ ScheduleWindow { day: "monday".to_string(), start: "09:00".to_string(), end: "17:00".to_string(), timezone: "America/New_York".to_string(), }, ], timezone: Some("America/New_York".to_string()), }; assert_eq!(calendar.booking_endpoints.len(), 2); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CalendarSection { /// Booking endpoints, each with independent visibility. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub booking_endpoints: Vec, /// iCal/CalDAV URL for real-time availability (free/busy). #[serde(skip_serializing_if = "Option::is_none")] pub availability_feed: Option, /// Preferred scheduling protocol: /// `"ical-invite"`, `"api"`, `"agent-negotiation"`, `"manual"`. #[serde(skip_serializing_if = "Option::is_none")] pub scheduling_protocol: Option, /// Recurring office hours / availability windows. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub office_hours: Vec, /// Default IANA timezone for this entity's schedule. #[serde(skip_serializing_if = "Option::is_none")] pub timezone: Option } ``` Source line: `126`. ## calendar::booking\_types [#calendarbooking_types] Standard booking types. ```rust pub mod booking_types; ``` Source line: `150`. ## calendar::booking\_types::CONSULTATION [#calendarbooking_typesconsultation] ```rust pub const CONSULTATION: &str; ``` Source line: `151`. ## calendar::booking\_types::SUPPORT [#calendarbooking_typessupport] ```rust pub const SUPPORT: &str; ``` Source line: `152`. ## calendar::booking\_types::MEETING [#calendarbooking_typesmeeting] ```rust pub const MEETING: &str; ``` Source line: `153`. ## calendar::booking\_types::TASK [#calendarbooking_typestask] ```rust pub const TASK: &str; ``` Source line: `154`. ## calendar::booking\_types::CUSTOM [#calendarbooking_typescustom] ```rust pub const CUSTOM: &str; ``` Source line: `155`. ## calendar::scheduling\_protocols [#calendarscheduling_protocols] Standard scheduling protocols. ```rust pub mod scheduling_protocols; ``` Source line: `159`. ## calendar::scheduling\_protocols::ICAL\_INVITE [#calendarscheduling_protocolsical_invite] iCalendar invite via email. ```rust pub const ICAL_INVITE: &str; ``` Source line: `161`. ## calendar::scheduling\_protocols::API [#calendarscheduling_protocolsapi] Direct API call to booking endpoint. ```rust pub const API: &str; ``` Source line: `163`. ## calendar::scheduling\_protocols::AGENT\_NEGOTIATION [#calendarscheduling_protocolsagent_negotiation] Agent-to-agent negotiation via MAP protocols. ```rust pub const AGENT_NEGOTIATION: &str; ``` Source line: `165`. ## calendar::scheduling\_protocols::MANUAL [#calendarscheduling_protocolsmanual] Manual / human-in-the-loop scheduling. ```rust pub const MANUAL: &str; ``` Source line: `167`. # oas-document · compliance URL: https://docs.openagent.id/reference/rust/oas-document/compliance Markdown: https://docs.openagent.id/reference/rust/oas-document/compliance.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/compliance.rs`. SHA-256: `d8e7bef91c2192744c6174ed6ca1caeff461d721db91f8f4f9a7e9149cdecbb0`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## compliance::Certification [#compliancecertification] A compliance certification held by the entity. # Examples [#examples] ``` use oas_document::compliance::Certification; let cert = Certification { standard: "SOC2 Type II".to_string(), issuer: Some("Vanta".to_string()), valid_until: Some("2027-06-30".to_string()), url: Some("https://acme.com/compliance/soc2".to_string()), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Certification { /// Standard name: `"SOC2 Type II"`, `"GDPR"`, `"HIPAA"`, `"ISO 27001"`. pub standard: String, /// Issuing body or audit firm. #[serde(skip_serializing_if = "Option::is_none")] pub issuer: Option, /// Expiry date (ISO 8601 date or datetime). #[serde(skip_serializing_if = "Option::is_none")] pub valid_until: Option, /// URL to certification evidence or public report. #[serde(skip_serializing_if = "Option::is_none")] pub url: Option } ``` Source line: `25`. ## compliance::ComplianceSection [#compliancecompliancesection] Compliance and jurisdiction section of an OAS Identity Document. # Examples [#examples-1] ``` use oas_document::compliance::{ComplianceSection, Certification}; let compliance = ComplianceSection { jurisdictions: vec!["US".to_string(), "EU".to_string()], certifications: vec![Certification { standard: "GDPR".to_string(), issuer: None, valid_until: None, url: None, }], terms_of_service_url: Some("https://acme.com/tos".to_string()), privacy_policy_url: Some("https://acme.com/privacy".to_string()), data_handling_policy_url: Some("https://acme.com/data-policy".to_string()), data_residency: Some("EU".to_string()), }; assert_eq!(compliance.jurisdictions.len(), 2); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ComplianceSection { /// Operating jurisdictions (ISO 3166-1 alpha-2 country codes). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub jurisdictions: Vec, /// Compliance certifications. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub certifications: Vec, /// Terms of service URL. #[serde(skip_serializing_if = "Option::is_none")] pub terms_of_service_url: Option, /// Privacy policy URL. #[serde(skip_serializing_if = "Option::is_none")] pub privacy_policy_url: Option, /// Data handling / data processing policy URL. #[serde(skip_serializing_if = "Option::is_none")] pub data_handling_policy_url: Option, /// Data residency region (ISO 3166-1 alpha-2 or region name). #[serde(skip_serializing_if = "Option::is_none")] pub data_residency: Option } ``` Source line: `66`. # oas-document · conformance URL: https://docs.openagent.id/reference/rust/oas-document/conformance Markdown: https://docs.openagent.id/reference/rust/oas-document/conformance.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/conformance.rs`. SHA-256: `4af11df070193dee1ef0d8e327a75debbdee373a6fc557a144f7e229e892cf65`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## conformance::ConformanceLevel [#conformanceconformancelevel] OAS conformance levels as defined in OAS Specification §10. * **L0**: Basic Identity — valid document, signature, and kind * **L1**: Accountable Identity — L0 + valid lineage to human root * **L2**: Full Identity — L1 + immutable ledger anchoring + third-party attestation # Examples [#examples] ``` use oas_document::conformance::ConformanceLevel; use std::str::FromStr; let level = ConformanceLevel::from_str("L1").unwrap(); assert!(level >= ConformanceLevel::L0); ``` ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum ConformanceLevel { /// Level 0 — Basic Identity (OAS Spec §10.1). L0, /// Level 1 — Accountable Identity (OAS Spec §10.2). L1, /// Level 2 — Full Identity (OAS Spec §10.3). L2, } ``` Source line: `25`. ## conformance::ConformanceLevel::as\_str [#conformanceconformancelevelas_str] Returns the string representation. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `36`. # oas-document · contact URL: https://docs.openagent.id/reference/rust/oas-document/contact Markdown: https://docs.openagent.id/reference/rust/oas-document/contact.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/contact.rs`. SHA-256: `b9714c05319246fe83cf72c2d2e9e01665b90f703afe1b3dc4cf1030db576d86`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## contact::ContactEntry [#contactcontactentry] A single contact entry in an entity's contact directory. Each entry represents one reachable channel (phone, email, social profile, etc.) with its own visibility level for access control. # DHT Behavior [#dht-behavior] For entries where `visibility` is not `public`, the DHT-stored copy contains: ```json { "id": "phone-1", "entryType": "phone", "label": "Support", "visibility": "organization", "available": true, "value": null } ``` The actual `value` is only served via the authenticated `OASPrivateEndpointService`. # Examples [#examples] ``` use oas_document::contact::ContactEntry; use oas_document::visibility::Visibility; let phone = ContactEntry { id: "phone-1".to_string(), entry_type: "phone".to_string(), value: "tel:+15551234567".to_string(), label: Some("Primary".to_string()), platform: None, handle: None, visibility: Visibility::Public, verified: Some(true), }; assert_eq!(phone.entry_type, "phone"); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ContactEntry { /// Fragment identifier (e.g., "phone-1", "email-2", "social-x"). pub id: String, /// Entry type: `"phone"`, `"email"`, `"social"`, `"website"`, `"messaging"`. pub entry_type: String, /// The contact value. Format depends on type: /// - phone: `tel:+15551234567` /// - email: `mailto:agent@example.com` /// - social: `https://x.com/agent` /// - website: `https://example.com/agent` /// - messaging: `https://t.me/agent_bot` pub value: String, /// Human-readable label (e.g., "Primary", "Support", "Sales", "Personal"). #[serde(skip_serializing_if = "Option::is_none")] pub label: Option, /// Platform name for social/messaging entries (e.g., "x", "linkedin", /// "discord", "telegram", "github", "slack", "whatsapp", "signal"). #[serde(skip_serializing_if = "Option::is_none")] pub platform: Option, /// Handle/username for social/messaging entries (e.g., "@agent42"). #[serde(skip_serializing_if = "Option::is_none")] pub handle: Option, /// Who can see this entry's actual value. /// Non-public entries show only the capability flag on the DHT. #[serde(default)] pub visibility: Visibility, /// Whether this contact channel has been verified by the entity. #[serde(skip_serializing_if = "Option::is_none")] pub verified: Option } ``` Source line: `53`. ## contact::ContactSection [#contactcontactsection] Contact directory section of an OAS Identity Document. Contains all reachable channels for an entity, each with independent visibility controls. # Standard Entry Types [#standard-entry-types] | Type | Value Format | Example | | ----------- | ---------------------------------- | ------------------------ | | `phone` | `tel:` URI (E.164) | `tel:+15551234567` | | `email` | `mailto:` URI | `mailto:agent@acme.com` | | `social` | HTTPS URL to profile | `https://x.com/agent42` | | `website` | HTTPS URL | `https://acme.com/agent` | | `messaging` | HTTPS URL or protocol-specific URI | `https://t.me/agent_bot` | # Examples [#examples-1] ``` use oas_document::contact::{ContactSection, ContactEntry}; use oas_document::visibility::Visibility; let contact = ContactSection { entries: vec![ ContactEntry { id: "email-1".to_string(), entry_type: "email".to_string(), value: "mailto:hello@agent.ai".to_string(), label: Some("Primary".to_string()), platform: None, handle: None, visibility: Visibility::Public, verified: Some(true), }, ContactEntry { id: "social-x".to_string(), entry_type: "social".to_string(), value: "https://x.com/agent42".to_string(), label: None, platform: Some("x".to_string()), handle: Some("@agent42".to_string()), visibility: Visibility::Public, verified: None, }, ], }; assert_eq!(contact.entries.len(), 2); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ContactSection { /// All contact entries for this entity. pub entries: Vec } ``` Source line: `140`. ## contact::entry\_types [#contactentry_types] Standard contact entry types. ```rust pub mod entry_types; ``` Source line: `146`. ## contact::entry\_types::PHONE [#contactentry_typesphone] Telephone number (value format: `tel:` URI). ```rust pub const PHONE: &str; ``` Source line: `148`. ## contact::entry\_types::EMAIL [#contactentry_typesemail] Email address (value format: `mailto:` URI). ```rust pub const EMAIL: &str; ``` Source line: `150`. ## contact::entry\_types::SOCIAL [#contactentry_typessocial] Social media profile (value: HTTPS URL). ```rust pub const SOCIAL: &str; ``` Source line: `152`. ## contact::entry\_types::WEBSITE [#contactentry_typeswebsite] Website (value: HTTPS URL). ```rust pub const WEBSITE: &str; ``` Source line: `154`. ## contact::entry\_types::MESSAGING [#contactentry_typesmessaging] Messaging endpoint (value: HTTPS URL or protocol-specific URI). ```rust pub const MESSAGING: &str; ``` Source line: `156`. ## contact::platforms [#contactplatforms] Standard social platform identifiers. ```rust pub mod platforms; ``` Source line: `160`. ## contact::platforms::X [#contactplatformsx] ```rust pub const X: &str; ``` Source line: `161`. ## contact::platforms::LINKEDIN [#contactplatformslinkedin] ```rust pub const LINKEDIN: &str; ``` Source line: `162`. ## contact::platforms::GITHUB [#contactplatformsgithub] ```rust pub const GITHUB: &str; ``` Source line: `163`. ## contact::platforms::DISCORD [#contactplatformsdiscord] ```rust pub const DISCORD: &str; ``` Source line: `164`. ## contact::platforms::TELEGRAM [#contactplatformstelegram] ```rust pub const TELEGRAM: &str; ``` Source line: `165`. ## contact::platforms::SLACK [#contactplatformsslack] ```rust pub const SLACK: &str; ``` Source line: `166`. ## contact::platforms::WHATSAPP [#contactplatformswhatsapp] ```rust pub const WHATSAPP: &str; ``` Source line: `167`. ## contact::platforms::SIGNAL [#contactplatformssignal] ```rust pub const SIGNAL: &str; ``` Source line: `168`. ## contact::platforms::MASTODON [#contactplatformsmastodon] ```rust pub const MASTODON: &str; ``` Source line: `169`. ## contact::platforms::BLUESKY [#contactplatformsbluesky] ```rust pub const BLUESKY: &str; ``` Source line: `170`. ## contact::platforms::YOUTUBE [#contactplatformsyoutube] ```rust pub const YOUTUBE: &str; ``` Source line: `171`. ## contact::platforms::INSTAGRAM [#contactplatformsinstagram] ```rust pub const INSTAGRAM: &str; ``` Source line: `172`. ## contact::platforms::TIKTOK [#contactplatformstiktok] ```rust pub const TIKTOK: &str; ``` Source line: `173`. ## contact::platforms::REDDIT [#contactplatformsreddit] ```rust pub const REDDIT: &str; ``` Source line: `174`. # oas-document · crate URL: https://docs.openagent.id/reference/rust/oas-document/crate Markdown: https://docs.openagent.id/reference/rust/oas-document/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/lib.rs`. SHA-256: `ae6cedb59a5abc8a4b74aaa59115ee9c7fab1f715ea69bf7870a264daf7434d3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## builder [#builder] # oas-document [#oas-document] OAS Identity Document types and validation for the Open Agent Specification. This crate provides the \[`OasDocument`] type for representing, constructing, and validating OAS Identity Documents as defined in OAS Specification §5. ## Key Types [#key-types] * \[`OasDocument`] — The core identity document * [`DocumentBuilder`](builder::DocumentBuilder) — Ergonomic document construction * [`DocumentProof`](proof_format::DocumentProof) — Ed25519Signature2020 proofs * [`LineageSection`](lineage_section::LineageSection) — Lineage chain data * [`ConformanceLevel`](conformance::ConformanceLevel) — L0/L1/L2 conformance * [`LifecycleStatus`](lifecycle::LifecycleStatus) — Entity lifecycle states ## Example [#example] ``` use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .controller("did:oas:test:hmr:alice") .conformance_level(ConformanceLevel::L1) .add_verification_method(&keypair) .name("Alice") .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); assert_eq!(doc.kind, "hmr"); assert!(doc.proof.is_some()); ``` ```rust pub mod builder; ``` Source line: `37`. ## calendar [#calendar] ```rust pub mod calendar; ``` Source line: `38`. ## compliance [#compliance] ```rust pub mod compliance; ``` Source line: `39`. ## conformance [#conformance] ```rust pub mod conformance; ``` Source line: `40`. ## contact [#contact] ```rust pub mod contact; ``` Source line: `41`. ## document [#document] ```rust pub mod document; ``` Source line: `42`. ## error [#error] ```rust pub mod error; ``` Source line: `43`. ## governance [#governance] ```rust pub mod governance; ``` Source line: `44`. ## interop [#interop] ```rust pub mod interop; ``` Source line: `45`. ## lifecycle [#lifecycle] ```rust pub mod lifecycle; ``` Source line: `46`. ## lineage\_section [#lineage_section] ```rust pub mod lineage_section; ``` Source line: `47`. ## operational [#operational] ```rust pub mod operational; ``` Source line: `48`. ## pricing [#pricing] ```rust pub mod pricing; ``` Source line: `49`. ## profile [#profile] ```rust pub mod profile; ``` Source line: `50`. ## proof\_format [#proof_format] ```rust pub mod proof_format; ``` Source line: `51`. ## relationships [#relationships] ```rust pub mod relationships; ``` Source line: `52`. ## reputation [#reputation] ```rust pub mod reputation; ``` Source line: `53`. ## service [#service] ```rust pub mod service; ``` Source line: `54`. ## verification\_method [#verification_method] ```rust pub mod verification_method; ``` Source line: `55`. ## visibility [#visibility] ```rust pub mod visibility; ``` Source line: `56`. ## pub use document::OasDocument; [#pub-use-documentoasdocument] ```rust pub use document::OasDocument; ``` Source line: `58`. ## pub use error::DocumentError; [#pub-use-errordocumenterror] ```rust pub use error::DocumentError; ``` Source line: `59`. ## pub use governance::\{ [#pub-use-governance] GovernancePolicy, GovernanceSection, GovernanceTransition, GovernanceTransitionProof, }; ```rust pub use governance::{ GovernancePolicy, GovernanceSection, GovernanceTransition, GovernanceTransitionProof, }; ``` Source line: `60`. # oas-document · document URL: https://docs.openagent.id/reference/rust/oas-document/document Markdown: https://docs.openagent.id/reference/rust/oas-document/document.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/document.rs`. SHA-256: `586da29287fbfd0b63c9f78262aa79e5be3ad43b9af1cf6e7d3736bd92c0d468`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## document::OAS\_CONTEXT [#documentoas_context] The OAS JSON-LD context URI. ```rust pub const OAS_CONTEXT: &str; ``` Source line: `28`. ## document::DID\_CONTEXT [#documentdid_context] The W3C DID context URI. ```rust pub const DID_CONTEXT: &str; ``` Source line: `31`. ## document::ED25519\_CONTEXT [#documented25519_context] The Ed25519 2020 suite context URI. ```rust pub const ED25519_CONTEXT: &str; ``` Source line: `34`. ## document::OAS\_VERSION [#documentoas_version] The current OAS specification version. ```rust pub const OAS_VERSION: &str; ``` Source line: `37`. ## document::DocumentMetadata [#documentdocumentmetadata] Metadata section of an OAS Identity Document. # Examples [#examples] ``` use oas_document::document::DocumentMetadata; let meta = DocumentMetadata { created: "2026-01-15T00:00:00Z".to_string(), updated: None, version: None, }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DocumentMetadata { /// ISO 8601 creation timestamp (required). pub created: String, /// ISO 8601 last update timestamp (optional). #[serde(skip_serializing_if = "Option::is_none")] pub updated: Option, /// Semantic version of this entity's definition (optional). #[serde(skip_serializing_if = "Option::is_none")] pub version: Option } ``` Source line: `53`. ## document::OasDocument [#documentoasdocument] An OAS Identity Document as defined in OAS Specification §5. This is the canonical representation of an autonomous entity's identity, extending the W3C DID Document with OAS-specific properties. # Examples [#examples-1] ``` use oas_document::OasDocument; let json = r#"{ "@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2020/v1", "https://openagent.id/ns/oas/v1"], "id": "did:oas:test:hmr:alice", "controller": "did:oas:test:hmr:alice", "verificationMethod": [{"id": "did:oas:test:hmr:alice#key-1", "type": "Ed25519VerificationKey2020", "controller": "did:oas:test:hmr:alice", "publicKeyMultibase": "zTest"}], "authentication": ["did:oas:test:hmr:alice#key-1"], "oasVersion": "1.0.0", "kind": "hmr", "conformanceLevel": "L1", "sequence": 1, "metadata": {"created": "2026-01-15T00:00:00Z"} }"#; let doc: OasDocument = serde_json::from_str(json).unwrap(); assert_eq!(doc.id, "did:oas:test:hmr:alice"); ``` ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OasDocument { /// JSON-LD contexts. MUST include the OAS context. #[serde(rename = "@context")] pub context: Vec, /// The `did:oas` identifier. pub id: String, /// DID of the controlling entity. pub controller: String, /// At least one Ed25519VerificationKey2020. pub verification_method: Vec, /// References to keys authorized for authentication. pub authentication: Vec, /// References to keys authorized for assertions. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub assertion_method: Vec, /// References to keys authorized for capability invocation. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capability_invocation: Vec, /// References to keys authorized for capability delegation. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capability_delegation: Vec, /// Service endpoints. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub service: Vec, /// OAS specification version (currently `"1.0.0"`). pub oas_version: String, /// Entity kind from the taxonomy. pub kind: String, /// Human-readable name (max 256 chars). #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// Human-readable description (max 4096 chars). #[serde(skip_serializing_if = "Option::is_none")] pub description: Option, /// Lineage information (required for L1+ non-root entities). #[serde(skip_serializing_if = "Option::is_none")] pub lineage: Option, /// Governance section (ENR entities only). /// Tracks which MHR governs this enterprise identity, epoch, and transition history. #[serde(skip_serializing_if = "Option::is_none")] pub governance: Option, /// Conformance level: L0, L1, or L2. pub conformance_level: ConformanceLevel, /// Lifecycle status. #[serde(skip_serializing_if = "Option::is_none")] pub lifecycle_status: Option, /// Monotonically increasing version counter (starting at 1). pub sequence: u64, /// Document metadata. pub metadata: DocumentMetadata, /// Document proof (Ed25519Signature2020). #[serde(skip_serializing_if = "Option::is_none")] pub proof: Option, /// Whether this identity has been revoked. #[serde(skip_serializing_if = "Option::is_none")] pub revoked: Option, /// Timestamp of revocation. #[serde(skip_serializing_if = "Option::is_none")] pub revoked_at: Option, // ── Extended Identity Sections (OAS §5.8–§5.16) ────────────────── /// Profile / presentation data (§5.8): avatar, tagline, categories. #[serde(default, skip_serializing_if = "Option::is_none")] pub profile: Option, /// Contact directory (§5.9): phones, emails, socials, websites. #[serde(default, skip_serializing_if = "Option::is_none")] pub contact: Option, /// Calendar & scheduling (§5.10): booking links, office hours. #[serde(default, skip_serializing_if = "Option::is_none")] pub calendar: Option, /// Operational specification (§5.11): SLA, rate limits, formats. #[serde(default, skip_serializing_if = "Option::is_none")] pub operational: Option, /// Pricing & economics (§5.12): cost model, billing, free tier. #[serde(default, skip_serializing_if = "Option::is_none")] pub pricing: Option, /// Interoperability (§5.13): protocols, API schemas, auth methods. #[serde(default, skip_serializing_if = "Option::is_none")] pub interoperability: Option, /// Reputation summary (§5.14): interactions, endorsements, uptime. #[serde(default, skip_serializing_if = "Option::is_none")] pub reputation: Option, /// Compliance & jurisdiction (§5.15): certifications, policy URLs. #[serde(default, skip_serializing_if = "Option::is_none")] pub compliance: Option, /// Relationships & affiliations (§5.16): org structure, partnerships. #[serde(default, skip_serializing_if = "Option::is_none")] pub relationships: Option } ``` Source line: `93`. ## document::OasDocument::default\_context [#documentoasdocumentdefault_context] Returns the default JSON-LD context array for OAS documents. ```rust pub fn default_context() -> Vec; ``` Source line: `214`. ## document::OasDocument::is\_root [#documentoasdocumentis_root] Returns true if this document represents a root entity (HMR, MHR, or ENR). ```rust pub fn is_root(&self) -> bool; ``` Source line: `223`. ## document::OasDocument::is\_revoked [#documentoasdocumentis_revoked] Returns true if this document has been revoked. ```rust pub fn is_revoked(&self) -> bool; ``` Source line: `228`. ## document::OasDocument::canonical\_digest [#documentoasdocumentcanonical_digest] Computes the canonical BLAKE3 commitment for this complete document. The digest covers the RFC 8785 canonical JSON representation, including the document proof and all status, relationship, key, and lineage fields. Lineage proofs bind this value to the authenticated parent state used at issuance time. # Returns [#returns] A lowercase `blake3:`-prefixed digest. # Errors [#errors] Returns \[`DocumentError::Crypto`] if canonicalization fails. ```rust pub fn canonical_digest(&self) -> Result; ``` Source line: `246`. ## document::OasDocument::primary\_public\_key\_multibase [#documentoasdocumentprimary_public_key_multibase] Returns the primary public key multibase string, if available. Looks for the first verification method's public key. ```rust pub fn primary_public_key_multibase(&self) -> Option<&str>; ``` Source line: `258`. ## document::OasDocument::find\_verification\_method [#documentoasdocumentfind_verification_method] Finds a verification method by its full ID or fragment. ```rust pub fn find_verification_method(&self, id_or_fragment: &str) -> Option<&VerificationMethod>; ``` Source line: `265`. # oas-document · error URL: https://docs.openagent.id/reference/rust/oas-document/error Markdown: https://docs.openagent.id/reference/rust/oas-document/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/error.rs`. SHA-256: `c054eaf593cb626500298c19fc5307892f8adb3b04aabc86f7665bfb6afe7a4b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::DocumentError [#errordocumenterror] Errors arising from OAS Identity Document operations. ```rust #[derive(Debug, Error)] pub enum DocumentError { /// The document is missing a required field. #[error("missing required field '{field}' in OAS Identity Document")] MissingField { /// The name of the missing field. field: String, }, /// A field value is invalid. #[error("invalid value for field '{field}': {reason}")] InvalidField { /// The field name. field: String, /// Why the value is invalid. reason: String, }, /// Document proof verification failed. #[error("document proof verification failed: {reason}")] ProofVerificationFailed { /// Why verification failed. reason: String, }, /// Document proof generation failed. #[error("document proof generation failed: {reason}")] ProofGenerationFailed { /// Why generation failed. reason: String, }, /// Conformance level requirements not met. #[error("conformance level {level} requirements not met: {reason}")] ConformanceNotMet { /// The conformance level that was not met. level: String, /// What requirement was not satisfied. reason: String, }, /// JSON serialization/deserialization failed. #[error("JSON error: {0}")] Json(#[from] serde_json::Error), /// DID parsing failed. #[error("DID error: {0}")] Did(#[from] oas_did::DidError), /// Cryptographic operation failed. #[error("crypto error: {0}")] Crypto(#[from] oas_crypto::CryptoError), /// The lifecycle status transition is not allowed. #[error("invalid lifecycle transition from '{from}' to '{to}'")] InvalidLifecycleTransition { /// Current status. from: String, /// Attempted new status. to: String, }, /// Sequence number is not valid. #[error("invalid sequence number {sequence}: {reason}")] InvalidSequence { /// The invalid sequence number. sequence: u64, /// Why it's invalid. reason: String, }, } ``` Source line: `8`. # oas-document · governance URL: https://docs.openagent.id/reference/rust/oas-document/governance Markdown: https://docs.openagent.id/reference/rust/oas-document/governance.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/governance.rs`. SHA-256: `a3080f49ab3529bad6cdbd7b4f6522a78abf72e1e43017e197a9c998ed7e7e6a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## governance::GovernanceSection [#governancegovernancesection] Governance section attached to ENR identity documents. Tracks the governing MHR, monotonic epoch counter, transition history, and governance policy constraints. # Invariants [#invariants] * `epoch` MUST strictly increase (no gaps, no rewinds). * `current_mhr` MUST reference a valid, non-revoked MHR DID. * Each transition's `from` MUST match the previous transition's `to`. # Examples [#examples] ``` use oas_document::governance::GovernanceSection; let json = r#"{ "currentMhr": "did:oas:prod:mhr:council-alpha", "epoch": 1, "transitions": [], "policy": { "transitionRequires": "mhr_threshold", "signingKeyRotationRequires": "mhr_threshold", "maxTransitionsPerDay": 1, "timelockHours": 24 } }"#; let gov: GovernanceSection = serde_json::from_str(json).unwrap(); assert_eq!(gov.epoch, 1); ``` ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GovernanceSection { /// DID of the MHR currently governing this ENR. pub current_mhr: String, /// Monotonically increasing epoch counter. /// Incremented on every governance transition. pub epoch: u64, /// Complete history of governance transitions. #[serde(default)] pub transitions: Vec, /// Governance policy constraints. pub policy: GovernancePolicy } ``` Source line: `42`. ## governance::GovernanceTransition [#governancegovernancetransition] A single governance transition record. Records the handoff from one MHR to another, including the cryptographic proof (FROST threshold signature from the outgoing MHR). ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GovernanceTransition { /// DID of the outgoing MHR (None for the initial governance assignment). #[serde(skip_serializing_if = "Option::is_none")] pub from: Option, /// DID of the incoming MHR. pub to: String, /// Epoch at which this transition occurred. pub epoch: u64, /// Cryptographic proof of the transition. pub proof: GovernanceTransitionProof } ``` Source line: `64`. ## governance::GovernanceTransitionProof [#governancegovernancetransitionproof] Proof that a governance transition was authorized. Contains a FROST threshold signature from the outgoing MHR members, proving that a quorum approved the handoff. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GovernanceTransitionProof { /// Proof type identifier. #[serde(rename = "type")] pub proof_type: String, /// FROST threshold signature from the outgoing MHR (base64url-encoded). pub mhr_threshold_signature: String, /// ISO 8601 timestamp of when the proof was created. pub timestamp: String } ``` Source line: `85`. ## governance::ENR\_GOVERNANCE\_PROOF\_TYPE [#governanceenr_governance_proof_type] The canonical proof type string for ENR governance transitions. ```rust pub const ENR_GOVERNANCE_PROOF_TYPE: &str; ``` Source line: `98`. ## governance::GovernancePolicy [#governancegovernancepolicy] Policy constraints governing how ENR transitions may occur. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GovernancePolicy { /// What is required to transition governance (e.g., `"mhr_threshold"`). pub transition_requires: String, /// What is required to rotate the ENR signing key (e.g., `"mhr_threshold"`). pub signing_key_rotation_requires: String, /// Maximum number of governance transitions allowed per 24-hour period. #[serde(default = "default_max_transitions")] pub max_transitions_per_day: u32, /// Mandatory delay (in hours) between initiating and confirming a transition. #[serde(default = "default_timelock")] pub timelock_hours: u32 } ``` Source line: `103`. ## governance::GovernancePolicy::default\_policy [#governancegovernancepolicydefault_policy] Creates a default governance policy with standard constraints. ```rust pub fn default_policy() -> Self; ``` Source line: `129`. # oas-document modules URL: https://docs.openagent.id/reference/rust/oas-document Markdown: https://docs.openagent.id/reference/rust/oas-document.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-document). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-document/crate) — 23 declarations * [builder](/reference/rust/oas-document/builder) — 22 declarations * [calendar](/reference/rust/oas-document/calendar) — 14 declarations * [compliance](/reference/rust/oas-document/compliance) — 2 declarations * [conformance](/reference/rust/oas-document/conformance) — 2 declarations * [contact](/reference/rust/oas-document/contact) — 23 declarations * [document](/reference/rust/oas-document/document) — 12 declarations * [error](/reference/rust/oas-document/error) — 1 declarations * [governance](/reference/rust/oas-document/governance) — 6 declarations * [interop](/reference/rust/oas-document/interop) — 17 declarations * [lifecycle](/reference/rust/oas-document/lifecycle) — 2 declarations * [lineage\_section](/reference/rust/oas-document/lineage_section) — 8 declarations * [operational](/reference/rust/oas-document/operational) — 3 declarations * [pricing](/reference/rust/oas-document/pricing) — 9 declarations * [profile](/reference/rust/oas-document/profile) — 1 declarations * [proof\_format](/reference/rust/oas-document/proof_format) — 4 declarations * [relationships](/reference/rust/oas-document/relationships) — 9 declarations * [reputation](/reference/rust/oas-document/reputation) — 1 declarations * [service](/reference/rust/oas-document/service) — 10 declarations * [verification\_method](/reference/rust/oas-document/verification_method) — 4 declarations * [visibility](/reference/rust/oas-document/visibility) — 4 declarations # oas-document · interop URL: https://docs.openagent.id/reference/rust/oas-document/interop Markdown: https://docs.openagent.id/reference/rust/oas-document/interop.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/interop.rs`. SHA-256: `c63c95edc05cade79ac2ae2d901517dc8a3083e24ab61422ae6e877d27fddb43`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## interop::ProtocolSupport [#interopprotocolsupport] A supported protocol with optional version and endpoint. # Examples [#examples] ``` use oas_document::interop::ProtocolSupport; let proto = ProtocolSupport { protocol: "mcp".to_string(), version: Some("2025-01".to_string()), endpoint: Some("https://agent.acme.com/mcp".to_string()), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProtocolSupport { /// Protocol identifier: `"mcp"`, `"a2a"`, `"rest"`, `"graphql"`, /// `"grpc"`, `"websocket"`, `"oas-map"`. pub protocol: String, /// Protocol version if applicable. #[serde(skip_serializing_if = "Option::is_none")] pub version: Option, /// Endpoint URL for this protocol. #[serde(skip_serializing_if = "Option::is_none")] pub endpoint: Option } ``` Source line: `24`. ## interop::ApiSchema [#interopapischema] An API schema reference. # Examples [#examples-1] ``` use oas_document::interop::ApiSchema; let schema = ApiSchema { schema_type: "openapi".to_string(), url: "https://agent.acme.com/openapi.json".to_string(), version: Some("3.1.0".to_string()), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApiSchema { /// Schema format: `"openapi"`, `"asyncapi"`, `"json-schema"`, /// `"protobuf"`, `"graphql-sdl"`. pub schema_type: String, /// URL to the schema document. pub url: String, /// Schema version. #[serde(skip_serializing_if = "Option::is_none")] pub version: Option } ``` Source line: `53`. ## interop::InteroperabilitySection [#interopinteroperabilitysection] Interoperability section of an OAS Identity Document. # Examples [#examples-2] ``` use oas_document::interop::{InteroperabilitySection, ProtocolSupport, ApiSchema}; let interop = InteroperabilitySection { protocols: vec![ ProtocolSupport { protocol: "mcp".to_string(), version: Some("2025-01".to_string()), endpoint: Some("https://agent.acme.com/mcp".to_string()), }, ProtocolSupport { protocol: "rest".to_string(), version: None, endpoint: Some("https://api.acme.com/v1".to_string()), }, ], api_schemas: vec![ApiSchema { schema_type: "openapi".to_string(), url: "https://api.acme.com/v1/openapi.json".to_string(), version: Some("3.1.0".to_string()), }], auth_methods: vec!["did-auth".to_string(), "api-key".to_string()], }; assert_eq!(interop.protocols.len(), 2); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct InteroperabilitySection { /// Protocols this entity supports. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub protocols: Vec, /// API schema references. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub api_schemas: Vec, /// Authentication methods accepted: `"did-auth"`, `"api-key"`, /// `"oauth2"`, `"mtls"`, `"bearer-token"`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub auth_methods: Vec } ``` Source line: `97`. ## interop::protocols [#interopprotocols] Standard protocol identifiers. ```rust pub mod protocols; ``` Source line: `113`. ## interop::protocols::MCP [#interopprotocolsmcp] Model Context Protocol. ```rust pub const MCP: &str; ``` Source line: `115`. ## interop::protocols::A2A [#interopprotocolsa2a] Google Agent-to-Agent protocol. ```rust pub const A2A: &str; ``` Source line: `117`. ## interop::protocols::REST [#interopprotocolsrest] REST / HTTP API. ```rust pub const REST: &str; ``` Source line: `119`. ## interop::protocols::GRAPHQL [#interopprotocolsgraphql] GraphQL API. ```rust pub const GRAPHQL: &str; ``` Source line: `121`. ## interop::protocols::GRPC [#interopprotocolsgrpc] gRPC. ```rust pub const GRPC: &str; ``` Source line: `123`. ## interop::protocols::WEBSOCKET [#interopprotocolswebsocket] WebSocket. ```rust pub const WEBSOCKET: &str; ``` Source line: `125`. ## interop::protocols::OAS\_MAP [#interopprotocolsoas_map] OAS MAP protocol suite. ```rust pub const OAS_MAP: &str; ``` Source line: `127`. ## interop::auth\_methods [#interopauth_methods] Standard authentication methods. ```rust pub mod auth_methods; ``` Source line: `131`. ## interop::auth\_methods::DID\_AUTH [#interopauth_methodsdid_auth] ```rust pub const DID_AUTH: &str; ``` Source line: `132`. ## interop::auth\_methods::API\_KEY [#interopauth_methodsapi_key] ```rust pub const API_KEY: &str; ``` Source line: `133`. ## interop::auth\_methods::OAUTH2 [#interopauth_methodsoauth2] ```rust pub const OAUTH2: &str; ``` Source line: `134`. ## interop::auth\_methods::MTLS [#interopauth_methodsmtls] ```rust pub const MTLS: &str; ``` Source line: `135`. ## interop::auth\_methods::BEARER\_TOKEN [#interopauth_methodsbearer_token] ```rust pub const BEARER_TOKEN: &str; ``` Source line: `136`. # oas-document · lifecycle URL: https://docs.openagent.id/reference/rust/oas-document/lifecycle Markdown: https://docs.openagent.id/reference/rust/oas-document/lifecycle.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/lifecycle.rs`. SHA-256: `156e12d04f059e681b4f389c5f15b84ffc412beb105c5b495434a29c9263a0df`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## lifecycle::LifecycleStatus [#lifecyclelifecyclestatus] The lifecycle statuses an OAS entity can be in. Per OAS Specification §5.3, the valid lifecycle statuses are: `nascent`, `active`, `dormant`, `suspended`, `terminated`, `archived`. # Examples [#examples] ``` use oas_document::lifecycle::LifecycleStatus; use std::str::FromStr; let status = LifecycleStatus::from_str("active").unwrap(); assert_eq!(status, LifecycleStatus::Active); ``` ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LifecycleStatus { /// Entity is created but not yet operational. Nascent, /// Entity is operational and accepting interactions. Active, /// Entity is temporarily inactive but may be reactivated. Dormant, /// Entity has been suspended (e.g., for policy violation). Suspended, /// Entity has been permanently shut down. Terminated, /// Entity is preserved for historical/audit purposes. Archived, } ``` Source line: `25`. ## lifecycle::LifecycleStatus::as\_str [#lifecyclelifecyclestatusas_str] Returns the string representation. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `42`. # oas-document · lineage_section URL: https://docs.openagent.id/reference/rust/oas-document/lineage_section Markdown: https://docs.openagent.id/reference/rust/oas-document/lineage_section.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/lineage_section.rs`. SHA-256: `73319761726f6da22a5b6e35caf1353a6f1e0b6b947d04c8f01ffab28d892956`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## lineage\_section::LineageSection [#lineage_sectionlineagesection] The lineage section of an OAS Identity Document. Contains the cryptographic chain linking an entity to its human root. Required for L1+ conformance on non-root entities. See OAS Specification §8 for the complete structure. # Examples [#examples] ``` use oas_document::lineage_section::LineageSection; let lineage = LineageSection { human_root_did: "did:oas:acme:hmr:alice".to_string(), creator_did: "did:oas:acme:hmr:alice".to_string(), generation: 0, derivation_proof: None, human_root_chain: vec![ "did:oas:acme:ao:research".to_string(), "did:oas:acme:hmr:alice".to_string(), ], org_inclusion_proof: None, anchor_refs: None, }; assert_eq!(lineage.generation, 0); ``` ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LineageSection { /// DID of the ultimate human root (HMR, MHR, or ENR). pub human_root_did: String, /// DID of the entity that directly created this entity. pub creator_did: String, /// Number of derivation steps from human root. /// 0 = created directly by human root. pub generation: u32, /// AgentLineageProof2025 linking this entity to its creator. #[serde(skip_serializing_if = "Option::is_none")] pub derivation_proof: Option, /// Ordered array of DIDs from this entity to human root. pub human_root_chain: Vec, /// Optional Merkle inclusion proof binding this entity to the /// `OrgLineageRoot` of its creator (an MHR / ENR org). REQUIRED at /// resolution time when the GAL has an `OrgLineageRoot` for the /// creator DID. Verification uses BLAKE3; see /// [`OrgInclusionProof`]. #[serde(skip_serializing_if = "Option::is_none")] pub org_inclusion_proof: Option, /// References to on-chain or transparency-log anchors attesting to /// this lineage section's registration. /// /// Lineage authority is backend-agnostic (see [`AnchorRef`]). An /// entity MAY be anchored on multiple backends at once - Sigil and an /// EAS attestation and a transparency log - and verifiers consult the /// refs for the schemes they trust. A verifier MUST ignore refs whose /// `scheme` it does not support rather than rejecting the document: /// unknown schemes are additive, never breaking. #[serde(skip_serializing_if = "Option::is_none")] pub anchor_refs: Option> } ``` Source line: `35`. ## lineage\_section::AnchorRef [#lineage_sectionanchorref] A reference to an on-chain (or transparency-log) anchor attesting to a lineage registration. Lineage *proofs* verify offline; lineage *authority* - proof that the claimed root exists, that this delegation was recorded, and that nothing in the chain is revoked or superseded - is what an anchor backend supplies. The scheme names the backend; the locator addresses the record within it. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnchorRef { /// The anchor scheme: `sigil`, `eas`, `ctlog`, or a future registered /// name. Verifiers ignore schemes they do not support. pub scheme: String, /// Scheme-specific locator: a transaction hash (`sigil`), an /// attestation UID (`eas`), a log identifier and leaf index (`ctlog`). /// Opaque to verifiers that do not implement the scheme. pub locator: String, /// Optional inclusion proof binding the locator to the anchor /// backend's canonical root. Presence semantics are scheme-specific; /// some schemes (EAS) are self-proving and carry none, others (batch /// Merkle anchoring) require one. #[serde(skip_serializing_if = "Option::is_none")] pub inclusion_proof: Option } ``` Source line: `84`. ## lineage\_section::AnchorRef::to\_uri [#lineage_sectionanchorrefto_uri] The display form: `anchor::`. ```rust pub fn to_uri(&self) -> String; ``` Source line: `104`. ## lineage\_section::AnchorRef::parse\_uri [#lineage_sectionanchorrefparse_uri] Parse the display form back into a ref (without a proof). The locator may itself contain colons (e.g. `ctlog` log-id:index forms), so parsing splits at the first two colons only. ```rust pub fn parse_uri(uri: &str) -> Option; ``` Source line: `112`. ## lineage\_section::AnchorInclusionProof [#lineage_sectionanchorinclusionproof] An inclusion proof binding an \[`AnchorRef`] locator to its backend's canonical root. The shape is the Merkle family generalization used by \[`OrgInclusionProof`], named by `proof_type` so a backend can register others: `merkle-blake3` (Sigil, transparency logs), `eas-attestation` (EAS, where the attestation itself is the proof and `root` is the schema UID), or future registered types. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnchorInclusionProof { /// The proof family: `merkle-blake3`, `eas-attestation`, or a future /// registered name. Verifiers ignore types they do not support. pub proof_type: String, /// The root this proof binds to (hex digest or backend-native form). pub root: String, /// The leaf the anchored registration hashes to. pub leaf_hash: String, /// Ordered sibling path from leaf to root (Merkle-family proofs). /// Empty for self-proving schemes. #[serde(default)] pub path: Vec } ``` Source line: `136`. ## lineage\_section::MerkleDirection [#lineage_sectionmerkledirection] Direction of a sibling node in a Merkle proof path. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum MerkleDirection { /// Sibling is on the left; reconstructed hash combines as /// `H(sibling || current)`. Left, /// Sibling is on the right; reconstructed hash combines as /// `H(current || sibling)`. Right, } ``` Source line: `156`. ## lineage\_section::MerkleProofNode [#lineage_sectionmerkleproofnode] One step in a Merkle inclusion proof path. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MerkleProofNode { /// `blake3:`-prefixed hex of the sibling hash at this level. pub sibling_hash: String, /// Direction of the sibling relative to the current node. pub direction: MerkleDirection } ``` Source line: `168`. ## lineage\_section::OrgInclusionProof [#lineage_sectionorginclusionproof] Merkle inclusion proof binding a child entity to an `OrgLineageRoot`. Canonicalization rules (verified by `oas-resolve::sigil_guard` with the BLAKE3-32 hash function): 1. **Leaf hash:** `blake3:` + hex(BLAKE3(child\_did\_utf8\_bytes)). The org commits to a tree of child DIDs. 2. **Internal nodes:** at each level, combine the running hash and the sibling per `direction`. `Left` → `H(sibling || current)`; `Right` → `H(current || sibling)`. Both halves are taken as raw 32-byte BLAKE3 outputs (after stripping the `blake3:` prefix). 3. **Root match:** the final reconstructed root MUST equal both `proof.merkle_root` and the `merkle_root` of the `OrgLineageRoot` returned by the GAL for the creator DID. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OrgInclusionProof { /// `blake3:`-prefixed hex of the org's Merkle root. MUST equal the /// on-chain `OrgLineageRoot.merkle_root`. pub merkle_root: String, /// `blake3:`-prefixed hex of the leaf — `BLAKE3(child_did)`. pub leaf_hash: String, /// Ordered path of sibling hashes from leaf to root. pub path: Vec } ``` Source line: `192`. # oas-document · operational URL: https://docs.openagent.id/reference/rust/oas-document/operational Markdown: https://docs.openagent.id/reference/rust/oas-document/operational.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/operational.rs`. SHA-256: `a0a03270339a7b9f4dbbeac3a800654edb63b530e9aafa6f9b92e160ea913360`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## operational::SlaCommitment [#operationalslacommitment] An SLA commitment for a specific metric. # Examples [#examples] ``` use oas_document::operational::SlaCommitment; let sla = SlaCommitment { metric: "response_time_p95".to_string(), target: "<500ms".to_string(), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SlaCommitment { /// Metric name: `"response_time_p95"`, `"uptime"`, `"throughput"`. pub metric: String, /// Target value: `"<500ms"`, `"99.9%"`, `"1000 req/min"`. pub target: String } ``` Source line: `25`. ## operational::RateLimit [#operationalratelimit] A rate limit specification. # Examples [#examples-1] ``` use oas_document::operational::RateLimit; let limit = RateLimit { resource: "requests".to_string(), limit: 1000, window: "minute".to_string(), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RateLimit { /// What is being limited: `"requests"`, `"tokens"`, `"bytes"`. pub resource: String, /// Numeric limit value. pub limit: u64, /// Time window: `"second"`, `"minute"`, `"hour"`, `"day"`. pub window: String } ``` Source line: `48`. ## operational::OperationalSection [#operationaloperationalsection] Operational specification section of an OAS Identity Document. # Examples [#examples-2] ``` use oas_document::operational::{OperationalSection, SlaCommitment, RateLimit}; let ops = OperationalSection { availability: Some("24/7".to_string()), sla: vec![SlaCommitment { metric: "uptime".to_string(), target: "99.9%".to_string(), }], rate_limits: vec![RateLimit { resource: "requests".to_string(), limit: 1000, window: "minute".to_string(), }], supported_input_formats: vec!["application/json".to_string()], supported_output_formats: vec!["application/json".to_string()], max_payload_bytes: Some(10_485_760), max_context_tokens: None, maintenance_windows: vec![], }; assert_eq!(ops.sla.len(), 1); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OperationalSection { /// Availability mode: `"24/7"`, `"business_hours"`, `"on_demand"`, `"scheduled"`. #[serde(skip_serializing_if = "Option::is_none")] pub availability: Option, /// SLA commitments. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sla: Vec, /// Rate limits. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub rate_limits: Vec, /// Accepted input MIME types (e.g., `"application/json"`, `"text/plain"`). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub supported_input_formats: Vec, /// Produced output MIME types. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub supported_output_formats: Vec, /// Maximum request payload size in bytes. #[serde(skip_serializing_if = "Option::is_none")] pub max_payload_bytes: Option, /// Maximum context window in tokens (for LLM-backed agents). #[serde(skip_serializing_if = "Option::is_none")] pub max_context_tokens: Option, /// Scheduled maintenance windows when the entity is unavailable. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub maintenance_windows: Vec } ``` Source line: `87`. # oas-document · pricing URL: https://docs.openagent.id/reference/rust/oas-document/pricing Markdown: https://docs.openagent.id/reference/rust/oas-document/pricing.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/pricing.rs`. SHA-256: `68ede0b953a50b00885b05e0bd4340215873db18de5ed95786652bca372aba9f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## pricing::CostEntry [#pricingcostentry] A cost entry describing pricing for a specific unit of work. # Examples [#examples] ``` use oas_document::pricing::CostEntry; let cost = CostEntry { unit: "request".to_string(), amount: "0.001".to_string(), currency: "USD".to_string(), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CostEntry { /// What is being priced: `"request"`, `"token"`, `"minute"`, /// `"task"`, `"subscription_monthly"`. pub unit: String, /// Amount as a decimal string (to avoid floating-point issues). pub amount: String, /// ISO 4217 currency code (e.g., `"USD"`, `"EUR"`, `"BTC"`, `"ETH"`). pub currency: String } ``` Source line: `26`. ## pricing::PricingSection [#pricingpricingsection] Pricing and economics section of an OAS Identity Document. # Examples [#examples-1] ``` use oas_document::pricing::{PricingSection, CostEntry}; use oas_document::visibility::Visibility; let pricing = PricingSection { model: "per_request".to_string(), costs: vec![CostEntry { unit: "request".to_string(), amount: "0.001".to_string(), currency: "USD".to_string(), }], currencies_accepted: vec!["USD".to_string(), "ETH".to_string()], billing_endpoint: Some("https://api.acme.com/billing".to_string()), free_tier_limits: Some("100 requests/day".to_string()), billing_visibility: Visibility::Authenticated, }; assert_eq!(pricing.model, "per_request"); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PricingSection { /// Pricing model: `"free"`, `"per_request"`, `"per_token"`, /// `"subscription"`, `"negotiated"`, `"custom"`. pub model: String, /// Individual cost entries. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub costs: Vec, /// Currencies accepted (ISO 4217 or crypto ticker). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub currencies_accepted: Vec, /// Billing/payment endpoint URL. #[serde(skip_serializing_if = "Option::is_none")] pub billing_endpoint: Option, /// Free tier description (e.g., "100 requests/day", "1000 tokens/month"). #[serde(skip_serializing_if = "Option::is_none")] pub free_tier_limits: Option, /// Visibility of billing details. #[serde(default)] pub billing_visibility: Visibility } ``` Source line: `62`. ## pricing::models [#pricingmodels] Standard pricing models. ```rust pub mod models; ``` Source line: `89`. ## pricing::models::FREE [#pricingmodelsfree] ```rust pub const FREE: &str; ``` Source line: `90`. ## pricing::models::PER\_REQUEST [#pricingmodelsper_request] ```rust pub const PER_REQUEST: &str; ``` Source line: `91`. ## pricing::models::PER\_TOKEN [#pricingmodelsper_token] ```rust pub const PER_TOKEN: &str; ``` Source line: `92`. ## pricing::models::SUBSCRIPTION [#pricingmodelssubscription] ```rust pub const SUBSCRIPTION: &str; ``` Source line: `93`. ## pricing::models::NEGOTIATED [#pricingmodelsnegotiated] ```rust pub const NEGOTIATED: &str; ``` Source line: `94`. ## pricing::models::CUSTOM [#pricingmodelscustom] ```rust pub const CUSTOM: &str; ``` Source line: `95`. # oas-document · profile URL: https://docs.openagent.id/reference/rust/oas-document/profile Markdown: https://docs.openagent.id/reference/rust/oas-document/profile.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/profile.rs`. SHA-256: `13d72c9dd8b98eb3ac9d1e010d03e26d64eea745cdc4dad9bf1e11334fbfaf6d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## profile::ProfileSection [#profileprofilesection] Profile section of an OAS Identity Document. Provides human-readable presentation data for the entity. All fields are optional — entities expose only what they choose to. # Examples [#examples] ``` use oas_document::profile::ProfileSection; let profile = ProfileSection { avatar_url: Some("https://cdn.example.com/agent-42/avatar.png".to_string()), banner_url: None, tagline: Some("AI-powered financial analysis agent".to_string()), categories: vec!["finance".to_string(), "analytics".to_string()], languages: vec!["en".to_string(), "es".to_string()], timezone: Some("America/New_York".to_string()), accent_color: Some("#3B82F6".to_string()), }; assert_eq!(profile.languages.len(), 2); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ProfileSection { /// URL to the entity's avatar image. #[serde(skip_serializing_if = "Option::is_none")] pub avatar_url: Option, /// URL to the entity's banner/header image. #[serde(skip_serializing_if = "Option::is_none")] pub banner_url: Option, /// Short tagline or bio (max 280 chars, like a tweet). #[serde(skip_serializing_if = "Option::is_none")] pub tagline: Option, /// Category tags for discovery (e.g., "finance", "customer-support", "research"). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub categories: Vec, /// Supported languages as ISO 639-1 codes (e.g., "en", "es", "zh"). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub languages: Vec, /// IANA timezone identifier (e.g., "America/New_York", "UTC"). #[serde(skip_serializing_if = "Option::is_none")] pub timezone: Option, /// Accent/brand color as hex (e.g., "#3B82F6"). #[serde(skip_serializing_if = "Option::is_none")] pub accent_color: Option } ``` Source line: `32`. # oas-document · proof_format URL: https://docs.openagent.id/reference/rust/oas-document/proof_format Markdown: https://docs.openagent.id/reference/rust/oas-document/proof_format.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/proof_format.rs`. SHA-256: `ef0aa12184d48759fd268ee0af6899f0b746a90969c8a0d9867cbd3f69777835`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proof\_format::DOCUMENT\_PROOF\_TYPE [#proof_formatdocument_proof_type] The fixed proof type for OAS document proofs. ```rust pub const DOCUMENT_PROOF_TYPE: &str; ``` Source line: `16`. ## proof\_format::DocumentProof [#proof_formatdocumentproof] An Ed25519Signature2020 document proof. See OAS Specification §5.5 for the complete format. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DocumentProof { /// Fixed: `"Ed25519Signature2020"` #[serde(rename = "type")] pub proof_type: String, /// ISO 8601 timestamp of when the proof was created. pub created: String, /// Reference to the verification method used (e.g., `did:oas:ns:hmr:a#key-1`). pub verification_method: String, /// The purpose of this proof (e.g., `"assertionMethod"`). pub proof_purpose: String, /// The multibase-encoded Ed25519 signature (base58btc with `z` prefix). pub proof_value: String } ``` Source line: `23`. ## proof\_format::DocumentProof::generate [#proof_formatdocumentproofgenerate] Generates a document proof by signing the canonical document bytes. Implements OAS Specification §5.5: 1. Canonicalize the document (without proof) via JCS 2. Sign the canonical bytes with the signing key 3. Encode as multibase base58btc # Arguments [#arguments] * `document_json` - The document as a JSON value (proof field MUST be absent/null). * `keypair` - The signing keypair. * `verification_method_id` - Full ID of the verification method (e.g., `did:oas:ns:hmr:a#key-1`). * `created` - ISO 8601 timestamp for the proof. # Returns [#returns] A \[`DocumentProof`] containing the signature. # Errors [#errors] Returns \[`DocumentError::ProofGenerationFailed`] if canonicalization or signing fails. ```rust pub fn generate( document_json: &serde_json::Value, keypair: &OasKeyPair, verification_method_id: &str, created: &str, ) -> Result; ``` Source line: `63`. ## proof\_format::DocumentProof::verify [#proof_formatdocumentproofverify] Verifies this document proof against the canonical document bytes. Implements OAS Specification §5.5 verification: 1. Canonicalize the document (without proof) via JCS 2. Decode the proof value from multibase 3. Verify the Ed25519 signature # Arguments [#arguments-1] * `document_json` - The document as a JSON value (proof field MUST be absent/null). * `public_key_bytes` - The 32-byte Ed25519 public key. # Returns [#returns-1] `Ok(())` if the proof is valid. # Errors [#errors-1] Returns \[`DocumentError::ProofVerificationFailed`] if verification fails. ```rust pub fn verify( &self, document_json: &serde_json::Value, public_key_bytes: &[u8], ) -> Result<(), DocumentError>; ``` Source line: `106`. # oas-document · relationships URL: https://docs.openagent.id/reference/rust/oas-document/relationships Markdown: https://docs.openagent.id/reference/rust/oas-document/relationships.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/relationships.rs`. SHA-256: `1f1695557c49d5b9ef6d901b860b2b3d27a4d6036ba1b039a349ccdebd4e9b80`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## relationships::Affiliation [#relationshipsaffiliation] A relationship to another OAS entity. # Examples [#examples] ``` use oas_document::relationships::Affiliation; let aff = Affiliation { did: "did:oas:prod:ao:research-team".to_string(), relationship: "member".to_string(), label: Some("Research Team".to_string()), }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Affiliation { /// DID of the related entity. pub did: String, /// Relationship type: `"member"`, `"partner"`, `"subsidiary"`, /// `"affiliate"`, `"delegate"`, `"advisor"`. pub relationship: String, /// Human-readable label for this affiliation. #[serde(skip_serializing_if = "Option::is_none")] pub label: Option } ``` Source line: `26`. ## relationships::RelationshipsSection [#relationshipsrelationshipssection] Relationships and affiliations section of an OAS Identity Document. # Examples [#examples-1] ``` use oas_document::relationships::{RelationshipsSection, Affiliation}; let rels = RelationshipsSection { parent_organization: Some("did:oas:prod:enr:acme-corp".to_string()), affiliations: vec![ Affiliation { did: "did:oas:prod:ao:ai-lab".to_string(), relationship: "member".to_string(), label: Some("AI Research Lab".to_string()), }, ], blocked_dids: vec![], }; assert!(rels.parent_organization.is_some()); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RelationshipsSection { /// DID of the parent organization (ENR or AO). /// Distinct from lineage `creator_did` — this is an organizational /// relationship, not a derivation chain link. #[serde(skip_serializing_if = "Option::is_none")] pub parent_organization: Option, /// Voluntary affiliations (teams, partnerships, memberships). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub affiliations: Vec, /// DIDs that this entity refuses to interact with. /// Stored as public assertions to enable pre-flight checks. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub blocked_dids: Vec } ``` Source line: `61`. ## relationships::relationship\_types [#relationshipsrelationship_types] Standard relationship types. ```rust pub mod relationship_types; ``` Source line: `79`. ## relationships::relationship\_types::MEMBER [#relationshipsrelationship_typesmember] ```rust pub const MEMBER: &str; ``` Source line: `80`. ## relationships::relationship\_types::PARTNER [#relationshipsrelationship_typespartner] ```rust pub const PARTNER: &str; ``` Source line: `81`. ## relationships::relationship\_types::SUBSIDIARY [#relationshipsrelationship_typessubsidiary] ```rust pub const SUBSIDIARY: &str; ``` Source line: `82`. ## relationships::relationship\_types::AFFILIATE [#relationshipsrelationship_typesaffiliate] ```rust pub const AFFILIATE: &str; ``` Source line: `83`. ## relationships::relationship\_types::DELEGATE [#relationshipsrelationship_typesdelegate] ```rust pub const DELEGATE: &str; ``` Source line: `84`. ## relationships::relationship\_types::ADVISOR [#relationshipsrelationship_typesadvisor] ```rust pub const ADVISOR: &str; ``` Source line: `85`. # oas-document · reputation URL: https://docs.openagent.id/reference/rust/oas-document/reputation Markdown: https://docs.openagent.id/reference/rust/oas-document/reputation.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/reputation.rs`. SHA-256: `a4eb12f6b2a4ff47180ef92822356d9383db9b2b419c08e85b89af9bdfac8902`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## reputation::ReputationSection [#reputationreputationsection] Reputation summary section of an OAS Identity Document. # Trust Model [#trust-model] * L0/L1: Self-reported — treat as claims, not facts. * L2: Backed by third-party attestation service, verifiable via `OASAttestationService` endpoint. # Examples [#examples] ``` use oas_document::reputation::ReputationSection; let rep = ReputationSection { total_interactions: Some(15_420), endorsement_count: Some(87), trust_score: Some("0.94".to_string()), uptime_30d: Some("99.7%".to_string()), uptime_90d: Some("99.5%".to_string()), first_active: Some("2026-01-15T00:00:00Z".to_string()), endorser_dids: vec![ "did:oas:prod:hmr:alice".to_string(), "did:oas:prod:enr:acme".to_string(), ], }; assert_eq!(rep.endorsement_count, Some(87)); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReputationSection { /// Total number of interactions/requests served. #[serde(skip_serializing_if = "Option::is_none")] pub total_interactions: Option, /// Number of endorsements received from other DIDs. #[serde(skip_serializing_if = "Option::is_none")] pub endorsement_count: Option, /// Aggregated trust score as a decimal string (0.0–1.0). #[serde(skip_serializing_if = "Option::is_none")] pub trust_score: Option, /// Uptime percentage over the last 30 days. #[serde(skip_serializing_if = "Option::is_none")] pub uptime_30d: Option, /// Uptime percentage over the last 90 days. #[serde(skip_serializing_if = "Option::is_none")] pub uptime_90d: Option, /// ISO 8601 timestamp of when this entity first became active. #[serde(skip_serializing_if = "Option::is_none")] pub first_active: Option, /// DIDs of entities that have endorsed this entity. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub endorser_dids: Vec } ``` Source line: `40`. # oas-document · service URL: https://docs.openagent.id/reference/rust/oas-document/service Markdown: https://docs.openagent.id/reference/rust/oas-document/service.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/service.rs`. SHA-256: `f130b2274ff01d645d8f04f7f31b2b0f4a775c72e9a7c195077c8286c7c616da`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## service::ServiceEndpoint [#serviceserviceendpoint] A service endpoint in an OAS Identity Document. See OAS Specification §5.6 for standard service types. # Examples [#examples] ``` use oas_document::service::ServiceEndpoint; let svc = ServiceEndpoint { id: "did:oas:ns:agent:bot#api".to_string(), service_type: "OASEntity".to_string(), service_endpoint: "https://example.com/bot".to_string(), label: Some("Primary API".to_string()), description: Some("Main agent interaction endpoint".to_string()), properties: None, }; ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ServiceEndpoint { /// The service ID (e.g., `did:oas:ns:agent:bot#service-1`). pub id: String, /// The service type. #[serde(rename = "type")] pub service_type: String, /// The service endpoint URI. pub service_endpoint: String, /// Human-readable label for this service. #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, /// Human-readable description of what this service does. #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, /// Arbitrary key-value properties for this service. /// Useful for protocol-specific metadata (e.g., API version, auth scheme). #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option> } ``` Source line: `28`. ## service::service\_types [#serviceservice_types] Standard service types defined by OAS Specification §5.6. ```rust pub mod service_types; ``` Source line: `54`. ## service::service\_types::OAS\_ENTITY [#serviceservice_typesoas_entity] Primary entity interaction endpoint. ```rust pub const OAS_ENTITY: &str; ``` Source line: `56`. ## service::service\_types::OAS\_COMMUNICATION [#serviceservice_typesoas_communication] Communication / messaging endpoint. ```rust pub const OAS_COMMUNICATION: &str; ``` Source line: `58`. ## service::service\_types::OAS\_LINEAGE\_QUERY [#serviceservice_typesoas_lineage_query] Lineage chain query service. ```rust pub const OAS_LINEAGE_QUERY: &str; ``` Source line: `60`. ## service::service\_types::OAS\_ATTESTATION [#serviceservice_typesoas_attestation] Third-party attestation service. ```rust pub const OAS_ATTESTATION: &str; ``` Source line: `62`. ## service::service\_types::OAS\_REVOCATION\_STATUS [#serviceservice_typesoas_revocation_status] Revocation status check endpoint. ```rust pub const OAS_REVOCATION_STATUS: &str; ``` Source line: `64`. ## service::service\_types::OAS\_CAPABILITY\_INVOCATION [#serviceservice_typesoas_capability_invocation] Capability invocation endpoint. ```rust pub const OAS_CAPABILITY_INVOCATION: &str; ``` Source line: `66`. ## service::service\_types::OAS\_GOVERNANCE [#serviceservice_typesoas_governance] Governance operations endpoint. ```rust pub const OAS_GOVERNANCE: &str; ``` Source line: `68`. ## service::service\_types::OAS\_PRIVATE\_ENDPOINT [#serviceservice_typesoas_private_endpoint] Authenticated endpoint for resolving visibility-restricted fields. Agents query this service with DID-Auth to retrieve fields that are redacted in the public DHT document. ```rust pub const OAS_PRIVATE_ENDPOINT: &str; ``` Source line: `72`. # oas-document · verification_method URL: https://docs.openagent.id/reference/rust/oas-document/verification_method Markdown: https://docs.openagent.id/reference/rust/oas-document/verification_method.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/verification_method.rs`. SHA-256: `453af7775498ea48130015c72defb829d538d8060ed6ccf301b5f4c5f60a4b2d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## verification\_method::VERIFICATION\_METHOD\_TYPE [#verification_methodverification_method_type] The fixed verification method type per OAS Specification §5.1. ```rust pub const VERIFICATION_METHOD_TYPE: &str; ``` Source line: `7`. ## verification\_method::VerificationMethod [#verification_methodverificationmethod] An Ed25519 verification method as defined in OAS Identity Documents. See OAS Specification §5.1 for the complete structure. # Examples [#examples] ``` use oas_document::verification_method::VerificationMethod; let vm = VerificationMethod { id: "did:oas:acme:hmr:alice#key-1".to_string(), method_type: "Ed25519VerificationKey2020".to_string(), controller: "did:oas:acme:hmr:alice".to_string(), public_key_multibase: "z6Mktest123".to_string(), }; assert_eq!(vm.key_id(), "key-1"); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VerificationMethod { /// The full key ID (e.g., `did:oas:acme:hmr:alice#key-1`). pub id: String, /// The verification method type. MUST be `Ed25519VerificationKey2020`. #[serde(rename = "type")] pub method_type: String, /// The DID that controls this key. pub controller: String, /// The public key encoded as multibase base58btc (with `z` prefix). pub public_key_multibase: String } ``` Source line: `28`. ## verification\_method::VerificationMethod::key\_id [#verification_methodverificationmethodkey_id] Extracts the key fragment (the part after `#`) from the ID. # Returns [#returns] The key fragment, or the full ID if no `#` is present. # Examples [#examples-1] ``` use oas_document::verification_method::VerificationMethod; let vm = VerificationMethod { id: "did:oas:ns:hmr:a#key-1".to_string(), method_type: "Ed25519VerificationKey2020".to_string(), controller: "did:oas:ns:hmr:a".to_string(), public_key_multibase: "zTest".to_string(), }; assert_eq!(vm.key_id(), "key-1"); ``` ```rust pub fn key_id(&self) -> &str; ``` Source line: `63`. ## verification\_method::VerificationMethod::new [#verification_methodverificationmethodnew] Creates a new verification method for an OAS entity. # Arguments [#arguments] * `did` - The entity's DID string. * `key_num` - The key number (used to form the fragment, e.g., `key-1`). * `public_key_multibase` - The multibase-encoded public key. ```rust pub fn new(did: &str, key_num: u32, public_key_multibase: &str) -> Self; ``` Source line: `77`. # oas-document · visibility URL: https://docs.openagent.id/reference/rust/oas-document/visibility Markdown: https://docs.openagent.id/reference/rust/oas-document/visibility.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-document/src/visibility.rs`. SHA-256: `d9380fe685f75a2d877377b171f261d8860a59f297a08483543107168c13c059`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## visibility::Visibility [#visibilityvisibility] Visibility level for access-controlled fields. Controls who can read a field's actual value versus seeing only a capability advertisement (e.g., "this agent has a calendar" without revealing the booking URL). # Examples [#examples] ``` use oas_document::visibility::Visibility; let vis = Visibility::Organization; assert_eq!(vis.as_str(), "organization"); assert!(!vis.is_public()); ``` ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Visibility { /// Visible to anyone resolving the DID. Full value stored on DHT. #[default] Public, /// Visible to any agent that can prove identity via DID-Auth. /// DHT stores only a capability flag; actual value served via /// authenticated endpoint. Authenticated, /// Visible only to members of the same Autonomous Organization or /// Entity Name Record (verified via lineage chain). /// DHT stores only a capability flag. Organization, /// Visible only to the entity itself. Never stored on the DHT. Private, } ``` Source line: `40`. ## visibility::Visibility::as\_str [#visibilityvisibilityas_str] Returns the string representation. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `61`. ## visibility::Visibility::is\_public [#visibilityvisibilityis_public] Returns `true` if this field should be fully visible on the public DHT. ```rust pub fn is_public(&self) -> bool; ``` Source line: `71`. ## visibility::Visibility::is\_redacted\_on\_dht [#visibilityvisibilityis_redacted_on_dht] Returns `true` if this field should be redacted (capability flag only) or hidden entirely in the DHT-stored copy. ```rust pub fn is_redacted_on_dht(&self) -> bool; ``` Source line: `77`. # oas-crypto · crate URL: https://docs.openagent.id/reference/rust/oas-crypto/crate Markdown: https://docs.openagent.id/reference/rust/oas-crypto/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/lib.rs`. SHA-256: `d41cbcc68d6f87d9c0f487dfe80b5d398691b07a89fe2861a74728317110faaa`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## derivation [#derivation] # oas-crypto [#oas-crypto] Cryptographic primitives for the Open Agent Specification (OAS). This crate provides the foundational cryptographic operations required by the OAS specification, including Ed25519 key management, HKDF-SHA256 key derivation, BLAKE3 content hashing, JCS canonicalization, and AgentLineageProof2025 generation and verification. ## Crate Architecture [#crate-architecture] * \[`keypair`] — Ed25519 keypair generation, signing, and verification * \[`derivation`] — HKDF-SHA256 child key derivation (OAS Spec §9.3) * \[`proof`] — AgentLineageProof2025 generation and verification (OAS Spec §9.4, §9.5) * \[`hashing`] — BLAKE3 content hashing * \[`jcs`] — JSON Canonicalization Scheme (RFC 8785) * \[`encoding`] — Multibase (base58btc) and base64url encoding ## Security Properties [#security-properties] * All key types implement \[`zeroize::Zeroize`] and \[`zeroize::ZeroizeOnDrop`] * No `unsafe` code (`#![forbid(unsafe_code)]`) * Constant-time signature verification via `ed25519-dalek` * Pure Rust — no C FFI dependencies ## Example [#example] ``` use oas_crypto::keypair::OasKeyPair; use oas_crypto::derivation::derive_child_keypair; use oas_crypto::proof::{AgentLineageProof, LineageProofBinding}; // Generate a parent (HMR) keypair let parent = OasKeyPair::generate(); // Derive a child keypair let child = derive_child_keypair(&parent, "/agent-my-bot").unwrap(); // Generate a lineage proof let child_public_key = child.public_key_multibase(); let proof = AgentLineageProof::generate_bound( &parent, &LineageProofBinding { parent_did: "did:oas:myns:hmr:alice", child_did: "did:oas:myns:agent:my-bot", derivation_path: "/agent-my-bot", verification_method: "did:oas:myns:hmr:alice#key-1", child_verification_method: "did:oas:myns:agent:my-bot#key-1", child_public_key_multibase: &child_public_key, parent_document_digest: "blake3:abababababababababababababababababababababababababababababababab", parent_document_sequence: 1, generation: 1, }, ).unwrap(); // Verification requires a key selected by validated external policy. assert!(proof.verify_with_key(&parent.verifying_key_bytes()).is_ok()); ``` ```rust pub mod derivation; ``` Source line: `60`. ## encoding [#encoding] ```rust pub mod encoding; ``` Source line: `61`. ## error [#error] ```rust pub mod error; ``` Source line: `62`. ## frost [#frost] ```rust #[cfg(feature = "frost")] pub mod frost; ``` Source line: `64`. ## hashing [#hashing] ```rust pub mod hashing; ``` Source line: `65`. ## jcs [#jcs] ```rust pub mod jcs; ``` Source line: `66`. ## keypair [#keypair] ```rust pub mod keypair; ``` Source line: `67`. ## proof [#proof] ```rust pub mod proof; ``` Source line: `68`. ## pub use error::CryptoError; [#pub-use-errorcryptoerror] ```rust pub use error::CryptoError; ``` Source line: `70`. # oas-crypto · derivation URL: https://docs.openagent.id/reference/rust/oas-crypto/derivation Markdown: https://docs.openagent.id/reference/rust/oas-crypto/derivation.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/derivation.rs`. SHA-256: `a0fbf0f5241327fb49081baadd2a77cc308afdff5b6096f9c1f349ac89a67724`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## derivation::derive\_child\_keypair [#derivationderive_child_keypair] Derives a child Ed25519 keypair from a parent keypair using HKDF-SHA256. Implements the key derivation algorithm from OAS Specification §9.3. The derived key material is clamped per RFC 8032 §5.1.5 by `ed25519-dalek` during key construction. # Arguments [#arguments] * `parent` - The parent entity's \[`OasKeyPair`]. * `derivation_path` - The derivation path string (e.g., `"/agent-analyst-42"`). # Returns [#returns] A new \[`OasKeyPair`] for the child entity. # Errors [#errors] Returns \[`CryptoError::DerivationFailed`] if HKDF expansion fails (should not happen with valid 32-byte inputs, but handled defensively). # Examples [#examples] ``` use oas_crypto::derivation::derive_child_keypair; use oas_crypto::keypair::OasKeyPair; let parent = OasKeyPair::generate(); let child = derive_child_keypair(&parent, "/agent-child-1").unwrap(); assert_ne!(parent.verifying_key_bytes(), child.verifying_key_bytes()); ``` ```rust pub fn derive_child_keypair( parent: &OasKeyPair, derivation_path: &str, ) -> Result; ``` Source line: `51`. ## derivation::derive\_key\_material [#derivationderive_key_material] Derives raw 32-byte key material using HKDF-SHA256. This is the lower-level function that performs the actual HKDF computation. Use \[`derive_child_keypair`] for the full keypair derivation workflow. # Arguments [#arguments-1] * `ikm` - Input key material (parent private key, 32 bytes). * `salt` - Salt (parent public key, 32 bytes). * `info` - Info string (derivation path as UTF-8 bytes). # Returns [#returns-1] 32 bytes of derived key material. # Errors [#errors-1] Returns \[`CryptoError::DerivationFailed`] if HKDF fails. # Examples [#examples-1] ``` use oas_crypto::derivation::derive_key_material; let ikm = [0u8; 32]; let salt = [1u8; 32]; let okm = derive_key_material(&ikm, &salt, "/test-path").unwrap(); assert_eq!(okm.len(), 32); ``` ```rust pub fn derive_key_material(ikm: &[u8], salt: &[u8], info: &str) -> Result<[u8; 32], CryptoError>; ``` Source line: `92`. # oas-crypto · encoding URL: https://docs.openagent.id/reference/rust/oas-crypto/encoding Markdown: https://docs.openagent.id/reference/rust/oas-crypto/encoding.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/encoding.rs`. SHA-256: `b10d5dd33a132cb8711b3595e6b0f999666d9c74eb5d27f02637159a7e0d4b52`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## encoding::multibase\_encode [#encodingmultibase_encode] Encodes bytes as multibase base58btc with the `z` prefix. This is the canonical encoding for Ed25519 public keys in OAS Identity Documents and AgentLineageProof2025 structures. # Arguments [#arguments] * `bytes` - The raw bytes to encode. # Returns [#returns] A string with the `z` prefix followed by base58btc-encoded data. # Examples [#examples] ``` use oas_crypto::encoding::multibase_encode; let encoded = multibase_encode(&[1, 2, 3]); assert!(encoded.starts_with('z')); ``` ```rust pub fn multibase_encode(bytes: &[u8]) -> String; ``` Source line: `31`. ## encoding::multibase\_decode [#encodingmultibase_decode] Decodes a multibase base58btc string (with `z` prefix) into raw bytes. # Arguments [#arguments-1] * `encoded` - A multibase-encoded string that MUST start with `z`. # Returns [#returns-1] The decoded raw bytes. # Errors [#errors] Returns \[`CryptoError::MultibaseDecodeFailed`] if: * The string does not start with `z` * The base58btc decoding fails # Examples [#examples-1] ``` use oas_crypto::encoding::{multibase_encode, multibase_decode}; let original = vec![1, 2, 3, 4, 5]; let encoded = multibase_encode(&original); let decoded = multibase_decode(&encoded).unwrap(); assert_eq!(original, decoded); ``` ```rust pub fn multibase_decode(encoded: &str) -> Result, CryptoError>; ``` Source line: `64`. ## encoding::base64url\_encode [#encodingbase64url_encode] Encodes bytes as base64url without padding (RFC 4648 §5). This is the canonical encoding for Ed25519 signatures in OAS. # Arguments [#arguments-2] * `bytes` - The raw bytes to encode. # Returns [#returns-2] A base64url-encoded string without padding. # Examples [#examples-2] ``` use oas_crypto::encoding::base64url_encode; let encoded = base64url_encode(&[1, 2, 3]); assert!(!encoded.contains('=')); ``` ```rust pub fn base64url_encode(bytes: &[u8]) -> String; ``` Source line: `101`. ## encoding::base64url\_decode [#encodingbase64url_decode] Decodes a base64url string (RFC 4648 §5) into raw bytes. Accepts input with or without padding. # Arguments [#arguments-3] * `encoded` - A base64url-encoded string. # Returns [#returns-3] The decoded raw bytes. # Errors [#errors-1] Returns \[`CryptoError::Base64DecodeFailed`] if the input is not valid base64url. # Examples [#examples-3] ``` use oas_crypto::encoding::{base64url_encode, base64url_decode}; let original = vec![10, 20, 30, 40, 50]; let encoded = base64url_encode(&original); let decoded = base64url_decode(&encoded).unwrap(); assert_eq!(original, decoded); ``` ```rust pub fn base64url_decode(encoded: &str) -> Result, CryptoError>; ``` Source line: `133`. # oas-crypto · error URL: https://docs.openagent.id/reference/rust/oas-crypto/error Markdown: https://docs.openagent.id/reference/rust/oas-crypto/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/error.rs`. SHA-256: `cebc0111a9abeddb65aa444ff3796175d34fc2b8263529c8b1f59ba8f44c1a59`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::CryptoError [#errorcryptoerror] Errors arising from OAS cryptographic operations. Every variant includes enough context to diagnose the issue without requiring a stack trace or access to private key material. # Examples [#examples] ``` use oas_crypto::CryptoError; let err = CryptoError::InvalidSignature { context: "lineage proof verification".to_string(), }; assert!(err.to_string().contains("lineage proof verification")); ``` ```rust #[derive(Debug, Error)] pub enum CryptoError { /// Ed25519 signature verification failed. #[error("signature verification failed during {context}")] InvalidSignature { /// What operation was being performed when verification failed. context: String, }, /// The provided key bytes have an invalid length. #[error("invalid key length: expected {expected} bytes, got {actual} bytes")] InvalidKeyLength { /// Expected number of bytes. expected: usize, /// Actual number of bytes provided. actual: usize, }, /// HKDF key derivation failed. #[error("HKDF key derivation failed for path '{derivation_path}': {reason}")] DerivationFailed { /// The derivation path that was being used. derivation_path: String, /// Why the derivation failed. reason: String, }, /// Multibase decoding failed. #[error("multibase decoding failed: {reason}")] MultibaseDecodeFailed { /// Why the decoding failed. reason: String, }, /// Base64url decoding failed. #[error("base64url decoding failed: {reason}")] Base64DecodeFailed { /// Why the decoding failed. reason: String, }, /// JSON canonicalization (JCS) failed. #[error("JCS canonicalization failed: {reason}")] CanonicalizationFailed { /// Why canonicalization failed. reason: String, }, /// The proof payload structure is invalid. #[error("invalid proof payload: {reason}")] InvalidProofPayload { /// Why the payload is invalid. reason: String, }, /// A legacy lineage proof omits bindings required for authorization. #[error( "legacy lineage proof is non-authorizing: {reason}; parse for migration only and issue a fully bound proof" )] LegacyInsecureProof { /// The missing or insecure legacy property. reason: String, }, /// Standalone verification was attempted without an external trust decision. #[error( "lineage proof verification requires a trusted parent key from a validated DID document or explicit verifier policy" )] VerifierTrustRequired, /// The lineage proof type is not supported. #[error("unsupported lineage proof type '{found}'; expected '{expected}'")] UnsupportedProofType { /// Proof type received from the input. found: String, /// Proof type supported by this implementation. expected: &'static str, }, /// The lineage proof algorithm is not supported. #[error("unsupported lineage proof algorithm '{found}'; expected '{expected}'")] UnsupportedProofAlgorithm { /// Algorithm received from the input. found: String, /// Algorithm supported by this implementation. expected: &'static str, }, /// The lineage proof canonicalization profile is not supported. #[error("unsupported lineage proof canonicalization '{found}'; expected '{expected}'")] UnsupportedCanonicalization { /// Canonicalization identifier received from the input. found: String, /// Canonicalization identifier supported by this implementation. expected: &'static str, }, /// The lineage proof purpose is not authorized for lineage delegation. #[error("unsupported lineage proof purpose '{found}'; expected '{expected}'")] UnsupportedProofPurpose { /// Proof purpose received from the input. found: String, /// Proof purpose required by this implementation. expected: &'static str, }, /// The proof's embedded parent key disagrees with the trusted verifier key. #[error("embedded parent key does not match the externally trusted verification key")] EmbeddedKeyMismatch, /// Ed25519 key construction failed. #[error("failed to construct Ed25519 key: {reason}")] KeyConstructionFailed { /// Why key construction failed. reason: String, }, /// FROST threshold key generation failed. /// /// Returned when the trusted dealer key generation process fails, /// typically due to invalid threshold parameters. #[error("FROST key generation failed for {min_signers}-of-{max_signers} threshold: {reason}")] FrostKeyGenFailed { /// The requested minimum number of signers. min_signers: u16, /// The requested total number of participants. max_signers: u16, /// Why key generation failed. reason: String, }, /// FROST signing round failed. /// /// Returned when a participant fails to produce their signature share /// during round 2 of the FROST protocol. #[error("FROST signing failed: {reason}")] FrostSigningFailed { /// Why the signing round failed. reason: String, }, /// FROST signature aggregation failed. /// /// Returned when the coordinator fails to combine individual signature /// shares into a valid group signature. #[error("FROST signature aggregation failed: {reason}")] FrostAggregationFailed { /// Why aggregation failed. reason: String, }, /// FROST group signature verification failed. /// /// Returned when a threshold signature does not verify against /// the group public key. #[error("FROST group signature verification failed: {reason}")] FrostVerificationFailed { /// Why verification failed. reason: String, }, /// Invalid participant selection for FROST signing. /// /// Returned when the provided participant indices are invalid — /// wrong count, out of range, or contain duplicates. #[error("invalid FROST participant selection: {reason}")] FrostInvalidParticipants { /// Why the participant selection is invalid. reason: String, }, /// FROST signature serialization failed. /// /// Returned when a FROST signature or key cannot be serialized to bytes. #[error("FROST serialization failed: {reason}")] FrostSerializationFailed { /// Why serialization failed. reason: String, }, } ``` Source line: `25`. # oas-crypto · frost URL: https://docs.openagent.id/reference/rust/oas-crypto/frost Markdown: https://docs.openagent.id/reference/rust/oas-crypto/frost.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/frost.rs`. SHA-256: `3912035cf53fba877d0f3104766a7316caa0801ccdd8d5361751c0deb3e85d0c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "frost")] ``` ## frost::FrostKeySet [#frostfrostkeyset] A complete FROST threshold key set for a group of participants. Generated via trusted dealer key generation using \[`frost_keygen`]. Contains individual key packages for each participant and the shared group public key package used for signature aggregation and verification. # Security [#security] The key packages contain secret shares that MUST be distributed securely to individual participants. In production, each participant should receive only their own key package. This struct holds all packages together for testing and single-node scenarios. Private key material is redacted in `Debug` output. # Examples [#examples] ``` use oas_crypto::frost::frost_keygen; let key_set = frost_keygen(2, 3).unwrap(); assert_eq!(key_set.min_signers(), 2); assert_eq!(key_set.max_signers(), 3); assert_eq!(key_set.group_public_key().len(), 32); ``` ```rust #[cfg(feature = "frost")] pub struct FrostKeySet { } ``` Source line: `77`. ## frost::FrostKeySet::group\_public\_key [#frostfrostkeysetgroup_public_key] Returns the group verifying (public) key as raw bytes. This key can verify any threshold signature produced by this key set. It is a standard 32-byte Ed25519 public key. # Returns [#returns] 32-byte Ed25519 verifying key for the group. # Panics [#panics] Never panics — serialization of a valid verifying key always succeeds. # Examples [#examples-1] ``` use oas_crypto::frost::frost_keygen; let key_set = frost_keygen(2, 3).unwrap(); assert_eq!(key_set.group_public_key().len(), 32); ``` ```rust #[cfg(feature = "frost")] pub fn group_public_key(&self) -> Vec; ``` Source line: `119`. ## frost::FrostKeySet::min\_signers [#frostfrostkeysetmin_signers] Returns the minimum number of signers required to produce a signature. # Returns [#returns-1] The threshold value `t` from the t-of-n configuration. ```rust #[cfg(feature = "frost")] pub fn min_signers(&self) -> u16; ``` Source line: `133`. ## frost::FrostKeySet::max\_signers [#frostfrostkeysetmax_signers] Returns the total number of participants in the group. # Returns [#returns-2] The total participant count `n` from the t-of-n configuration. ```rust #[cfg(feature = "frost")] pub fn max_signers(&self) -> u16; ``` Source line: `142`. ## frost::FrostKeySet::pubkey\_package [#frostfrostkeysetpubkey_package] Returns a reference to the FROST public key package. Useful for advanced scenarios like manual signature aggregation or interoperability with other FROST implementations. ```rust #[cfg(feature = "frost")] pub fn pubkey_package(&self) -> &frost::keys::PublicKeyPackage; ``` Source line: `150`. ## frost::frost\_keygen [#frostfrost_keygen] Generates a FROST threshold key set using trusted dealer key generation. Creates a t-of-n threshold configuration where any `min_signers` participants out of `max_signers` total can collaboratively sign. The dealer generates all secret shares and distributes them — the dealer must be trusted. # Arguments [#arguments] * `min_signers` - Minimum number of participants required to sign (threshold `t`). Must be >= 2 for threshold security. * `max_signers` - Total number of participants (`n`). Must be >= `min_signers`. # Returns [#returns-3] A \[`FrostKeySet`] containing all participant key packages and the group public key. # Errors [#errors] Returns \[`CryptoError::FrostKeyGenFailed`] if: * `min_signers` \< 2 (single-signer defeats the purpose of threshold) * `max_signers` \< `min_signers` (impossible threshold) * Internal FROST key generation fails # Examples [#examples-2] ``` use oas_crypto::frost::frost_keygen; // 3-of-5 threshold let key_set = frost_keygen(3, 5).unwrap(); assert_eq!(key_set.min_signers(), 3); assert_eq!(key_set.max_signers(), 5); assert_eq!(key_set.group_public_key().len(), 32); // 2-of-2 is the minimum valid threshold let key_set_2 = frost_keygen(2, 2).unwrap(); assert_eq!(key_set_2.min_signers(), 2); ``` ```rust #[cfg(feature = "frost")] pub fn frost_keygen(min_signers: u16, max_signers: u16) -> Result; ``` Source line: `193`. ## frost::frost\_sign [#frostfrost_sign] Performs a complete FROST threshold signing operation. Executes the full two-round FROST signing protocol with the specified participants. The result is a standard 64-byte Ed25519 signature that can be verified by any Ed25519 verifier using the group public key. # Arguments [#arguments-1] * `message` - The message bytes to sign. * `key_set` - The FROST key set generated by \[`frost_keygen`]. * `participant_indices` - Zero-based indices selecting which participants sign. Must contain exactly \[`FrostKeySet::min_signers()`] entries, with no duplicates, and all indices must be \< \[`FrostKeySet::max_signers()`]. # Returns [#returns-4] A 64-byte Ed25519 signature. # Errors [#errors-1] Returns \[`CryptoError::FrostInvalidParticipants`] if: * Number of participants doesn't equal `min_signers` * Any participant index is out of range * Duplicate participant indices are provided Returns \[`CryptoError::FrostSigningFailed`] if a signing round fails. Returns \[`CryptoError::FrostAggregationFailed`] if signature aggregation fails. Returns \[`CryptoError::FrostSerializationFailed`] if the signature cannot be serialized. # Examples [#examples-3] ``` use oas_crypto::frost::{frost_keygen, frost_sign}; let key_set = frost_keygen(2, 3).unwrap(); // Any 2 of the 3 participants can sign let sig_01 = frost_sign(b"hello", &key_set, &[0, 1]).unwrap(); let sig_12 = frost_sign(b"hello", &key_set, &[1, 2]).unwrap(); let sig_02 = frost_sign(b"hello", &key_set, &[0, 2]).unwrap(); assert_eq!(sig_01.len(), 64); assert_eq!(sig_12.len(), 64); assert_eq!(sig_02.len(), 64); ``` ```rust #[cfg(feature = "frost")] pub fn frost_sign( message: &[u8], key_set: &FrostKeySet, participant_indices: &[usize], ) -> Result, CryptoError>; ``` Source line: `298`. ## frost::frost\_verify [#frostfrost_verify] Verifies a FROST threshold signature against a group public key. Since FROST produces standard Ed25519 signatures, this delegates to the same Ed25519 verification used throughout OAS. The group public key is obtained from \[`FrostKeySet::group_public_key`]. # Arguments [#arguments-2] * `message` - The original message that was signed. * `signature_bytes` - The 64-byte Ed25519 signature from \[`frost_sign`]. * `group_public_key` - The 32-byte group verifying key from \[`FrostKeySet::group_public_key`]. # Returns [#returns-5] `Ok(())` if the signature is valid. # Errors [#errors-2] Returns \[`CryptoError::FrostVerificationFailed`] if the signature does not verify against the group public key. Returns \[`CryptoError::InvalidKeyLength`] if key or signature bytes are the wrong length. # Examples [#examples-4] ``` use oas_crypto::frost::{frost_keygen, frost_sign, frost_verify}; let key_set = frost_keygen(2, 3).unwrap(); let sig = frost_sign(b"test", &key_set, &[0, 1]).unwrap(); // Valid verification assert!(frost_verify(b"test", &sig, &key_set.group_public_key()).is_ok()); // Wrong message fails assert!(frost_verify(b"wrong", &sig, &key_set.group_public_key()).is_err()); ``` ```rust #[cfg(feature = "frost")] pub fn frost_verify( message: &[u8], signature_bytes: &[u8], group_public_key: &[u8], ) -> Result<(), CryptoError>; ``` Source line: `441`. # oas-crypto · hashing URL: https://docs.openagent.id/reference/rust/oas-crypto/hashing Markdown: https://docs.openagent.id/reference/rust/oas-crypto/hashing.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/hashing.rs`. SHA-256: `7043e0367e09a7c6b8bf52cfa75671909b2d72f083d906fb04fb6ae538b0e6d4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## hashing::blake3\_hash [#hashingblake3_hash] BLAKE3 content hashing for OAS documents and data. Provides content-addressable hashing used for document integrity checks and content addressing in registries. Computes the BLAKE3 hash of the given data. Returns the 32-byte hash as a fixed-size array. # Arguments [#arguments] * `data` - The bytes to hash. # Returns [#returns] A 32-byte BLAKE3 hash. # Examples [#examples] ``` use oas_crypto::hashing::blake3_hash; let hash = blake3_hash(b"hello world"); assert_eq!(hash.len(), 32); ``` ```rust pub fn blake3_hash(data: &[u8]) -> [u8; 32]; ``` Source line: `27`. ## hashing::blake3\_hash\_hex [#hashingblake3_hash_hex] Computes the BLAKE3 hash and returns it as a hex string. # Arguments [#arguments-1] * `data` - The bytes to hash. # Returns [#returns-1] A 64-character lowercase hex string of the BLAKE3 hash. # Examples [#examples-1] ``` use oas_crypto::hashing::blake3_hash_hex; let hex = blake3_hash_hex(b"hello world"); assert_eq!(hex.len(), 64); ``` ```rust pub fn blake3_hash_hex(data: &[u8]) -> String; ``` Source line: `49`. # oas-crypto modules URL: https://docs.openagent.id/reference/rust/oas-crypto Markdown: https://docs.openagent.id/reference/rust/oas-crypto.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-crypto). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-crypto/crate) — 9 declarations * [derivation](/reference/rust/oas-crypto/derivation) — 2 declarations * [encoding](/reference/rust/oas-crypto/encoding) — 4 declarations * [error](/reference/rust/oas-crypto/error) — 1 declarations * [frost](/reference/rust/oas-crypto/frost) — 8 declarations * [hashing](/reference/rust/oas-crypto/hashing) — 2 declarations * [jcs](/reference/rust/oas-crypto/jcs) — 2 declarations * [keypair](/reference/rust/oas-crypto/keypair) — 11 declarations * [proof](/reference/rust/oas-crypto/proof) — 12 declarations # oas-crypto · jcs URL: https://docs.openagent.id/reference/rust/oas-crypto/jcs Markdown: https://docs.openagent.id/reference/rust/oas-crypto/jcs.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/jcs.rs`. SHA-256: `986712ea5cf59171c3bbecd9190179fa28b95600fc589bbb9c5368fd06f00e35`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## jcs::canonicalize [#jcscanonicalize] Canonicalizes a JSON value using JCS (RFC 8785). Produces a deterministic byte representation where object keys are sorted lexicographically and no insignificant whitespace is present. # Arguments [#arguments] * `value` - A \[`serde_json::Value`] to canonicalize. # Returns [#returns] The canonical JSON bytes. # Errors [#errors] Returns \[`CryptoError::CanonicalizationFailed`] if serialization fails. # Examples [#examples] ``` use oas_crypto::jcs::canonicalize; use serde_json::json; let value = json!({"b": 1, "a": 2}); let canonical = canonicalize(&value).unwrap(); let s = String::from_utf8(canonical).unwrap(); assert_eq!(s, r#"{"a":2,"b":1}"#); ``` ```rust pub fn canonicalize(value: &serde_json::Value) -> Result, CryptoError>; ``` Source line: `38`. ## jcs::canonicalize\_to\_string [#jcscanonicalize_to_string] Canonicalizes a JSON value and returns it as a UTF-8 string. # Arguments [#arguments-1] * `value` - A \[`serde_json::Value`] to canonicalize. # Returns [#returns-1] The canonical JSON as a string. # Errors [#errors-1] Returns \[`CryptoError::CanonicalizationFailed`] if serialization fails. # Examples [#examples-1] ``` use oas_crypto::jcs::canonicalize_to_string; use serde_json::json; let value = json!({"z": "last", "a": "first"}); let s = canonicalize_to_string(&value).unwrap(); assert_eq!(s, r#"{"a":"first","z":"last"}"#); ``` ```rust pub fn canonicalize_to_string(value: &serde_json::Value) -> Result; ``` Source line: `68`. # oas-crypto · keypair URL: https://docs.openagent.id/reference/rust/oas-crypto/keypair Markdown: https://docs.openagent.id/reference/rust/oas-crypto/keypair.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/keypair.rs`. SHA-256: `e48a1d5d5de36a4eeda6ecdd09ec08192fd8d71cd34fd2b7d0a88da97643922b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## keypair::OasKeyPair [#keypairoaskeypair] An Ed25519 keypair for an OAS entity. Holds both the signing (private) and verifying (public) keys. The signing key is zeroized on drop to prevent key material from persisting in memory. # Security [#security] * Private key bytes are never exposed via `Debug` * The signing key implements `ZeroizeOnDrop` * All signature operations use constant-time comparison # Examples [#examples] ``` use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let message = b"hello OAS"; let signature = keypair.sign(message); assert!(OasKeyPair::verify_with_key(&keypair.verifying_key_bytes(), message, &signature).is_ok()); ``` ```rust pub struct OasKeyPair { } ``` Source line: `36`. ## keypair::OasKeyPair::generate [#keypairoaskeypairgenerate] Generates a new random Ed25519 keypair using the OS CSPRNG. # Returns [#returns] A fresh \[`OasKeyPair`] with a cryptographically random signing key. # Examples [#examples-1] ``` use oas_crypto::keypair::OasKeyPair; let kp = OasKeyPair::generate(); assert_eq!(kp.verifying_key_bytes().len(), 32); ``` ```rust pub fn generate() -> Self; ``` Source line: `76`. ## keypair::OasKeyPair::from\_signing\_key\_bytes [#keypairoaskeypairfrom_signing_key_bytes] Constructs an \[`OasKeyPair`] from raw 32-byte signing key material. The verifying key is automatically derived from the signing key. # Arguments [#arguments] * `bytes` - Exactly 32 bytes of Ed25519 signing key material. # Returns [#returns-1] An \[`OasKeyPair`] constructed from the provided key material. # Errors [#errors] Returns \[`CryptoError::InvalidKeyLength`] if `bytes` is not exactly 32 bytes. # Examples [#examples-2] ``` use oas_crypto::keypair::OasKeyPair; let kp1 = OasKeyPair::generate(); let bytes = kp1.signing_key_bytes(); let kp2 = OasKeyPair::from_signing_key_bytes(&bytes).unwrap(); assert_eq!(kp1.verifying_key_bytes(), kp2.verifying_key_bytes()); ``` ```rust pub fn from_signing_key_bytes(bytes: &[u8]) -> Result; ``` Source line: `111`. ## keypair::OasKeyPair::verifying\_key\_from\_bytes [#keypairoaskeypairverifying_key_from_bytes] Constructs a verifying-only reference from raw 32-byte public key bytes. This does NOT create a full keypair — only the public key is available. Use this for signature verification when you don't have the private key. # Arguments [#arguments-1] * `bytes` - Exactly 32 bytes of an Ed25519 verifying (public) key. # Returns [#returns-2] The constructed \[`VerifyingKey`]. # Errors [#errors-1] Returns \[`CryptoError::KeyConstructionFailed`] if the bytes are not a valid Ed25519 point. # Examples [#examples-3] ``` use oas_crypto::keypair::OasKeyPair; let kp = OasKeyPair::generate(); let vk = OasKeyPair::verifying_key_from_bytes(&kp.verifying_key_bytes()).unwrap(); assert_eq!(vk.as_bytes(), &kp.verifying_key_bytes()); ``` ```rust pub fn verifying_key_from_bytes(bytes: &[u8]) -> Result; ``` Source line: `151`. ## keypair::OasKeyPair::sign [#keypairoaskeypairsign] Signs a message with this keypair's signing key. # Arguments [#arguments-2] * `message` - The message bytes to sign. # Returns [#returns-3] A 64-byte Ed25519 signature. # Examples [#examples-4] ``` use oas_crypto::keypair::OasKeyPair; let kp = OasKeyPair::generate(); let sig = kp.sign(b"message"); assert_eq!(sig.len(), 64); ``` ```rust pub fn sign(&self, message: &[u8]) -> Vec; ``` Source line: `181`. ## keypair::OasKeyPair::verify\_with\_key [#keypairoaskeypairverify_with_key] Verifies an Ed25519 signature against a public key. Uses constant-time comparison internally (provided by `ed25519-dalek`). # Arguments [#arguments-3] * `public_key_bytes` - The 32-byte Ed25519 verifying key. * `message` - The original message that was signed. * `signature_bytes` - The 64-byte Ed25519 signature. # Returns [#returns-4] `Ok(())` if the signature is valid. # Errors [#errors-2] Returns \[`CryptoError::InvalidSignature`] if verification fails. Returns \[`CryptoError::InvalidKeyLength`] if key/signature bytes are wrong length. # Examples [#examples-5] ``` use oas_crypto::keypair::OasKeyPair; let kp = OasKeyPair::generate(); let sig = kp.sign(b"test"); assert!(OasKeyPair::verify_with_key(&kp.verifying_key_bytes(), b"test", &sig).is_ok()); assert!(OasKeyPair::verify_with_key(&kp.verifying_key_bytes(), b"wrong", &sig).is_err()); ``` ```rust pub fn verify_with_key( public_key_bytes: &[u8], message: &[u8], signature_bytes: &[u8], ) -> Result<(), CryptoError>; ``` Source line: `214`. ## keypair::OasKeyPair::signing\_key\_bytes [#keypairoaskeypairsigning_key_bytes] Returns the raw 32-byte signing (private) key bytes. # Security [#security-1] Handle with extreme care. Never log, serialize, or transmit this value. The returned array should be zeroized after use. ```rust pub fn signing_key_bytes(&self) -> [u8; 32]; ``` Source line: `240`. ## keypair::OasKeyPair::verifying\_key\_bytes [#keypairoaskeypairverifying_key_bytes] Returns the raw 32-byte verifying (public) key bytes. ```rust pub fn verifying_key_bytes(&self) -> [u8; 32]; ``` Source line: `245`. ## keypair::OasKeyPair::public\_key\_multibase [#keypairoaskeypairpublic_key_multibase] Returns the public key encoded as multibase base58btc (with `z` prefix). This is the canonical format for `publicKeyMultibase` in OAS Identity Documents. # Examples [#examples-6] ``` use oas_crypto::keypair::OasKeyPair; let kp = OasKeyPair::generate(); let mb = kp.public_key_multibase(); assert!(mb.starts_with('z')); ``` ```rust pub fn public_key_multibase(&self) -> String; ``` Source line: `261`. ## keypair::OasKeyPair::signing\_key [#keypairoaskeypairsigning_key] Returns a reference to the inner `ed25519-dalek` \[`SigningKey`]. ```rust pub fn signing_key(&self) -> &SigningKey; ``` Source line: `266`. ## keypair::OasKeyPair::verifying\_key [#keypairoaskeypairverifying_key] Returns a reference to the inner `ed25519-dalek` \[`VerifyingKey`]. ```rust pub fn verifying_key(&self) -> &VerifyingKey; ``` Source line: `271`. # oas-crypto · proof URL: https://docs.openagent.id/reference/rust/oas-crypto/proof Markdown: https://docs.openagent.id/reference/rust/oas-crypto/proof.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-crypto/src/proof.rs`. SHA-256: `bbcf0d5c349f02b368d9f599469e1312b3b9343941aae04f1def95045af08434`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## proof::PROOF\_TYPE [#proofproof_type] The fixed proof type identifier per OAS Specification §9.1. ```rust pub const PROOF_TYPE: &str; ``` Source line: `19`. ## proof::PROOF\_ALGORITHM [#proofproof_algorithm] The fixed algorithm identifier per OAS Specification §9.2. ```rust pub const PROOF_ALGORITHM: &str; ``` Source line: `22`. ## proof::PROOF\_CANONICALIZATION [#proofproof_canonicalization] The only canonicalization profile accepted for authorizing lineage proofs. ```rust pub const PROOF_CANONICALIZATION: &str; ``` Source line: `25`. ## proof::PROOF\_PURPOSE [#proofproof_purpose] The verification relationship required for lineage authorization. ```rust pub const PROOF_PURPOSE: &str; ``` Source line: `28`. ## proof::LineageProofBinding [#prooflineageproofbinding] Security bindings required when issuing an authorizing lineage proof. The proof signs every field in this structure as well as the proof type, algorithm, canonicalization profile, proof purpose, and parent public key. ```rust #[derive(Debug, Clone, Copy)] pub struct LineageProofBinding<'a> { /// DID of the parent authorizing the child. pub parent_did: &'a str, /// DID of the child receiving authorization. pub child_did: &'a str, /// Stable derivation or authorization path. pub derivation_path: &'a str, /// Parent verification method authorized for capability delegation. pub verification_method: &'a str, /// Child verification method committed by the parent. pub child_verification_method: &'a str, /// Child public key committed by the parent. pub child_public_key_multibase: &'a str, /// BLAKE3 digest of the complete authenticated parent DID document. pub parent_document_digest: &'a str, /// Monotonic sequence of the authenticated parent DID document. pub parent_document_sequence: u64, /// Child position in the complete root-to-child chain. pub generation: u32 } ``` Source line: `35`. ## proof::AgentLineageProof [#proofagentlineageproof] An AgentLineageProof2025 linking a child entity to its parent. This proof establishes cryptographic accountability by demonstrating that the parent entity authorized the creation of the child entity. See OAS Specification §9 for the complete proof format. # Examples [#examples] ``` use oas_crypto::proof::{AgentLineageProof, LineageProofBinding}; use oas_crypto::keypair::OasKeyPair; let parent = OasKeyPair::generate(); let child = OasKeyPair::generate(); let proof = AgentLineageProof::generate_bound( &parent, &LineageProofBinding { parent_did: "did:oas:test:hmr:parent", child_did: "did:oas:test:agent:child", derivation_path: "/agent-child", verification_method: "did:oas:test:hmr:parent#key-1", child_verification_method: "did:oas:test:agent:child#key-1", child_public_key_multibase: &child.public_key_multibase(), parent_document_digest: "blake3:abababababababababababababababababababababababababababababababab", parent_document_sequence: 1, generation: 1, }, ).unwrap(); assert!(proof.verify_with_key(&parent.verifying_key_bytes()).is_ok()); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AgentLineageProof { /// Fixed: `"AgentLineageProof2025"` #[serde(rename = "type")] pub proof_type: String, /// DID of the parent entity. pub parent_did: String, /// DID of the child entity. pub child_did: String, /// The HKDF info parameter used for key derivation (e.g., `"/agent-child"`). pub derivation_path: String, /// Fixed: `"HKDF-SHA256-Ed25519"` pub algorithm: String, /// Parent's public key, multibase-encoded (base58btc with `z` prefix). pub public_key_multibase: String, /// Parent verification method selected from the authenticated parent document. #[serde(default, skip_serializing_if = "Option::is_none")] pub verification_method: Option, /// Verification relationship authorizing the parent key for lineage. #[serde(default, skip_serializing_if = "Option::is_none")] pub proof_purpose: Option, /// Canonicalization profile used to construct the signed payload. #[serde(default, skip_serializing_if = "Option::is_none")] pub canonicalization: Option, /// Child verification method committed by the parent. #[serde(default, skip_serializing_if = "Option::is_none")] pub child_verification_method: Option, /// Child public key committed by the parent. #[serde(default, skip_serializing_if = "Option::is_none")] pub child_public_key_multibase: Option, /// Digest of the authenticated parent document used for issuance. #[serde(default, skip_serializing_if = "Option::is_none")] pub parent_document_digest: Option, /// Sequence of the authenticated parent document used for issuance. #[serde(default, skip_serializing_if = "Option::is_none")] pub parent_document_sequence: Option, /// Position of the child in the complete lineage chain. #[serde(default, skip_serializing_if = "Option::is_none")] pub generation: Option, /// Ed25519 signature by the parent key over the canonical proof payload, /// encoded as base64url. pub signature: String } ``` Source line: `90`. ## proof::AgentLineageProof::generate [#proofagentlineageproofgenerate] Generates a legacy, non-authorizing AgentLineageProof2025. Implements OAS Specification §9.4: 1. Construct the canonical proof payload via JCS 2. Sign the payload with the parent's Ed25519 signing key 3. Encode the signature as base64url # Arguments [#arguments] * `parent_keypair` - The parent entity's keypair (used for signing). * `parent_did` - The parent entity's DID string. * `child_did` - The child entity's DID string. * `derivation_path` - The HKDF derivation path. # Returns [#returns] A parseable migration proof that strict verification rejects with \[`CryptoError::LegacyInsecureProof`]. # Errors [#errors] Returns \[`CryptoError::CanonicalizationFailed`] if JCS canonicalization fails. # Examples [#examples-1] ``` use oas_crypto::proof::AgentLineageProof; use oas_crypto::keypair::OasKeyPair; let parent = OasKeyPair::generate(); let proof = AgentLineageProof::generate( &parent, "did:oas:ns:hmr:alice", "did:oas:ns:agent:bot", "/agent-bot", ).unwrap(); assert_eq!(proof.proof_type, "AgentLineageProof2025"); assert!(matches!( proof.verify(), Err(oas_crypto::CryptoError::LegacyInsecureProof { .. }) )); ``` ```rust pub fn generate( parent_keypair: &OasKeyPair, parent_did: &str, child_did: &str, derivation_path: &str, ) -> Result; ``` Source line: `190`. ## proof::AgentLineageProof::generate\_bound [#proofagentlineageproofgenerate_bound] Generates a fully bound authorizing lineage proof. The signature commits to both DIDs, both verification methods and public keys, the authenticated parent document state, suite and proof purpose, canonicalization profile, path, and chain position. # Arguments [#arguments-1] * `parent_keypair` - Parent signing key authorized by the parent document. * `binding` - Security-relevant fields committed by the signature. # Returns [#returns-1] A fully bound \[`AgentLineageProof`]. # Errors [#errors-1] Returns \[`CryptoError::InvalidProofPayload`] for malformed fields or a canonicalization error if JCS encoding fails. ```rust pub fn generate_bound( parent_keypair: &OasKeyPair, binding: &LineageProofBinding<'_>, ) -> Result; ``` Source line: `237`. ## proof::AgentLineageProof::verify [#proofagentlineageproofverify] Rejects standalone verification without an external trust decision. # Returns [#returns-2] This method never returns `Ok(())`. Authorizing verification requires \[`Self::verify_with_key`] with a key obtained from a validated parent DID document or explicit verifier trust policy. # Errors [#errors-2] Returns \[`CryptoError::LegacyInsecureProof`] for an unbound legacy proof, or \[`CryptoError::VerifierTrustRequired`] for a fully bound proof. ```rust pub fn verify(&self) -> Result<(), CryptoError>; ``` Source line: `277`. ## proof::AgentLineageProof::verify\_with\_key [#proofagentlineageproofverify_with_key] Verifies this proof against a specific public key (not the embedded one). Use this when you have already resolved the parent document and want to verify the proof against the known parent public key. # Arguments [#arguments-2] * `parent_public_key_bytes` - The 32-byte Ed25519 public key of the parent. # Returns [#returns-3] `Ok(())` if the proof is valid against the provided key. # Errors [#errors-3] Returns an error if the proof is legacy, its suite or bindings are unsupported, the embedded parent key disagrees with the trusted key, or signature verification fails. ```rust pub fn verify_with_key(&self, parent_public_key_bytes: &[u8]) -> Result<(), CryptoError>; ``` Source line: `300`. ## proof::AgentLineageProof::validate\_security\_profile [#proofagentlineageproofvalidate_security_profile] Validates mandatory authorizing fields and fixed suite values. # Errors [#errors-4] Returns a typed profile, suite, purpose, key encoding, or legacy error. ```rust pub fn validate_security_profile(&self) -> Result<(), CryptoError>; ``` Source line: `326`. ## proof::canonical\_proof\_payload [#proofcanonical_proof_payload] Constructs deterministic RFC 8785 bytes for a fully bound proof. Every representable security-relevant field except the signature itself is included. Legacy proofs therefore cannot produce authorizing canonical bytes through this function. # Arguments [#arguments-3] * `proof` - Fully bound proof whose signature payload is required. # Returns [#returns-4] Deterministic JCS UTF-8 bytes. # Errors [#errors-5] Returns a typed profile or canonicalization error. ```rust pub fn canonical_proof_payload(proof: &AgentLineageProof) -> Result, CryptoError>; ``` Source line: `413`. # oas-lineage · config URL: https://docs.openagent.id/reference/rust/oas-lineage/config Markdown: https://docs.openagent.id/reference/rust/oas-lineage/config.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-lineage/src/config.rs`. SHA-256: `0e27fd221acf46d7e641769308ca22fc9b2863914e9bfc81b9f6010168eb6044`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::TrustAnchor [#configtrustanchor] A verifier-controlled trust anchor for an OAS root document. Trust anchors are local policy inputs. They are never inferred from the document or proof being verified. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TrustAnchor { /// Root DID authorized by this anchor. pub did: String, /// Authorized verification method on the root document. pub verification_method: String, /// Authorized Ed25519 public key in multibase format. pub public_key_multibase: String, /// Optional commitment to the exact trusted root document state. pub document_digest: Option } ``` Source line: `17`. ## config::TrustAnchor::new [#configtrustanchornew] Creates a key-pinned trust anchor. ```rust pub fn new( did: impl Into, verification_method: impl Into, public_key_multibase: impl Into, ) -> Self; ``` Source line: `30`. ## config::TrustAnchor::with\_document\_digest [#configtrustanchorwith_document_digest] Pins this anchor to an exact canonical root document digest. ```rust #[must_use] pub fn with_document_digest(mut self, digest: impl Into) -> Self; ``` Source line: `45`. ## config::VerifyConfig [#configverifyconfig] Configuration for the lineage verification algorithm. All values have sensible defaults from the OAS Specification §8.3. # Examples [#examples] ``` use oas_lineage::config::VerifyConfig; // Use defaults from the specification let config = VerifyConfig::default(); assert_eq!(config.max_generation, 16); // Or customize let config = VerifyConfig::new() .with_max_generation(8) .with_total_timeout(std::time::Duration::from_secs(15)); assert_eq!(config.max_generation, 8); ``` ```rust #[derive(Debug, Clone)] pub struct VerifyConfig { /// Maximum generation depth allowed. /// /// Per OAS Spec §8.3 rule 6: RECOMMENDED default is 16. /// Entities exceeding this depth MAY be rejected. pub max_generation: u32, /// Per-hop resolution timeout. /// /// Per OAS Spec §8.3 rule 7: RECOMMENDED 5 seconds. /// Applied to each parent document resolution individually. pub per_hop_timeout: Duration, /// Total timeout for the entire chain verification. /// /// Per OAS Spec §8.3 rule 7: RECOMMENDED 30 seconds. /// If the total elapsed time exceeds this, verification /// reports `unverifiable` (not `invalid`). pub total_timeout: Duration, /// Whether to verify document signatures for each parent. /// /// Defaults to `true`. Set to `false` only when parent documents /// have already been verified by the resolver. pub verify_document_signatures: bool, /// Verifier-controlled root trust anchors. pub trust_anchors: Vec } ``` Source line: `71`. ## config::VerifyConfig::new [#configverifyconfignew] Creates a new `VerifyConfig` with default values. Equivalent to \[`VerifyConfig::default()`]. ```rust pub fn new() -> Self; ``` Source line: `123`. ## config::VerifyConfig::with\_max\_generation [#configverifyconfigwith_max_generation] Sets the maximum generation depth. # Arguments [#arguments] * `depth` - Maximum number of derivation steps from human root. ```rust pub fn with_max_generation(mut self, depth: u32) -> Self; ``` Source line: `132`. ## config::VerifyConfig::with\_per\_hop\_timeout [#configverifyconfigwith_per_hop_timeout] Sets the per-hop resolution timeout. # Arguments [#arguments-1] * `timeout` - Duration to wait for each parent resolution. ```rust pub fn with_per_hop_timeout(mut self, timeout: Duration) -> Self; ``` Source line: `142`. ## config::VerifyConfig::with\_total\_timeout [#configverifyconfigwith_total_timeout] Sets the total verification timeout. # Arguments [#arguments-2] * `timeout` - Maximum duration for the entire chain verification. ```rust pub fn with_total_timeout(mut self, timeout: Duration) -> Self; ``` Source line: `152`. ## config::VerifyConfig::with\_verify\_signatures [#configverifyconfigwith_verify_signatures] Sets whether to verify document signatures at each hop. # Arguments [#arguments-3] * `verify` - `true` to verify signatures (default), `false` to skip. ```rust pub fn with_verify_signatures(mut self, verify: bool) -> Self; ``` Source line: `162`. ## config::VerifyConfig::with\_trust\_anchor [#configverifyconfigwith_trust_anchor] Adds a verifier-controlled root trust anchor. ```rust #[must_use] pub fn with_trust_anchor(mut self, anchor: TrustAnchor) -> Self; ``` Source line: `169`. # oas-lineage · crate URL: https://docs.openagent.id/reference/rust/oas-lineage/crate Markdown: https://docs.openagent.id/reference/rust/oas-lineage/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-lineage/src/lib.rs`. SHA-256: `b334f1b452eb9c64f265f349c4a530fa82ee13b20bb2827ca7476fc7e3e07177`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config [#config] # oas-lineage [#oas-lineage] Agent lineage verification for the Open Agent Specification (OAS). This crate implements the lineage verification algorithm from OAS Specification §8 and Appendix C, including full cryptographic chain walking, structural validation, and child entity derivation. ## Key Types [#key-types] * [`verify_lineage`](verify::verify_lineage) — Full cryptographic chain verification * [`derive_child_entity`](derive::derive_child_entity) — Create child entities with lineage * [`DocumentProvider`](provider::DocumentProvider) — Trait for document resolution * [`InMemoryProvider`](provider::InMemoryProvider) — In-memory provider for testing * [`VerifyConfig`](config::VerifyConfig) — Verification configuration * [`VerifyResult`](verify::VerifyResult) — Verification result with warnings ## Example: Verify a lineage chain [#example-verify-a-lineage-chain] ``` use oas_lineage::verify::verify_lineage; use oas_lineage::config::{TrustAnchor, VerifyConfig}; use oas_lineage::provider::InMemoryProvider; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; // Root entities require an explicit verifier-controlled trust anchor. let keypair = OasKeyPair::generate(); let root = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L1) .add_verification_method(&keypair) .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); let provider = InMemoryProvider::new(); let anchor = TrustAnchor::new( &root.id, format!("{}#key-1", root.id), keypair.public_key_multibase(), ).with_document_digest(root.canonical_digest().unwrap()); let config = VerifyConfig::new().with_trust_anchor(anchor); let result = verify_lineage(&root, &provider, &config).unwrap(); assert_eq!(result.chain_length, 1); ``` ## Example: Derive a child entity [#example-derive-a-child-entity] ``` use oas_lineage::derive::derive_child_entity; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; let root_keypair = OasKeyPair::generate(); let root_doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L1) .add_verification_method(&root_keypair) .build_and_sign(&root_keypair, "2026-01-15T00:00:00Z") .unwrap(); let child = derive_child_entity( &root_keypair, &root_doc, "did:oas:test:agent:bot", "/agent-bot", ).unwrap(); assert_eq!(child.lineage.generation, 1); assert_eq!(child.lineage.human_root_did, "did:oas:test:hmr:alice"); ``` ```rust pub mod config; ``` Source line: `73`. ## derive [#derive] ```rust pub mod derive; ``` Source line: `74`. ## error [#error] ```rust pub mod error; ``` Source line: `75`. ## provider [#provider] ```rust pub mod provider; ``` Source line: `76`. ## verify [#verify] ```rust pub mod verify; ``` Source line: `77`. ## pub use error::LineageError; [#pub-use-errorlineageerror] ```rust pub use error::LineageError; ``` Source line: `79`. # oas-lineage · derive URL: https://docs.openagent.id/reference/rust/oas-lineage/derive Markdown: https://docs.openagent.id/reference/rust/oas-lineage/derive.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-lineage/src/derive.rs`. SHA-256: `e61d3a231537dc09a8c22676cfd438afe2420195531b1246f80e567becd443db`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## derive::DerivedChild [#derivederivedchild] The result of deriving a child entity. Contains the child's Ed25519 keypair and a complete \[`LineageSection`] ready to be included in the child's identity document. # Examples [#examples] ``` use oas_lineage::derive::DerivedChild; // DerivedChild is returned by derive_child_entity() // It contains the child keypair and lineage section. ``` ```rust #[derive(Debug)] pub struct DerivedChild { /// The derived Ed25519 keypair for the child entity. pub keypair: OasKeyPair, /// The lineage section to include in the child's identity document. pub lineage: LineageSection } ``` Source line: `31`. ## derive::derive\_child\_entity [#derivederive_child_entity] Derives a new child entity from a parent, producing a keypair and lineage. Performs the complete child entity derivation workflow per OAS Spec §9: 1. Derives a child Ed25519 keypair using HKDF-SHA256 (§9.3). 2. Generates an AgentLineageProof2025 (§9.4). 3. Constructs a complete \[`LineageSection`] with the correct `humanRootDid`, `creatorDid`, `generation`, and `humanRootChain`. # Arguments [#arguments] * `parent_keypair` - The parent entity's keypair (used for signing the proof and as HKDF input for key derivation). * `parent_doc` - The parent entity's identity document (used to extract the parent's DID and lineage information). * `child_did` - The DID for the new child entity. * `derivation_path` - The HKDF derivation path (e.g., `"/agent-bot-42"`). # Returns [#returns] A \[`DerivedChild`] containing the derived keypair and lineage section. # Errors [#errors] Returns \[`LineageError`] if: * The parent is a non-root entity without lineage (\[`LineageError::MissingLineage`]). * Key derivation fails (\[`LineageError::Crypto`]). * Proof generation fails (\[`LineageError::Crypto`]). # Examples [#examples-1] ``` use oas_lineage::derive::derive_child_entity; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; let root_keypair = OasKeyPair::generate(); let root_doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L1) .add_verification_method(&root_keypair) .build_and_sign(&root_keypair, "2026-01-15T00:00:00Z") .unwrap(); let child = derive_child_entity( &root_keypair, &root_doc, "did:oas:test:agent:bot", "/agent-bot", ).unwrap(); assert_eq!(child.lineage.human_root_did, "did:oas:test:hmr:alice"); assert_eq!(child.lineage.generation, 1); ``` ```rust pub fn derive_child_entity( parent_keypair: &OasKeyPair, parent_doc: &OasDocument, child_did: &str, derivation_path: &str, ) -> Result; ``` Source line: `94`. # oas-lineage · error URL: https://docs.openagent.id/reference/rust/oas-lineage/error Markdown: https://docs.openagent.id/reference/rust/oas-lineage/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-lineage/src/error.rs`. SHA-256: `8a965b2b82baa8cd43ce1599aafeb2dcb9bf6367f4698d2fa3c6d018ba0c8025`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::LineageError [#errorlineageerror] Errors that can occur during lineage verification and chain operations. Each variant contains enough context to diagnose the problem, including DIDs, generation depths, and specific reasons for failure. See OAS Specification §8 and Appendix C for the verification algorithm. ```rust #[derive(Debug, Error)] pub enum LineageError { /// A non-root entity is missing its required lineage section. /// /// Per OAS Spec §8.3 rule 1, every non-root entity MUST have lineage. #[error("non-root entity missing required lineage section (DID: {did})")] MissingLineage { /// The DID of the entity missing lineage. did: String, }, /// The `humanRootChain` array is empty. #[error("human root chain is empty for entity {did}")] EmptyChain { /// The DID of the entity with an empty chain. did: String, }, /// The lineage chain does not terminate at an HMR, MHR, or ENR entity. /// /// Per OAS Spec §8.3 rule 2. #[error("chain does not terminate at human root: last DID is '{last_did}'; expected kind 'hmr', 'mhr', or 'enr'")] ChainNotTerminatingAtRoot { /// The last DID in the chain (which should be an HMR, MHR, or ENR). last_did: String, }, /// The generation field does not match `humanRootChain.len() - 1`. /// /// Per OAS Spec §8.3 rule 3. #[error("generation {generation} does not match chain length minus one ({expected})")] GenerationMismatch { /// The declared generation value. generation: u32, /// The expected value (`humanRootChain.len() - 1`). expected: usize, }, /// The lineage chain exceeds the configured maximum generation depth. /// /// Per OAS Spec §8.3 rule 6. #[error("generation depth {depth} exceeds maximum allowed depth {max_depth}")] ChainTooDeep { /// The actual generation depth. depth: u32, /// The configured maximum. max_depth: u32, }, /// A parent document could not be resolved during chain verification. /// /// Per OAS Spec Appendix C, step 6. #[error("cannot resolve parent document '{parent_did}': {reason}")] ResolutionFailed { /// The parent DID that failed to resolve. parent_did: String, /// The reason resolution failed. reason: String, }, /// A parent entity in the chain has been revoked. /// /// Per OAS Spec §8.3 rule 5 (revocation cascades). #[error("parent entity is revoked: {parent_did}")] ParentRevoked { /// The revoked parent DID. parent_did: String, }, /// A parent document's signature is invalid. #[error("parent document signature invalid for '{parent_did}': {reason}")] ParentSignatureInvalid { /// The parent DID with the invalid signature. parent_did: String, /// Details of the signature failure. reason: String, }, /// The terminal root is not authorized by verifier-controlled policy. #[error("root '{root_did}' is not trusted by verifier policy: {reason}")] UntrustedRoot { /// The untrusted root DID. root_did: String, /// Details of the trust-anchor failure. reason: String, }, /// A document is revoked. #[error("document is revoked: {did}")] DocumentRevoked { /// DID of the revoked document. did: String, }, /// A document is outside its configured validity window. #[error("document is not currently valid: {did}")] DocumentInactive { /// DID of the inactive document. did: String, }, /// The derivation proof type is not `AgentLineageProof2025`. #[error("unknown proof type '{found}'; expected 'AgentLineageProof2025'")] UnknownProofType { /// The unexpected proof type. found: String, }, /// The proof's `parentDid` does not match the expected parent in the chain. #[error("proof parent DID mismatch: proof contains '{proof_parent}' but chain expects '{chain_parent}'")] ProofParentMismatch { /// The parentDid from the proof. proof_parent: String, /// The expected parent from the chain. chain_parent: String, }, /// The proof's `childDid` does not match the expected child in the chain. #[error("proof child DID mismatch: proof contains '{proof_child}' but chain expects '{chain_child}'")] ProofChildMismatch { /// The childDid from the proof. proof_child: String, /// The expected child from the chain. chain_child: String, }, /// The Ed25519 signature on a lineage proof is invalid. #[error("lineage proof signature invalid at generation {generation}: {reason}")] ProofSignatureInvalid { /// The generation index where verification failed. generation: usize, /// Details of the signature failure. reason: String, }, /// A legacy proof omits mandatory signed security bindings. #[error("legacy lineage proof is non-authorizing: {reason}")] LegacyInsecureProof { /// The missing or insecure legacy binding. reason: String, }, /// The proof algorithm is not supported by the strict verifier. #[error("unsupported lineage proof algorithm '{found}'")] UnsupportedProofAlgorithm { /// The unsupported algorithm. found: String, }, /// The canonicalization profile is not supported by the strict verifier. #[error("unsupported lineage canonicalization profile '{found}'")] UnsupportedCanonicalization { /// The unsupported canonicalization profile. found: String, }, /// The proof purpose is not supported by the strict verifier. #[error("unsupported lineage proof purpose '{found}'")] UnsupportedProofPurpose { /// The unsupported proof purpose. found: String, }, /// A lineage proof key is not the referenced authorized parent key. #[error( "lineage proof key does not match parent document '{parent_did}' method '{verification_method}'" )] ParentKeyMismatch { /// The parent DID. parent_did: String, /// Verification method referenced by the proof. verification_method: String, }, /// A lineage proof does not bind the child's verification key. #[error( "lineage proof child key does not match child document '{child_did}' method '{verification_method}'" )] ChildKeyMismatch { /// The child DID. child_did: String, /// Verification method referenced by the proof. verification_method: String, }, /// A lineage proof does not bind the resolved parent document state. #[error("lineage proof parent document binding mismatch for '{parent_did}': {reason}")] ParentDocumentMismatch { /// The parent DID. parent_did: String, /// Details of the mismatch. reason: String, }, /// A verification method is not authorized for lineage delegation. #[error( "verification method '{verification_method}' is not authorized for lineage delegation by '{parent_did}'" )] InvalidKeyPurpose { /// The parent DID. parent_did: String, /// Verification method lacking the required relationship. verification_method: String, }, /// The declared lineage contains a repeated DID. #[error("lineage chain contains a cycle at '{did}'")] ChainCycle { /// The repeated DID. did: String, }, /// Resolved lineage metadata does not continue the declared chain. #[error("lineage chain continuity failed at '{did}': {reason}")] ChainContinuity { /// DID at which continuity failed. did: String, /// Details of the discontinuity. reason: String, }, /// The total timeout for lineage verification was exceeded. /// /// Per OAS Spec §8.3 rule 7. #[error("lineage verification total timeout exceeded after {elapsed_secs:.1}s (limit: {limit_secs}s)")] TotalTimeout { /// Elapsed time in seconds. elapsed_secs: f64, /// Configured limit in seconds. limit_secs: f64, }, /// A non-root entity's lineage section is missing its derivation proof. #[error("derivation proof is missing for entity '{did}'")] MissingDerivationProof { /// The DID of the entity without a proof. did: String, }, /// The parent's public key referenced by the proof was not found in /// the parent's verification methods. #[error("parent public key not found in parent document '{parent_did}'")] ParentKeyNotFound { /// The parent DID. parent_did: String, }, /// An underlying cryptographic error occurred. #[error("cryptographic error: {0}")] Crypto(#[from] oas_crypto::CryptoError), } ``` Source line: `16`. # oas-lineage modules URL: https://docs.openagent.id/reference/rust/oas-lineage Markdown: https://docs.openagent.id/reference/rust/oas-lineage.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-lineage). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-lineage/crate) — 6 declarations * [config](/reference/rust/oas-lineage/config) — 10 declarations * [derive](/reference/rust/oas-lineage/derive) — 2 declarations * [error](/reference/rust/oas-lineage/error) — 1 declarations * [provider](/reference/rust/oas-lineage/provider) — 6 declarations * [verify](/reference/rust/oas-lineage/verify) — 3 declarations # oas-lineage · provider URL: https://docs.openagent.id/reference/rust/oas-lineage/provider Markdown: https://docs.openagent.id/reference/rust/oas-lineage/provider.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-lineage/src/provider.rs`. SHA-256: `c2b7bc7746cab041982221c20a525f6718b4728f1dfd142041c8fc51d0c81678`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## provider::DocumentProvider [#providerdocumentprovider] A provider that resolves `did:oas` identifiers to \[`OasDocument`]s. This trait is the bridge between lineage verification and document resolution. The verification algorithm calls `resolve()` for each parent in the lineage chain. # Implementation Notes [#implementation-notes] * Implementations SHOULD enforce per-hop timeouts internally. * Implementations SHOULD cache resolved documents to avoid redundant lookups. * Implementations MUST return the most recent valid document for a DID. # Examples [#examples] ``` use oas_lineage::provider::{DocumentProvider, InMemoryProvider}; use oas_document::OasDocument; let provider = InMemoryProvider::new(); // Empty provider returns an error for any DID assert!(provider.resolve("did:oas:test:hmr:alice").is_err()); ``` ```rust pub trait DocumentProvider { /// Resolves a `did:oas` identifier to its identity document. /// /// # Arguments /// /// * `did` - The `did:oas` identifier to resolve. /// /// # Returns /// /// The resolved [`OasDocument`], or a [`LineageError::ResolutionFailed`] /// if the document cannot be found or resolution fails. /// /// # Errors /// /// Returns [`LineageError::ResolutionFailed`] if the DID cannot be resolved. fn resolve(&self, did: &str) -> Result; } ``` Source line: `38`. ## provider::InMemoryProvider [#providerinmemoryprovider] An in-memory document provider for testing and development. Stores documents in a \[`HashMap`] keyed by DID string. Useful for unit tests that need to verify lineage chains without network access. # Examples [#examples-1] ``` use oas_lineage::provider::InMemoryProvider; use oas_lineage::provider::DocumentProvider; let mut provider = InMemoryProvider::new(); // Register documents, then use for lineage verification assert_eq!(provider.len(), 0); ``` ```rust #[derive(Debug, Clone, Default)] pub struct InMemoryProvider { } ``` Source line: `73`. ## provider::InMemoryProvider::new [#providerinmemoryprovidernew] Creates an empty in-memory provider. ```rust pub fn new() -> Self; ``` Source line: `79`. ## provider::InMemoryProvider::register [#providerinmemoryproviderregister] Registers a document in the provider. The document is stored under its `id` field. # Arguments [#arguments] * `doc` - The document to register. ```rust pub fn register(&mut self, doc: OasDocument); ``` Source line: `92`. ## provider::InMemoryProvider::len [#providerinmemoryproviderlen] Returns the number of registered documents. ```rust pub fn len(&self) -> usize; ``` Source line: `97`. ## provider::InMemoryProvider::is\_empty [#providerinmemoryprovideris_empty] Returns true if no documents are registered. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `102`. # oas-lineage · verify URL: https://docs.openagent.id/reference/rust/oas-lineage/verify Markdown: https://docs.openagent.id/reference/rust/oas-lineage/verify.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-lineage/src/verify.rs`. SHA-256: `fbe78af078f918131bde6fc1b752e4e451afd41b832f518fb5ac9c8d2b819b26`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## verify::VerifyResult [#verifyverifyresult] The result of a successful lineage verification. Contains metadata about the verification process and any warnings that were encountered (e.g., expired liveness attestations). # Examples [#examples] ``` use oas_lineage::verify::VerifyResult; let result = VerifyResult { chain_length: 3, human_root_did: "did:oas:test:hmr:alice".to_string(), warnings: vec![], }; assert!(result.is_clean()); ``` ```rust #[derive(Debug, Clone)] pub struct VerifyResult { /// The total length of the verified chain (including the entity itself). pub chain_length: usize, /// The DID of the human root at the end of the chain. pub human_root_did: String, /// Non-fatal warnings encountered during verification. /// /// Examples: expired liveness attestations. pub warnings: Vec } ``` Source line: `49`. ## verify::VerifyResult::is\_clean [#verifyverifyresultis_clean] Returns `true` if no warnings were raised. ```rust pub fn is_clean(&self) -> bool; ``` Source line: `64`. ## verify::verify\_lineage [#verifyverify_lineage] Verifies the complete lineage chain of an OAS Identity Document. Implements the normative verification algorithm from OAS Spec Appendix C: 1. Root entities (HMR, MHR, or ENR) must match verifier trust anchors. 2. Verifies the lineage section exists for non-root entities. 3. Verifies the chain terminates at an HMR, MHR, or ENR. 4. Verifies generation matches chain length minus one. 5. Enforces maximum generation depth. 6. Walks the chain, verifying each AgentLineageProof2025 signature against the resolved parent document's public key. 7. Optionally checks human root liveness. # Arguments [#arguments] * `document` - The document whose lineage to verify. * `provider` - A \[`DocumentProvider`] for resolving parent documents. * `config` - Configuration (timeouts, max depth). # Returns [#returns] A \[`VerifyResult`] on success, containing chain metadata and any warnings. # Errors [#errors] Returns \[`LineageError`] if any step of the verification fails. See the individual error variants for specific failure modes. # Examples [#examples-1] ``` use oas_lineage::verify::verify_lineage; use oas_lineage::config::{TrustAnchor, VerifyConfig}; use oas_lineage::provider::InMemoryProvider; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let root = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L1) .add_verification_method(&keypair) .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); let provider = InMemoryProvider::new(); let anchor = TrustAnchor::new( &root.id, format!("{}#key-1", root.id), keypair.public_key_multibase(), ).with_document_digest(root.canonical_digest().unwrap()); let config = VerifyConfig::new().with_trust_anchor(anchor); let result = verify_lineage(&root, &provider, &config); assert!(result.is_ok()); ``` ```rust pub fn verify_lineage( document: &OasDocument, provider: &dyn DocumentProvider, config: &VerifyConfig, ) -> Result; ``` Source line: `124`. # oas-resolve · anchored URL: https://docs.openagent.id/reference/rust/oas-resolve/anchored Markdown: https://docs.openagent.id/reference/rust/oas-resolve/anchored.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/anchored.rs`. SHA-256: `fa71502f19c501a71ac700d39ae94217811409ce35453a6b070dc94041069170`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## anchored::AnchorRecord [#anchoredanchorrecord] Minimal canonical view of a GAL root anchor (HMR / MHR / ENR). ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct AnchorRecord { /// Subject DID this anchor is bound to. pub did: String, /// Lifecycle status reported by the GAL: `"active"`, `"rotating"`, /// `"revoked"`. Anything other than `"active"` is rejected. pub status: String, /// Block height at which this anchor version was published. Must be /// less than or equal to the GAL's current finalized block. pub anchored_at_block: u64, /// BLAKE3 commitment to the canonical off-chain DID document. pub metadata_commitment: String } ``` Source line: `87`. ## anchored::AnchorStatus [#anchoredanchorstatus] Result of a `check_revocation` call. Resolvers MUST call this first. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AnchorStatus { pub revoked: bool, /// Optional human-readable reason commitment. #[serde(default, skip_serializing_if = "Option::is_none")] pub reason_commitment: Option } ``` Source line: `102`. ## anchored::OrgLineageRoot [#anchoredorglineageroot] Minimal canonical view of a GAL `OrgLineageRoot`. Only the fields the guard needs for inclusion verification are surfaced. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct OrgLineageRoot { /// Org DID (typically MHR or ENR). pub org_did: String, /// `blake3:`-prefixed hex of the on-chain Merkle root. pub merkle_root: String, /// On-chain status: `"active"` / `"rotating"` / `"revoked"`. pub status: String, /// Block height at which this version of the root was published. pub anchored_at_block: u64 } ``` Source line: `113`. ## anchored::AnchorError [#anchoredanchorerror] Errors returned by a `LineageAnchor`. Mapped into `ResolveError` variants by \[`AnchoredResolver`]. ```rust #[derive(Debug, thiserror::Error)] pub enum AnchorError { /// Underlying transport / RPC failure. #[error("anchor transport error: {0}")] Transport(String), /// Backend returned a structurally invalid record. #[error("invalid anchor record: {0}")] InvalidRecord(String), } ``` Source line: `127`. ## anchored::LineageAnchor [#anchoredlineageanchor] Read-only view of the Sigil GAL needed by the verification guard. This is intentionally a **subset** of `mars-protocol::SigilAnchorClient` — resolvers do not need to submit anchors. A production adapter that wraps `mars-protocol::SigilAnchorClient` lives in `sigil-sdk`. ```rust #[async_trait] pub trait LineageAnchor: Send + Sync { /// Revocation-first check. Returns `revoked: true` for subjects with /// any cascade kind (single, cascade-root, cascade-org). async fn check_revocation(&self, did: &str) -> Result; /// Fetch the typed HMR anchor for a DID, or `None` if absent. async fn get_hmr(&self, did: &str) -> Result, AnchorError>; /// Fetch the typed MHR anchor for a DID, or `None` if absent. async fn get_mhr(&self, did: &str) -> Result, AnchorError>; /// Fetch the typed ENR anchor for a DID, or `None` if absent. async fn get_enr(&self, did: &str) -> Result, AnchorError>; /// Fetch the typed `OrgLineageRoot` for an org DID, or `None` if /// the GAL has no Merkle commitment for that DID. /// /// Default impl returns `None` — implementations that want to /// participate in Rule 7 (org Merkle inclusion) override this. async fn get_org_root(&self, _org_did: &str) -> Result, AnchorError> ; /// Current finalized block height. The guard uses this to reject /// anchors whose `anchored_at_block` lies in the future. async fn current_finalized_block(&self) -> Result; } ``` Source line: `142`. ## anchored::MemoryAnchor [#anchoredmemoryanchor] In-memory `LineageAnchor` for tests. Deterministic, no I/O. ```rust pub struct MemoryAnchor { } ``` Source line: `171`. ## anchored::MemoryAnchor::new [#anchoredmemoryanchornew] Empty source with `current_finalized_block = 0`. ```rust pub fn new() -> Self; ``` Source line: `193`. ## anchored::MemoryAnchor::set\_block [#anchoredmemoryanchorset_block] Set the current finalized block height. ```rust pub fn set_block(&self, block: u64); ``` Source line: `200`. ## anchored::MemoryAnchor::insert\_hmr [#anchoredmemoryanchorinsert_hmr] Pre-populate an HMR anchor. ```rust pub fn insert_hmr(&self, anchor: AnchorRecord); ``` Source line: `207`. ## anchored::MemoryAnchor::insert\_mhr [#anchoredmemoryanchorinsert_mhr] Pre-populate an MHR anchor. ```rust pub fn insert_mhr(&self, anchor: AnchorRecord); ``` Source line: `214`. ## anchored::MemoryAnchor::insert\_enr [#anchoredmemoryanchorinsert_enr] Pre-populate an ENR anchor. ```rust pub fn insert_enr(&self, anchor: AnchorRecord); ``` Source line: `221`. ## anchored::MemoryAnchor::insert\_revocation [#anchoredmemoryanchorinsert_revocation] Mark a DID as revoked. ```rust pub fn insert_revocation(&self, did: &str, reason: Option<&str>); ``` Source line: `228`. ## anchored::MemoryAnchor::insert\_org\_root [#anchoredmemoryanchorinsert_org_root] Pre-populate an `OrgLineageRoot` (Rule 7 inclusion verification). ```rust pub fn insert_org_root(&self, root: OrgLineageRoot); ``` Source line: `241`. ## anchored::AnchoredResolver [#anchoredanchoredresolver] Wraps any inner \[`Resolver`] with a \[`LineageAnchor`] backend and enforces the GAL verification rules on every resolution. ```rust pub struct AnchoredResolver where R: Resolver, G: LineageAnchor, { } ``` Source line: `308`. ## anchored::AnchoredResolver\::new [#anchoredanchoredresolverr-gnew] Build a guard around an inner resolver and GAL backend. ```rust pub fn new(inner: R, anchor: G) -> Self; ``` Source line: `323`. ## anchored::document\_metadata\_commitment [#anchoreddocument_metadata_commitment] Compute the BLAKE3 hex digest of a DID document's canonical JSON (RFC 8785 / JCS). This is the value committed to by GAL anchors. ```rust pub fn document_metadata_commitment(doc: &OasDocument) -> Result; ``` Source line: `330`. ## anchored::org\_leaf\_hash [#anchoredorg_leaf_hash] BLAKE3 of the canonical org leaf — `BLAKE3(child_did_utf8_bytes)`. Exposed so test fixtures and indexers can compute the same value. ```rust pub fn org_leaf_hash(child_did: &str) -> String; ``` Source line: `729`. # oas-resolve · cache URL: https://docs.openagent.id/reference/rust/oas-resolve/cache Markdown: https://docs.openagent.id/reference/rust/oas-resolve/cache.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/cache.rs`. SHA-256: `58ff23aa2ef2f94c0540dfb51cb76895d205c58b67009f25fbce5a14356d75d1`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## cache::CachingResolver [#cachecachingresolver] A caching wrapper around any \[`Resolver`]. Stores resolved documents in memory with a configurable TTL. Expired entries are lazily evicted on the next access. # Examples [#examples] ``` use oas_resolve::cache::CachingResolver; use oas_resolve::memory::InMemoryResolver; use std::time::Duration; let inner = InMemoryResolver::new(); let caching = CachingResolver::new(inner, Duration::from_secs(300)); ``` ```rust pub struct CachingResolver { } ``` Source line: `39`. ## cache::CachingResolver\::new [#cachecachingresolverrnew] Creates a new caching resolver. # Arguments [#arguments] * `inner` - The underlying resolver to wrap. * `ttl` - How long to cache resolved documents. ```rust pub fn new(inner: R, ttl: Duration) -> Self; ``` Source line: `52`. ## cache::CachingResolver\::invalidate [#cachecachingresolverrinvalidate] Invalidates a specific cached entry. # Arguments [#arguments-1] * `did` - The DID to invalidate. ```rust pub fn invalidate(&self, did: &str); ``` Source line: `65`. ## cache::CachingResolver\::clear [#cachecachingresolverrclear] Clears all cached entries. ```rust pub fn clear(&self); ``` Source line: `72`. ## cache::CachingResolver\::len [#cachecachingresolverrlen] Returns the number of entries currently in the cache (including expired). ```rust pub fn len(&self) -> usize; ``` Source line: `79`. ## cache::CachingResolver\::is\_empty [#cachecachingresolverris_empty] Returns true if the cache is empty. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `84`. # oas-resolve · crate URL: https://docs.openagent.id/reference/rust/oas-resolve/crate Markdown: https://docs.openagent.id/reference/rust/oas-resolve/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/lib.rs`. SHA-256: `cbec0de8bef5896f07fe96d25b680e99d01f120a9c7e9463ecb1a6655996d0d2`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## anchored [#anchored] # oas-resolve [#oas-resolve] DID resolution for the Open Agent Specification (OAS). This crate provides the [`Resolver`](resolver::Resolver) trait and several implementations for resolving `did:oas` identifiers to OAS Identity Documents. ## Key Types [#key-types] * [`Resolver`](resolver::Resolver) — The core async resolution trait * [`InMemoryResolver`](memory::InMemoryResolver) — In-memory resolver for testing * [`CachingResolver`](cache::CachingResolver) — TTL-based caching wrapper * [`FallbackResolver`](fallback::FallbackResolver) — Priority-ordered fallback chain * \[`ResolveError`] — Resolution errors with OAS §12.5 error codes * [`ResolutionMetadata`](metadata::ResolutionMetadata) — Resolution process metadata ## Design [#design] Per OAS Specification §12, resolution is defined as an abstract protocol. This crate provides the trait and utility implementations. Concrete backends (DHT, HTTP, blockchain) implement the [`Resolver`](resolver::Resolver) trait. ## Example [#example] ``` use oas_resolve::resolver::Resolver; use oas_resolve::memory::InMemoryResolver; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; # tokio_test::block_on(async { let keypair = OasKeyPair::generate(); let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L1) .add_verification_method(&keypair) .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); let resolver = InMemoryResolver::new(); resolver.register(doc); let resolved = resolver.resolve("did:oas:test:hmr:alice").await.unwrap(); assert_eq!(resolved.id, "did:oas:test:hmr:alice"); # }); ``` ```rust pub mod anchored; ``` Source line: `48`. ## cache [#cache] ```rust pub mod cache; ``` Source line: `49`. ## error [#error] ```rust pub mod error; ``` Source line: `50`. ## fallback [#fallback] ```rust pub mod fallback; ``` Source line: `51`. ## memory [#memory] ```rust pub mod memory; ``` Source line: `52`. ## metadata [#metadata] ```rust pub mod metadata; ``` Source line: `53`. ## resolver [#resolver] ```rust pub mod resolver; ``` Source line: `54`. ## pub use anchored::\{ [#pub-use-anchored] document\_metadata\_commitment, org\_leaf\_hash, AnchorError, AnchorRecord, AnchorStatus, AnchoredResolver, LineageAnchor, MemoryAnchor, OrgLineageRoot, }; ```rust pub use anchored::{ document_metadata_commitment, org_leaf_hash, AnchorError, AnchorRecord, AnchorStatus, AnchoredResolver, LineageAnchor, MemoryAnchor, OrgLineageRoot, }; ``` Source line: `56`. ## pub use error::ResolveError; [#pub-use-errorresolveerror] ```rust pub use error::ResolveError; ``` Source line: `60`. ## pub use anchored::\{ [#pub-use-anchored-1] AnchorError as GalSourceError, AnchorRecord as GalRootAnchor, AnchorStatus as GalRevocationStatus, AnchoredResolver as SigilGuardedResolver, LineageAnchor as SigilGalSource, MemoryAnchor as MemoryGalSource, OrgLineageRoot as GalOrgLineageRoot, }; ```rust pub use anchored::{ AnchorError as GalSourceError, AnchorRecord as GalRootAnchor, AnchorStatus as GalRevocationStatus, AnchoredResolver as SigilGuardedResolver, LineageAnchor as SigilGalSource, MemoryAnchor as MemoryGalSource, OrgLineageRoot as GalOrgLineageRoot, }; ``` Source line: `65`. # oas-resolve · error URL: https://docs.openagent.id/reference/rust/oas-resolve/error Markdown: https://docs.openagent.id/reference/rust/oas-resolve/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/error.rs`. SHA-256: `178fa1d8a81c986f7ff475bcbd5bce7e750260bb1bd2a0c8ccdcd8a366491e40`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::ResolveError [#errorresolveerror] Errors that can occur during DID resolution. Each variant corresponds to a structured error code from OAS Specification §12.5. # Examples [#examples] ``` use oas_resolve::error::ResolveError; let err = ResolveError::NotFound { did: "did:oas:test:agent:missing".to_string(), }; assert_eq!(err.error_code(), "notFound"); ``` ```rust #[derive(Debug, Error)] pub enum ResolveError { /// DID not found in any consulted registry. /// /// Error code: `notFound` #[error("DID not found: '{did}'")] NotFound { /// The DID that was not found. did: String, }, /// Document signature does not verify. /// /// Error code: `invalidSignature` #[error("document signature invalid for '{did}': {reason}")] InvalidSignature { /// The DID of the document with the invalid signature. did: String, /// Details about the signature failure. reason: String, }, /// The DID has been revoked. /// /// Error code: `revoked` #[error("DID has been revoked: '{did}'")] Revoked { /// The revoked DID. did: String, }, /// Lineage chain verification failed. /// /// Error code: `lineageInvalid` #[error("lineage verification failed for '{did}': {reason}")] LineageInvalid { /// The DID whose lineage is invalid. did: String, /// Details about the lineage failure. reason: String, }, /// Lineage chain could not be fully verified (timeout, missing ancestor). /// /// Error code: `lineageUnverifiable` #[error("lineage unverifiable for '{did}': {reason}")] LineageUnverifiable { /// The DID whose lineage could not be verified. did: String, /// Details about why verification failed. reason: String, }, /// The human root in the lineage chain is revoked. /// /// Error code: `humanRootRevoked` #[error("human root revoked for lineage of '{did}': root DID '{root_did}'")] HumanRootRevoked { /// The DID of the entity whose root is revoked. did: String, /// The revoked human root DID. root_did: String, }, /// Human root's liveness attestation has expired. /// /// Error code: `humanRootLivenessExpired` #[error("human root liveness expired for '{did}': root DID '{root_did}'")] HumanRootLivenessExpired { /// The DID of the entity whose root liveness expired. did: String, /// The human root DID with expired liveness. root_did: String, }, /// Conflicting documents found across registries. /// /// Error code: `conflictDetected` #[error("conflicting documents detected for '{did}': {reason}")] ConflictDetected { /// The DID with conflicting documents. did: String, /// Details about the conflict. reason: String, }, /// Entity's generation exceeds resolver's MAX_GENERATION. /// /// Error code: `maxGenerationExceeded` #[error("max generation exceeded for '{did}': generation {generation} exceeds limit {max_generation}")] MaxGenerationExceeded { /// The DID of the entity exceeding the limit. did: String, /// The entity's generation. generation: u32, /// The resolver's maximum generation. max_generation: u32, }, /// A network or I/O error occurred during resolution. #[error("resolution I/O error for '{did}': {reason}")] IoError { /// The DID being resolved. did: String, /// Details of the I/O failure. reason: String, }, /// An internal resolver error. #[error("internal resolver error: {reason}")] Internal { /// Details of the internal error. reason: String, }, /// The terminal root (HMR / MHR / ENR) is not anchored on the /// Global Anchor Layer (Sigil), or the anchor record is in a /// non-active state, or its anchor block lies in the future. /// /// Error code: `notAnchored` #[error("root not anchored on Sigil for '{did}': {reason}")] NotAnchored { /// The DID whose root could not be verified against the GAL. did: String, /// Details about why the GAL anchor was rejected. reason: String, }, /// The BLAKE3 commitment recorded by the on-chain anchor does not /// match the canonical hash of the resolved DID document. The /// document is considered tampered and is rejected. /// /// Error code: `metadataMismatch` #[error("metadata commitment mismatch for '{did}': {reason}")] MetadataMismatch { /// The DID whose document failed the commitment check. did: String, /// Details about the mismatch (expected vs actual). reason: String, }, /// A non-root entity (kind not in {`hmr`, `mhr`, `enr`}) presented /// no lineage section. Required for L1+ documents. /// /// Error code: `missingLineage` #[error("missing lineage section for non-root '{did}'")] MissingLineage { /// The DID whose lineage section was missing. did: String, }, /// The lineage anchor backend was unreachable while resolving. The /// resolver fails closed: an unreachable anchor means revocation /// state cannot be confirmed and the resolution MUST be rejected. /// /// Error code: `galUnreachable` - retained for wire compatibility /// with consumers that already match on it (the backend this variant /// first described was Sigil's GAL). An `anchorUnreachable` alias may /// replace it at the next major version. #[error("lineage anchor unreachable for '{did}': {reason}")] AnchorUnreachable { /// The DID being resolved. did: String, /// Details of the anchor transport / RPC failure. reason: String, }, /// An expected on-chain org lineage Merkle inclusion proof was /// missing or did not verify. /// /// Error code: `orgInclusionMissing` #[error("org Merkle inclusion missing or invalid for '{did}': {reason}")] OrgInclusionMissing { /// The DID whose org inclusion check failed. did: String, /// Details about the failure. reason: String, }, /// A non-root entity has a `lineage` section but no /// `derivation_proof`. Required for L1+ resolution. /// /// Error code: `missingLineageProof` #[error("missing AgentLineageProof2025 derivation proof for '{did}'")] MissingLineageProof { /// The DID whose proof is missing. did: String, }, /// A legacy lineage proof omits mandatory signed security bindings. /// /// Error code: `legacyInsecureProof` #[error("legacy lineage proof is non-authorizing for '{did}': {reason}")] LegacyInsecureProof { /// The child DID whose proof is non-authorizing. did: String, /// The missing or insecure binding. reason: String, }, /// The parent's `AgentLineageProof2025` signature does not verify /// against the parent DID document's declared key. The child /// document is considered untrustworthy and is rejected. /// /// Error code: `parentSignatureInvalid` #[error("parent signature invalid for '{did}': {reason}")] ParentSignatureInvalid { /// The child DID whose lineage proof failed verification. did: String, /// Details about the signature failure. reason: String, }, /// The parent public key referenced by the lineage proof is not /// present in the parent DID document's `verificationMethod` list. /// The proof would otherwise sign correctly, but the key is /// orphaned — not bound to the parent's declared identity. /// /// Error code: `parentKeyNotInDocument` #[error("proof key not declared by parent '{parent_did}' for child '{did}'")] ParentKeyNotInDocument { /// The child DID. did: String, /// The parent DID whose document was inspected. parent_did: String, }, } ``` Source line: `25`. ## error::ResolveError::error\_code [#errorresolveerrorerror_code] Returns the OAS Spec §12.5 error code string for this error. # Examples [#examples-1] ``` use oas_resolve::error::ResolveError; let err = ResolveError::Revoked { did: "did:oas:test:hmr:alice".to_string() }; assert_eq!(err.error_code(), "revoked"); ``` ```rust pub fn error_code(&self) -> &'static str; ``` Source line: `263`. # oas-resolve · fallback URL: https://docs.openagent.id/reference/rust/oas-resolve/fallback Markdown: https://docs.openagent.id/reference/rust/oas-resolve/fallback.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/fallback.rs`. SHA-256: `d896098c170df028892ba94542076fc2b89085ee858d4d8fa239ee2461cb9832`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## fallback::FallbackResolver [#fallbackfallbackresolver] A resolver that tries multiple backend resolvers in priority order. Per OAS Spec §12.4 (Registry priority): resolvers MAY be configured with a priority-ordered list of registries. # Examples [#examples] ``` use oas_resolve::fallback::FallbackResolver; use oas_resolve::memory::InMemoryResolver; let primary = InMemoryResolver::new(); let secondary = InMemoryResolver::new(); let fallback = FallbackResolver::new(vec![ Box::new(primary), Box::new(secondary), ]); ``` ```rust pub struct FallbackResolver { } ``` Source line: `31`. ## fallback::FallbackResolver::new [#fallbackfallbackresolvernew] Creates a new fallback resolver with the given backends. Resolvers are tried in order — the first one to return a successful result wins. # Arguments [#arguments] * `resolvers` - Priority-ordered list of resolvers. ```rust pub fn new(resolvers: Vec>) -> Self; ``` Source line: `44`. ## fallback::FallbackResolver::resolver\_count [#fallbackfallbackresolverresolver_count] Returns the number of configured backend resolvers. ```rust pub fn resolver_count(&self) -> usize; ``` Source line: `49`. # oas-resolve modules URL: https://docs.openagent.id/reference/rust/oas-resolve Markdown: https://docs.openagent.id/reference/rust/oas-resolve.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-resolve). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-resolve/crate) — 10 declarations * [anchored](/reference/rust/oas-resolve/anchored) — 17 declarations * [cache](/reference/rust/oas-resolve/cache) — 6 declarations * [error](/reference/rust/oas-resolve/error) — 2 declarations * [fallback](/reference/rust/oas-resolve/fallback) — 3 declarations * [memory](/reference/rust/oas-resolve/memory) — 6 declarations * [metadata](/reference/rust/oas-resolve/metadata) — 3 declarations * [resolver](/reference/rust/oas-resolve/resolver) — 1 declarations # oas-resolve · memory URL: https://docs.openagent.id/reference/rust/oas-resolve/memory Markdown: https://docs.openagent.id/reference/rust/oas-resolve/memory.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/memory.rs`. SHA-256: `f949fec8753d0e034fc1bd52e2b9f986d0a5b941fc1d5aed7278088416db697d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## memory::InMemoryResolver [#memoryinmemoryresolver] An in-memory DID resolver for testing and development. Stores documents in a thread-safe `HashMap`. Documents are registered via [`register`](InMemoryResolver::register) and resolved via the \[`Resolver`] trait. # Thread Safety [#thread-safety] Uses `RwLock` for interior mutability, allowing concurrent reads with exclusive writes. # Examples [#examples] ``` use oas_resolve::memory::InMemoryResolver; use oas_resolve::resolver::Resolver; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_crypto::keypair::OasKeyPair; # tokio_test::block_on(async { let keypair = OasKeyPair::generate(); let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L1) .add_verification_method(&keypair) .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); let resolver = InMemoryResolver::new(); resolver.register(doc); let resolved = resolver.resolve("did:oas:test:hmr:alice").await; assert!(resolved.is_ok()); # }); ``` ```rust pub struct InMemoryResolver { } ``` Source line: `52`. ## memory::InMemoryResolver::new [#memoryinmemoryresolvernew] Creates an empty in-memory resolver. ```rust pub fn new() -> Self; ``` Source line: `58`. ## memory::InMemoryResolver::register [#memoryinmemoryresolverregister] Registers a document in the resolver. The document is stored under its `id` field. If a document with the same ID already exists, it is replaced. # Arguments [#arguments] * `doc` - The document to register. ```rust pub fn register(&self, doc: OasDocument); ``` Source line: `72`. ## memory::InMemoryResolver::len [#memoryinmemoryresolverlen] Returns the number of registered documents. ```rust pub fn len(&self) -> usize; ``` Source line: `79`. ## memory::InMemoryResolver::is\_empty [#memoryinmemoryresolveris_empty] Returns true if no documents are registered. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `84`. ## memory::InMemoryResolver::remove [#memoryinmemoryresolverremove] Removes a document from the resolver. # Arguments [#arguments-1] * `did` - The DID of the document to remove. # Returns [#returns] The removed document, if it existed. ```rust pub fn remove(&self, did: &str) -> Option; ``` Source line: `97`. # oas-resolve · metadata URL: https://docs.openagent.id/reference/rust/oas-resolve/metadata Markdown: https://docs.openagent.id/reference/rust/oas-resolve/metadata.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/metadata.rs`. SHA-256: `a1a4521862aef723f58382875693766297e92801f5431959f97740539dbe70a5`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## metadata::ResolutionMetadata [#metadataresolutionmetadata] Metadata about the resolution process itself. Corresponds to the `didResolutionMetadata` field in OAS Spec §12.3. # Examples [#examples] ``` use oas_resolve::metadata::ResolutionMetadata; let meta = ResolutionMetadata { content_type: "application/did+ld+json".to_string(), retrieved: "2026-01-15T12:00:00Z".to_string(), resolver_identity: None, }; assert_eq!(meta.content_type, "application/did+ld+json"); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ResolutionMetadata { /// The content type of the resolved document. pub content_type: String, /// ISO 8601 timestamp of when the resolution occurred. pub retrieved: String, /// DID of the resolver that performed the resolution (optional). #[serde(skip_serializing_if = "Option::is_none")] pub resolver_identity: Option } ``` Source line: `28`. ## metadata::DocumentResolutionMetadata [#metadatadocumentresolutionmetadata] Metadata about the resolved document. Corresponds to the `didDocumentMetadata` field in OAS Spec §12.3. # Examples [#examples-1] ``` use oas_resolve::metadata::DocumentResolutionMetadata; let meta = DocumentResolutionMetadata { created: "2026-01-15T00:00:00Z".to_string(), updated: None, version_id: Some("3".to_string()), lineage_verified: Some(true), human_root_active: Some(true), conformance_level: Some("L2".to_string()), attestation_count: Some(5), }; assert!(meta.lineage_verified.unwrap_or(false)); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DocumentResolutionMetadata { /// ISO 8601 creation timestamp of the document. pub created: String, /// ISO 8601 last update timestamp (if any). #[serde(skip_serializing_if = "Option::is_none")] pub updated: Option, /// Version identifier (typically the sequence number as a string). #[serde(skip_serializing_if = "Option::is_none")] pub version_id: Option, /// Whether the lineage chain was verified during resolution. #[serde(skip_serializing_if = "Option::is_none")] pub lineage_verified: Option, /// Whether the human root entity is active (not revoked). #[serde(skip_serializing_if = "Option::is_none")] pub human_root_active: Option, /// The conformance level of the resolved document. #[serde(skip_serializing_if = "Option::is_none")] pub conformance_level: Option, /// Number of attestations associated with this entity. #[serde(skip_serializing_if = "Option::is_none")] pub attestation_count: Option } ``` Source line: `72`. ## metadata::ResolutionResult [#metadataresolutionresult] A complete resolution result combining document, resolution metadata, and document metadata. Implements the full resolution response structure from OAS Spec §12.3. # Examples [#examples-2] ``` use oas_resolve::metadata::{ResolutionResult, ResolutionMetadata, DocumentResolutionMetadata}; use oas_document::OasDocument; // ResolutionResult is returned by resolver implementations ``` ```rust #[derive(Debug, Clone)] pub struct ResolutionResult { /// The resolved identity document. pub document: oas_document::OasDocument, /// Metadata about the resolution process. pub resolution_metadata: ResolutionMetadata, /// Metadata about the resolved document. pub document_metadata: DocumentResolutionMetadata } ``` Source line: `115`. # oas-resolve · resolver URL: https://docs.openagent.id/reference/rust/oas-resolve/resolver Markdown: https://docs.openagent.id/reference/rust/oas-resolve/resolver.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-resolve/src/resolver.rs`. SHA-256: `35b732ff5e27f260a8e97c59ed22c82404abd5508da9ec278b0992dab4524509`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## resolver::Resolver [#resolverresolver] An async resolver that maps `did:oas` identifiers to identity documents. This is the critical abstraction per OAS Specification §12. OAS defines the trait; consumers implement it. # Implementation Requirements [#implementation-requirements] Per OAS Spec §12.2: 1. MUST return the most recent valid document for the given DID. 2. MUST verify the document's signature before returning it. 3. MUST check revocation status and indicate if revoked. 4. SHOULD verify lineage for L1+ documents. 5. MUST return a structured error on failure. # Examples [#examples] ``` use oas_resolve::resolver::Resolver; use oas_resolve::memory::InMemoryResolver; let resolver = InMemoryResolver::new(); // The resolver is ready but empty — all lookups will return NotFound. ``` ```rust #[async_trait] pub trait Resolver: Send + Sync { /// Resolves a `did:oas` identifier to its identity document. /// /// # Arguments /// /// * `did` - The `did:oas` identifier to resolve. /// /// # Returns /// /// The resolved [`OasDocument`]. /// /// # Errors /// /// Returns a [`ResolveError`] if: /// - The DID is not found ([`ResolveError::NotFound`]) /// - The document signature is invalid ([`ResolveError::InvalidSignature`]) /// - The document is revoked ([`ResolveError::Revoked`]) /// - Any other resolution error occurs async fn resolve(&self, did: &str) -> Result; } ``` Source line: `37`. # oas-sdk · anchor_policy URL: https://docs.openagent.id/reference/rust/oas-sdk/anchor_policy Markdown: https://docs.openagent.id/reference/rust/oas-sdk/anchor_policy.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/anchor_policy.rs`. SHA-256: `a7973d1474d6a9e82c69cdb9054b4e24f957fd1cb22400f09b3d3056bbf04710`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "resolve")] ``` ## anchor\_policy::AnchorPolicy [#anchor_policyanchorpolicy] The verifier's anchor policy. `trusted_schemes` is ordered most-preferred-first. The default policy trusts Sigil only — the ecosystem's reference anchor and the home of the lineage economics (generation decay, publisher bonds), which only Sigil computes. ```rust #[cfg(feature = "resolve")] #[derive(Debug, Clone, PartialEq, Eq)] pub struct AnchorPolicy { /// Ordered anchor schemes, most preferred first. pub trusted_schemes: Vec } ``` Source line: `38`. ## anchor\_policy::AnchorPolicy::trusting [#anchor_policyanchorpolicytrusting] A policy trusting the given schemes in order. ```rust #[cfg(feature = "resolve")] pub fn trusting(schemes: impl IntoIterator>) -> Self; ``` Source line: `53`. ## anchor\_policy::AnchorPolicy::sigil\_then\_eas [#anchor_policyanchorpolicysigil_then_eas] Sigil preferred, EAS as fallback. ```rust #[cfg(feature = "resolve")] pub fn sigil_then_eas() -> Self; ``` Source line: `63`. ## anchor\_policy::AnchorBackends [#anchor_policyanchorbackends] A registry of anchor backends by scheme name. ```rust #[cfg(feature = "resolve")] pub type AnchorBackends<'a> = HashMap; ``` Source line: `69`. ## anchor\_policy::VerifyWithAnchorRequest [#anchor_policyverifywithanchorrequest] Typed policy inputs for \[`verify_with_anchor_policy`]. Grouping these verifier-controlled values prevents positional argument mistakes and keeps the authority policy explicit at call sites. ```rust #[cfg(feature = "resolve")] pub struct VerifyWithAnchorRequest<'a> { /// Ordered verifier trust policy for anchor backends. pub policy: &'a AnchorPolicy, /// Available anchor backends keyed by scheme. pub backends: AnchorBackends<'a>, /// Expected authority path from the trusted root to the subject. pub path_kind: crate::lineage::AuthorityPathKind, /// Scopes the confirmed authority must grant. pub required_scopes: &'a [String], /// Optional lower bound for backend finality. pub min_finalized_block: Option } ``` Source line: `75`. ## anchor\_policy::AnchoredAuthoritySource [#anchor_policyanchoredauthoritysource] A \[`LineageAuthoritySource`] that dispatches to anchor backends per the verifier's \[`AnchorPolicy`]. ```rust #[cfg(feature = "resolve")] pub struct AnchoredAuthoritySource<'a> { } ``` Source line: `90`. ## anchor\_policy::AnchoredAuthoritySource\<'a>::new [#anchor_policyanchoredauthoritysourceanew] Build the dispatcher. A trusted scheme with no registered backend cannot confirm authority, so it contributes nothing to the decision: the dispatcher proceeds with the backends that exist and, if none confirms, fails closed with the policy named in the error. An unregistered trusted scheme is a legal state (a verifier may not run every backend it would trust); silently treating it as a pass is the failure this shape prevents. ```rust #[cfg(feature = "resolve")] pub fn new(policy: AnchorPolicy, backends: AnchorBackends<'a>) -> Self; ``` Source line: `104`. ## anchor\_policy::verify\_with\_anchor\_policy [#anchor_policyverify_with_anchor_policy] Verify lineage with an explicit anchor policy, in one call. The facade-level entry for the common case: offline lineage verification (portable) followed by authority confirmation against the trusted anchor schemes the document's lineage section points at. If you do not have a document-shaped anchor reference set, this composes identically to calling `verify_privileged_authority` with an \[`AnchoredAuthoritySource`]. # Errors [#errors] Fails closed: any backend error, absent anchor, non-active status, or unconfirmed finality means the privileged action is not authorized. ```rust #[cfg(feature = "resolve")] #[cfg(feature = "resolve")] pub fn verify_with_anchor_policy( document: &OasDocument, provider: &dyn oas_lineage::provider::DocumentProvider, config: &oas_lineage::config::VerifyConfig, request: VerifyWithAnchorRequest<'_>, ) -> Result; ``` Source line: `275`. # oas-sdk · attestation URL: https://docs.openagent.id/reference/rust/oas-sdk/attestation Markdown: https://docs.openagent.id/reference/rust/oas-sdk/attestation.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/attestation.rs`. SHA-256: `ced1e63868a56de8ae5158a1d9cbce1540346b506bbd9d0c347fa152b578300a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## attestation::create\_attestation [#attestationcreate_attestation] Creates and signs an attestation credential in a single call. Combines credential building and signing for the common case where you have all the information upfront. # Arguments [#arguments] * `issuer_did` - The issuer's `did:oas` identifier. * `subject_did` - The subject entity's `did:oas` identifier. * `attestation_type` - The OAS §13.2 attestation type. * `claims` - Additional credential subject claims as key-value pairs. * `issuer_keypair` - The issuer's Ed25519 keypair. * `verification_method_id` - Full verification method ID (e.g., `"did:oas:test:hmr:a#key-1"`). * `issuance_date` - ISO 8601 timestamp. * `expiration_date` - Optional ISO 8601 expiration timestamp. # Returns [#returns] A signed \[`OasCredential`]. # Errors [#errors] Returns \[`OasError::Attestation`] if building, validation, or signing fails. # Examples [#examples] ``` use oas_sdk::attestation::create_attestation; use oas_attestation::types::AttestationType; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let cred = create_attestation( "did:oas:test:hmr:auditor", "did:oas:test:agent:target", AttestationType::SecurityAudit, &[ ("auditType", serde_json::json!("codeAudit")), ("result", serde_json::json!("pass")), ("severityFindings", serde_json::json!({"critical": 0})), ("toolOrMethodology", serde_json::json!("OWASP")), ("auditDate", serde_json::json!("2026-01-15T00:00:00Z")), ], &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", None, ); assert!(cred.is_ok()); ``` ```rust #[allow(clippy::too_many_arguments)] pub fn create_attestation( issuer_did: &str, subject_did: &str, attestation_type: AttestationType, claims: &[(&str, serde_json::Value)], issuer_keypair: &OasKeyPair, verification_method_id: &str, issuance_date: &str, expiration_date: Option<&str>, ) -> Result; ``` Source line: `65`. ## attestation::verify\_attestation [#attestationverify_attestation] Verifies an attestation credential's proof. Validates structure and cryptographic proof against the issuer's public key. # Arguments [#arguments-1] * `credential` - The signed credential to verify. * `issuer_public_key` - The 32-byte Ed25519 public key of the issuer. # Returns [#returns-1] `Ok(())` if valid. # Errors [#errors-1] Returns \[`OasError::Attestation`] if verification fails. # Examples [#examples-1] ``` use oas_sdk::attestation::{create_attestation, verify_attestation}; use oas_attestation::types::AttestationType; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let cred = create_attestation( "did:oas:test:hmr:auditor", "did:oas:test:agent:target", AttestationType::ExpertEndorsement, &[ ("expertDid", serde_json::json!("did:oas:test:hmr:auditor")), ("domain", serde_json::json!("security")), ("endorsementType", serde_json::json!("capability")), ("confidence", serde_json::json!(0.9)), ], &keypair, "did:oas:test:hmr:auditor#key-1", "2026-01-15T00:00:00Z", None, ).unwrap(); let result = verify_attestation(&cred, &keypair.verifying_key_bytes()); assert!(result.is_ok()); ``` ```rust pub fn verify_attestation( credential: &OasCredential, issuer_public_key: &[u8], ) -> Result<(), OasError>; ``` Source line: `144`. ## attestation::verify\_attestation\_with\_time [#attestationverify_attestation_with_time] Verifies an attestation credential with temporal checks. In addition to proof verification, checks that the credential is within its valid time window. # Arguments [#arguments-2] * `credential` - The signed credential to verify. * `issuer_public_key` - The 32-byte Ed25519 public key of the issuer. * `now` - Current time as ISO 8601 string. # Returns [#returns-2] `Ok(())` if valid and within time window. # Errors [#errors-2] Returns \[`OasError::Attestation`] if verification fails or the credential is expired/not yet valid. ```rust pub fn verify_attestation_with_time( credential: &OasCredential, issuer_public_key: &[u8], now: &str, ) -> Result<(), OasError>; ``` Source line: `169`. # oas-sdk · config URL: https://docs.openagent.id/reference/rust/oas-sdk/config Markdown: https://docs.openagent.id/reference/rust/oas-sdk/config.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/config.rs`. SHA-256: `4038079d8f84273a076b937fa015546f3ad4f002cd8fd55e41afdbaa50f8a6c4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::SdkConfig [#configsdkconfig] Configuration for the OAS SDK. Controls resolution, lineage verification settings, and other SDK-wide parameters. # Examples [#examples] ``` use oas_sdk::config::SdkConfig; use std::time::Duration; let config = SdkConfig::builder() .max_generation(8) .per_hop_timeout(Duration::from_secs(3)) .build(); assert_eq!(config.max_generation(), 8); ``` ```rust #[derive(Debug, Clone)] pub struct SdkConfig { } ``` Source line: `28`. ## config::SdkConfig::builder [#configsdkconfigbuilder] Creates a new \[`SdkConfigBuilder`]. ```rust pub fn builder() -> SdkConfigBuilder; ``` Source line: `38`. ## config::SdkConfig::max\_generation [#configsdkconfigmax_generation] Returns the maximum allowed lineage generation depth. ```rust pub fn max_generation(&self) -> u32; ``` Source line: `43`. ## config::SdkConfig::per\_hop\_timeout [#configsdkconfigper_hop_timeout] Returns the per-hop resolution timeout. ```rust pub fn per_hop_timeout(&self) -> Duration; ``` Source line: `48`. ## config::SdkConfig::total\_timeout [#configsdkconfigtotal_timeout] Returns the total lineage verification timeout. ```rust pub fn total_timeout(&self) -> Duration; ``` Source line: `53`. ## config::SdkConfig::verify\_document\_signatures [#configsdkconfigverify_document_signatures] Returns whether document signature verification is enabled. ```rust pub fn verify_document_signatures(&self) -> bool; ``` Source line: `58`. ## config::SdkConfig::trust\_anchors [#configsdkconfigtrust_anchors] Returns verifier-controlled lineage root trust anchors. ```rust pub fn trust_anchors(&self) -> &[oas_lineage::config::TrustAnchor]; ``` Source line: `63`. ## config::SdkConfig::to\_lineage\_config [#configsdkconfigto_lineage_config] Converts this configuration into a lineage [`VerifyConfig`](oas_lineage::config::VerifyConfig). ```rust pub fn to_lineage_config(&self) -> oas_lineage::config::VerifyConfig; ``` Source line: `68`. ## config::SdkConfigBuilder [#configsdkconfigbuilder-1] Builder for \[`SdkConfig`]. # Examples [#examples-1] ``` use oas_sdk::config::SdkConfig; let config = SdkConfig::builder() .max_generation(8) .verify_document_signatures(false) .build(); ``` ```rust #[derive(Debug, Default)] pub struct SdkConfigBuilder { } ``` Source line: `106`. ## config::SdkConfigBuilder::max\_generation [#configsdkconfigbuildermax_generation] Sets the maximum allowed lineage generation depth. Default: 16 (per OAS Specification §8). ```rust pub fn max_generation(mut self, max: u32) -> Self; ``` Source line: `114`. ## config::SdkConfigBuilder::per\_hop\_timeout [#configsdkconfigbuilderper_hop_timeout] Sets the per-hop resolution timeout. Default: 5 seconds. ```rust pub fn per_hop_timeout(mut self, timeout: Duration) -> Self; ``` Source line: `122`. ## config::SdkConfigBuilder::total\_timeout [#configsdkconfigbuildertotal_timeout] Sets the total lineage verification timeout. Default: 30 seconds. ```rust pub fn total_timeout(mut self, timeout: Duration) -> Self; ``` Source line: `130`. ## config::SdkConfigBuilder::verify\_document\_signatures [#configsdkconfigbuilderverify_document_signatures] Sets whether to verify document proof signatures during lineage verification. Default: true. ```rust pub fn verify_document_signatures(mut self, verify: bool) -> Self; ``` Source line: `138`. ## config::SdkConfigBuilder::trust\_anchor [#configsdkconfigbuildertrust_anchor] Adds a verifier-controlled lineage root trust anchor. ```rust pub fn trust_anchor(mut self, anchor: oas_lineage::config::TrustAnchor) -> Self; ``` Source line: `144`. ## config::SdkConfigBuilder::build [#configsdkconfigbuilderbuild] Builds the configuration. ```rust pub fn build(self) -> SdkConfig; ``` Source line: `150`. # oas-sdk · crate URL: https://docs.openagent.id/reference/rust/oas-sdk/crate Markdown: https://docs.openagent.id/reference/rust/oas-sdk/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/lib.rs`. SHA-256: `b03c0548ed311d0008bcdee9297c8dc60b2520f5090b17dc5abd3e87053e7608`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## anchor\_policy [#anchor_policy] # oas-sdk [#oas-sdk] Unified SDK for the Open Agent Specification (OAS). This crate provides a single entry point for all OAS operations: identity creation, lineage derivation, attestation, and resolution. It re-exports the lower-level crates and adds high-level workflow functions. ## Quick Start [#quick-start] ``` use oas_sdk::identity::create_hmr; use oas_sdk::lineage::derive_child; // 1. Create a Human Root identity let root = create_hmr("test", "alice", "2026-01-15T00:00:00Z").unwrap(); assert_eq!(root.document.id, "did:oas:test:hmr:alice"); // 2. Derive a child agent let agent = derive_child( &root.keypair, &root.document, "test", "agent", "analyzer", "agent/analyzer", "2026-01-15T00:00:00Z", ).unwrap(); assert_eq!(agent.document.id, "did:oas:test:agent:analyzer"); assert!(agent.document.lineage.is_some()); ``` ## Crate Organization [#crate-organization] | Module | Purpose | | ---------------- | ------------------------------------------------------------------------- | | \[`identity`] | Root identity creation (HMR, MHR) | | \[`lineage`] | Child derivation, local chain verification, privileged authority contract | | \[`attestation`] | Create, sign, and verify W3C VCs | | \[`config`] | SDK-wide configuration | | \[`error`] | Unified error type | ## Sub-Crate Re-exports [#sub-crate-re-exports] For advanced usage, the individual crates are re-exported: * `oas_sdk::crypto` → \[`oas_crypto`] * `oas_sdk::did` → \[`oas_did`] * `oas_sdk::document` → \[`oas_document`] * `oas_sdk::lineage_crate` → \[`oas_lineage`] * `oas_sdk::resolve` → \[`oas_resolve`] (requires `resolve` feature) * `oas_sdk::attestation_crate` → \[`oas_attestation`] ```rust #[cfg(feature = "resolve")] pub mod anchor_policy; ``` Source line: `53`. ## attestation [#attestation] ```rust pub mod attestation; ``` Source line: `54`. ## config [#config] ```rust pub mod config; ``` Source line: `55`. ## error [#error] ```rust pub mod error; ``` Source line: `56`. ## identity [#identity] ```rust pub mod identity; ``` Source line: `57`. ## lineage [#lineage] ```rust pub mod lineage; ``` Source line: `58`. ## pub use oas\_attestation as attestation\_crate; [#pub-use-oas_attestation-as-attestation_crate] ```rust pub use oas_attestation as attestation_crate; ``` Source line: `61`. ## pub use oas\_crypto as crypto; [#pub-use-oas_crypto-as-crypto] ```rust pub use oas_crypto as crypto; ``` Source line: `62`. ## pub use oas\_did as did; [#pub-use-oas_did-as-did] ```rust pub use oas_did as did; ``` Source line: `63`. ## pub use oas\_document as document; [#pub-use-oas_document-as-document] ```rust pub use oas_document as document; ``` Source line: `64`. ## pub use oas\_lineage as lineage\_crate; [#pub-use-oas_lineage-as-lineage_crate] ```rust pub use oas_lineage as lineage_crate; ``` Source line: `65`. ## pub use oas\_resolve as resolve; [#pub-use-oas_resolve-as-resolve] ```rust #[cfg(feature = "resolve")] pub use oas_resolve as resolve; ``` Source line: `67`. ## pub use error::OasError; [#pub-use-erroroaserror] ```rust pub use error::OasError; ``` Source line: `69`. # oas-sdk · error URL: https://docs.openagent.id/reference/rust/oas-sdk/error Markdown: https://docs.openagent.id/reference/rust/oas-sdk/error.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/error.rs`. SHA-256: `0457ecc9696116283584ed709d0dac7459d1d5353fe97385a37f8f6e8b1d5cd8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::OasError [#erroroaserror] Unified error type for OAS SDK operations. Aggregates errors from all underlying crates so callers need only handle one error type. # Examples [#examples] ``` use oas_sdk::error::OasError; fn example() -> Result<(), OasError> { // Any sub-crate error can be converted via `?` Ok(()) } ``` ```rust #[derive(Debug, Error)] pub enum OasError { /// A DID parsing error. #[error("DID error: {0}")] Did(#[from] oas_did::DidError), /// A cryptographic operation error. #[error("crypto error: {0}")] Crypto(#[from] oas_crypto::CryptoError), /// A document operation error. #[error("document error: {0}")] Document(#[from] oas_document::DocumentError), /// A lineage verification error. #[error("lineage error: {0}")] Lineage(#[from] oas_lineage::LineageError), /// A privileged lineage authority verification error. #[error("lineage authority error: {reason}")] LineageAuthority { /// Description of why privileged authority was not accepted. reason: String, }, /// A DID resolution error. #[cfg(feature = "resolve")] #[error("resolve error: {0}")] Resolve(#[from] oas_resolve::ResolveError), /// An attestation operation error. #[error("attestation error: {0}")] Attestation(#[from] oas_attestation::AttestationError), /// A JSON serialization error. #[error("JSON error: {0}")] Json(#[from] serde_json::Error), /// An SDK configuration or usage error. #[error("SDK error: {reason}")] Sdk { /// Description of what went wrong. reason: String, }, } ``` Source line: `25`. # oas-sdk · identity URL: https://docs.openagent.id/reference/rust/oas-sdk/identity Markdown: https://docs.openagent.id/reference/rust/oas-sdk/identity.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/identity.rs`. SHA-256: `654abc5c2246dab8bdf0c0effdd8037ea2551b53ed23f3a535226d5db67183db`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## identity::CreatedIdentity [#identitycreatedidentity] The result of creating a new root identity. Contains the signed identity document and the keypair used to sign it. The caller is responsible for securely storing the keypair. ```rust #[derive(Debug)] pub struct CreatedIdentity { /// The signed OAS Identity Document. pub document: OasDocument, /// The Ed25519 keypair for this identity. pub keypair: OasKeyPair } ``` Source line: `19`. ## identity::create\_hmr [#identitycreate_hmr] Creates a new Human Root (HMR) identity. Generates a fresh Ed25519 keypair, constructs an OAS Identity Document for a `did:oas::hmr:` DID, and signs it. # Arguments [#arguments] * `namespace` - The OAS namespace (e.g., `"l1fe"`, `"test"`). * `identifier` - The unique identifier within the namespace. * `created` - ISO 8601 timestamp for the document metadata. # Returns [#returns] A \[`CreatedIdentity`] containing the signed document and keypair. # Errors [#errors] Returns \[`OasError`] if DID construction or document building fails. # Examples [#examples] ``` use oas_sdk::identity::create_hmr; let identity = create_hmr("test", "alice", "2026-01-15T00:00:00Z"); assert!(identity.is_ok()); let identity = identity.unwrap(); assert_eq!(identity.document.id, "did:oas:test:hmr:alice"); ``` ```rust pub fn create_hmr( namespace: &str, identifier: &str, created: &str, ) -> Result; ``` Source line: `55`. ## identity::create\_mhr [#identitycreate_mhr] Creates a new Multi-Human Root (MHR) identity. Similar to \[`create_hmr`] but for multi-human threshold root entities. MHR identities use `did:oas::mhr:`. # Arguments [#arguments-1] * `namespace` - The OAS namespace (e.g., `"l1fe"`, `"test"`). * `identifier` - The unique identifier within the namespace. * `created` - ISO 8601 timestamp for the document metadata. # Returns [#returns-1] A \[`CreatedIdentity`] containing the signed document and keypair. # Errors [#errors-1] Returns \[`OasError`] if DID construction or document building fails. # Examples [#examples-1] ``` use oas_sdk::identity::create_mhr; let identity = create_mhr("test", "system1", "2026-01-15T00:00:00Z"); assert!(identity.is_ok()); let identity = identity.unwrap(); assert_eq!(identity.document.id, "did:oas:test:mhr:system1"); ``` ```rust pub fn create_mhr( namespace: &str, identifier: &str, created: &str, ) -> Result; ``` Source line: `101`. ## identity::create\_root\_with\_keypair [#identitycreate_root_with_keypair] Creates a new root identity with a pre-existing keypair. Use this when you need to control the keypair (e.g., loading from storage). # Arguments [#arguments-2] * `namespace` - The OAS namespace. * `kind` - The entity kind (`"hmr"` or `"mhr"`). * `identifier` - The unique identifier. * `keypair` - The Ed25519 keypair to use. * `created` - ISO 8601 timestamp. # Returns [#returns-2] A signed \[`OasDocument`]. # Errors [#errors-2] Returns \[`OasError`] if document building fails. # Examples [#examples-2] ``` use oas_sdk::identity::create_root_with_keypair; use oas_crypto::keypair::OasKeyPair; let keypair = OasKeyPair::generate(); let doc = create_root_with_keypair("test", "hmr", "alice", &keypair, "2026-01-15T00:00:00Z"); assert!(doc.is_ok()); ``` ```rust pub fn create_root_with_keypair( namespace: &str, kind: &str, identifier: &str, keypair: &OasKeyPair, created: &str, ) -> Result; ``` Source line: `148`. # oas-sdk modules URL: https://docs.openagent.id/reference/rust/oas-sdk Markdown: https://docs.openagent.id/reference/rust/oas-sdk.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-sdk). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-sdk/crate) — 13 declarations * [anchor\_policy](/reference/rust/oas-sdk/anchor_policy) — 8 declarations * [attestation](/reference/rust/oas-sdk/attestation) — 3 declarations * [config](/reference/rust/oas-sdk/config) — 15 declarations * [error](/reference/rust/oas-sdk/error) — 1 declarations * [identity](/reference/rust/oas-sdk/identity) — 4 declarations * [lineage](/reference/rust/oas-sdk/lineage) — 10 declarations # oas-sdk · lineage URL: https://docs.openagent.id/reference/rust/oas-sdk/lineage Markdown: https://docs.openagent.id/reference/rust/oas-sdk/lineage.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-sdk/src/lineage.rs`. SHA-256: `dfb1c98b450d92cbca537fbbb0b1c744efda2674b3b83ba27dafa2ae5557a988`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## lineage::DerivedIdentity [#lineagederivedidentity] The result of deriving a child entity. Contains the signed child identity document and the derived keypair. ```rust #[derive(Debug)] pub struct DerivedIdentity { /// The signed child OAS Identity Document (with lineage section). pub document: OasDocument, /// The derived Ed25519 keypair for this child entity. pub keypair: OasKeyPair } ``` Source line: `22`. ## lineage::AuthorityPathKind [#lineageauthoritypathkind] A required privileged authority path shape. OAS keeps this intentionally small and stringly-extensible so downstream systems can add product-specific paths without forking lineage semantics. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub enum AuthorityPathKind { /// Human root delegates authority to an agent. HumanToAgent, /// Agent acts on behalf of an organization. AgentToOrg, /// Organization delegates authority to an agent. OrgToAgent, /// Agent acts toward a human subject. AgentToHuman, /// Deployment-specific path kind. Custom(String), } ``` Source line: `34`. ## lineage::AuthorityPathKind::as\_str [#lineageauthoritypathkindas_str] Stable wire label for this path kind. ```rust pub fn as_str(&self) -> &str; ``` Source line: `49`. ## lineage::LineageAuthorityRequest [#lineagelineageauthorityrequest] Request passed from OAS into a Sigil-backed lineage authority source. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct LineageAuthorityRequest { /// DID whose authority is being checked. pub subject_did: String, /// Root DID proven by portable/local lineage verification. pub local_root_did: String, /// Local chain as declared by the document, ordered root to subject when known. pub local_chain: Vec, /// Required privileged path kind. pub path_kind: AuthorityPathKind, /// Scopes the caller wants this lineage path to authorize. pub required_scopes: Vec, /// Optional lower bound for acceptable Sigil finality. pub min_finalized_block: Option } ``` Source line: `62`. ## lineage::LineageAuthorityRecord [#lineagelineageauthorityrecord] Sigil-backed authority record returned by a lineage finality source. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct LineageAuthorityRecord { /// DID whose authority was verified. pub subject_did: String, /// Finalized root DID for the verified authority path. pub root_did: String, /// Reconstructed finalized path, ordered root to subject. pub finalized_path: Vec, /// Sigil block height at which the authority proof is finalized. pub finalized_block: u64, /// Backend/source identifier, e.g. "sigil_gal". pub source: String, /// Scopes proven for this path. pub scopes: Vec, /// Optional authority expiry timestamp. pub expires_at: Option } ``` Source line: `79`. ## lineage::LineageAuthorityVerification [#lineagelineageauthorityverification] Result of privileged lineage authority verification. ```rust #[derive(Debug, Clone)] pub struct LineageAuthorityVerification { /// Portable local lineage verification result. pub portable: VerifyResult, /// Sigil-backed finality record. pub authority: LineageAuthorityRecord } ``` Source line: `98`. ## lineage::LineageAuthoritySource [#lineagelineageauthoritysource] Backend that proves privileged lineage authority. Production implementations are expected to query Sigil GAL or verify a fresh proof/cache of Sigil GAL state. Implementations must fail closed: returning an error means the privileged action is not authorized. ```rust pub trait LineageAuthoritySource { /// Verify the requested path against finalized lineage state. fn verify_authority( &self, request: &LineageAuthorityRequest, ) -> Result; } ``` Source line: `110`. ## lineage::derive\_child [#lineagederive_child] Derives a child entity from a parent identity. Performs HKDF-SHA256 key derivation, constructs a lineage proof, builds the child document with the lineage section, and signs it. # Arguments [#arguments] * `parent_keypair` - The parent's Ed25519 keypair. * `parent_doc` - The parent's signed OAS Identity Document. * `child_namespace` - The child's namespace (often same as parent). * `child_kind` - The child's entity kind (e.g., `"agent"`, `"tool"`). * `child_identifier` - The child's unique identifier. * `derivation_path` - The HKDF derivation path string. * `created` - ISO 8601 timestamp. # Returns [#returns] A \[`DerivedIdentity`] containing the signed child document and derived keypair. # Errors [#errors] Returns \[`OasError`] if key derivation, document building, or signing fails. # Examples [#examples] ``` use oas_sdk::identity::create_hmr; use oas_sdk::lineage::derive_child; let parent = create_hmr("test", "alice", "2026-01-15T00:00:00Z").unwrap(); let child = derive_child( &parent.keypair, &parent.document, "test", "agent", "analyzer", "agent/analyzer", "2026-01-15T00:00:00Z", ); assert!(child.is_ok()); let child = child.unwrap(); assert_eq!(child.document.id, "did:oas:test:agent:analyzer"); assert!(child.document.lineage.is_some()); ``` ```rust pub fn derive_child( parent_keypair: &OasKeyPair, parent_doc: &OasDocument, child_namespace: &str, child_kind: &str, child_identifier: &str, derivation_path: &str, created: &str, ) -> Result; ``` Source line: `162`. ## lineage::verify\_chain [#lineageverify_chain] Verifies a lineage chain for a given document. Walks the chain from the child to the root, verifying each hop's AgentLineageProof2025 signature. # Arguments [#arguments-1] * `document` - The document whose lineage to verify. * `provider` - A provider that can resolve parent DIDs to documents. * `config` - Verification configuration (timeouts, max depth). # Returns [#returns-1] A \[`VerifyResult`] on success. # Errors [#errors-1] Returns \[`OasError::Lineage`] if verification fails. # Examples [#examples-1] ``` use oas_sdk::identity::create_hmr; use oas_sdk::lineage::{derive_child, verify_chain}; use oas_lineage::provider::InMemoryProvider; use oas_lineage::config::{TrustAnchor, VerifyConfig}; let parent = create_hmr("test", "alice", "2026-01-15T00:00:00Z").unwrap(); let child = derive_child( &parent.keypair, &parent.document, "test", "agent", "bot", "agent/bot", "2026-01-15T00:00:00Z", ).unwrap(); let mut provider = InMemoryProvider::new(); provider.register(parent.document.clone()); let anchor = TrustAnchor::new( &parent.document.id, format!("{}#key-1", parent.document.id), parent.keypair.public_key_multibase(), ).with_document_digest(parent.document.canonical_digest().unwrap()); let config = VerifyConfig::new().with_trust_anchor(anchor); let result = verify_chain(&child.document, &provider, &config); assert!(result.is_ok()); ``` ```rust pub fn verify_chain( document: &OasDocument, provider: &dyn DocumentProvider, config: &VerifyConfig, ) -> Result; ``` Source line: `241`. ## lineage::verify\_privileged\_authority [#lineageverify_privileged_authority] Verifies local lineage and then requires Sigil-backed privileged authority. This is the SDK-level contract downstream systems should call before issuing ACTs, credentials, sessions, org membership, wallet authority, or other privileged access. If the authority source is unavailable or rejects the request, this function fails closed. ```rust pub fn verify_privileged_authority( document: &OasDocument, provider: &dyn DocumentProvider, config: &VerifyConfig, authority_source: &dyn LineageAuthoritySource, path_kind: AuthorityPathKind, required_scopes: &[String], min_finalized_block: Option, ) -> Result; ``` Source line: `255`. # openagent-aegis-core · crate URL: https://docs.openagent.id/reference/rust/openagent-aegis-core/crate Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-core/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-core/src/lib.rs`. SHA-256: `88d7730fc7e6ae32363a1c3e20c911711e49b185bd5482f35302a01053d22c78`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error [#error] ```rust pub mod error; ``` Source line: `8`. ## plugin [#plugin] ```rust pub mod plugin; ``` Source line: `9`. ## types [#types] ```rust pub mod types; ``` Source line: `10`. ## pub use error::\*; [#pub-use-error] ```rust pub use error::*; ``` Source line: `12`. ## pub use plugin::\*; [#pub-use-plugin] ```rust pub use plugin::*; ``` Source line: `13`. ## pub use types::\*; [#pub-use-types] ```rust pub use types::*; ``` Source line: `14`. # openagent-aegis-core · error URL: https://docs.openagent.id/reference/rust/openagent-aegis-core/error Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-core/error.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-core/src/error.rs`. SHA-256: `de788643c270b4ca24b0ecb740416c4c537f2576e7bbe7f3730ceb6a409e6938`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::ResolverError [#errorresolvererror] Errors from the DID Resolver plugin interface (AEGIS Spec §4.1). ```rust #[derive(Debug, Error)] pub enum ResolverError { /// DID does not exist in the resolver's namespace. #[error("DID not found: {did}")] NotFound { did: String }, /// DID string is malformed. #[error("invalid DID format: {reason}")] InvalidFormat { reason: String }, /// Resolution did not complete within the timeout. #[error("resolution timed out after {timeout_ms}ms for DID: {did}")] ResolutionTimeout { did: String, timeout_ms: u64 }, /// DID has been deactivated. #[error("DID has been deactivated: {did}")] Deactivated { did: String }, /// Resolution failed due to network issues. #[error("network error resolving DID {did}: {reason}")] NetworkError { did: String, reason: String }, /// This resolver does not support DID creation. #[error("DID creation not supported by this resolver")] CreationNotSupported, /// This resolver does not support DID updates. #[error("DID update not supported by this resolver")] UpdateNotSupported, /// This resolver does not support DID deactivation. #[error("DID deactivation not supported by this resolver")] DeactivationNotSupported, } ``` Source line: `10`. ## error::AuthError [#errorautherror] Errors from the Auth Provider plugin interface (AEGIS Spec §4.2). ```rust #[derive(Debug, Error)] pub enum AuthError { /// The credential is invalid or could not be verified. #[error("invalid credential: {reason}")] InvalidCredential { reason: String }, /// The credential has expired. #[error("credential expired at {expired_at}")] CredentialExpired { expired_at: String }, /// The session has been revoked. #[error("session revoked: {session_id}")] SessionRevoked { session_id: String }, /// The session has expired. #[error("session expired: {session_id}")] SessionExpired { session_id: String }, /// The challenge has expired or is invalid. #[error("challenge invalid: {reason}")] ChallengeInvalid { reason: String }, /// The provider is unavailable. #[error("auth provider unavailable: {provider}")] ProviderUnavailable { provider: String }, /// Refresh is not supported by this provider. #[error("refresh not supported by provider: {provider}")] RefreshNotSupported { provider: String }, /// Revocation is not supported by this provider. #[error("revocation not supported by provider: {provider}")] RevocationNotSupported { provider: String }, /// Internal error within the auth provider. #[error("auth provider internal error: {reason}")] Internal { reason: String }, } ``` Source line: `46`. ## error::PolicyError [#errorpolicyerror] Errors from the Policy Engine plugin interface (AEGIS Spec §4.3). ```rust #[derive(Debug, Error)] pub enum PolicyError { /// Policy evaluation failed. #[error("policy evaluation failed: {reason}")] EvaluationFailed { reason: String }, /// Policy engine timed out (must complete within 100ms). #[error("policy evaluation timed out after {timeout_ms}ms")] Timeout { timeout_ms: u64 }, /// Policy engine is unavailable — fail closed. #[error("policy engine unavailable; denying request (fail-closed)")] EngineUnavailable, /// No policy engine is registered. #[error("no policy engine registered; denying request (fail-closed)")] NoPolicyEngine, /// Policy configuration error. #[error("policy configuration error: {reason}")] ConfigError { reason: String }, } ``` Source line: `86`. ## error::VerificationError [#errorverificationerror] Errors from the Verification Infrastructure (AEGIS Spec §5). ```rust #[derive(Debug, Error)] pub enum VerificationError { /// DID resolution failed. #[error("resolution failed for {did}: {reason}")] ResolutionFailed { did: String, reason: String }, /// OAS schema validation failed. #[error("schema validation failed for {did}: {reason}")] InvalidSchema { did: String, reason: String }, /// Document signature is invalid. #[error("invalid document signature for {did}")] InvalidSignature { did: String }, /// Lineage chain verification failed. #[error("lineage verification failed for {did}: {reason}")] LineageFailed { did: String, reason: String }, /// Maximum lineage depth exceeded. #[error("lineage depth {depth} exceeds maximum {max_depth} for {did}")] MaxDepthExceeded { did: String, depth: u32, max_depth: u32, }, /// Identity has been revoked. #[error("identity revoked: {did}")] Revoked { did: String }, /// Identity has been suspended. #[error("identity suspended: {did}")] Suspended { did: String }, /// Human root revoked — entire lineage invalid. #[error("human root {human_root} has been revoked")] HumanRootRevoked { human_root: String }, /// Lineage generation number mismatch. #[error("generation mismatch for {did}: expected {expected}, found {found}")] GenerationMismatch { did: String, expected: u32, found: u32, }, /// Verification timed out. #[error("verification timed out for {did}")] Timeout { did: String }, /// Consistency violation between registries. #[error("consistency violation for {did}: {reason}")] ConsistencyViolation { did: String, reason: String }, } ``` Source line: `110`. ## error::KeyError [#errorkeyerror] Errors from the Key Management Framework (AEGIS Spec §6). ```rust #[derive(Debug, Error)] pub enum KeyError { /// Key generation failed. #[error("key generation failed: {reason}")] GenerationFailed { reason: String }, /// Key derivation failed. #[error("key derivation failed: {reason}")] DerivationFailed { reason: String }, /// Key rotation failed. #[error("key rotation failed: {reason}")] RotationFailed { reason: String }, /// Key recovery failed. #[error("key recovery failed: {reason}")] RecoveryFailed { reason: String }, /// MPC ceremony failed. #[error("MPC ceremony failed: {reason}")] MpcFailed { reason: String }, /// Key not found. #[error("key not found: {key_id}")] NotFound { key_id: String }, /// Key storage error. #[error("key storage error: {reason}")] StorageError { reason: String }, /// Signing operation failed. #[error("signing failed: {reason}")] SigningFailed { reason: String }, /// Unsupported key type. #[error("unsupported key type: {key_type}")] UnsupportedKeyType { key_type: String }, } ``` Source line: `166`. ## error::DelegationError [#errordelegationerror] Errors from the Delegation Model (AEGIS Spec §9). ```rust #[derive(Debug, Error)] pub enum DelegationError { /// Delegation proof is invalid. #[error("invalid delegation proof: {reason}")] InvalidProof { reason: String }, /// Delegation has been revoked. #[error("delegation {delegation_id} has been revoked")] Revoked { delegation_id: String }, /// Delegation has expired. #[error("delegation {delegation_id} has expired")] Expired { delegation_id: String }, /// Delegation depth exceeds maximum. #[error("delegation depth {depth} exceeds maximum {max_depth}")] MaxDepthExceeded { depth: u32, max_depth: u32 }, /// Scope amplification attempted — delegate cannot exceed delegator. #[error("scope amplification not permitted: {reason}")] ScopeAmplification { reason: String }, /// Delegator not found. #[error("delegator not found: {did}")] DelegatorNotFound { did: String }, /// Delegate not found. #[error("delegate not found: {did}")] DelegateNotFound { did: String }, } ``` Source line: `206`. ## error::WalletError [#errorwalleterror] Errors from the Wallet Infrastructure (AEGIS Spec §10). ```rust #[derive(Debug, Error)] pub enum WalletError { /// Transaction authorization failed. #[error("transaction authorization failed: {reason}")] AuthorizationFailed { reason: String }, /// Signing ceremony failed. #[error("signing ceremony failed: {reason}")] SigningFailed { reason: String }, /// Unsupported chain. #[error("unsupported chain: {chain}")] UnsupportedChain { chain: String }, /// Address derivation failed. #[error("address derivation failed for chain {chain}: {reason}")] DerivationFailed { chain: String, reason: String }, /// Policy denied the transaction. #[error("transaction denied by policy: {reason}")] PolicyDenied { reason: String }, /// Obligation could not be fulfilled. #[error("obligation fulfillment failed: {reason}")] ObligationFailed { reason: String }, /// Batch operation partially failed. #[error("batch operation failed: {succeeded} of {total} transactions succeeded")] BatchPartialFailure { succeeded: usize, total: usize }, } ``` Source line: `238`. # openagent-aegis-core modules URL: https://docs.openagent.id/reference/rust/openagent-aegis-core Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-core.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-openagent-aegis-core). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/openagent-aegis-core/crate) — 6 declarations * [error](/reference/rust/openagent-aegis-core/error) — 7 declarations * [plugin](/reference/rust/openagent-aegis-core/plugin) — 20 declarations * [types](/reference/rust/openagent-aegis-core/types) — 40 declarations # openagent-aegis-core · plugin URL: https://docs.openagent.id/reference/rust/openagent-aegis-core/plugin Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-core/plugin.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-core/src/plugin.rs`. SHA-256: `31309c020db740be017aadfba79c93a91f34f46791eca5b9801d67ff4d0a365a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## plugin::CreateDidParams [#plugincreatedidparams] Parameters for creating a new DID. ```rust #[derive(Debug, Clone)] pub struct CreateDidParams { /// Entity kind (human, agent, organization). pub entity_kind: String, /// Namespace for the DID. pub namespace: String, /// Unique identifier within the namespace. pub identifier: String, /// Additional creation parameters. pub metadata: HashMap } ``` Source line: `25`. ## plugin::DidCreationResult [#plugindidcreationresult] Result of creating a new DID. ```rust #[derive(Debug, Clone)] pub struct DidCreationResult { /// The created DID string. pub did: String, /// The initial OAS Identity Document. pub document: OasDocument } ``` Source line: `38`. ## plugin::DidResolver [#plugindidresolver] DID Resolver plugin interface (AEGIS Spec §4.1). Enables AEGIS to resolve any DID method without coupling to a specific resolution mechanism. Each resolver handles one or more DID methods. ```rust #[async_trait] pub trait DidResolver: Send + Sync { /// Resolve a DID to its DID Document. /// /// MUST return a valid OAS Document or an error. /// MUST complete within 5 seconds (SHOULD within 3 seconds). async fn resolve(&self, did: &str) -> Result; /// Check if this resolver handles the given DID. fn handles(&self, did: &str) -> bool; /// List supported DID methods (e.g., ["oas", "key"]). fn supported_methods(&self) -> Vec; /// Create a new DID (optional — not all resolvers support creation). async fn create(&self, _params: CreateDidParams) -> Result ; /// Update a DID Document (optional). async fn update(&self, _did: &str, _document: OasDocument) -> Result<(), ResolverError> ; /// Deactivate a DID (optional). async fn deactivate(&self, _did: &str) -> Result<(), ResolverError> ; } ``` Source line: `50`. ## plugin::AuthProvider [#pluginauthprovider] Auth Provider plugin interface (AEGIS Spec §4.2). Validates credentials and returns authentication context. Each provider handles specific credential types (OAuth, challenge-response, API keys, etc.). ```rust #[async_trait] pub trait AuthProvider: Send + Sync { /// Validate a credential and return auth context. /// /// MUST return a valid `AuthContext` or an error. /// MUST verify cryptographic integrity of the credential. async fn validate(&self, credential: &AuthCredential) -> Result; /// Get identity information from auth context. async fn get_identity(&self, ctx: &AuthContext) -> Result; /// Get the provider identifier. fn provider_name(&self) -> &str; /// Refresh a session or token (optional). async fn refresh(&self, _ctx: &AuthContext) -> Result ; /// Revoke a session (optional). async fn revoke(&self, _ctx: &AuthContext) -> Result<(), AuthError> ; } ``` Source line: `88`. ## plugin::PolicyEngine [#pluginpolicyengine] Policy Engine plugin interface (AEGIS Spec §4.3). Evaluates authorization decisions. Only one policy engine is active at any time. If unavailable, AEGIS MUST fail-closed (deny all). ```rust #[async_trait] pub trait PolicyEngine: Send + Sync { /// Evaluate a policy request. /// /// MUST return a `PolicyDecision` including allowed/denied and obligations. /// MUST complete within 100ms (SHOULD within 50ms). /// Evaluation MUST be deterministic. async fn evaluate(&self, request: &PolicyRequest) -> Result; /// Simple permission check (convenience wrapper). async fn check_permission(&self, check: &PermissionCheck) -> Result; /// Get the engine identifier. fn engine_name(&self) -> &str; /// List policies for an identity (optional). async fn get_policies(&self, _did: &str) -> Result, PolicyError> ; } ``` Source line: `125`. ## plugin::PluginRegistry [#pluginpluginregistry] The Plugin Registry manages all loaded plugins and routes requests to the appropriate plugin (AEGIS Spec §4.4). Requirements: * Supports multiple DID Resolvers (routes by `handles()` method matching). * Supports multiple Auth Providers (keyed by `provider_name()`). * Supports exactly one Policy Engine. * Plugin registration order is deterministic. ```rust pub struct PluginRegistry { } ``` Source line: `157`. ## plugin::PluginRegistry::new [#pluginpluginregistrynew] Create an empty plugin registry. ```rust pub fn new() -> Self; ``` Source line: `168`. ## plugin::PluginRegistry::register\_resolver [#pluginpluginregistryregister_resolver] Register a DID Resolver plugin. Resolvers are tried in registration order. The first resolver whose `handles()` returns true for a given DID is used. ```rust pub fn register_resolver(&mut self, resolver: Arc); ``` Source line: `180`. ## plugin::PluginRegistry::register\_auth\_provider [#pluginpluginregistryregister_auth_provider] Register an Auth Provider plugin. Providers are keyed by `provider_name()`. Registering a provider with the same name replaces the previous one. ```rust pub fn register_auth_provider(&mut self, provider: Arc); ``` Source line: `188`. ## plugin::PluginRegistry::set\_policy\_engine [#pluginpluginregistryset_policy_engine] Set the active Policy Engine plugin. Only one policy engine may be active. Setting a new one replaces the previous engine. ```rust pub fn set_policy_engine(&mut self, engine: Arc); ``` Source line: `197`. ## plugin::PluginRegistry::resolve\_did [#pluginpluginregistryresolve_did] Resolve a DID by routing to the appropriate resolver. Iterates over registered resolvers in order and uses the first resolver whose `handles()` method returns true. ```rust pub async fn resolve_did(&self, did: &str) -> Result; ``` Source line: `205`. ## plugin::PluginRegistry::validate\_credential [#pluginpluginregistryvalidate_credential] Validate a credential by routing to the named provider, or trying each provider if no explicit name is given. ```rust pub async fn validate_credential( &self, credential: &AuthCredential, provider_name: Option<&str>, ) -> Result; ``` Source line: `218`. ## plugin::PluginRegistry::evaluate\_policy [#pluginpluginregistryevaluate_policy] Evaluate a policy request. If no policy engine is registered, MUST fail-closed. ```rust pub async fn evaluate_policy( &self, request: &PolicyRequest, ) -> Result; ``` Source line: `249`. ## plugin::PluginRegistry::check\_permission [#pluginpluginregistrycheck_permission] Simple permission check via the policy engine. ```rust pub async fn check_permission(&self, check: &PermissionCheck) -> Result; ``` Source line: `260`. ## plugin::PluginRegistry::get\_resolver\_for [#pluginpluginregistryget_resolver_for] Get a DID resolver by DID method. ```rust pub fn get_resolver_for(&self, did: &str) -> Option<&Arc>; ``` Source line: `268`. ## plugin::PluginRegistry::get\_auth\_provider [#pluginpluginregistryget_auth_provider] Get an auth provider by name. ```rust pub fn get_auth_provider(&self, name: &str) -> Option<&Arc>; ``` Source line: `273`. ## plugin::PluginRegistry::get\_policy\_engine [#pluginpluginregistryget_policy_engine] Get the active policy engine. ```rust pub fn get_policy_engine(&self) -> Option<&Arc>; ``` Source line: `278`. ## plugin::PluginRegistry::resolver\_count [#pluginpluginregistryresolver_count] Returns the number of registered DID resolvers. ```rust pub fn resolver_count(&self) -> usize; ``` Source line: `283`. ## plugin::PluginRegistry::auth\_provider\_count [#pluginpluginregistryauth_provider_count] Returns the number of registered auth providers. ```rust pub fn auth_provider_count(&self) -> usize; ``` Source line: `288`. ## plugin::PluginRegistry::has\_policy\_engine [#pluginpluginregistryhas_policy_engine] Returns true if a policy engine is registered. ```rust pub fn has_policy_engine(&self) -> bool; ``` Source line: `293`. # openagent-aegis-core · types URL: https://docs.openagent.id/reference/rust/openagent-aegis-core/types Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-core/types.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-core/src/types.rs`. SHA-256: `180fdeda863a1f5e2265e1497a1672861899b783630464af1ecbeeb940e60c6b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## types::AuthContext [#typesauthcontext] The output of successful authentication (AEGIS Spec §7.1). Produced by an Auth Provider plugin and consumed by the Policy Engine. Bridges "who is this entity?" to "what may this entity do?" ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuthContext { /// Name of the Auth Provider that validated this credential. pub provider: String, /// Unique identifier within the provider's namespace. pub subject: String, /// Resolved DID for the authenticated entity. pub did: Option, /// Session identifier for stateful authentication. pub session_id: Option, /// Expiration time of this authentication context. pub expires_at: Option>, /// Provider-specific claims (opaque to AEGIS core). #[serde(default)] pub claims: HashMap } ``` Source line: `24`. ## types::AegisIdentity [#typesaegisidentity] Identity information extracted from authentication. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AegisIdentity { /// The entity's DID. pub did: String, /// Entity kind (human, agent, organization, delegated). pub identity_type: IdentityType, /// Display name if available. pub display_name: Option, /// Verified conformance level. pub conformance_level: Option } ``` Source line: `42`. ## types::IdentityType [#typesidentitytype] The type of entity being authenticated. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum IdentityType { Human, Agent, Organization, /// Enterprise identity governed by an MHR (ENR entity). Enterprise, Delegated, } ``` Source line: `56`. ## types::AuthCredential [#typesauthcredential] Credential types supported by AEGIS (AEGIS Spec §7.2). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum AuthCredential { /// Opaque bearer token (OAuth2, JWT). BearerToken { token: String }, /// HTTP session cookie. SessionCookie { cookie: String }, /// Long-lived API key. ApiKey { key: String }, /// Challenge signed with identity key (AEGIS Spec §7.3). SignedChallenge { did: String, challenge: String, signature: String, timestamp: String, nonce: String, }, /// Scoped, time-bounded capability token. CapabilityToken { token: String }, /// WebAuthn/FIDO2 passkey assertion. PasskeyAssertion { credential_id: String, authenticator_data: String, client_data_json: String, signature: String, }, /// Plugin-defined custom credential type. Custom { provider: String, data: serde_json::Value, }, } ``` Source line: `68`. ## types::Session [#typessession] Session token structure (AEGIS Spec §7.4). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Session { /// Unique session identifier. pub session_id: String, /// DID of the authenticated entity. pub did: String, /// Auth Provider that issued this session. pub provider: String, /// Session creation time. pub created_at: DateTime, /// Session expiration time. pub expires_at: DateTime, /// Authorized scopes for this session. #[serde(default)] pub scope: Vec, /// Optional device fingerprint binding. pub device_binding: Option } ``` Source line: `101`. ## types::PolicyRequest [#typespolicyrequest] Policy request structure (AEGIS Spec §8.1). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PolicyRequest { /// DID of the entity requesting the action. pub principal: String, /// The action being requested. pub action: String, /// The resource being acted upon. pub resource: String, /// Additional context for policy evaluation. pub context: PolicyContext } ``` Source line: `125`. ## types::PolicyContext [#typespolicycontext] Context provided alongside a policy request. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PolicyContext { /// Authentication context. pub auth_context: Option, /// Verified lineage chain summary. pub lineage: Option, /// Entity's verified conformance level. pub conformance_level: Option, /// Current session information. pub session: Option, /// Additional key-value context. #[serde(default)] pub extra: HashMap } ``` Source line: `138`. ## types::LineageSummary [#typeslineagesummary] Summary of a verified lineage chain. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LineageSummary { /// Number of hops to human root. pub depth: u32, /// DID of the human root. pub human_root: String, /// Whether the lineage was cryptographically verified. pub verified: bool } ``` Source line: `154`. ## types::PolicyDecision [#typespolicydecision] Policy decision structure (AEGIS Spec §8.2). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PolicyDecision { /// Whether the action is permitted. pub allowed: bool, /// Human-readable explanation. pub reason: Option, /// Actions that MUST be performed if allowed. #[serde(default)] pub obligations: Vec, /// Audit-relevant metadata. pub audit_info: AuditInfo } ``` Source line: `165`. ## types::Obligation [#typesobligation] An obligation that MUST be fulfilled (AEGIS Spec §8.3). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Obligation { /// Obligation type. pub obligation_type: ObligationType, /// Obligation-specific parameters. #[serde(default)] pub params: HashMap, /// Deadline for fulfillment (ISO 8601 duration). pub deadline: Option } ``` Source line: `179`. ## types::ObligationType [#typesobligationtype] Obligation types (AEGIS Spec §8.3). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ObligationType { /// Record the operation in an audit log. Log, /// Notify the human root or designated monitor. Notify, /// Obtain explicit approval before proceeding. Approve, /// Place funds in escrow pending confirmation. Escrow, /// Apply a rate or amount limit. Limit, } ``` Source line: `192`. ## types::AuditInfo [#typesauditinfo] Audit information attached to policy decisions. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuditInfo { /// Unique ID for this audit event. pub audit_id: Uuid, /// Timestamp of the decision. pub timestamp: DateTime, /// Policy engine that produced the decision. pub engine: String, /// Policies that were evaluated. #[serde(default)] pub policies_evaluated: Vec } ``` Source line: `207`. ## types::PermissionCheck [#typespermissioncheck] Permission check (simplified policy query). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PermissionCheck { /// DID of the entity. pub principal: String, /// The permission to check. pub permission: String, /// The resource scope. pub resource: Option } ``` Source line: `221`. ## types::RevocationStatus [#typesrevocationstatus] Revocation status values (AEGIS Spec §5.4). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RevocationStatus { /// Identity is valid and not revoked. Active, /// Identity has been explicitly revoked. Revoked, /// Identity is temporarily suspended. Suspended, /// Identity has passed its expiration date. Expired, /// Revocation status cannot be determined. Unknown, } ``` Source line: `237`. ## types::LivenessStatus [#typeslivenessstatus] Liveness status (AEGIS Spec §5.5). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum LivenessStatus { /// Human root demonstrated liveness within the configured period. Active, /// Liveness period exceeded — warning issued. Warning, /// Liveness period significantly exceeded — identity is stale. Stale, /// Liveness status cannot be determined. Unknown, } ``` Source line: `253`. ## types::VerificationResult [#typesverificationresult] Verification result structure (AEGIS Spec §5.7). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VerificationResult { /// The verified DID. pub did: String, /// Whether the document signature is valid. pub signature_valid: bool, /// Whether the lineage chain is valid. pub lineage_valid: bool, /// Number of hops to human root. pub lineage_depth: u32, /// DID of the human root. pub human_root: Option, /// Current revocation status. pub revocation_status: RevocationStatus, /// Liveness status. pub liveness_status: LivenessStatus, /// Verified conformance level (0, 1, or 2). pub conformance_level: u8, /// Non-fatal warnings. #[serde(default)] pub warnings: Vec, /// Timestamp of verification. pub verified_at: DateTime } ``` Source line: `266`. ## types::VerificationConfig [#typesverificationconfig] Verification pipeline configuration. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VerificationConfig { /// Maximum lineage depth (default: 16). #[serde(default = "default_max_lineage_depth")] pub max_lineage_depth: u32, /// Per-hop timeout in seconds (default: 5). #[serde(default = "default_per_hop_timeout")] pub per_hop_timeout_secs: u64, /// Total verification timeout in seconds (default: 30). #[serde(default = "default_total_timeout")] pub total_timeout_secs: u64, /// Verification cache TTL in seconds (default: 300). #[serde(default = "default_cache_ttl")] pub cache_ttl_secs: u64, /// Liveness period in days (default: 90). #[serde(default = "default_liveness_period")] pub liveness_period_days: u32, /// Conformance level to verify against. #[serde(default)] pub conformance_level: u8 } ``` Source line: `292`. ## types::Delegation [#typesdelegation] Delegation structure (AEGIS Spec §9.1). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Delegation { /// Unique delegation identifier. pub id: String, /// DID of the entity granting authority. pub delegator: String, /// DID of the entity receiving authority. pub delegate: String, /// Permitted actions, resources, and constraints. pub scope: DelegationScope, /// Delegation creation time. pub created: DateTime, /// Delegation expiration time. pub expires: Option>, /// Whether the delegation can be revoked before expiration. pub revocable: bool, /// Cryptographic proof of the delegation. pub proof: DelegationProof } ``` Source line: `348`. ## types::DelegationScope [#typesdelegationscope] Delegation scope constraints (AEGIS Spec §9.4). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationScope { /// Permitted actions. #[serde(default)] pub actions: Vec, /// Permitted resources (contract addresses, chain names, etc.). #[serde(default)] pub resources: Vec, /// Permitted blockchain networks. #[serde(default)] pub chains: Vec, /// Quantitative constraints. pub limits: Option, /// Time-based constraints. pub temporal: Option } ``` Source line: `369`. ## types::SpendingLimits [#typesspendinglimits] Spending limits for delegation and policy (AEGIS Spec §8.4). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SpendingLimits { /// Maximum value per transaction. pub max_amount: Option, /// Maximum aggregate value per 24-hour period. pub daily_volume: Option, /// Permitted asset types. #[serde(default)] pub asset_allowlist: Vec, /// Permitted destination addresses. #[serde(default)] pub recipient_allowlist: Vec, /// Value above which owner approval is required. pub approval_threshold: Option } ``` Source line: `387`. ## types::TemporalConstraints [#typestemporalconstraints] Temporal policy constraints (AEGIS Spec §8.6). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TemporalConstraints { /// Policy effective start time. pub valid_from: Option>, /// Policy expiration time. pub valid_until: Option>, /// Time-of-day window (business hours). pub active_hours: Option, /// Minimum time between successive operations (ISO 8601 duration). pub cooldown: Option } ``` Source line: `404`. ## types::ActiveHours [#typesactivehours] Active hours window. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ActiveHours { /// Start hour (0–23). pub start_hour: u8, /// End hour (0–23). pub end_hour: u8, /// Timezone (IANA, e.g. "America/New_York"). pub timezone: String } ``` Source line: `417`. ## types::DelegationProof [#typesdelegationproof] Delegation proof (AEGIS Spec §9.7). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DelegationProof { /// Proof type — always "AegisDelegationProof2025". #[serde(rename = "type")] pub proof_type: String, /// Verification method DID URL. pub verification_method: String, /// Proof creation time. pub created: DateTime, /// Base64url-encoded signature. pub jws: String } ``` Source line: `428`. ## types::SessionKey [#typessessionkey] Session key structure (AEGIS Spec §9.3). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionKey { /// The temporary signing public key (multibase-encoded). pub session_key: String, /// DID of the identity this session key represents. pub principal: String, /// Permitted actions and constraints. pub scope: DelegationScope, /// Maximum number of operations. pub max_transactions: Option, /// Creation time. pub created: DateTime, /// Expiration time (REQUIRED, max 24 hours). pub expires: DateTime, /// Signed by the principal's identity key. pub proof: DelegationProof } ``` Source line: `442`. ## types::WalletType [#typeswallettype] Wallet types (AEGIS Spec §10.1). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum WalletType { /// Standard private key-controlled address. Eoa, /// Account abstraction (ERC-4337) with programmable logic. Smart, /// Chain-native account abstraction (Aptos, Sui, StarkNet). Abstract, } ``` Source line: `466`. ## types::Chain [#typeschain] Supported blockchain chains. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Chain { Ethereum, Polygon, Arbitrum, Optimism, Base, Solana, Bitcoin, Cosmos, Osmosis, Aptos, Sui, Starknet, } ``` Source line: `478`. ## types::Chain::coin\_type [#typeschaincoin_type] Returns the BIP-44 coin type for this chain. ```rust pub fn coin_type(&self) -> u32; ``` Source line: `495`. ## types::Chain::derivation\_standard [#typeschainderivation_standard] Returns the derivation standard name. ```rust pub fn derivation_standard(&self) -> &'static str; ``` Source line: `508`. ## types::SigningMode [#typessigningmode] Signing ceremony mode (AEGIS Spec §10.3). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SigningMode { /// Single party holds the complete key. Direct, /// Multiple parties participate via MPC. Mpc, /// Key resides in a TEE enclave. Tee, /// External key management system. External, } ``` Source line: `519`. ## types::BatchMode [#typesbatchmode] Batch operation mode (AEGIS Spec §10.6). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum BatchMode { /// All transactions must succeed or none are signed. AllOrNothing, /// Sign only the authorized transactions. BestEffort, } ``` Source line: `533`. ## types::KeyRole [#typeskeyrole] Key types and roles (AEGIS Spec §6.1). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum KeyRole { /// Primary signing key for OAS Identity Documents. Identity, /// Used in challenge-response authentication. Authentication, /// Signing assertions and attestations. Assertion, /// Signing delegation proofs. Delegation, /// Temporary, scoped signing authority. Session, /// Used in key recovery procedures. Recovery, /// Signing blockchain transactions. Chain, } ``` Source line: `547`. ## types::KeyGenerationMode [#typeskeygenerationmode] Key generation mode (AEGIS Spec §6.2). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum KeyGenerationMode { /// Single party generates and holds the complete key. Direct, /// Distributed key generation via MPC. Mpc, /// Generated inside a TEE enclave. Tee, /// Generated on an HSM. Hsm, } ``` Source line: `567`. ## types::ThresholdConfig [#typesthresholdconfig] MPC threshold configuration (AEGIS Spec §6.3). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ThresholdConfig { /// Minimum shares required (t). pub threshold: u16, /// Total number of shares (n). pub total_shares: u16 } ``` Source line: `580`. ## types::Guardian [#typesguardian] Guardian structure for social recovery (AEGIS Spec §6.7). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Guardian { /// Guardian type. pub guardian_type: GuardianType, /// Guardian identifier (DID, email, phone, or device ID). pub identifier: String, /// Weight toward the recovery threshold. pub weight: u32 } ``` Source line: `589`. ## types::GuardianType [#typesguardiantype] Guardian types for key recovery. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum GuardianType { /// OAS identity (DID). Identity, /// Email address. Email, /// Phone number. Phone, /// Hardware device. Hardware, } ``` Source line: `601`. ## types::MAX\_PAGE\_SIZE [#typesmax_page_size] Maximum items per page. ```rust pub const MAX_PAGE_SIZE: i64; ``` Source line: `617`. ## types::DEFAULT\_PAGE\_SIZE [#typesdefault_page_size] Default items per page. ```rust pub const DEFAULT_PAGE_SIZE: i64; ``` Source line: `620`. ## types::Pagination [#typespagination] Shared pagination parameters for list queries. `limit` is clamped to `1..=MAX_PAGE_SIZE` and `offset` is clamped to `>= 0`. ```rust #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct Pagination { /// Maximum number of items to return (1..=1000). pub limit: i64, /// Number of items to skip (>= 0). pub offset: i64 } ``` Source line: `626`. ## types::Pagination::new [#typespaginationnew] Create a new `Pagination` with clamped values. ```rust pub fn new(limit: i64, offset: i64) -> Self; ``` Source line: `635`. ## types::RecoveryConfig [#typesrecoveryconfig] Social recovery configuration (AEGIS Spec §6.7). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RecoveryConfig { /// Designated recovery guardians. pub guardians: Vec, /// Minimum total weight required for recovery. pub threshold: u32, /// Mandatory delay before recovery executes (ISO 8601 duration). pub timelock: String } ``` Source line: `654`. # oas-wasm · crate URL: https://docs.openagent.id/reference/rust/oas-wasm/crate Markdown: https://docs.openagent.id/reference/rust/oas-wasm/crate.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-wasm/src/lib.rs`. SHA-256: `8d2572603058d7249a6f0778adecaea168d1d4ce07764b7a36ce40c7e6b70f56`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## parse\_did [#parse_did] ```rust pub mod parse_did; ``` Source line: `34`. ## validate\_document [#validate_document] ```rust pub mod validate_document; ``` Source line: `35`. ## verify\_lineage [#verify_lineage] ```rust pub mod verify_lineage; ``` Source line: `36`. ## pub use identity\_bridge::\{create\_hmr, create\_mhr, derive\_child, sign\_message, verify\_signature}; [#pub-use-identity_bridgecreate_hmr-create_mhr-derive_child-sign_message-verify_signature] ```rust pub use identity_bridge::{create_hmr, create_mhr, derive_child, sign_message, verify_signature}; ``` Source line: `38`. # oas-wasm · identity_bridge URL: https://docs.openagent.id/reference/rust/oas-wasm/identity_bridge Markdown: https://docs.openagent.id/reference/rust/oas-wasm/identity_bridge.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-wasm/src/identity_bridge.rs`. SHA-256: `2ca92579395ffd417fd1a0559317fca6bc82204f67e332da73d4b2a4a5bd4843`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## identity\_bridge::create\_hmr [#identity_bridgecreate_hmr] Create a Human Root identity and export the result as JSON. ```rust pub fn create_hmr(input_json: &str) -> String; ``` Source line: `171`. ## identity\_bridge::create\_mhr [#identity_bridgecreate_mhr] Create a Multi-Human Root identity and export the result as JSON. ```rust pub fn create_mhr(input_json: &str) -> String; ``` Source line: `176`. ## identity\_bridge::derive\_child [#identity_bridgederive_child] Derive a child identity and export the result as JSON. ```rust pub fn derive_child(input_json: &str) -> String; ``` Source line: `181`. ## identity\_bridge::sign\_message [#identity_bridgesign_message] Sign a UTF-8 message with a base64url-encoded Ed25519 private key. ```rust pub fn sign_message(input_json: &str) -> String; ``` Source line: `270`. ## identity\_bridge::verify\_signature [#identity_bridgeverify_signature] Verify a UTF-8 message signature against a multibase-encoded public key. ```rust pub fn verify_signature(input_json: &str) -> String; ``` Source line: `302`. # oas-wasm modules URL: https://docs.openagent.id/reference/rust/oas-wasm Markdown: https://docs.openagent.id/reference/rust/oas-wasm.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/oas-oas-oas-wasm). [Focused integration guide](/oas/overview). ## Modules [#modules] * [crate](/reference/rust/oas-wasm/crate) — 4 declarations * [identity\_bridge](/reference/rust/oas-wasm/identity_bridge) — 5 declarations * [parse\_did](/reference/rust/oas-wasm/parse_did) — 3 declarations * [validate\_document](/reference/rust/oas-wasm/validate_document) — 2 declarations * [verify\_lineage](/reference/rust/oas-wasm/verify_lineage) — 3 declarations # oas-wasm · parse_did URL: https://docs.openagent.id/reference/rust/oas-wasm/parse_did Markdown: https://docs.openagent.id/reference/rust/oas-wasm/parse_did.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-wasm/src/parse_did.rs`. SHA-256: `87786ad2c36cd290819ae24aeb347cb4201dfc2fa7d12acf33d8fd25dbc7c21f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## parse\_did::ParsedDid [#parse_didparseddid] Parsed DID components returned from WASM. ```rust #[derive(Debug, Serialize)] pub struct ParsedDid { /// The full DID string. pub did: String, /// The namespace component. pub namespace: String, /// The entity kind. pub kind: String, /// The identifier component. pub identifier: String } ``` Source line: `11`. ## parse\_did::ParseDidResult [#parse_didparsedidresult] Result of a DID parse operation, serialized as JSON. ```rust #[derive(Debug, Serialize)] pub struct ParseDidResult { /// Whether the parse succeeded. pub ok: bool, /// The parsed DID (present if `ok` is true). #[serde(skip_serializing_if = "Option::is_none")] pub parsed: Option, /// Error message (present if `ok` is false). #[serde(skip_serializing_if = "Option::is_none")] pub error: Option } ``` Source line: `24`. ## parse\_did::parse\_did [#parse_didparse_did] Parses a `did:oas` string and returns the result as JSON. This is a synchronous, allocation-friendly function suitable for WASM. # Arguments [#arguments] * `did` - The DID string to parse. # Returns [#returns] A JSON string containing a \[`ParseDidResult`]. # Examples [#examples] ``` use oas_wasm::parse_did::parse_did; let result = parse_did("did:oas:test:agent:bot"); assert!(result.contains("\"ok\":true")); assert!(result.contains("\"kind\":\"agent\"")); let result = parse_did("not-a-did"); assert!(result.contains("\"ok\":false")); ``` ```rust #[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)] pub fn parse_did(did: &str) -> String; ``` Source line: `60`. # oas-wasm · validate_document URL: https://docs.openagent.id/reference/rust/oas-wasm/validate_document Markdown: https://docs.openagent.id/reference/rust/oas-wasm/validate_document.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-wasm/src/validate_document.rs`. SHA-256: `5f4d7cf8a957d95937b2e8327aaed826dfde71262a09247ee57a376096b2f785`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## validate\_document::ValidateDocumentResult [#validate_documentvalidatedocumentresult] Result of a document validation, serialized as JSON. ```rust #[derive(Debug, Serialize)] pub struct ValidateDocumentResult { /// Whether validation passed. pub ok: bool, /// The document's DID (if parsing succeeded). #[serde(skip_serializing_if = "Option::is_none")] pub did: Option, /// The document's entity kind (if parsing succeeded). #[serde(skip_serializing_if = "Option::is_none")] pub kind: Option, /// The document's conformance level (if parsing succeeded). #[serde(skip_serializing_if = "Option::is_none")] pub conformance_level: Option, /// Whether the document has a proof. pub has_proof: bool, /// Validation errors (empty if valid). pub errors: Vec } ``` Source line: `13`. ## validate\_document::validate\_document [#validate_documentvalidate_document] Validates an OAS Identity Document from JSON. Checks: * JSON deserialization * Required fields present * DID format valid * Conformance level field present # Arguments [#arguments] * `document_json` - The document as a JSON string. # Returns [#returns] A JSON string containing a \[`ValidateDocumentResult`]. # Examples [#examples] ``` use oas_wasm::validate_document::validate_document; use oas_crypto::keypair::OasKeyPair; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; let keypair = OasKeyPair::generate(); let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L0) .add_verification_method(&keypair) .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); let json = serde_json::to_string(&doc).unwrap(); let result = validate_document(&json); assert!(result.contains("\"ok\":true")); ``` ```rust #[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)] pub fn validate_document(document_json: &str) -> String; ``` Source line: `67`. # oas-wasm · verify_lineage URL: https://docs.openagent.id/reference/rust/oas-wasm/verify_lineage Markdown: https://docs.openagent.id/reference/rust/oas-wasm/verify_lineage.md Declared module signatures, types, configuration, and source documentation. Source: `oas/oas/oas-wasm/src/verify_lineage.rs`. SHA-256: `0c9cc23d0054f81e4c6beb897009376acde39711afa4a2c544a1bfb2edeac5ec`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## verify\_lineage::VerifyLineageInput [#verify_lineageverifylineageinput] Input for lineage verification. ```rust #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct VerifyLineageInput { /// The document whose lineage to verify (as JSON). pub document: serde_json::Value, /// Pre-fetched parent documents keyed by DID. pub parents: HashMap, /// Optional maximum generation depth (defaults to 16). #[serde(alias = "maxGeneration")] pub max_generation: Option, /// Verifier-controlled root trust anchors. #[serde(default, alias = "trustAnchors")] pub trust_anchors: Vec } ``` Source line: `19`. ## verify\_lineage::VerifyLineageResult [#verify_lineageverifylineageresult] Result of lineage verification. ```rust #[derive(Debug, Serialize)] pub struct VerifyLineageResult { /// Whether the lineage is valid. pub ok: bool, /// The root DID (if chain terminates at a root). #[serde(skip_serializing_if = "Option::is_none")] pub root_did: Option, /// The generation depth. #[serde(skip_serializing_if = "Option::is_none")] pub generation: Option, /// Stable typed error code (if verification failed). #[serde(skip_serializing_if = "Option::is_none")] pub error_code: Option, /// Error message (if verification failed). #[serde(skip_serializing_if = "Option::is_none")] pub error: Option } ``` Source line: `34`. ## verify\_lineage::verify\_lineage [#verify_lineageverify_lineage] Verifies a lineage chain using pre-fetched documents. This is a synchronous function suitable for WASM environments. All parent documents must be provided upfront — no network requests are made. # Arguments [#arguments] * `input_json` - JSON string containing a \[`VerifyLineageInput`]. # Returns [#returns] A JSON string containing a \[`VerifyLineageResult`]. # Examples [#examples] ``` use oas_wasm::verify_lineage::verify_lineage; use oas_crypto::keypair::OasKeyPair; use oas_document::builder::DocumentBuilder; use oas_document::conformance::ConformanceLevel; use oas_lineage::config::TrustAnchor; let keypair = OasKeyPair::generate(); let doc = DocumentBuilder::new("did:oas:test:hmr:alice", "hmr") .conformance_level(ConformanceLevel::L0) .add_verification_method(&keypair) .build_and_sign(&keypair, "2026-01-15T00:00:00Z") .unwrap(); let anchor = TrustAnchor::new( &doc.id, format!("{}#key-1", doc.id), keypair.public_key_multibase(), ).with_document_digest(doc.canonical_digest().unwrap()); let input = serde_json::json!({ "document": doc, "parents": {}, "trustAnchors": [anchor] }); let result = verify_lineage(&serde_json::to_string(&input).unwrap()); assert!(result.contains("\"ok\":true")); ``` ```rust #[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen)] pub fn verify_lineage(input_json: &str) -> String; ``` Source line: `112`. # openagent-aegis-policy · composition URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy/composition Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy/composition.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-policy/src/composition.rs`. SHA-256: `6b4d2e93ec58ba98a74ead0461584ac801c85007e6f5403b77df2ad71db2824a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## composition::compose\_decisions [#compositioncompose_decisions] Compose multiple policy decisions into a single decision. Follows AEGIS composition rules: 1. **Deny overrides**: If any decision has `allowed: false`, the final decision is denied. The reason is built from all deny reasons. 2. **Obligations accumulate**: All obligations from allowed decisions are collected into the final decision. 3. **Audit trail**: The composed audit info records all engines and policies evaluated across all input decisions. If the input slice is empty, returns an allowed decision with no obligations (vacuous truth: no policies evaluated means no objections). ```rust pub fn compose_decisions(decisions: &[PolicyDecision]) -> PolicyDecision; ``` Source line: `29`. # openagent-aegis-policy · contract URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy/contract Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy/contract.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-policy/src/contract.rs`. SHA-256: `9d21e57d47b6f7c9f646d2cf8eba95976db130f12ab31b6a297e6482e9951c03`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## contract::ContractPolicy [#contractcontractpolicy] Contract interaction policy dimensions. ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractPolicy { /// Allowed contract addresses. Empty list means all contracts are permitted. pub contract_allowlist: Vec, /// Allowed function names. Empty list means all functions are permitted. pub function_allowlist: Vec, /// Allowed blockchain chains. Empty list means all chains are permitted. pub chain_allowlist: Vec, /// Maximum gas allowed for the interaction. None means no gas limit. pub gas_limit: Option } ``` Source line: `15`. ## contract::ContractInteraction [#contractcontractinteraction] A contract interaction to evaluate against policy. ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractInteraction { /// The target contract address. pub contract_address: String, /// The function being called. pub function_name: String, /// The blockchain chain for this interaction. pub chain: String, /// Estimated gas usage. None if unknown. pub gas_estimate: Option } ``` Source line: `28`. ## contract::ContractPolicyEvaluator [#contractcontractpolicyevaluator] Evaluates contract interaction policy constraints. ```rust pub struct ContractPolicyEvaluator; ``` Source line: `40`. ## contract::ContractPolicyEvaluator::evaluate [#contractcontractpolicyevaluatorevaluate] Evaluate a contract interaction against the given policy. Checks the following dimensions in order: 1. Contract allowlist -- the contract address must be in the allowed set. 2. Function allowlist -- the function name must be in the allowed set. 3. Chain allowlist -- the chain must be in the allowed set. 4. Gas limit -- the gas estimate must not exceed the limit. Empty allowlists are permissive (all values accepted). Returns a deny `PolicyDecision` with reason on the first violation found. Returns an allow `PolicyDecision` on success. ```rust pub fn evaluate( policy: &ContractPolicy, interaction: &ContractInteraction, ) -> Result; ``` Source line: `54`. # openagent-aegis-policy · crate URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy/crate Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-policy/src/lib.rs`. SHA-256: `4d0513d5b022efc203ba22a565acaccec45761e802bc4d1102ac476636cdd6ab`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## composition [#composition] ```rust pub mod composition; ``` Source line: `5`. ## contract [#contract] ```rust pub mod contract; ``` Source line: `6`. ## lineage [#lineage] ```rust pub mod lineage; ``` Source line: `7`. ## spending [#spending] ```rust pub mod spending; ``` Source line: `8`. ## temporal [#temporal] ```rust pub mod temporal; ``` Source line: `9`. # openagent-aegis-policy modules URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-openagent-aegis-policy). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/openagent-aegis-policy/crate) — 5 declarations * [composition](/reference/rust/openagent-aegis-policy/composition) — 1 declarations * [contract](/reference/rust/openagent-aegis-policy/contract) — 4 declarations * [lineage](/reference/rust/openagent-aegis-policy/lineage) — 3 declarations * [spending](/reference/rust/openagent-aegis-policy/spending) — 4 declarations * [temporal](/reference/rust/openagent-aegis-policy/temporal) — 3 declarations # openagent-aegis-policy · lineage URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy/lineage Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy/lineage.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-policy/src/lineage.rs`. SHA-256: `f8f831d7a059cdd1915b904f69c08c4c2040cb0640998174f1b6bae5c366896c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## lineage::LineagePolicy [#lineagelineagepolicy] Lineage policy dimensions. ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct LineagePolicy { /// Minimum conformance level required (0, 1, or 2). pub min_conformance_level: Option, /// Maximum allowed lineage depth (hops to human root). pub max_lineage_depth: Option, /// Required human root liveness period in days. If the human root's /// liveness status is not `Active`, the interaction may be denied or /// warned depending on the status. pub required_human_root_liveness: Option, /// Required attestation types that must be present. Currently checked /// against `VerificationResult::warnings` for documentation purposes; /// a full implementation would check an attestation registry. pub required_attestations: Vec, /// DIDs of human roots that are banned. pub banned_human_roots: Vec } ``` Source line: `17`. ## lineage::LineagePolicyEvaluator [#lineagelineagepolicyevaluator] Evaluates lineage-aware policy constraints. ```rust pub struct LineagePolicyEvaluator; ``` Source line: `35`. ## lineage::LineagePolicyEvaluator::evaluate [#lineagelineagepolicyevaluatorevaluate] Evaluate a lineage policy against a verification result. Checks the following dimensions in order: 1. Banned human roots -- deny if the human root is in the banned list. 2. Conformance level -- deny if below minimum. 3. Lineage depth -- deny if exceeds maximum. 4. Human root liveness -- deny if liveness status is not Active. 5. Signature and lineage validity -- deny if not valid. Returns a deny `PolicyDecision` with reason on the first violation found. Returns an allow `PolicyDecision` on success. ```rust pub fn evaluate( policy: &LineagePolicy, verification: &VerificationResult, ) -> Result; ``` Source line: `49`. # openagent-aegis-policy · spending URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy/spending Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy/spending.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-policy/src/spending.rs`. SHA-256: `d738d77fb45bbce2138bd6339f2609b54478bbf9c2bea677092eeac3f0e3f302`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## spending::TransactionInfo [#spendingtransactioninfo] A transaction to evaluate against spending policies. ```rust #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct TransactionInfo { /// The asset being transferred (e.g. "ETH", "USDC"). pub asset: String, /// Decimal string representing the amount (e.g. "1.5"). pub amount: String, /// Recipient address. pub recipient: String, /// Blockchain chain identifier. pub chain: String } ``` Source line: `19`. ## spending::SpendingPolicyEvaluator [#spendingspendingpolicyevaluator] Evaluates spending policy constraints against a transaction. ```rust pub struct SpendingPolicyEvaluator; ``` Source line: `31`. ## spending::SpendingPolicyEvaluator::evaluate [#spendingspendingpolicyevaluatorevaluate] Evaluate a transaction against spending limits. Checks the following dimensions in order: 1. Asset allowlist -- the transaction asset must be in the allowed set. 2. Recipient allowlist -- the recipient must be in the allowed set. 3. Max amount per transaction. 4. Daily volume (daily\_spent + amount must not exceed daily\_volume). 5. Approval threshold -- if amount exceeds threshold, an Approve obligation is added. Empty allowlists are permissive (all values accepted). Returns a deny `PolicyDecision` with reason on the first violation found. Returns an allow `PolicyDecision` on success, possibly with obligations. ```rust pub fn evaluate( limits: &SpendingLimits, tx: &TransactionInfo, daily_spent: &str, ) -> Result; ``` Source line: `46`. ## spending::parse\_amount [#spendingparse_amount] Parse a decimal string into an f64. Returns a `PolicyError::EvaluationFailed` if the string is not a valid number, is negative, or is non-finite (NaN / infinity). ```rust pub fn parse_amount(s: &str) -> Result; ``` Source line: `177`. # openagent-aegis-policy · temporal URL: https://docs.openagent.id/reference/rust/openagent-aegis-policy/temporal Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-policy/temporal.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-policy/src/temporal.rs`. SHA-256: `1bb6e72f5cc87d20e111ffad01127805ee6e9ff889de94235efcab0ac3737539`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## temporal::TemporalPolicyEvaluator [#temporaltemporalpolicyevaluator] Evaluates temporal policy constraints. ```rust pub struct TemporalPolicyEvaluator; ``` Source line: `14`. ## temporal::TemporalPolicyEvaluator::evaluate [#temporaltemporalpolicyevaluatorevaluate] Evaluate temporal constraints without cooldown checking. Checks: 1. Validity window -- `now` must be between `valid_from` and `valid_until`. 2. Active hours -- current hour must be within the active hours window. Note: active\_hours check uses UTC hour. The timezone field on `ActiveHours` is recorded for documentation purposes but this evaluator operates in UTC to maintain determinism. Callers should convert `now` to the appropriate timezone before calling if timezone-aware checks are required. ```rust pub fn evaluate( constraints: &TemporalConstraints, now: DateTime, ) -> Result; ``` Source line: `27`. ## temporal::TemporalPolicyEvaluator::evaluate\_with\_cooldown [#temporaltemporalpolicyevaluatorevaluate_with_cooldown] Evaluate temporal constraints with optional cooldown checking. Checks all constraints from `evaluate` plus: 3\. Cooldown -- if `last_operation` is provided, ensures enough time has elapsed since the last operation per the cooldown duration. The cooldown is specified as an ISO 8601 duration string. This evaluator supports a simplified subset: `PT{n}S` (seconds), `PT{n}M` (minutes), `PT{n}H` (hours), and `P{n}D` (days). ```rust pub fn evaluate_with_cooldown( constraints: &TemporalConstraints, now: DateTime, last_operation: Option>, ) -> Result; ``` Source line: `43`. # openagent-aegis-sdk · client URL: https://docs.openagent.id/reference/rust/openagent-aegis-sdk/client Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-sdk/client.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-sdk/src/client.rs`. SHA-256: `6ab6ca8c8d7eaa5cf749ada855fd6f79bf97d236811596e80512d7e1ebe079ce`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client::AegisStores [#clientaegisstores] Collection of pluggable storage backends for the AEGIS client. All stores are wrapped in `Arc` for safe shared access. By default the client uses in-memory implementations; callers can provide PostgreSQL-backed (or any other) implementations via the \[`AegisClient::with_stores`] constructor. ```rust pub struct AegisStores { /// Session persistence store. pub session_store: Arc, /// Nonce tracking store (replay prevention). pub nonce_store: Arc, /// Delegation persistence store. pub delegation_store: Arc, /// Revocation tracking store. pub revocation_store: Arc, /// Key persistence store. pub key_store: Arc, /// Verification result cache store. pub verification_cache_store: Arc } ``` Source line: `43`. ## client::AegisClient [#clientaegisclient] Unified AEGIS client. Holds a \[`PluginRegistry`], a verification pipeline, a session manager, a delegation tree, and optionally a transaction pipeline. The client also exposes pluggable \[`AegisStores`] for async persistent storage backends. ```rust pub struct AegisClient { /// Plugin registry for DID resolvers, auth providers, and the policy engine. pub registry: Arc, /// Verification pipeline (resolution -> signature -> lineage -> revocation -> liveness -> cache). pub verifier: VerificationPipeline, /// Session manager. pub sessions: SessionManager, /// Delegation tree for tracking active delegations. pub delegations: DelegationTree, /// Transaction authorization pipeline (present only when a signing backend is provided). pub transactions: Option, /// Configuration snapshot. pub config: AegisConfig, /// Pluggable persistent storage backends. pub stores: AegisStores } ``` Source line: `76`. ## client::AegisClient::new [#clientaegisclientnew] Create a new AEGIS client with the given plugin registry and config. Uses in-memory storage backends by default. No signing backend is attached; call [`with_signer`](Self::with_signer) to enable the transaction pipeline, or [`with_stores`](Self::with_stores) to inject custom storage backends. ```rust pub fn new(registry: Arc, config: AegisConfig) -> Self; ``` Source line: `100`. ## client::AegisClient::with\_stores [#clientaegisclientwith_stores] Create a new AEGIS client with custom storage backends. This constructor allows callers to inject PostgreSQL-backed or other persistent storage implementations for all AEGIS storage traits. ```rust pub fn with_stores( registry: Arc, config: AegisConfig, stores: AegisStores, ) -> Self; ``` Source line: `126`. ## client::AegisClient::with\_defaults [#clientaegisclientwith_defaults] Create a client with default configuration. ```rust pub fn with_defaults(registry: Arc) -> Self; ``` Source line: `153`. ## client::AegisClient::with\_signer [#clientaegisclientwith_signer] Attach a signing backend so the transaction pipeline is available. ```rust pub fn with_signer(mut self, signer: Arc) -> Self; ``` Source line: `158`. ## client::AegisClient::verify\_identity [#clientaegisclientverify_identity] Verify an identity by DID. Runs the full verification pipeline: resolution -> signature -> lineage -> revocation -> liveness. Results are cached according to the verification config TTL. ```rust pub async fn verify_identity( &self, did: &str, ) -> Result; ``` Source line: `170`. ## client::AegisClient::verify\_identity\_fresh [#clientaegisclientverify_identity_fresh] Verify an identity, bypassing the cache. ```rust pub async fn verify_identity_fresh( &self, did: &str, ) -> Result; ``` Source line: `178`. ## client::AegisClient::authenticate [#clientaegisclientauthenticate] Authenticate a credential through the registered auth providers. On success a new \[`Session`] is created and returned. ```rust pub async fn authenticate( &self, credential: &AuthCredential, identity_type: IdentityType, ) -> Result; ``` Source line: `190`. ## client::AegisClient::get\_session [#clientaegisclientget_session] Look up a session by its ID. ```rust pub fn get_session(&self, session_id: &str) -> Result; ``` Source line: `215`. ## client::AegisClient::revoke\_session [#clientaegisclientrevoke_session] Revoke a session. ```rust pub fn revoke_session(&self, session_id: &str) -> Result<(), AuthError>; ``` Source line: `220`. ## client::AegisClient::is\_session\_valid [#clientaegisclientis_session_valid] Check whether a session is still valid (exists and not expired). ```rust pub fn is_session_valid(&self, session_id: &str) -> bool; ``` Source line: `225`. ## client::AegisClient::authorize [#clientaegisclientauthorize] Evaluate a policy request through the registered policy engine. ```rust pub async fn authorize(&self, request: &PolicyRequest) -> Result; ``` Source line: `232`. ## client::AegisClient::compose\_policy\_decisions [#clientaegisclientcompose_policy_decisions] Compose multiple policy decisions using deny-overrides (spec SS8.6). ```rust pub fn compose_policy_decisions(&self, decisions: &[PolicyDecision]) -> PolicyDecision; ``` Source line: `237`. ## client::AegisClient::delegate [#clientaegisclientdelegate] Create a delegation from `delegator_did` to `delegate_did` with the given scope, signed by the delegator's key. The delegation is automatically added to the internal delegation tree. ```rust pub fn delegate( &mut self, delegator_did: &str, delegate_did: &str, scope: DelegationScope, expires: Option>, signing_key: &SigningKey, verification_method: &str, ) -> Result; ``` Source line: `247`. ## client::AegisClient::verify\_delegation [#clientaegisclientverify_delegation] Verify a delegation proof against the delegator's public key. ```rust pub fn verify_delegation( &self, delegation: &Delegation, delegator_public_key: &VerifyingKey, ) -> Result; ``` Source line: `270`. ## client::AegisClient::revoke\_delegation [#clientaegisclientrevoke_delegation] Revoke a delegation by ID. Cascading: all child delegations derived from the revoked delegation are also revoked. Returns the list of revoked delegation IDs. ```rust pub fn revoke_delegation( &mut self, delegation_id: &str, ) -> Result, DelegationError>; ``` Source line: `282`. ## client::AegisClient::sign\_transaction [#clientaegisclientsign_transaction] Authorize and sign a transaction through the full pipeline: verify identity -> check delegation -> evaluate policy -> fulfill obligations -> sign. Requires a signing backend to be attached via [`with_signer`](Self::with_signer). ```rust pub async fn sign_transaction( &self, tx: Transaction, auth: &AuthContext, policy_decision: &PolicyDecision, ) -> Result; ``` Source line: `296`. # openagent-aegis-sdk · config URL: https://docs.openagent.id/reference/rust/openagent-aegis-sdk/config Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-sdk/config.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-sdk/src/config.rs`. SHA-256: `06a2b6645268ef69be09316360676a4fbdf065ffc1b428de4559bd41fd97615f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::AegisConfig [#configaegisconfig] Top-level AEGIS SDK configuration. Corresponds to the YAML configuration format defined in AEGIS Spec Appendix B. Controls verification behaviour, session lifetimes, and key storage parameters. ```rust #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct AegisConfig { /// Verification pipeline settings. #[serde(default)] pub verification: VerificationConfig, /// Session lifetime settings. #[serde(default)] pub sessions: SessionConfig, /// Key storage settings. #[serde(default)] pub keys: KeyConfig, /// Storage backend selection. #[serde(default)] pub storage_backend: StorageBackend } ``` Source line: `13`. ## config::SessionConfig [#configsessionconfig] Session lifetime configuration. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionConfig { /// Maximum lifetime for human sessions in seconds (default: 86400 = 24h). pub human_lifetime_secs: u64, /// Maximum lifetime for agent sessions in seconds (default: 3600 = 1h). pub agent_lifetime_secs: u64, /// Maximum lifetime for session keys in seconds (default: 86400 = 24h). pub session_key_max_secs: u64 } ``` Source line: `33`. ## config::StorageBackend [#configstoragebackend] Storage backend selection. Controls which persistence layer the SDK uses for sessions, nonces, delegations, revocations, and verification cache. ```rust #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StorageBackend { /// In-memory storage (default). Suitable for testing and single-instance /// deployments. #[default] InMemory, /// PostgreSQL-backed storage. Requires a valid connection URL. Postgres { /// PostgreSQL connection URL (e.g., `postgres://user:pass@host/db`). url: String, }, } ``` Source line: `58`. ## config::KeyConfig [#configkeyconfig] Key storage configuration. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KeyConfig { /// Encryption algorithm for at-rest keys (default: "AES-256-GCM"). pub encryption_algorithm: String, /// Whether to zeroize key material on drop (default: true). pub zeroize_on_drop: bool } ``` Source line: `72`. # openagent-aegis-sdk · crate URL: https://docs.openagent.id/reference/rust/openagent-aegis-sdk/crate Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-sdk/crate.md Declared module signatures, types, configuration, and source documentation. Source: `aegis/openagent-aegis-sdk/src/lib.rs`. SHA-256: `83968235678802fdbfb94a7eb82f2246bb076573da27fa4a3c6ab060e6e44b3a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client [#client] ```rust pub mod client; ``` Source line: `8`. ## config [#config] ```rust pub mod config; ``` Source line: `9`. ## pub use client::\{AegisClient, AegisStores}; [#pub-use-clientaegisclient-aegisstores] ```rust pub use client::{AegisClient, AegisStores}; ``` Source line: `11`. ## pub use config::\{AegisConfig, StorageBackend}; [#pub-use-configaegisconfig-storagebackend] ```rust pub use config::{AegisConfig, StorageBackend}; ``` Source line: `12`. ## pub use aegis\_auth; [#pub-use-aegis_auth] ```rust pub use aegis_auth; ``` Source line: `15`. ## pub use aegis\_delegate; [#pub-use-aegis_delegate] ```rust pub use aegis_delegate; ``` Source line: `16`. ## pub use aegis\_keys; [#pub-use-aegis_keys] ```rust pub use aegis_keys; ``` Source line: `17`. ## pub use aegis\_verify; [#pub-use-aegis_verify] ```rust pub use aegis_verify; ``` Source line: `18`. ## pub use aegis\_wallet; [#pub-use-aegis_wallet] ```rust pub use aegis_wallet; ``` Source line: `19`. ## pub use openagent\_aegis\_core; [#pub-use-openagent_aegis_core] ```rust pub use openagent_aegis_core; ``` Source line: `20`. ## pub use openagent\_aegis\_policy; [#pub-use-openagent_aegis_policy] ```rust pub use openagent_aegis_policy; ``` Source line: `21`. # openagent-aegis-sdk modules URL: https://docs.openagent.id/reference/rust/openagent-aegis-sdk Markdown: https://docs.openagent.id/reference/rust/openagent-aegis-sdk.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/aegis-openagent-aegis-sdk). [Focused integration guide](/aegis/overview). ## Modules [#modules] * [crate](/reference/rust/openagent-aegis-sdk/crate) — 11 declarations * [client](/reference/rust/openagent-aegis-sdk/client) — 18 declarations * [config](/reference/rust/openagent-aegis-sdk/config) — 4 declarations # openagent-auth-protocol · crate URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/crate Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/lib.rs`. SHA-256: `986125777224d8b43f4ca1fb0a3c2b107512be4c4fcd1b8eabd61e27f3c4d240`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error [#error] ```rust pub mod error; ``` Source line: `45`. ## handshake [#handshake] ```rust pub mod handshake; ``` Source line: `46`. ## message [#message] ```rust pub mod message; ``` Source line: `47`. ## session [#session] ```rust pub mod session; ``` Source line: `48`. ## transport [#transport] ```rust pub mod transport; ``` Source line: `49`. ## types [#types] ```rust pub mod types; ``` Source line: `50`. ## pub use error::AuthProtocolError; [#pub-use-errorauthprotocolerror] ```rust pub use error::AuthProtocolError; ``` Source line: `52`. ## pub use message::\{ [#pub-use-message] IdentityChallenge, IdentityProof, IdentityVerified, KeyType, TrustTier, CHALLENGE\_TYPE, }; ```rust pub use message::{ IdentityChallenge, IdentityProof, IdentityVerified, KeyType, TrustTier, CHALLENGE_TYPE, }; ``` Source line: `53`. ## pub use session::\{InMemorySessionStore, Session, SessionId, SessionState, SessionStore}; [#pub-use-sessioninmemorysessionstore-session-sessionid-sessionstate-sessionstore] ```rust pub use session::{InMemorySessionStore, Session, SessionId, SessionState, SessionStore}; ``` Source line: `56`. ## pub use transport::AuthTransport; [#pub-use-transportauthtransport] ```rust pub use transport::AuthTransport; ``` Source line: `57`. ## pub use types::\{ConformanceLevel, DidDocument, DiscoveryDocument, LineageLink, LineageProof}; [#pub-use-typesconformancelevel-diddocument-discoverydocument-lineagelink-lineageproof] ```rust pub use types::{ConformanceLevel, DidDocument, DiscoveryDocument, LineageLink, LineageProof}; ``` Source line: `58`. ## ::VERSION [#version] Crate version. ```rust pub const VERSION: &str; ``` Source line: `61`. # openagent-auth-protocol · error URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/error Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/error.rs`. SHA-256: `5d1c97c1abadd46bbf983286ab6542c824a0453eb896492461e6f860577a7f09`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::AuthProtocolError [#errorauthprotocolerror] Errors arising from Core Protocol handshake operations. ```rust #[derive(Debug, Error)] pub enum AuthProtocolError { /// The protocol version in the received message is not supported. #[error( "unsupported protocol version {received}; this implementation supports version {supported}" )] UnsupportedVersion { /// The version received from the peer. received: u8, /// The version this implementation supports. supported: u8, }, /// A challenge failed the Section 4 field constraints. #[error("invalid challenge: {reason}")] InvalidChallenge { /// What constraint failed. reason: String, }, /// A proof failed the Section 15.3 shape checks. #[error("invalid proof: {reason}")] InvalidProof { /// What constraint failed. reason: String, }, /// The nonce echoed in the proof does not match the challenge. #[error("nonce mismatch: challenge carried {expected}, proof echoed {received}")] NonceMismatch { /// The nonce in the challenge. expected: String, /// The nonce echoed in the proof. received: String, }, /// The challenge nonce has expired (anti-replay protection). #[error("challenge expired: issued at {issued}, expiry was {expiry}, current time is {now}")] ChallengeExpired { /// When the challenge was issued. issued: String, /// When it expired. expiry: String, /// Current timestamp. now: String, }, /// A nonce was reused (replay attack detected). #[error("replay detected: nonce {nonce_hex} has already been used in a prior handshake")] ReplayDetected { /// Hex-encoded nonce that was replayed. nonce_hex: String, }, /// Signature verification failed against the trusted key set. #[error("signature verification failed: {reason}")] SignatureVerificationFailed { /// Why verification failed. reason: String, }, /// The peer's DID document is structurally invalid or missing required fields. #[error("invalid DID document for {did}: {reason}")] InvalidDidDocument { /// The DID whose document was invalid. did: String, /// What was wrong. reason: String, }, /// The transport layer failed to send or receive a message. #[error("transport error: {reason}")] TransportFailed { /// Underlying transport error. reason: String, }, /// A timeout occurred waiting for a response from the peer. #[error("timeout waiting for {step} response after {timeout_secs}s")] Timeout { /// Which protocol step timed out. step: String, /// How long we waited. timeout_secs: u64, }, /// Serialization or deserialization of a protocol message failed. #[error("message serialization failed for {message_type}: {reason}")] SerializationFailed { /// The message type being (de)serialized. message_type: String, /// Underlying failure reason. reason: String, }, /// The challenge expiry duration exceeds the maximum allowed (300 seconds, /// per Section 7 of the Core Protocol Specification). #[error("challenge expiry {requested_secs}s exceeds maximum allowed {max_secs}s")] ExpiryTooLong { /// The requested expiry in seconds. requested_secs: u64, /// The maximum allowed. max_secs: u64, }, /// An internal failure that is not the peer's fault (e.g. a poisoned /// lock in a session store). Surfaced rather than panicked, per the /// workspace no-panic policy. #[error("internal error: {0}")] Internal(String), /// A presented session token does not identify a live session. #[error("session not found: {session_id}")] SessionNotFound { /// The token or identifier presented. session_id: String, }, /// A session exists but has expired and was removed. #[error("session expired: {session_id}")] SessionExpired { /// The token or identifier presented. session_id: String, }, } ``` Source line: `17`. # openagent-auth-protocol · handshake URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/handshake Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/handshake.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/handshake.rs`. SHA-256: `45c722316200bf93f48609255516c92106a0cb15ca1741a777f02c4f7c7941a9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## handshake::DEFAULT\_SESSION\_TTL\_SECS [#handshakedefault_session_ttl_secs] Default session TTL in seconds (5 minutes). ```rust pub const DEFAULT_SESSION_TTL_SECS: u32; ``` Source line: `13`. ## handshake::DEFAULT\_CHALLENGE\_TTL\_SECS [#handshakedefault_challenge_ttl_secs] Default challenge TTL in seconds (Section 7: default 30s, max 300s). ```rust pub const DEFAULT_CHALLENGE_TTL_SECS: u32; ``` Source line: `16`. ## handshake::MAX\_CHALLENGE\_TTL\_SECS [#handshakemax_challenge_ttl_secs] Maximum challenge TTL in seconds (Section 7). ```rust pub const MAX_CHALLENGE_TTL_SECS: u32; ``` Source line: `19`. ## handshake::WELL\_KNOWN\_PATH [#handshakewell_known_path] Well-known path for discovery. ```rust pub const WELL_KNOWN_PATH: &str; ``` Source line: `22`. ## handshake::AUTH\_ENDPOINT\_PATH [#handshakeauth_endpoint_path] Well-known path for the auth endpoint. ```rust pub const AUTH_ENDPOINT_PATH: &str; ``` Source line: `25`. ## handshake::PROVE\_ENDPOINT\_PATH [#handshakeprove_endpoint_path] Well-known path for the prove endpoint. ```rust pub const PROVE_ENDPOINT_PATH: &str; ``` Source line: `28`. ## handshake::generate\_nonce [#handshakegenerate_nonce] Generate a nonce per Section 7: 32 CSPRNG bytes as 64 lowercase hex chars. ```rust pub fn generate_nonce() -> Result; ``` Source line: `31`. ## handshake::new\_challenge [#handshakenew_challenge] Construct a fresh \[`IdentityChallenge`] for `origin`, stamping the current UTC time in the Section 4 format (`Z` suffix, seconds precision). ```rust pub fn new_challenge( origin: &str, realm: Option, ) -> Result; ``` Source line: `39`. ## handshake::canonical\_challenge\_bytes [#handshakecanonical_challenge_bytes] The signing payload for an \[`IdentityProof`]: the JCS-canonicalized (RFC 8785) UTF-8 bytes of the challenge object, with no framing, prefix, or envelope (Section 5 / Section 15.2). ```rust pub fn canonical_challenge_bytes( challenge: &IdentityChallenge, ) -> Result, AuthProtocolError>; ``` Source line: `56`. ## handshake::validate\_challenge [#handshakevalidate_challenge] Validate an \[`IdentityChallenge`] against the Section 4 field constraints. A server MUST reject a challenge whose `type` differs, and an agent MUST reject a malformed challenge before signing it: signing binds the agent to these exact bytes. ```rust pub fn validate_challenge(challenge: &IdentityChallenge) -> Result<(), AuthProtocolError>; ``` Source line: `77`. ## handshake::validate\_nonce [#handshakevalidate_nonce] The nonce field: exactly 64 lowercase hex characters (Section 7). ```rust pub fn validate_nonce(nonce: &str) -> Result<(), AuthProtocolError>; ``` Source line: `100`. ## handshake::validate\_timestamp [#handshakevalidate_timestamp] The timestamp field: ISO 8601 UTC with `Z` suffix and seconds precision (Section 4.2). Fractional seconds and numeric offsets are rejected. ```rust pub fn validate_timestamp(timestamp: &str) -> Result<(), AuthProtocolError>; ``` Source line: `118`. ## handshake::validate\_origin [#handshakevalidate_origin] The origin field: `scheme://host[:port]` per RFC 6454 (Section 4.2). ```rust pub fn validate_origin(origin: &str) -> Result<(), AuthProtocolError>; ``` Source line: `131`. ## handshake::validate\_proof\_shape [#handshakevalidate_proof_shape] Validate an \[`IdentityProof`] against a challenge (Section 15.3): the echoed nonce must match, and the key shape must match the declared scheme. Signature verification itself belongs to the verifier, which knows the trusted key set. ```rust pub fn validate_proof_shape( proof: &IdentityProof, challenge: &IdentityChallenge, ) -> Result<(), AuthProtocolError>; ``` Source line: `150`. # openagent-auth-protocol modules URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-crates-openagent-auth-protocol). [Focused integration guide](/features/auth-protocol). ## Modules [#modules] * [crate](/reference/rust/openagent-auth-protocol/crate) — 12 declarations * [error](/reference/rust/openagent-auth-protocol/error) — 1 declarations * [handshake](/reference/rust/openagent-auth-protocol/handshake) — 14 declarations * [message](/reference/rust/openagent-auth-protocol/message) — 7 declarations * [session](/reference/rust/openagent-auth-protocol/session) — 8 declarations * [transport](/reference/rust/openagent-auth-protocol/transport) — 1 declarations * [types](/reference/rust/openagent-auth-protocol/types) — 7 declarations # openagent-auth-protocol · message URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/message Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/message.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/message.rs`. SHA-256: `c5b5442b0fb5d236093b1e4a4c62ea4823f363fd1e063000fdf2639ec4693c88`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## message::CHALLENGE\_TYPE [#messagechallenge_type] The literal `type` value of an \[`IdentityChallenge`], per Section 15.2. ```rust pub const CHALLENGE_TYPE: &str; ``` Source line: `19`. ## message::IdentityChallenge [#messageidentitychallenge] Server → Agent: a cryptographic challenge (Section 15.2). The signing payload for the proof is the JCS-canonicalized (RFC 8785) UTF-8 byte representation of this object — no framing, prefix, or envelope. Use \[`crate::handshake::canonical_challenge_bytes`]. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct IdentityChallenge { /// MUST be the literal string `openagent-challenge-v1`. #[serde(rename = "type")] pub message_type: String, /// 64-character lowercase hexadecimal string (32 CSPRNG bytes). pub nonce: String, /// ISO 8601 UTC timestamp, `Z` suffix, seconds precision. pub timestamp: String, /// Server origin per RFC 6454: `scheme://host[:port]`. pub origin: String, /// Optional protection-space identifier. Omitted entirely when absent. #[serde(default, skip_serializing_if = "Option::is_none")] pub realm: Option } ``` Source line: `27`. ## message::IdentityChallenge::new [#messageidentitychallengenew] Construct a challenge of the current format version. ```rust pub fn new(nonce: String, timestamp: String, origin: String, realm: Option) -> Self; ``` Source line: `44`. ## message::KeyType [#messagekeytype] Signature scheme used for an \[`IdentityProof`] (Section 15.3). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum KeyType { /// Ed25519 (32-byte public key). Ed25519, /// secp256k1 (33-byte compressed SEC1 public key). Secp256k1, } ``` Source line: `58`. ## message::IdentityProof [#messageidentityproof] Agent → Server: the cryptographic proof of identity (Section 15.3). ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct IdentityProof { /// Base64url (no padding) signature over the JCS-canonicalized challenge /// bytes. 64 bytes for both schemes. pub signature: String, /// Base64url (no padding) raw public key: 32 bytes (Ed25519) or 33 bytes /// (secp256k1 compressed). pub public_key: String, /// The signature scheme. pub key_type: KeyType, /// The nonce from the challenge, echoed to assist server-side lookup. pub nonce: String } ``` Source line: `76`. ## message::TrustTier [#messagetrusttier] The resolution tier the server assigns after verification (Section 15.4). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum TrustTier { /// Identity verified against the presented key only. Anonymous, /// Identity resolved with additional registry context. Identified, /// Identity resolved with full lineage authority. Sovereign, } ``` Source line: `92`. ## message::IdentityVerified [#messageidentityverified] Server → Agent: identity confirmed; session issued (Section 15.4). The `session_token` replaces further challenge-response cycles until expiry; the agent presents it as a bearer credential (Section 12). ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct IdentityVerified { /// Most specific resolved DID for the agent. pub did: String, /// The resolution tier assigned by the server. pub trust_tier: TrustTier, /// JWT session token for subsequent requests. pub session_token: String, /// ISO 8601 UTC timestamp of session expiry. pub session_expires: String, /// Granted capability identifiers, populated by Arsenal when present. #[serde(default, skip_serializing_if = "Option::is_none")] pub capabilities: Option> } ``` Source line: `116`. # openagent-auth-protocol · session URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/session Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/session.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/session.rs`. SHA-256: `846a27ff5bfe6506161ceae4398609265381bae29a2a2cdf9816a125e4d270e8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session::SessionId [#sessionsessionid] Opaque session identifier (BLAKE3 of random bytes, hex-encoded). ```rust pub type SessionId = String; ``` Source line: `17`. ## session::SessionState [#sessionsessionstate] States a session transitions through during the handshake. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum SessionState { /// Challenge issued; waiting for PROVE. AwaitingProof, /// Handshake complete; session is usable. Established, /// Session revoked or expired. Closed, } ``` Source line: `21`. ## session::Session [#sessionsession] An authenticated session between two agents. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Session { /// Unique session identifier. pub id: SessionId, /// Current handshake state. pub state: SessionState, /// DID of the initiator (client). pub initiator_did: String, /// DID of the responder (server). pub responder_did: String, /// Nonce issued in the CHALLENGE step. pub nonce: String, /// When the session was created. pub created_at: DateTime, /// When the session expires. pub expires_at: DateTime, /// Capabilities granted upon establishment. #[serde(default)] pub capabilities: Vec } ``` Source line: `32`. ## session::Session::is\_expired [#sessionsessionis_expired] Returns `true` if the session has expired. ```rust pub fn is_expired(&self) -> bool; ``` Source line: `54`. ## session::Session::is\_valid [#sessionsessionis_valid] Returns `true` if the session is established and not expired. ```rust pub fn is_valid(&self) -> bool; ``` Source line: `59`. ## session::SessionStore [#sessionsessionstore] Trait for pluggable session storage backends. Implementations must be `Send + Sync` for use with async runtimes. ```rust #[async_trait::async_trait] pub trait SessionStore: Send + Sync { /// Persist a new or updated session. async fn put(&self, session: Session) -> Result<(), AuthProtocolError>; /// Retrieve a session by its ID. Returns `None` if not found. async fn get(&self, id: &str) -> Result, AuthProtocolError>; /// Remove a session by its ID. async fn remove(&self, id: &str) -> Result<(), AuthProtocolError>; } ``` Source line: `68`. ## session::InMemorySessionStore [#sessioninmemorysessionstore] In-memory session store — suitable for tests and single-node deployments. ```rust #[derive(Debug, Clone, Default)] pub struct InMemorySessionStore { } ``` Source line: `79`. ## session::InMemorySessionStore::new [#sessioninmemorysessionstorenew] Creates a new empty session store. ```rust pub fn new() -> Self; ``` Source line: `85`. # openagent-auth-protocol · transport URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/transport Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/transport.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/transport.rs`. SHA-256: `476f11d26cb734a256dfa734f413bb7660732700cddc9b8f2c274aa386a7faa2`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## transport::AuthTransport [#transportauthtransport] Transport-agnostic interface for the agent side of the identity flow. The agent either receives a challenge passively (a `401` with a `WWW-Authenticate` challenge on the HTTP binding) or fetches one proactively, then proves. Responders handle inbound proofs through their framework-specific integration (e.g. an Axum layer). ```rust #[async_trait] pub trait AuthTransport: Send + Sync { /// Request a challenge from the server (proactive flow). async fn fetch_challenge(&self, endpoint: &str) -> Result; /// Send an [`IdentityProof`] and receive the [`IdentityVerified`] session. async fn prove( &self, endpoint: &str, proof: &IdentityProof, ) -> Result; } ``` Source line: `21`. # openagent-auth-protocol · types URL: https://docs.openagent.id/reference/rust/openagent-auth-protocol/types Markdown: https://docs.openagent.id/reference/rust/openagent-auth-protocol/types.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-auth-protocol/src/types.rs`. SHA-256: `399d81227f0317d5513cd77a42d84da7b8f6f4772057de68a851138b880dd485`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## types::ConformanceLevel [#typesconformancelevel] Conformance levels for entity classification (Bioagentic). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ConformanceLevel { /// L0: Passive signals only (UA, TLS fingerprint). #[serde(rename = "L0")] L0, /// L1: Behavioral analysis (18-dim feature extraction). #[serde(rename = "L1")] L1, /// L2: Full cryptographic proof (Ed25519 / FIDO2). #[serde(rename = "L2")] L2, } ``` Source line: `11`. ## types::ConformanceLevel::level [#typesconformancelevellevel] Returns the numeric ordering (L0=0, L1=1, L2=2). ```rust pub fn level(&self) -> u8; ``` Source line: `25`. ## types::ConformanceLevel::satisfies [#typesconformancelevelsatisfies] Returns true if `self` satisfies the `required` level. ```rust pub fn satisfies(&self, required: &Self) -> bool; ``` Source line: `34`. ## types::DidDocument [#typesdiddocument] Minimal DID document fragment for the handshake. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DidDocument { /// Canonical DID (e.g. `did:oas:l1fe:agent:my-bot`). pub id: String, /// Multibase-encoded Ed25519 verification key. pub verification_key: String, /// Entity kind (`agent`, `tool`, `service`, etc.). pub kind: String, /// Optional parent DID for lineage. #[serde(skip_serializing_if = "Option::is_none")] pub parent: Option } ``` Source line: `51`. ## types::LineageProof [#typeslineageproof] Cryptographic lineage proof linking an agent to its human root. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LineageProof { /// Chain of DID-to-DID attestations from the agent back to HMR. pub chain: Vec } ``` Source line: `65`. ## types::LineageLink [#typeslineagelink] A single link in the lineage chain. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LineageLink { /// DID of the parent (delegator). pub from: String, /// DID of the child (delegatee). pub to: String, /// Ed25519 signature by `from` over the delegation assertion. pub signature: String, /// ISO-8601 timestamp of the delegation. pub issued_at: String } ``` Source line: `72`. ## types::DiscoveryDocument [#typesdiscoverydocument] Server discovery response at `GET /.well-known/openagent`. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DiscoveryDocument { /// Auth endpoint path (default: `/.well-known/openagent/auth`). pub auth_endpoint: String, /// Supported protocol versions. pub supported_versions: Vec, /// Server's DID. pub server_did: String, /// Minimum conformance level required. pub required_conformance_level: ConformanceLevel } ``` Source line: `85`. # openagent-capability · crate URL: https://docs.openagent.id/reference/rust/openagent-capability/crate Markdown: https://docs.openagent.id/reference/rust/openagent-capability/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-capability/src/lib.rs`. SHA-256: `b24b099555e8f3131cecb5682e0bfe244cce4064305779bd6f0dadf79d2efebd`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## pub use agent\_capability\_token::\{ [#pub-use-agent_capability_token] claims\_to\_signing\_payload, envelope\_from\_parts, verify, ActClaims, ActEnvelope, ActError, ActResult, Confirmation, Delegation, PublicKeyBytes, Scope, Verifier, ALGORITHM\_ED25519, FORMAT\_VERSION, MAX\_ACT\_BYTES, SCOPE\_SEGMENTS, WILDCARD, }; ```rust pub use agent_capability_token::{ claims_to_signing_payload, envelope_from_parts, verify, ActClaims, ActEnvelope, ActError, ActResult, Confirmation, Delegation, PublicKeyBytes, Scope, Verifier, ALGORITHM_ED25519, FORMAT_VERSION, MAX_ACT_BYTES, SCOPE_SEGMENTS, WILDCARD, }; ``` Source line: `43`. ## pub use agent\_capability\_token::sign; [#pub-use-agent_capability_tokensign] ```rust #[cfg(feature = "sign")] pub use agent_capability_token::sign; ``` Source line: `50`. ## ::require\_scopes [#require_scopes] Asserts that `claims` grants every scope in `required`. Convenience over \[`Scope::covers`], kept because scope presence checks are the most common thing a verifier does after \[`verify`] and the spelling is easy to get wrong: wildcards expand in a grant and are literal in a request, so a holder must not be able to widen its own authority by requesting `*`. # Errors [#errors] Returns \[`ActError::MissingScope`] with the first required scope the token does not cover. ```rust pub fn require_scopes(claims: &ActClaims, required: &[Scope]) -> ActResult<()>; ``` Source line: `63`. # openagent-capability modules URL: https://docs.openagent.id/reference/rust/openagent-capability Markdown: https://docs.openagent.id/reference/rust/openagent-capability.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagents-openagent-id-crates-openagent-capability). [Focused integration guide](/api-reference/openagent-server). ## Modules [#modules] * [crate](/reference/rust/openagent-capability/crate) — 3 declarations # openagent-client · crate URL: https://docs.openagent.id/reference/rust/openagent-client/crate Markdown: https://docs.openagent.id/reference/rust/openagent-client/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-client/src/lib.rs`. SHA-256: `23b524b4bb88ff2889460df8f132972d7e3b707a7f3af5891a1f6d26c69240f4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error [#error] ```rust pub mod error; ``` Source line: `14`. ## ::OpenAgentClient [#openagentclient] An OpenAgent client that handles the challenge-response flow transparently. Wraps an Ed25519 signing key. On each `fetch`, if the server returns 401, the client automatically signs the challenge and retries. Session tokens are cached and reused until they expire. ```rust pub struct OpenAgentClient { } ``` Source line: `30`. ## ::AuthenticatedResponse [#authenticatedresponse] Response from a successful OpenAgent-authenticated request. ```rust #[derive(Debug)] pub struct AuthenticatedResponse { pub status: u16, pub did: Option, pub trust_tier: Option, pub session_token: Option, /// Legacy lineage response metadata retained only for migration and audit. /// /// This value is never an authorization grant. pub legacy_lineage_evidence: Option, pub body: Vec, pub headers: reqwest::header::HeaderMap } ``` Source line: `43`. ## ::OpenAgentClient::new [#openagentclientnew] Creates a new client from a 32-byte Ed25519 secret key. ```rust pub fn new(secret_key: &[u8; 32]) -> Self; ``` Source line: `70`. ## ::OpenAgentClient::public\_key\_bytes [#openagentclientpublic_key_bytes] Returns the Ed25519 public key as bytes. ```rust pub fn public_key_bytes(&self) -> [u8; 32]; ``` Source line: `79`. ## ::OpenAgentClient::fetch [#openagentclientfetch] Sends an authenticated request to the given URL. The full flow: 1. If a cached session token exists for this origin, try Bearer auth 2. If no session or session is rejected (401), do challenge-response 3. Cache the new session token 4. Return the final response ```rust pub async fn fetch( &self, url: &str, body: Option<&[u8]>, ) -> Result; ``` Source line: `90`. # openagent-client · error URL: https://docs.openagent.id/reference/rust/openagent-client/error Markdown: https://docs.openagent.id/reference/rust/openagent-client/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-client/src/error.rs`. SHA-256: `765b122c694fce1392af3c172bd77dfa289e9873ac48ecff105e0a2ab3f5a054`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::ClientError [#errorclienterror] Errors from the OpenAgent client. ```rust #[derive(Debug, thiserror::Error)] pub enum ClientError { #[error("invalid URL: {0}")] InvalidUrl(String), #[error("HTTP request failed: {0}")] Http(reqwest::Error), #[error("server returned 401 but no WWW-Authenticate header with OpenAgent challenge")] NoChallengeHeader, #[error("malformed challenge: {0}")] MalformedChallenge(String), #[error("server rejected the signed challenge")] AuthenticationRejected, } ``` Source line: `5`. # openagent-client modules URL: https://docs.openagent.id/reference/rust/openagent-client Markdown: https://docs.openagent.id/reference/rust/openagent-client.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagents-openagent-id-crates-openagent-client). [Focused integration guide](/api-reference/openagent-server). ## Modules [#modules] * [crate](/reference/rust/openagent-client/crate) — 6 declarations * [error](/reference/rust/openagent-client/error) — 1 declarations # openagent-claude-agent · audit URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/audit Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/audit.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/audit.rs`. SHA-256: `132364e5627d22ac9cdf310625d67c4fd39583c23ca482194e5fada810de2bcb`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit::GENESIS\_PREV\_HASH [#auditgenesis_prev_hash] Sentinel for the head of the chain (64 zero hex chars). ```rust pub const GENESIS_PREV_HASH: &str; ``` Source line: `13`. ## audit::AuditKind [#auditauditkind] Categories of audit events. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum AuditKind { /// Session lifecycle: opened. SessionStart, /// Session lifecycle: closed. SessionStop, /// Tool call preflight (pre-execution scope check). ToolPreflight, /// Tool call completed. ToolComplete, /// Skill invocation preflight (policy check before body runs). SkillPreflight, /// Skill invocation completed. SkillComplete, /// Outbound / inbound message audit. MessageSigned, /// Generic policy denial. PolicyDeny, } ``` Source line: `19`. ## audit::Outcome [#auditoutcome] Outcome of an audited operation. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Outcome { /// Operation was allowed (gating check). Allow, /// Operation was denied (gating check). Deny, /// Operation completed successfully. Ok, /// Operation failed. Error, } ``` Source line: `41`. ## audit::AuditRecord [#auditauditrecord] One audit record. Hash chained via `prev_hash` -> `hash`. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuditRecord { /// Monotonic sequence within the session. pub seq: u64, /// ISO-8601 timestamp. pub timestamp: String, /// Session id. pub session_id: String, /// Agent DID. pub agent_did: String, /// Event category. pub kind: AuditKind, /// Tool / skill name when applicable. #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, /// Outcome of the operation. pub outcome: Outcome, /// Hash of the request payload. #[serde(skip_serializing_if = "Option::is_none")] pub input_hash: Option, /// Hash of the response payload. #[serde(skip_serializing_if = "Option::is_none")] pub output_hash: Option, /// Pointer to the previous record's `hash` field. pub prev_hash: String, /// This record's hash (computed from every field except `hash` itself). pub hash: String, /// Free-form context. #[serde(skip_serializing_if = "Option::is_none")] pub context: Option } ``` Source line: `54`. ## audit::AuditSink [#auditauditsink] Audit sink trait — implement to ship records to a durable backend. ```rust #[async_trait] pub trait AuditSink: Send + Sync { /// Append a single record. MUST be best-effort and non-throwing. async fn append(&self, record: AuditRecord); } ``` Source line: `87`. ## audit::AuditChain [#auditauditchain] Builds and signs (hash-chains) audit records for a single session. ```rust pub struct AuditChain { } ``` Source line: `93`. ## audit::AuditChain::new [#auditauditchainnew] Construct a new chain rooted at the genesis prev hash. ```rust pub fn new( session_id: impl Into, agent_did: impl Into, sink: std::sync::Arc, ) -> Self; ``` Source line: `103`. ## audit::AuditChain::append [#auditauditchainappend] Append a record. Sink errors are swallowed by design. ```rust pub async fn append( &self, kind: AuditKind, name: Option<&str>, outcome: Outcome, input_hash: Option, output_hash: Option, context: Option, ) -> Result; ``` Source line: `118`. ## audit::AuditChain::head [#auditauditchainhead] Current chain head. ```rust pub fn head(&self) -> String; ``` Source line: `166`. ## audit::hash\_record [#audithash_record] Compute the hash of a record (excludes the `hash` field itself). ```rust pub fn hash_record(record: &AuditRecord) -> Result; ``` Source line: `175`. ## audit::verify\_chain [#auditverify_chain] Verify a previously emitted chain. ```rust pub fn verify_chain(records: &[AuditRecord]) -> Result<()>; ``` Source line: `185`. ## audit::InMemoryAuditSink [#auditinmemoryauditsink] In-memory audit sink (handy for tests + dev). ```rust #[derive(Debug, Default)] pub struct InMemoryAuditSink { } ``` Source line: `202`. ## audit::InMemoryAuditSink::new [#auditinmemoryauditsinknew] Construct a new in-memory sink. ```rust pub fn new() -> Self; ``` Source line: `208`. ## audit::InMemoryAuditSink::snapshot [#auditinmemoryauditsinksnapshot] Snapshot the buffered records (test helper). ```rust pub fn snapshot(&self) -> Vec; ``` Source line: `213`. ## audit::FanOutAuditSink [#auditfanoutauditsink] Fan-out sink: dispatch each record to every inner sink. ```rust pub struct FanOutAuditSink { } ``` Source line: `231`. ## audit::FanOutAuditSink::new [#auditfanoutauditsinknew] Construct a new fan-out sink. ```rust pub fn new(sinks: Vec>) -> Self; ``` Source line: `237`. # openagent-claude-agent · crate URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/crate Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/lib.rs`. SHA-256: `e8f91183afd16d5b68e4263a8ac0e6b53399b2e83daea317c8758d1f22ac7e51`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit [#audit] ```rust pub mod audit; ``` Source line: `62`. ## error [#error] ```rust pub mod error; ``` Source line: `63`. ## hash [#hash] ```rust pub mod hash; ``` Source line: `64`. ## hooks [#hooks] ```rust pub mod hooks; ``` Source line: `65`. ## identity [#identity] ```rust pub mod identity; ``` Source line: `66`. ## plugin [#plugin] ```rust pub mod plugin; ``` Source line: `67`. ## policy [#policy] ```rust pub mod policy; ``` Source line: `68`. ## pub use error::Error; [#pub-use-errorerror] ```rust pub use error::Error; ``` Source line: `70`. ## pub use hooks::\{HookContext, OpenAgentHooks}; [#pub-use-hookshookcontext-openagenthooks] ```rust pub use hooks::{HookContext, OpenAgentHooks}; ``` Source line: `71`. ## pub use plugin::\{OpenAgentPlugin, PluginConfig}; [#pub-use-pluginopenagentplugin-pluginconfig] ```rust pub use plugin::{OpenAgentPlugin, PluginConfig}; ``` Source line: `72`. # openagent-claude-agent · error URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/error Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/error.rs`. SHA-256: `72d4525fbfa0afd56bb272039df2f356fc7e12968ae58d7049cd238fb25500ac`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::Result [#errorresult] Result alias used throughout the crate. ```rust pub type Result = std::result::Result; ``` Source line: `6`. ## error::Error [#errorerror] All errors produced by `openagent-claude-agent`. ```rust #[derive(Debug, Error)] pub enum Error { /// Configuration was invalid at construction time. #[error("invalid configuration: {0}")] Config(String), /// A hook was invoked before the session was started. #[error("hook called before session_start")] NoActiveSession, /// A tool call was rejected because the agent lacks the required scope. #[error("tool denied: {tool} (required scope: {required_scope}; reason: {reason})")] ToolDenied { /// Tool name. tool: String, /// Scope that was checked. required_scope: String, /// Human-readable reason. reason: String, }, /// A skill invocation was rejected by the skills policy. #[error("skill denied: {skill} (reason: {reason})")] SkillDenied { /// Skill name. skill: String, /// Reason for denial. reason: String, }, /// Identity signing failed. #[error("signing failed: {0}")] Sign(String), /// Audit chain verification failed. #[error("audit chain broken at index {index}")] AuditBroken { /// Index in the chain where verification failed. index: usize, }, /// JSON (de)serialisation failure. #[error("serialization error: {0}")] Serde(#[from] serde_json::Error), /// I/O failure (sink, file, etc). #[error("io error: {0}")] Io(#[from] std::io::Error), } ``` Source line: `10`. # openagent-claude-agent · hash URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/hash Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/hash.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/hash.rs`. SHA-256: `09cb9f60075ccb9fec692f4a351ddb5a0f34500627c339d5985d3ef95d2f2b0c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## hash::hash\_hex [#hashhash_hex] Hash a byte buffer with BLAKE3 and return lowercase hex. ```rust pub fn hash_hex(bytes: &[u8]) -> String; ``` Source line: `6`. ## hash::canonical\_json [#hashcanonical_json] Stable JSON serialisation (object keys sorted) for canonical hashing. `serde_json` orders object keys lexicographically when using `serde_json::to_value` over a `BTreeMap`-like structure. We canonicalise by round-tripping through `serde_json::Value` and re-emitting via a helper that sorts maps. ```rust pub fn canonical_json(value: &T) -> Result; ``` Source line: `17`. ## hash::hash\_value [#hashhash_value] Hash a serialisable value via canonical JSON. ```rust pub fn hash_value(value: &T) -> Result; ``` Source line: `24`. # openagent-claude-agent · hooks URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/hooks Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/hooks.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/hooks.rs`. SHA-256: `3bf764fae3216f04fddedb38b0a7577d86ac1c17c79e524af886d11402a0a892`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## hooks::HookContext [#hookshookcontext] Per-session hook context. Constructed on session start, threaded through subsequent hook invocations, dropped on session end. ```rust pub struct HookContext { /// The verified agent identity. pub identity: Arc, /// Capability checker (Arsenal-backed in production). pub capabilities: Arc, /// Skills policy (defaults to `DenyUnlessScopedSkillsPolicy`). pub skills_policy: Arc, /// Audit chain for this session. pub chain: Arc, /// Whether outbound messages are signed with the agent's key. pub sign_messages: bool } ``` Source line: `27`. ## hooks::OpenAgentHooks [#hooksopenagenthooks] Lifecycle hook trait. Implement this in any Rust agent harness to receive OpenAgent enforcement and audit events. ```rust #[async_trait] pub trait OpenAgentHooks: Send + Sync { /// Called once when a new session begins. async fn on_session_start(&self, session_id: &str) -> Result<()>; /// Called once when the session ends. async fn on_session_end(&self) -> Result<()>; /// Called before a tool runs. Returns Err(ToolDenied) on deny in /// `Throw` mode; otherwise returns Ok with the (allow=false) audit /// trail already recorded. async fn pre_tool_use(&self, tool_name: &str, args: &Value) -> Result<()>; /// Called after a tool runs. async fn post_tool_use( &self, tool_name: &str, result: &Value, ok: bool, error: Option<&str>, ) -> Result<()>; /// Called when an outbound or inbound message passes through the agent. async fn on_message(&self, body: &[u8], outbound: bool) -> Result>; /// Called when the agent attempts to invoke a SKILLS.md skill. async fn on_skill_invoke(&self, skill_name: &str, args: Option<&Value>) -> Result<()>; } ``` Source line: `43`. # openagent-claude-agent · identity URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/identity Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/identity.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/identity.rs`. SHA-256: `735ea2a719fe37faba2ad65743fcb6490dd942db130f310b7ffa7208bff4ae8d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## identity::OpenAgentIdentity [#identityopenagentidentity] A signing key + DID, structurally compatible with the OAS identity surface. Implementations must NOT expose the secret key directly — signing operations go through the \[`OpenAgentIdentity::sign`] method. ```rust #[async_trait] pub trait OpenAgentIdentity: Send + Sync { /// The fully-qualified DID, e.g. `did:oas:test:agent:foo`. fn did(&self) -> &str; /// Entity kind: `hmr`, `mhr`, `agent`, `tool`, `skill`, ... fn kind(&self) -> &str; /// 32-byte Ed25519 public key. Returned by value (32 bytes is cheap) /// so adapters that wrap an external SDK don't need to cache. fn public_key(&self) -> [u8; 32]; /// Optional lineage chain (HMR -> ... -> this agent). fn lineage(&self) -> Vec ; /// Sign a payload. Implementations must never log or expose the key. async fn sign(&self, payload: &[u8]) -> Result>; } ``` Source line: `15`. ## identity::Identity [#identityidentity] Default in-process identity used by tests and dev harnesses. Signing is intentionally a deterministic stub — production deployments must replace this with an OAS-backed implementation that holds a real Ed25519 key. ```rust #[derive(Debug, Clone)] pub struct Identity { } ``` Source line: `41`. ## identity::Identity::new [#identityidentitynew] Construct a new identity. ```rust pub fn new(did: impl Into, kind: impl Into, public_key: [u8; 32]) -> Self; ``` Source line: `50`. ## identity::Identity::with\_lineage [#identityidentitywith_lineage] Set the lineage chain (builder). ```rust #[must_use] pub fn with_lineage(mut self, lineage: Vec) -> Self; ``` Source line: `61`. ## identity::OpenAgentSdkIdentity [#identityopenagentsdkidentity] Adapter that exposes an \[`openagent_sdk::OpenAgent`] as an \[`OpenAgentIdentity`]. This is the production wiring: hand the plugin an `OpenAgent` built via `OpenAgentBuilder` and it will pull DID, public key, and Ed25519 signing through the wrapped SDK. ```rust pub struct OpenAgentSdkIdentity { } ``` Source line: `105`. ## identity::OpenAgentSdkIdentity::new [#identityopenagentsdkidentitynew] Wrap an existing `openagent_sdk::OpenAgent`. ```rust pub fn new(inner: openagent_sdk::OpenAgent) -> Self; ``` Source line: `111`. ## identity::OpenAgentSdkIdentity::inner [#identityopenagentsdkidentityinner] Borrow the underlying SDK agent (escape hatch for advanced users). ```rust pub fn inner(&self) -> &openagent_sdk::OpenAgent; ``` Source line: `116`. # openagent-claude-agent modules URL: https://docs.openagent.id/reference/rust/openagent-claude-agent Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-integrations-claude-agent-sdk-rust). [Focused integration guide](/integrations/frameworks). ## Modules [#modules] * [crate](/reference/rust/openagent-claude-agent/crate) — 10 declarations * [audit](/reference/rust/openagent-claude-agent/audit) — 16 declarations * [error](/reference/rust/openagent-claude-agent/error) — 2 declarations * [hash](/reference/rust/openagent-claude-agent/hash) — 3 declarations * [hooks](/reference/rust/openagent-claude-agent/hooks) — 2 declarations * [identity](/reference/rust/openagent-claude-agent/identity) — 7 declarations * [plugin](/reference/rust/openagent-claude-agent/plugin) — 10 declarations * [policy](/reference/rust/openagent-claude-agent/policy) — 19 declarations # openagent-claude-agent · plugin URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/plugin Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/plugin.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/plugin.rs`. SHA-256: `87304e5c59bf4e6a5b65c3631673ed87107bc9dc98e2c8eeaff4ddd5a89c3f22`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## plugin::DenyMode [#plugindenymode] Behaviour on a denied tool / skill request. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DenyMode { /// Return `Err(Error::ToolDenied / SkillDenied)`. Throw, /// Record the deny in the audit log and return `Ok(())`. Block, } ``` Source line: `22`. ## plugin::PluginConfig [#pluginpluginconfig] Plugin configuration. ```rust pub struct PluginConfig { /// The verified OpenAgent identity to attach to the session. Any /// implementor of [`OpenAgentIdentity`] is accepted — typically an /// [`crate::identity::OpenAgentSdkIdentity`] in production or /// [`crate::identity::Identity`] in tests. pub identity: Arc, /// Capability checker (Arsenal-backed in production). pub capabilities: Arc, /// Skills policy. pub skills_policy: Arc, /// Audit sink. pub sink: Arc, /// Sign outbound messages with the agent key. pub sign_messages: bool, /// Behaviour on deny. pub deny_mode: DenyMode } ``` Source line: `30`. ## plugin::OpenAgentPlugin [#pluginopenagentplugin] The composition root that drives the lifecycle hooks. ```rust pub struct OpenAgentPlugin { } ``` Source line: `49`. ## plugin::OpenAgentPlugin::new [#pluginopenagentpluginnew] Construct a new plugin from configuration. ```rust pub fn new(config: PluginConfig) -> Self; ``` Source line: `65`. ## plugin::OpenAgentPlugin::session\_start [#pluginopenagentpluginsession_start] Begin a new session — must be called before any other hook. ```rust pub async fn session_start(&self, session_id: &str) -> Result<()>; ``` Source line: `80`. ## plugin::OpenAgentPlugin::session\_end [#pluginopenagentpluginsession_end] End the current session. ```rust pub async fn session_end(&self) -> Result<()>; ``` Source line: `112`. ## plugin::OpenAgentPlugin::pre\_tool\_use [#pluginopenagentpluginpre_tool_use] Verify a tool call against Arsenal scopes (preflight). ```rust pub async fn pre_tool_use(&self, tool_name: &str, args: &Value) -> Result<()>; ``` Source line: `131`. ## plugin::OpenAgentPlugin::post\_tool\_use [#pluginopenagentpluginpost_tool_use] Emit a post-tool-use audit record. ```rust pub async fn post_tool_use( &self, tool_name: &str, result: &Value, ok: bool, error: Option<&str>, ) -> Result<()>; ``` Source line: `179`. ## plugin::OpenAgentPlugin::on\_message [#pluginopenagentpluginon_message] Sign an outbound message and emit an audit record. ```rust pub async fn on_message(&self, body: &[u8], outbound: bool) -> Result>; ``` Source line: `203`. ## plugin::OpenAgentPlugin::on\_skill\_invoke [#pluginopenagentpluginon_skill_invoke] Consult the skills policy before a SKILLS.md skill runs. ```rust pub async fn on_skill_invoke( &self, skill_name: &str, args: Option<&Value>, ) -> Result<()>; ``` Source line: `234`. # openagent-claude-agent · policy URL: https://docs.openagent.id/reference/rust/openagent-claude-agent/policy Markdown: https://docs.openagent.id/reference/rust/openagent-claude-agent/policy.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/claude-agent-sdk/rust/src/policy.rs`. SHA-256: `6cd87a54d42dfa671bac1443a09d0d1b7555f810e604c4866440a6131dde8097`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## policy::TOOL\_SCOPE\_PREFIX [#policytool_scope_prefix] Canonical scope prefix for tool invocations. ```rust pub const TOOL_SCOPE_PREFIX: &str; ``` Source line: `12`. ## policy::SKILL\_SCOPE\_PREFIX [#policyskill_scope_prefix] Canonical scope prefix for skill invocations. ```rust pub const SKILL_SCOPE_PREFIX: &str; ``` Source line: `15`. ## policy::tool\_scope [#policytool_scope] Build a canonical scope string for a tool name. ```rust #[must_use] pub fn tool_scope(name: &str) -> String; ``` Source line: `19`. ## policy::skill\_scope [#policyskill_scope] Build a canonical scope string for a skill name. ```rust #[must_use] pub fn skill_scope(name: &str) -> String; ``` Source line: `25`. ## policy::ScopeDecision [#policyscopedecision] Result of a single scope check. ```rust #[derive(Debug, Clone)] pub struct ScopeDecision { /// Whether the request is allowed. pub allowed: bool, /// Matched scope string (if any). pub matched_scope: Option, /// Human-readable reason for denial. pub reason: Option } ``` Source line: `31`. ## policy::ScopeDecision::allow [#policyscopedecisionallow] Build an allow decision. ```rust pub fn allow(matched: impl Into) -> Self; ``` Source line: `42`. ## policy::ScopeDecision::deny [#policyscopedecisiondeny] Build a deny decision. ```rust pub fn deny(reason: impl Into) -> Self; ``` Source line: `51`. ## policy::CapabilityChecker [#policycapabilitychecker] Trait implemented by anything that can authorise scope requests. ```rust #[async_trait] pub trait CapabilityChecker: Send + Sync { /// Check whether the agent currently holds the requested scope. async fn check(&self, scope: &str) -> Result; } ``` Source line: `62`. ## policy::StaticCapabilityChecker [#policystaticcapabilitychecker] Static capability checker backed by a fixed allow-list. Supports literal scopes and one wildcard form: any entry ending in `*` matches anything starting with the prefix preceding the `*`. ```rust #[derive(Debug, Default)] pub struct StaticCapabilityChecker { } ``` Source line: `72`. ## policy::StaticCapabilityChecker::new [#policystaticcapabilitycheckernew] Construct a checker from an iterator of scope strings. ```rust pub fn new(scopes: I) -> Self where I: IntoIterator, S: Into,; ``` Source line: `79`. ## policy::SkillDecision [#policyskilldecision] Decision returned by \[`SkillsPolicy`]. ```rust #[derive(Debug, Clone)] pub struct SkillDecision { /// Allow / deny. pub allowed: bool, /// Reason on deny. pub reason: Option, /// Matched scope on allow. pub matched_scope: Option } ``` Source line: `115`. ## policy::SkillsPolicy [#policyskillspolicy] Skills policy: gates SKILLS.md skill invocations. ```rust #[async_trait] pub trait SkillsPolicy: Send + Sync { /// Evaluate whether the named skill may be invoked by the current agent. async fn evaluate( &self, skill_name: &str, identity: &dyn OpenAgentIdentity, capabilities: &dyn CapabilityChecker, ) -> Result; } ``` Source line: `126`. ## policy::DenyUnlessScopedSkillsPolicy [#policydenyunlessscopedskillspolicy] Default policy: deny unless the agent holds `skills:invoke:`. ```rust #[derive(Debug, Default, Clone, Copy)] pub struct DenyUnlessScopedSkillsPolicy; ``` Source line: `138`. ## policy::AllowListSkillsPolicy [#policyallowlistskillspolicy] Allow-list skills policy: only listed skills are permitted, and the inner policy (defaults to \[`DenyUnlessScopedSkillsPolicy`]) must also allow the call. ```rust pub struct AllowListSkillsPolicy { } ``` Source line: `173`. ## policy::AllowListSkillsPolicy::new [#policyallowlistskillspolicynew] Construct a new allow-list policy. ```rust pub fn new(allowed: I, inner: Option>) -> Self where I: IntoIterator, S: Into,; ``` Source line: `180`. ## policy::OpenAgentSdkSkillsPolicy [#policyopenagentsdkskillspolicy] Adapter that bridges the OpenAgent SDK's `SkillsPolicy` (synchronous, owned by an `OpenAgent`) into this crate's async \[`SkillsPolicy`]. Use this when you've already configured a skills policy on an `openagent_sdk::OpenAgent` (e.g., via `with_skills_policy`) and want the same policy to gate Claude Agent SDK skill invocations. ```rust pub struct OpenAgentSdkSkillsPolicy { } ``` Source line: `217`. ## policy::OpenAgentSdkSkillsPolicy::new [#policyopenagentsdkskillspolicynew] Wrap an `openagent_sdk::SkillsPolicyHandle`. ```rust pub fn new(inner: openagent_sdk::SkillsPolicyHandle) -> Self; ``` Source line: `223`. ## policy::CompositeSkillsPolicy [#policycompositeskillspolicy] Composite policy: every inner policy must allow. ```rust pub struct CompositeSkillsPolicy { } ``` Source line: `252`. ## policy::CompositeSkillsPolicy::new [#policycompositeskillspolicynew] Construct a composite policy from a Vec of inner policies. ```rust pub fn new(policies: Vec>) -> Self; ``` Source line: `258`. # openagent-http · axum URL: https://docs.openagent.id/reference/rust/openagent-http/axum Markdown: https://docs.openagent.id/reference/rust/openagent-http/axum.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/axum.rs`. SHA-256: `cfdd6182f5b3b456e5e000560b61735b50ac4bd786b8dae6dddb65a1157766e8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "axum-integration")] ``` ## axum::OpenAgentState [#axumopenagentstate] Shared state for the Axum integration. ```rust #[cfg(feature = "axum-integration")] #[derive(Clone)] pub struct OpenAgentState { /// The server configuration (origin, realm, TTLs, trust tier). pub config: Arc } ``` Source line: `35`. ## axum::OpenAgentState\::new [#axumopenagentstatesnew] Creates a new integration state. ```rust #[cfg(feature = "axum-integration")] pub fn new(config: ServerConfig, store: S) -> Self; ``` Source line: `43`. ## axum::OpenAgentState\::store [#axumopenagentstatesstore] The session store. ```rust #[cfg(feature = "axum-integration")] pub fn store(&self) -> &S; ``` Source line: `51`. ## axum::OpenAgentExtractor [#axumopenagentextractor] Axum extractor providing the authenticated agent context. Routes can take this as an argument to get the verified session. ```rust #[cfg(feature = "axum-integration")] #[derive(Debug, Clone)] pub struct OpenAgentExtractor { } ``` Source line: `60`. ## axum::OpenAgentExtractor::peer\_did [#axumopenagentextractorpeer_did] Returns the authenticated agent's DID (or presented-key placeholder until a resolver names it). ```rust #[cfg(feature = "axum-integration")] pub fn peer_did(&self) -> &str; ``` Source line: `67`. ## axum::OpenAgentExtractor::session\_token [#axumopenagentextractorsession_token] Returns the session token. ```rust #[cfg(feature = "axum-integration")] pub fn session_token(&self) -> &str; ``` Source line: `72`. ## axum::OpenAgentExtractor::session [#axumopenagentextractorsession] Returns the underlying session. ```rust #[cfg(feature = "axum-integration")] pub fn session(&self) -> &Session; ``` Source line: `77`. ## axum::core\_routes [#axumcore_routes] Build an Axum router with the well-known endpoints: * `GET /.well-known/openagent` — discovery * `POST /.well-known/openagent/auth` — issue an \[`openagent_auth_protocol::message::IdentityChallenge`] * `POST /.well-known/openagent/auth/prove` — verify an \[`IdentityProof`], return \[`IdentityVerified`] ```rust #[cfg(feature = "axum-integration")] pub fn core_routes(state: OpenAgentState) -> Router where S: SessionStore + Clone + Send + Sync + 'static,; ``` Source line: `154`. ## axum::protected\_router [#axumprotected_router] Convenience: merge the well-known endpoints with application routes. ```rust #[cfg(feature = "axum-integration")] pub fn protected_router( state: OpenAgentState, app_routes: Router>, ) -> Router where S: SessionStore + Clone + Send + Sync + 'static,; ``` Source line: `207`. # openagent-http · client URL: https://docs.openagent.id/reference/rust/openagent-http/client Markdown: https://docs.openagent.id/reference/rust/openagent-http/client.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/client.rs`. SHA-256: `49ea43248efb494f9d157791b6f6359a1970209f8005fc34e38ea48925ef950a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client::ClientConfig [#clientclientconfig] Configuration for the HTTP auth client. ```rust #[derive(Debug, Clone)] pub struct ClientConfig { /// The agent's DID. Reported to the server for audit and, where the /// deployment resolves DIDs, for trust-tier assignment. The agent proves /// possession of the key - lineage evaluation is the server's job. pub did: String } ``` Source line: `24`. ## client::HttpAuthClient [#clienthttpauthclient] HTTP client that performs the Core Protocol identity flow over REST. ```rust pub struct HttpAuthClient { } ``` Source line: `32`. ## client::HttpAuthClient::new [#clienthttpauthclientnew] Creates a new HTTP auth client. # Arguments [#arguments] * `config`: Agent identity configuration * `signing_key_bytes`: 32-byte Ed25519 signing key ```rust pub fn new( config: ClientConfig, signing_key_bytes: &[u8; 32], ) -> Result; ``` Source line: `44`. ## client::HttpAuthClient::with\_client [#clienthttpauthclientwith_client] Creates a client with a custom `reqwest::Client`. ```rust pub fn with_client( config: ClientConfig, signing_key_bytes: &[u8; 32], client: reqwest::Client, ) -> Self; ``` Source line: `58`. ## client::HttpAuthClient::authenticate [#clienthttpauthclientauthenticate] Performs the full identity flow against the given base URL. 1. Discovers the auth endpoint via `GET /.well-known/openagent` (tolerating discovery failure and falling back to the default path) 2. Fetches an `openagent-challenge-v1` challenge 3. Signs the JCS-canonical challenge bytes and proves 4. Returns an \[`AuthenticatedSession`] carrying the session token ```rust pub async fn authenticate( &self, base_url: &str, ) -> Result; ``` Source line: `79`. # openagent-http · crate URL: https://docs.openagent.id/reference/rust/openagent-http/crate Markdown: https://docs.openagent.id/reference/rust/openagent-http/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/lib.rs`. SHA-256: `e8edfdccf52752530c137986e9048db7421eab6c4e467f7eb2573eeddc5eef63`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client [#client] ```rust pub mod client; ``` Source line: `29`. ## discovery [#discovery] ```rust pub mod discovery; ``` Source line: `30`. ## headers [#headers] ```rust pub mod headers; ``` Source line: `31`. ## server [#server] ```rust pub mod server; ``` Source line: `32`. ## session [#session] ```rust pub mod session; ``` Source line: `33`. ## transport [#transport] ```rust pub mod transport; ``` Source line: `34`. ## axum [#axum] ```rust #[cfg(feature = "axum-integration")] pub mod axum; ``` Source line: `37`. ## pub use headers::\{HEADER\_OPENAGENT\_DID, HEADER\_OPENAGENT\_SESSION, OPENAGENT\_AUTH\_SCHEME}; [#pub-use-headersheader_openagent_did-header_openagent_session-openagent_auth_scheme] ```rust pub use headers::{HEADER_OPENAGENT_DID, HEADER_OPENAGENT_SESSION, OPENAGENT_AUTH_SCHEME}; ``` Source line: `39`. ## pub use transport::HttpTransport; [#pub-use-transporthttptransport] ```rust pub use transport::HttpTransport; ``` Source line: `40`. ## ::VERSION [#version] Crate version. ```rust pub const VERSION: &str; ``` Source line: `43`. # openagent-http · discovery URL: https://docs.openagent.id/reference/rust/openagent-http/discovery Markdown: https://docs.openagent.id/reference/rust/openagent-http/discovery.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/discovery.rs`. SHA-256: `76dfb34252ff2196b5f6cb0c381771dba74eb929cf75c150dcad78d85744fb9c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## discovery::fetch\_discovery [#discoveryfetch_discovery] Fetch the discovery document from a server. Sends `GET /.well-known/openagent` and parses the response. ```rust pub async fn fetch_discovery( http_client: &reqwest::Client, base_url: &str, ) -> Result; ``` Source line: `14`. ## discovery::resolve\_auth\_endpoint [#discoveryresolve_auth_endpoint] Resolve the full auth endpoint URL from a base URL and discovery document. ```rust pub fn resolve_auth_endpoint(base_url: &str, doc: &DiscoveryDocument) -> String; ``` Source line: `47`. ## discovery::resolve\_prove\_endpoint [#discoveryresolve_prove_endpoint] Resolve the prove endpoint URL (auth endpoint + `/prove`). ```rust pub fn resolve_prove_endpoint(base_url: &str, doc: &DiscoveryDocument) -> String; ``` Source line: `54`. # openagent-http · headers URL: https://docs.openagent.id/reference/rust/openagent-http/headers Markdown: https://docs.openagent.id/reference/rust/openagent-http/headers.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/headers.rs`. SHA-256: `8c24d4281714b6d4a9eae19e89a1e696427759aa9516860fa5542623e23935d4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## headers::OPENAGENT\_AUTH\_SCHEME [#headersopenagent_auth_scheme] The canonical authorization scheme for OpenAgent-authenticated requests, per the Core Protocol HTTP binding. ```rust pub const OPENAGENT_AUTH_SCHEME: &str; ``` Source line: `11`. ## headers::HEADER\_OPENAGENT\_DID [#headersheader_openagent_did] Header carrying the authenticated agent's DID. ```rust pub const HEADER_OPENAGENT_DID: &str; ``` Source line: `14`. ## headers::HEADER\_OPENAGENT\_SESSION [#headersheader_openagent_session] Header carrying the session token (alternative to the Authorization header for clients that cannot set it). ```rust pub const HEADER_OPENAGENT_SESSION: &str; ``` Source line: `18`. ## headers::CONTENT\_TYPE\_JSON [#headerscontent_type_json] Content-Type for all Core Protocol JSON payloads. ```rust pub const CONTENT_TYPE_JSON: &str; ``` Source line: `21`. ## headers::extract\_openagent\_token [#headersextract_openagent_token] Extract the session token from an `Authorization: OpenAgent ` header. Returns `None` if the header is missing, malformed, or uses a different scheme. ```rust pub fn extract_openagent_token(authorization: &str) -> Option<&str>; ``` Source line: `26`. ## headers::build\_openagent\_header [#headersbuild_openagent_header] Build an `Authorization: OpenAgent ` header value. ```rust pub fn build_openagent_header(token: &str) -> String; ``` Source line: `42`. ## headers::build\_challenge\_header [#headersbuild_challenge_header] Build a `WWW-Authenticate: OpenAgent challenge=""` header value for the reactive flow: the challenge object serialized and base64url encoded (per the HTTP binding, Section 4.3 of the specification). ```rust pub fn build_challenge_header(challenge: &IdentityChallenge) -> String; ``` Source line: `49`. ## headers::parse\_challenge\_header [#headersparse_challenge_header] Decode a challenge from a `WWW-Authenticate` header value (client side of the reactive flow). ```rust pub fn parse_challenge_header(header_value: &str) -> Option; ``` Source line: `57`. # openagent-http modules URL: https://docs.openagent.id/reference/rust/openagent-http Markdown: https://docs.openagent.id/reference/rust/openagent-http.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-adapters-http-rust). [Focused integration guide](/integrations/adapters). ## Modules [#modules] * [crate](/reference/rust/openagent-http/crate) — 10 declarations * [client](/reference/rust/openagent-http/client) — 5 declarations * [discovery](/reference/rust/openagent-http/discovery) — 3 declarations * [headers](/reference/rust/openagent-http/headers) — 8 declarations * [server](/reference/rust/openagent-http/server) — 10 declarations * [session](/reference/rust/openagent-http/session) — 10 declarations * [transport](/reference/rust/openagent-http/transport) — 4 declarations * [axum](/reference/rust/openagent-http/axum) — 9 declarations # openagent-http · server URL: https://docs.openagent.id/reference/rust/openagent-http/server Markdown: https://docs.openagent.id/reference/rust/openagent-http/server.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/server.rs`. SHA-256: `f5e13912bf968d446ee97104dfd709bc4dfae668cd06db2029c64eee261f1f5e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## server::ServerConfig [#serverserverconfig] Server configuration for the HTTP adapter. ```rust #[derive(Debug, Clone)] pub struct ServerConfig { /// The server's origin per RFC 6454 (`scheme://host[:port]`). Bound into /// every challenge the server issues. pub origin: String, /// Optional protection-space identifier. pub realm: Option, /// The trust tier assigned to verified agents. Deployments with DID /// resolution and registry context assign higher tiers in their own /// policy layer; this adapter's default is key-possession-only. pub trust_tier: TrustTier, /// Session TTL in seconds. pub session_ttl_secs: u32, /// Challenge TTL in seconds. pub challenge_ttl_secs: u32 } ``` Source line: `29`. ## server::ServerConfig::new [#serverserverconfignew] Creates a new server configuration with sensible defaults. ```rust pub fn new(origin: impl Into) -> Self; ``` Source line: `47`. ## server::ServerConfig::with\_realm [#serverserverconfigwith_realm] Sets the protection-space identifier. ```rust pub fn with_realm(mut self, realm: impl Into) -> Self; ``` Source line: `58`. ## server::ServerConfig::with\_trust\_tier [#serverserverconfigwith_trust_tier] Sets the trust tier assigned to verified agents. ```rust pub fn with_trust_tier(mut self, tier: TrustTier) -> Self; ``` Source line: `64`. ## server::ServerConfig::with\_session\_ttl [#serverserverconfigwith_session_ttl] Sets the session TTL. ```rust pub fn with_session_ttl(mut self, secs: u32) -> Self; ``` Source line: `70`. ## server::ServerConfig::with\_challenge\_ttl [#serverserverconfigwith_challenge_ttl] Sets the challenge TTL. ```rust pub fn with_challenge_ttl(mut self, secs: u32) -> Self; ``` Source line: `76`. ## server::handle\_discovery [#serverhandle_discovery] Handle `GET /.well-known/openagent` — returns the discovery document. ```rust pub fn handle_discovery(config: &ServerConfig) -> DiscoveryDocument; ``` Source line: `83`. ## server::handle\_challenge [#serverhandle_challenge] Handle the challenge step — issue an \[`IdentityChallenge`]. Creates a fresh challenge per Section 4 and records a pending session keyed by the nonce, so the proof step can find exactly one challenge to answer and a nonce can never be answered twice. ```rust pub async fn handle_challenge( config: &ServerConfig, store: &S, ) -> Result; ``` Source line: `97`. ## server::handle\_prove [#serverhandle_prove] Handle the prove step — verify an \[`IdentityProof`] and issue a session. Verification is normative-ordered: shape checks first (nonce echo, key length per scheme), then the pending challenge (present, unexpired), then the signature over the JCS-canonical challenge bytes. The nonce is consumed on success *and* on signature failure - a failed answer must not be retryable, or a verifier becomes an oracle. ```rust pub async fn handle_prove( config: &ServerConfig, store: &S, proof: &IdentityProof, ) -> Result; ``` Source line: `137`. ## server::validate\_authenticated\_request [#servervalidate_authenticated_request] Validate an authenticated request by checking the session store. Looks up the session by its token, verifies it is established and not expired, and returns it. ```rust pub async fn validate_authenticated_request( store: &S, session_token: &str, ) -> Result; ``` Source line: `256`. # openagent-http · session URL: https://docs.openagent.id/reference/rust/openagent-http/session Markdown: https://docs.openagent.id/reference/rust/openagent-http/session.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/session.rs`. SHA-256: `ba53a721c939d4b67d6e8d1a17c097716926a28910a8ec424fba9bf88d35586b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session::AuthenticatedSession [#sessionauthenticatedsession] An authenticated HTTP session obtained after a successful OAAP handshake. Wraps a `reqwest::Client` and attaches the `Authorization: OAS `, `X-OpenAgent-DID`, and `X-OpenAgent-Session` headers to every request. ```rust #[derive(Debug, Clone)] pub struct AuthenticatedSession { } ``` Source line: `17`. ## session::AuthenticatedSession::new [#sessionauthenticatedsessionnew] Creates a new authenticated session. ```rust pub fn new( client: reqwest::Client, base_url: String, session_id: String, peer_did: String, session_token: String, expires_at: i64, ) -> Self; ``` Source line: `30`. ## session::AuthenticatedSession::is\_expired [#sessionauthenticatedsessionis_expired] Returns true if the session has expired. ```rust pub fn is_expired(&self) -> bool; ``` Source line: `49`. ## session::AuthenticatedSession::session\_id [#sessionauthenticatedsessionsession_id] Returns the session ID. ```rust pub fn session_id(&self) -> &str; ``` Source line: `54`. ## session::AuthenticatedSession::peer\_did [#sessionauthenticatedsessionpeer_did] Returns the peer DID. ```rust pub fn peer_did(&self) -> &str; ``` Source line: `59`. ## session::AuthenticatedSession::base\_url [#sessionauthenticatedsessionbase_url] Returns the base URL of the authenticated server. ```rust pub fn base_url(&self) -> &str; ``` Source line: `64`. ## session::AuthenticatedSession::get [#sessionauthenticatedsessionget] Sends an authenticated GET request. ```rust pub async fn get(&self, path: &str) -> Result; ``` Source line: `69`. ## session::AuthenticatedSession::post [#sessionauthenticatedsessionpost] Sends an authenticated POST request with a JSON body. ```rust pub async fn post( &self, path: &str, body: &impl serde::Serialize, ) -> Result; ``` Source line: `84`. ## session::AuthenticatedSession::put [#sessionauthenticatedsessionput] Sends an authenticated PUT request with a JSON body. ```rust pub async fn put( &self, path: &str, body: &impl serde::Serialize, ) -> Result; ``` Source line: `104`. ## session::AuthenticatedSession::delete [#sessionauthenticatedsessiondelete] Sends an authenticated DELETE request. ```rust pub async fn delete(&self, path: &str) -> Result; ``` Source line: `124`. # openagent-http · transport URL: https://docs.openagent.id/reference/rust/openagent-http/transport Markdown: https://docs.openagent.id/reference/rust/openagent-http/transport.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/http/rust/src/transport.rs`. SHA-256: `3c74f3a12577b95f58fdecb1da9c390d554f6bf1df536c197a4c1a322e16dc1c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## transport::HttpTransport [#transporthttptransport] HTTP transport carrying the identity flow over REST. The challenge is fetched with `POST ` and the proof with `POST /prove`, per the HTTP binding's proactive form. The reactive form (`401` + `WWW-Authenticate`) is handled by the client, which also understands challenge headers. ```rust pub struct HttpTransport { } ``` Source line: `16`. ## transport::HttpTransport::new [#transporthttptransportnew] Creates a new HTTP transport with the given `reqwest` client. ```rust pub fn new(client: reqwest::Client) -> Self; ``` Source line: `22`. ## transport::HttpTransport::with\_defaults [#transporthttptransportwith_defaults] Creates a new HTTP transport with a default client. ```rust pub fn with_defaults() -> Result; ``` Source line: `27`. ## transport::HttpTransport::inner [#transporthttptransportinner] Returns a reference to the inner reqwest client. ```rust pub fn inner(&self) -> &reqwest::Client; ``` Source line: `38`. # openagent-mcp · crate URL: https://docs.openagent.id/reference/rust/openagent-mcp/crate Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/lib.rs`. SHA-256: `11aff0aa5e83e1a0673b1faf7ed5fb90ca60cb9637f517d3e53e152186cbce35`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## pub use rmcp\_adapter::RmcpOpenAgent; [#pub-use-rmcp_adapterrmcpopenagent] ```rust #[cfg(feature = "rmcp")] pub use rmcp_adapter::RmcpOpenAgent; ``` Source line: `58`. ## pub use errors::\{McpAuthError, McpErrorCode}; [#pub-use-errorsmcpautherror-mcperrorcode] ```rust pub use errors::{McpAuthError, McpErrorCode}; ``` Source line: `60`. ## pub use handler::\{ [#pub-use-handler] InMemoryToolHandler, RegisteredTool, ToolCall, ToolHandler, ToolResult, WithOpenAgent, WrappedHandler, }; ```rust pub use handler::{ InMemoryToolHandler, RegisteredTool, ToolCall, ToolHandler, ToolResult, WithOpenAgent, WrappedHandler, }; ``` Source line: `61`. ## pub use middleware::\{OpenAgentMiddleware, default\_require\_scopes, default\_scope\_format}; [#pub-use-middlewareopenagentmiddleware-default_require_scopes-default_scope_format] ```rust pub use middleware::{OpenAgentMiddleware, default_require_scopes, default_scope_format}; ``` Source line: `65`. ## pub use skills::\{ [#pub-use-skills] InMemorySkillsStore, SkillsPolicy, SkillsPolicyDecision, SkillsRule, SkillsStore, DEFAULT\_SKILL\_TOOL\_NAMES, }; ```rust pub use skills::{ InMemorySkillsStore, SkillsPolicy, SkillsPolicyDecision, SkillsRule, SkillsStore, DEFAULT_SKILL_TOOL_NAMES, }; ``` Source line: `66`. ## pub use types::\{ [#pub-use-types] Agent, AuditMeta, Config, ErrorHook, Identity, IdentityVerifier, PostCallHook, PreCallHook, ScopeDeriver, VerifiedIdentity, }; ```rust pub use types::{ Agent, AuditMeta, Config, ErrorHook, Identity, IdentityVerifier, PostCallHook, PreCallHook, ScopeDeriver, VerifiedIdentity, }; ``` Source line: `70`. # openagent-mcp · errors URL: https://docs.openagent.id/reference/rust/openagent-mcp/errors Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/errors.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/errors.rs`. SHA-256: `e79319eebdefb1f95676a8579a2e34cf8aee982a73d7bb530b47dcc5942f07c8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## errors::McpErrorCode [#errorsmcperrorcode] JSON-RPC + MCP error codes used by the middleware. All entries lie inside the `-32000..=-32099` server-error range reserved by the JSON-RPC spec for application use. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[repr(i32)] pub enum McpErrorCode { /// Generic server error. ServerError = -32000, /// Identity verification failed (no envelope, bad proof, etc.). AuthenticationFailed = -32001, /// Caller does not hold the required scopes. AuthorizationDenied = -32002, /// Skills policy hook returned `allow: false`. SkillsPolicyDenied = -32003, /// Method or tool not found. MethodNotFound = -32601, /// Invalid parameters. InvalidParams = -32602, /// Internal error. InternalError = -32603, } ``` Source line: `18`. ## errors::McpErrorCode::as\_i32 [#errorsmcperrorcodeas_i32] Return the underlying integer code. ```rust pub fn as_i32(self) -> i32; ``` Source line: `37`. ## errors::McpAuthError [#errorsmcpautherror] All errors produced by the middleware. Subclasses set a default \[`McpErrorCode`] that maps to a JSON-RPC error code. ```rust #[derive(Debug, Error)] pub enum McpAuthError { /// `_meta.openagent.identity` was absent on a tool call. #[error("Tool '{tool}' requires an OpenAgent identity in _meta.openagent.identity")] MissingIdentity { /// The tool name the call targeted. tool: String, }, /// The verifier rejected the supplied envelope. #[error("Identity verification failed for tool '{tool}': {reason}")] VerificationFailed { /// The tool name. tool: String, /// Human-readable reason from the verifier. reason: String, }, /// The verified identity does not hold the required scopes. #[error( "Tool '{tool}' requires scopes [{required}], caller holds [{held}]" )] AuthorizationDenied { /// The tool name. tool: String, /// Required scopes, comma-joined for display. required: String, /// Held scopes, comma-joined for display. held: String, }, /// The skills policy denied the call. #[error("Skills policy denied tool '{tool}'{}", reason.as_ref().map(|r| format!(": {r}")).unwrap_or_default())] SkillsPolicyDenied { /// The tool name. tool: String, /// Optional reason from the policy hook. reason: Option, }, /// Tool body or downstream component returned an error. #[error("Tool '{tool}' failed: {source}")] ToolFailed { /// The tool name. tool: String, /// Underlying error type-erased to a string. source: Box, }, /// Generic internal error. Use sparingly — prefer one of the variants /// above when the failure category is known. #[error("Internal middleware error: {0}")] Internal(String), } ``` Source line: `45`. ## errors::McpAuthError::code [#errorsmcpautherrorcode] Map the error to a JSON-RPC error code. ```rust pub fn code(&self) -> McpErrorCode; ``` Source line: `101`. ## errors::McpAuthError::to\_json\_rpc [#errorsmcpautherrorto_json_rpc] Render the error as a JSON-RPC error envelope. ```rust pub fn to_json_rpc(&self) -> JsonRpcError; ``` Source line: `113`. ## errors::JsonRpcError [#errorsjsonrpcerror] Serializable JSON-RPC error envelope. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct JsonRpcError { /// JSON-RPC error code. pub code: i32, /// Human-readable message. pub message: String, /// Optional structured data payload. #[serde(skip_serializing_if = "Option::is_none")] pub data: Option } ``` Source line: `147`. # openagent-mcp · handler URL: https://docs.openagent.id/reference/rust/openagent-mcp/handler Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/handler.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/handler.rs`. SHA-256: `90e5087e39d015e22b608bba0f1550506c76121634c4718f0b82463c42463243`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## handler::ToolCall [#handlertoolcall] A single inbound `tools/call` request. `meta` carries the request metadata pulled from the MCP envelope — in particular `meta["openagent"]["identity"]` is where the auth envelope lives. The middleware reads it and never modifies it in place. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ToolCall { /// The tool name (e.g., `"search_web"`). pub name: String, /// JSON arguments the caller supplied. #[serde(default)] pub arguments: serde_json::Value, /// Request metadata. Identity envelope lives at /// `meta["openagent"]["identity"]`. #[serde(default)] pub meta: serde_json::Value } ``` Source line: `32`. ## handler::ToolResult [#handlertoolresult] A single outbound tool result. The middleware stamps audit metadata onto `meta` after the handler returns. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ToolResult { /// MCP content blocks (text, image, resource_link, etc). #[serde(default)] pub content: serde_json::Value, /// Optional structured content (the new MCP 2025 field). #[serde(default, skip_serializing_if = "Option::is_none")] pub structured_content: Option, /// Optional `isError` flag for error responses returned via the /// happy-path channel. #[serde(default, skip_serializing_if = "Option::is_none")] pub is_error: Option, /// Result metadata. Audit metadata is stamped here on success. #[serde(default)] pub meta: serde_json::Value } ``` Source line: `47`. ## handler::ToolResult::text [#handlertoolresulttext] Build a simple text result with no metadata. ```rust pub fn text(message: impl Into) -> Self; ``` Source line: `65`. ## handler::RegisteredTool [#handlerregisteredtool] Description of a registered tool, returned by \[`ToolHandler::list_tools`]. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RegisteredTool { /// Tool name. pub name: String, /// Optional description for clients. #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option } ``` Source line: `78`. ## handler::ToolHandler [#handlertoolhandler] The trait every concrete server handler implements. Two methods — `list_tools` and `call_tool` — keep the surface narrow and stable across MCP SDK versions. ```rust #[async_trait] pub trait ToolHandler: Send + Sync { /// Return the tools this handler exposes. async fn list_tools(&self) -> Vec; /// Execute a single tool call. Implementations should NOT do any /// authentication or authorization — that runs in the middleware /// before this is invoked. async fn call_tool(&self, call: ToolCall) -> Result; } ``` Source line: `90`. ## handler::WithOpenAgent [#handlerwithopenagent] Marker trait — anything that implements \[`ToolHandler`] can be wrapped via \[`WithOpenAgent::with_openagent`]. ````rust pub trait WithOpenAgent: ToolHandler + Sized { /// Wrap this handler with the OpenAgent middleware. /// /// ```no_run /// use openagent_mcp::{Config, InMemoryToolHandler, OpenAgentMiddleware, WithOpenAgent}; /// # use std::sync::Arc; /// # async fn example(agent: std::sync::Arc) { /// let handler = InMemoryToolHandler::new(); /// let middleware = OpenAgentMiddleware::new(Config::new(agent)); /// let authed = handler.with_openagent(middleware); /// # let _ = authed; /// # } /// ``` fn with_openagent(self, middleware: OpenAgentMiddleware) -> WrappedHandler ; } ```` Source line: `102`. ## handler::WrappedHandler [#handlerwrappedhandler] Result of wrapping a \[`ToolHandler`] with \[`OpenAgentMiddleware`]. `WrappedHandler` itself implements \[`ToolHandler`], so the wrapped instance is a drop-in replacement for the original — the rest of your server code keeps working unchanged. ```rust pub struct WrappedHandler { } ``` Source line: `130`. ## handler::InMemoryToolHandler [#handlerinmemorytoolhandler] In-memory test handler. Useful for unit and integration tests of the middleware (and as a tiny example of what a custom handler looks like). ```rust #[derive(Default)] pub struct InMemoryToolHandler { } ``` Source line: `173`. ## handler::InMemoryToolHandler::new [#handlerinmemorytoolhandlernew] Create an empty handler. ```rust pub fn new() -> Self; ``` Source line: `199`. ## handler::InMemoryToolHandler::register [#handlerinmemorytoolhandlerregister] Register a tool. The handler closure receives the deserialized arguments and returns a \[`ToolResult`]. ```rust pub async fn register( &self, name: impl Into, description: Option<&str>, handler: F, ) where F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static, Fut: std::future::Future> + Send + 'static,; ``` Source line: `205`. # openagent-mcp modules URL: https://docs.openagent.id/reference/rust/openagent-mcp Markdown: https://docs.openagent.id/reference/rust/openagent-mcp.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-integrations-mcp-rust). [Focused integration guide](/integrations/frameworks). ## Modules [#modules] * [crate](/reference/rust/openagent-mcp/crate) — 6 declarations * [errors](/reference/rust/openagent-mcp/errors) — 6 declarations * [handler](/reference/rust/openagent-mcp/handler) — 10 declarations * [middleware](/reference/rust/openagent-mcp/middleware) — 5 declarations * [skills](/reference/rust/openagent-mcp/skills) — 14 declarations * [types](/reference/rust/openagent-mcp/types) — 25 declarations * [rmcp\_adapter](/reference/rust/openagent-mcp/rmcp_adapter) — 4 declarations # openagent-mcp · middleware URL: https://docs.openagent.id/reference/rust/openagent-mcp/middleware Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/middleware.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/middleware.rs`. SHA-256: `4fc7a846d77047ae227b86d30edf99d9cc86666781c3bb2a00168c404965d9fe`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## middleware::default\_scope\_format [#middlewaredefault_scope_format] Default scope format used when \[`Config::with_require_scopes`] is not supplied. Returns `mcp::invoke`. ```rust pub fn default_scope_format(tool_name: &str) -> String; ``` Source line: `32`. ## middleware::default\_require\_scopes [#middlewaredefault_require_scopes] Default scope deriver used when \[`Config::with_require_scopes`] is not supplied. ```rust pub fn default_require_scopes(tool_name: &str, _args: &serde_json::Value) -> Vec; ``` Source line: `38`. ## middleware::OpenAgentMiddleware [#middlewareopenagentmiddleware] The middleware engine. Cheap to clone — internally just an `Arc` over the config and a derived scope deriver. ```rust #[derive(Clone)] pub struct OpenAgentMiddleware { } ``` Source line: `47`. ## middleware::OpenAgentMiddleware::new [#middlewareopenagentmiddlewarenew] Create a new middleware engine. ```rust pub fn new(config: Config) -> Self; ``` Source line: `62`. ## middleware::OpenAgentMiddleware::run [#middlewareopenagentmiddlewarerun] Run the middleware pipeline against a single call. The `inner` closure is invoked once the auth pipeline approves the call. It receives the (unmodified) `ToolCall`. This is the function adapters call from inside their concrete `call_tool` implementations. Most users do not call it directly — they wrap their handler with \[`crate::WithOpenAgent::with_openagent`] instead. ```rust pub async fn run(&self, call: ToolCall, inner: F) -> Result where F: FnOnce( ToolCall, ) -> Pin> + Send>> + Send + 'static,; ``` Source line: `82`. # openagent-mcp · rmcp_adapter URL: https://docs.openagent.id/reference/rust/openagent-mcp/rmcp_adapter Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/rmcp_adapter.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/rmcp_adapter.rs`. SHA-256: `6259f4263bbaaf3272b3af31186470920d98d8db0723bae0985d573a7f477a63`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "rmcp")] ``` ## rmcp\_adapter::RmcpOpenAgent [#rmcp_adapterrmcpopenagent] Newtype wrapper around a \[`WrappedHandler`] that exposes a method the user's `rmcp::ServerHandler::call_tool` implementation can delegate to. ## Usage [#usage] ```rust // 1. Build your handler and wrap it with the middleware. use openagent_mcp::{Config, InMemoryToolHandler, OpenAgentMiddleware, RmcpOpenAgent, WithOpenAgent}; # async fn example(agent: std::sync::Arc) { let inner = InMemoryToolHandler::new(); let middleware = OpenAgentMiddleware::new(Config::new(agent)); let wrapped = inner.with_openagent(middleware); let adapter = RmcpOpenAgent::new(wrapped); // 2. From your rmcp ServerHandler::call_tool, delegate: // async fn call_tool(&self, params: CallToolRequestParam, ctx: RequestContext) // -> Result // { // adapter.dispatch(params, &ctx).await // } # let _ = adapter; # } ``` The dispatch helper handles the JSON conversion and error mapping so the rmcp glue stays a one-liner. ```rust #[cfg(feature = "rmcp")] pub struct RmcpOpenAgent where H: ToolHandler + 'static, { } ``` Source line: `63`. ## rmcp\_adapter::RmcpOpenAgent\::new [#rmcp_adapterrmcpopenagenthnew] Wrap an \[`WrappedHandler`] so it can be plugged into rmcp. ```rust #[cfg(feature = "rmcp")] pub fn new(handler: WrappedHandler) -> Self; ``` Source line: `86`. ## rmcp\_adapter::RmcpOpenAgent\::dispatch\_value [#rmcp_adapterrmcpopenagenthdispatch_value] Translate an rmcp `CallToolRequestParam` into a \[`ToolCall`], run the middleware pipeline, and return a \[`ToolResult`] ready to be converted back into rmcp's `CallToolResult` by the caller. We deliberately do not import rmcp's types here — the conversion to and from those types lives in the user's `ServerHandler` implementation. That way, when rmcp bumps its API again, only the user's call site needs to be touched. ```rust #[cfg(feature = "rmcp")] pub async fn dispatch_value( &self, name: String, arguments: serde_json::Value, meta: serde_json::Value, ) -> Result; ``` Source line: `100`. ## rmcp\_adapter::RmcpOpenAgent\::handler [#rmcp_adapterrmcpopenagenthhandler] Borrow the inner wrapped handler. Useful for tests and for callers that want to invoke `list_tools` directly. ```rust #[cfg(feature = "rmcp")] pub fn handler(&self) -> &Arc>; ``` Source line: `116`. # openagent-mcp · skills URL: https://docs.openagent.id/reference/rust/openagent-mcp/skills Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/skills.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/skills.rs`. SHA-256: `3f20542523a5bba4da4bbccb5f14e50431ae45505dc1251e2194c7344e44a684`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## skills::DEFAULT\_SKILL\_TOOL\_NAMES [#skillsdefault_skill_tool_names] Tool name prefixes the middleware treats as skill-like by default. ```rust pub const DEFAULT_SKILL_TOOL_NAMES: &[&str]; ``` Source line: `21`. ## skills::SkillsRule [#skillsskillsrule] A single rule mapping a skill name to the DIDs allowed to invoke it. `dids: None` means "any verified caller". ```rust #[derive(Debug, Clone)] pub struct SkillsRule { /// The skill name as it appears in SKILLS.md. pub skill_name: String, /// DIDs allowed to invoke this skill, or `None` for any. pub dids: Option>, /// Optional human-readable reason returned on denial. pub reason: Option } ``` Source line: `32`. ## skills::SkillsPolicyDecision [#skillsskillspolicydecision] Decision returned by \[`SkillsPolicy::decide`]. ```rust #[derive(Debug, Clone)] pub struct SkillsPolicyDecision { /// Whether to allow the call. pub allow: bool, /// Optional reason — set on denial. pub reason: Option } ``` Source line: `43`. ## skills::SkillsPolicyDecision::allow [#skillsskillspolicydecisionallow] Build an allow decision. ```rust pub fn allow() -> Self; ``` Source line: `52`. ## skills::SkillsPolicyDecision::deny [#skillsskillspolicydecisiondeny] Build a deny decision with a reason. ```rust pub fn deny(reason: impl Into) -> Self; ``` Source line: `60`. ## skills::SkillsStore [#skillsskillsstore] Storage backend for skills rules. Implementations may be in-memory, file-backed, or fetched from a remote service. ```rust #[async_trait] pub trait SkillsStore: Send + Sync { /// Look up the rule for a given skill name. Return `None` if no /// rule is configured. async fn lookup(&self, skill_name: &str) -> Option; } ``` Source line: `71`. ## skills::InMemorySkillsStore [#skillsinmemoryskillsstore] In-memory store. Construct from a list of rules and pass to \[`SkillsPolicy::new`]. ```rust #[derive(Debug, Default)] pub struct InMemorySkillsStore { } ``` Source line: `80`. ## skills::InMemorySkillsStore::new [#skillsinmemoryskillsstorenew] Build a store from a list of rules. ```rust pub fn new(rules: impl IntoIterator) -> Self; ``` Source line: `86`. ## skills::InMemorySkillsStore::with\_rule [#skillsinmemoryskillsstorewith_rule] Return a NEW store with the given rule applied (immutable update — the original is left untouched). ```rust pub fn with_rule(&self, rule: SkillsRule) -> Self; ``` Source line: `96`. ## skills::SkillNameExtractor [#skillsskillnameextractor] Configurable matcher: returns the skill name if a tool call should be checked against the skills policy, or `None` to skip the check. ```rust pub type SkillNameExtractor = Arc Option + Send + Sync>; ``` Source line: `112`. ## skills::SkillsPolicy [#skillsskillspolicy] The skills policy hook. Construct via \[`SkillsPolicy::new`]. The policy decides per call whether the tool is skill-like, looks up a rule from the configured store, and matches the verified DID against the rule. ```rust #[derive(Clone)] pub struct SkillsPolicy { } ``` Source line: `120`. ## skills::SkillsPolicy::new [#skillsskillspolicynew] Build a policy from a store, using the default skill-name extractor that: * Treats the tool as a skill if its name is in \[`DEFAULT_SKILL_TOOL_NAMES`]. * Reads `args["skill"]` or `args["skillName"]` for the skill name. ```rust pub fn new(store: Arc) -> Self; ``` Source line: `139`. ## skills::SkillsPolicy::with\_extractor [#skillsskillspolicywith_extractor] Override the extractor with a custom matcher. ```rust pub fn with_extractor(mut self, extractor: SkillNameExtractor) -> Self; ``` Source line: `147`. ## skills::SkillsPolicy::decide [#skillsskillspolicydecide] Decide whether a call should be allowed. ```rust pub async fn decide( &self, tool_name: &str, args: &serde_json::Value, identity: &VerifiedIdentity, ) -> SkillsPolicyDecision; ``` Source line: `153`. # openagent-mcp · types URL: https://docs.openagent.id/reference/rust/openagent-mcp/types Markdown: https://docs.openagent.id/reference/rust/openagent-mcp/types.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/integrations/mcp/rust/src/types.rs`. SHA-256: `b7bab88be56f0adcd317993328ebffa29830ff8ac0d6091c5a7baa116c42b086`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## types::Did [#typesdid] A decentralized identifier — typically `did:oas::...`, but any format the configured \[`IdentityVerifier`] understands is allowed. ```rust pub type Did = String; ``` Source line: `18`. ## types::Identity [#typesidentity] Identity envelope attached to an outbound MCP `tools/call` request. The middleware extracts this from `_meta.openagent.identity` on the inbound request. `proof` is opaque to the middleware — it can be a signed challenge response, an Arsenal Agent Capability Token, or any other format the verifier knows how to validate. ```rust #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct Identity { /// Caller's DID. pub did: Did, /// Verifiable proof — opaque to the middleware. pub proof: String, /// Optional bearer-style nonce for replay protection. #[serde(default, skip_serializing_if = "Option::is_none")] pub nonce: Option, /// Optional context fields the verifier may use (issuer DID, /// audience, claimed scopes). Always validated against the verifier /// policy — never trusted as input. #[serde(default, skip_serializing_if = "Option::is_none")] pub context: Option } ``` Source line: `27`. ## types::VerifiedIdentity [#typesverifiedidentity] The result of a successful identity verification. Carries the audit id stamped onto the response, the held scopes, and any verifier claims. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VerifiedIdentity { /// Verified DID. pub did: Did, /// Scopes the caller actually holds (post-verification). pub scopes: Vec, /// Audit identifier echoed back to the caller in the response. pub audit_id: String, /// Verifier-issued claims about the caller. pub claims: serde_json::Value } ``` Source line: `46`. ## types::AuditMeta [#typesauditmeta] Audit metadata stamped onto the response `_meta.openagent` block. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AuditMeta { /// Identifier for correlating logs end-to-end. pub audit_id: String, /// DID of the caller that was successfully verified. pub verified_did: Did, /// Scopes the caller exercised on this call. pub scopes: Vec } ``` Source line: `59`. ## types::IdentityVerifier [#typesidentityverifier] The trait every identity verifier implements. Production deployments will use the verifier from `openagent-sdk`; tests use the \[`crate::handler::InMemoryToolHandler`]-friendly fake found in the `tests/` directory. ```rust #[async_trait] pub trait IdentityVerifier: Send + Sync { /// Verify the supplied identity envelope and return the resulting /// [`VerifiedIdentity`]. Implementations MUST be deterministic for a /// given `(identity, required_scopes)` pair and MUST NOT mutate /// either argument. async fn verify( &self, identity: &Identity, required_scopes: &[String], ) -> Result; } ``` Source line: `73`. ## types::Agent [#typesagent] Minimal Agent surface used by the middleware. ```rust #[async_trait] pub trait Agent: Send + Sync { /// The agent's own DID. fn did(&self) -> &str; /// The verifier the agent's MCP server uses to authenticate /// inbound calls. fn verifier(&self) -> Arc; /// Sign an outbound call so the receiving server can authenticate /// the agent. Returns the identity envelope to attach to the /// request `_meta.openagent.identity` field. async fn sign_request( &self, tool_name: &str, audience: Option<&str>, ) -> Result; } ``` Source line: `87`. ## types::ScopeDeriver [#typesscopederiver] Function type that derives the required scopes for a tool from the tool name and arguments. ```rust pub type ScopeDeriver = Arc Vec + Send + Sync>; ``` Source line: `107`. ## types::PreCallHook [#typesprecallhook] Hook fired before the tool body executes. ```rust pub type PreCallHook = Arc< dyn Fn(&PreCallContext<'_>) -> futures_compat::BoxFuture<'static, ()> + Send + Sync, >; ``` Source line: `111`. ## types::PostCallHook [#typespostcallhook] Hook fired after the tool body executes successfully. ```rust pub type PostCallHook = Arc< dyn Fn(&PostCallContext<'_>) -> futures_compat::BoxFuture<'static, ()> + Send + Sync, >; ``` Source line: `116`. ## types::ErrorHook [#typeserrorhook] Hook fired when the auth pipeline or tool body errors. ```rust pub type ErrorHook = Arc< dyn Fn(&ErrorContext<'_>) -> futures_compat::BoxFuture<'static, ()> + Send + Sync, >; ``` Source line: `121`. ## types::PreCallContext [#typesprecallcontext] Context passed to a \[`PreCallHook`]. ```rust #[derive(Debug)] pub struct PreCallContext<'a> { /// The tool name. pub tool_name: &'a str, /// Arguments the caller supplied. pub args: &'a serde_json::Value, /// The verified identity. pub identity: &'a VerifiedIdentity } ``` Source line: `127`. ## types::PostCallContext [#typespostcallcontext] Context passed to a \[`PostCallHook`]. ```rust #[derive(Debug)] pub struct PostCallContext<'a> { /// The tool name. pub tool_name: &'a str, /// Arguments the caller supplied. pub args: &'a serde_json::Value, /// The verified identity. pub identity: &'a VerifiedIdentity, /// Wall-clock duration of the call, in milliseconds. pub duration_ms: u128, /// The successful tool result, after audit metadata stamping. pub result: &'a serde_json::Value } ``` Source line: `138`. ## types::ErrorContext [#typeserrorcontext] Context passed to an \[`ErrorHook`]. ```rust #[derive(Debug)] pub struct ErrorContext<'a> { /// The tool name. pub tool_name: &'a str, /// Arguments the caller supplied. pub args: &'a serde_json::Value, /// The verified identity, if the auth pipeline got far enough to /// produce one. pub identity: Option<&'a VerifiedIdentity>, /// The error that aborted the call. pub error: &'a McpAuthError } ``` Source line: `153`. ## types::Config [#typesconfig] Configuration for the \[`crate::OpenAgentMiddleware`]. ```rust #[derive(Clone)] pub struct Config { } ``` Source line: `167`. ## types::Config::new [#typesconfignew] Create a new config from the agent. All hooks default to none and identity is required. ```rust pub fn new(agent: Arc) -> Self; ``` Source line: `196`. ## types::Config::with\_require\_scopes [#typesconfigwith_require_scopes] Override the per-tool scope deriver. Defaults to `["mcp::invoke"]`. ```rust pub fn with_require_scopes(mut self, deriver: ScopeDeriver) -> Self; ``` Source line: `211`. ## types::Config::with\_require\_identity [#typesconfigwith_require_identity] Set whether the middleware should reject calls without an identity envelope. Defaults to `true`. ```rust pub fn with_require_identity(mut self, require: bool) -> Self; ``` Source line: `218`. ## types::Config::with\_skills\_policy [#typesconfigwith_skills_policy] Install a skills policy hook. See \[`crate::skills`]. ```rust pub fn with_skills_policy(mut self, policy: SkillsPolicy) -> Self; ``` Source line: `224`. ## types::Config::with\_pre\_call [#typesconfigwith_pre_call] Install a pre-call hook. ```rust pub fn with_pre_call(mut self, hook: PreCallHook) -> Self; ``` Source line: `230`. ## types::Config::with\_post\_call [#typesconfigwith_post_call] Install a post-call hook. ```rust pub fn with_post_call(mut self, hook: PostCallHook) -> Self; ``` Source line: `236`. ## types::Config::with\_on\_error [#typesconfigwith_on_error] Install an error hook. ```rust pub fn with_on_error(mut self, hook: ErrorHook) -> Self; ``` Source line: `242`. ## types::Config::with\_extra [#typesconfigwith_extra] Attach an arbitrary metadata field to the config (for observability or custom adapters). Returns the new config. ```rust pub fn with_extra(mut self, key: impl Into, value: serde_json::Value) -> Self; ``` Source line: `249`. ## types::Config::agent [#typesconfigagent] Borrow the underlying agent. ```rust pub fn agent(&self) -> &Arc; ``` Source line: `255`. ## types::futures\_compat [#typesfutures_compat] Tiny adapter module so the public API can use boxed futures without pulling in the full `futures` crate. Keeping this in-tree avoids a dependency that has historically caused version conflicts inside the L1fe ecosystem. ```rust pub mod futures_compat; ``` Source line: `264`. ## types::futures\_compat::BoxFuture [#typesfutures_compatboxfuture] A future that has been boxed onto the heap with a `'static` lifetime. Used by hook signatures. ```rust pub type BoxFuture<'a, T> = Pin + Send + 'a>>; ``` Source line: `270`. # openagent-crypto-wasm · aead URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/aead Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/aead.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/aead.rs`. SHA-256: `b05c0a00dca8d771fd7d2443a5bd1f00e5d223dc3acfda28d9a8bf5a626d674c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## aead::AES256GCM\_KEY\_LEN [#aeadaes256gcm_key_len] Length of an AES-256-GCM key in bytes. ```rust pub const AES256GCM_KEY_LEN: usize; ``` Source line: `22`. ## aead::AES256GCM\_NONCE\_LEN [#aeadaes256gcm_nonce_len] Length of an AES-256-GCM nonce in bytes (96 bits, recommended). ```rust pub const AES256GCM_NONCE_LEN: usize; ``` Source line: `24`. ## aead::XCHACHA20POLY1305\_KEY\_LEN [#aeadxchacha20poly1305_key_len] Length of an XChaCha20-Poly1305 key in bytes. ```rust pub const XCHACHA20POLY1305_KEY_LEN: usize; ``` Source line: `27`. ## aead::XCHACHA20POLY1305\_NONCE\_LEN [#aeadxchacha20poly1305_nonce_len] Length of an XChaCha20-Poly1305 nonce in bytes (192 bits, extended). ```rust pub const XCHACHA20POLY1305_NONCE_LEN: usize; ``` Source line: `29`. ## aead::aes256gcm\_encrypt [#aeadaes256gcm_encrypt] Encrypts `plaintext` with AES-256-GCM. Returns `ciphertext || tag` (16-byte tag appended). # Errors [#errors] * \[`CryptoError::InvalidLength`] if `key` or `nonce` has the wrong length. * \[`CryptoError::AeadFailed`] if the underlying cipher rejects the input. ```rust pub fn aes256gcm_encrypt( key: &[u8], nonce: &[u8], plaintext: &[u8], aad: &[u8], ) -> Result, CryptoError>; ``` Source line: `39`. ## aead::aes256gcm\_decrypt [#aeadaes256gcm_decrypt] Decrypts `ciphertext` with AES-256-GCM, verifying the tag. `ciphertext` must be `actual_ciphertext || tag`. Returns the plaintext on successful tag verification. # Errors [#errors-1] * \[`CryptoError::InvalidLength`] if `key` or `nonce` has the wrong length. * \[`CryptoError::AeadFailed`] (operation = `"decrypt"`) on tag failure. ```rust pub fn aes256gcm_decrypt( key: &[u8], nonce: &[u8], ciphertext: &[u8], aad: &[u8], ) -> Result, CryptoError>; ``` Source line: `89`. ## aead::xchacha20poly1305\_encrypt [#aeadxchacha20poly1305_encrypt] Encrypts `plaintext` with XChaCha20-Poly1305 (extended-nonce variant). Returns `ciphertext || tag` (16-byte tag appended). # Errors [#errors-2] * \[`CryptoError::InvalidLength`] if `key` or `nonce` has the wrong length. * \[`CryptoError::AeadFailed`] if the cipher rejects the input. ```rust pub fn xchacha20poly1305_encrypt( key: &[u8], nonce: &[u8], plaintext: &[u8], aad: &[u8], ) -> Result, CryptoError>; ``` Source line: `138`. ## aead::xchacha20poly1305\_decrypt [#aeadxchacha20poly1305_decrypt] Decrypts `ciphertext` with XChaCha20-Poly1305, verifying the tag. # Errors [#errors-3] * \[`CryptoError::InvalidLength`] if `key` or `nonce` has the wrong length. * \[`CryptoError::AeadFailed`] (operation = `"decrypt"`) on tag failure. ```rust pub fn xchacha20poly1305_decrypt( key: &[u8], nonce: &[u8], ciphertext: &[u8], aad: &[u8], ) -> Result, CryptoError>; ``` Source line: `185`. # openagent-crypto-wasm · blake3_hash URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/blake3_hash Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/blake3_hash.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/blake3_hash.rs`. SHA-256: `8ecfbe5691e332d06ec01ba5e08495b7e630e3257697784491a49b54ff511b40`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## blake3\_hash::HASH\_LEN [#blake3_hashhash_len] BLAKE3 output length in bytes. ```rust pub const HASH_LEN: usize; ``` Source line: `12`. ## blake3\_hash::KEY\_LEN [#blake3_hashkey_len] BLAKE3 keyed-hash key length in bytes. ```rust pub const KEY_LEN: usize; ``` Source line: `14`. ## blake3\_hash::hash [#blake3_hashhash] Computes the BLAKE3 hash of `data`. # Examples [#examples] ``` let h = openagent_crypto_wasm::blake3_hash::hash(b"hello world"); assert_eq!(h.len(), 32); ``` ```rust pub fn hash(data: &[u8]) -> [u8; HASH_LEN]; ``` Source line: `24`. ## blake3\_hash::keyed\_hash [#blake3_hashkeyed_hash] Computes the keyed BLAKE3 hash of `data` under the 32-byte `key`. # Errors [#errors] \[`CryptoError::InvalidLength`] if `key` is not exactly 32 bytes. ```rust pub fn keyed_hash(key: &[u8], data: &[u8]) -> Result<[u8; HASH_LEN], CryptoError>; ``` Source line: `33`. ## blake3\_hash::derive\_key [#blake3_hashderive_key] Derives a 32-byte key using BLAKE3's key-derivation mode. `context` should be a hard-coded ASCII string unique per application/protocol (BLAKE3 KDF best practice). ```rust pub fn derive_key(context: &str, key_material: &[u8]) -> [u8; HASH_LEN]; ``` Source line: `44`. # openagent-crypto-wasm · crate URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/crate Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/lib.rs`. SHA-256: `ca7f8f0e1dcb8f5effbb78f617609f811f8d519ada03695de6199cebdbf2ce9d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## aead [#aead] ```rust pub mod aead; ``` Source line: `86`. ## blake3\_hash [#blake3_hash] ```rust pub mod blake3_hash; ``` Source line: `87`. ## ct [#ct] ```rust pub mod ct; ``` Source line: `88`. ## ed25519 [#ed25519] ```rust pub mod ed25519; ``` Source line: `89`. ## encoding [#encoding] ```rust pub mod encoding; ``` Source line: `90`. ## error [#error] ```rust pub mod error; ``` Source line: `91`. ## frost [#frost] ```rust pub mod frost; ``` Source line: `92`. ## hkdf\_sha256 [#hkdf_sha256] ```rust pub mod hkdf_sha256; ``` Source line: `93`. ## jcs [#jcs] ```rust pub mod jcs; ``` Source line: `94`. ## kdf\_password [#kdf_password] ```rust pub mod kdf_password; ``` Source line: `95`. ## sha [#sha] ```rust pub mod sha; ``` Source line: `96`. ## x25519 [#x25519] ```rust pub mod x25519; ``` Source line: `97`. ## wasm\_api [#wasm_api] ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] pub mod wasm_api; ``` Source line: `101`. ## pub use error::CryptoError; [#pub-use-errorcryptoerror] ```rust pub use error::CryptoError; ``` Source line: `103`. ## ::VERSION [#version] Crate version, sourced from `Cargo.toml` at compile time. ```rust pub const VERSION: &str; ``` Source line: `106`. # openagent-crypto-wasm · ct URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/ct Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/ct.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/ct.rs`. SHA-256: `f322224a71a82f8f9092f36c0e26fd7a73322f9083bec9f3aece14b0ba508d51`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## ct::ct\_eq [#ctct_eq] Returns `true` iff `a` and `b` have the same length and identical contents. Comparison is **constant time** with respect to slice length: the entire `a` slice is consumed before returning. Use this for comparing secrets, MAC tags, and any byte sequence whose contents must not leak via timing. # Examples [#examples] ``` use openagent_crypto_wasm::ct::ct_eq; assert!(ct_eq(b"abc", b"abc")); assert!(!ct_eq(b"abc", b"abd")); assert!(!ct_eq(b"abc", b"abcd")); ``` ```rust pub fn ct_eq(a: &[u8], b: &[u8]) -> bool; ``` Source line: `28`. ## ct::fill\_random [#ctfill_random] Fills `out` with cryptographically secure random bytes. On native targets this calls `getrandom::getrandom` which delegates to the OS CSPRNG (`/dev/urandom`, `getrandom(2)`, `BCryptGenRandom`, etc.). On WebAssembly with the `wasm` feature enabled, the same call routes through the JS host's `crypto.getRandomValues`. # Errors [#errors] \[`CryptoError::RngFailed`] if the underlying CSPRNG returns an error (extremely rare; usually only on misconfigured WASI environments). ```rust pub fn fill_random(out: &mut [u8]) -> Result<(), CryptoError>; ``` Source line: `46`. ## ct::random\_bytes [#ctrandom_bytes] Returns `n` cryptographically secure random bytes. ```rust pub fn random_bytes(n: usize) -> Result, CryptoError>; ``` Source line: `53`. # openagent-crypto-wasm · ed25519 URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/ed25519 Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/ed25519.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/ed25519.rs`. SHA-256: `e179bc0994784a264936ee081d125197bc8c5a2396fd4195a5c539e3fd97c0f4`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## ed25519::SIGNING\_KEY\_LEN [#ed25519signing_key_len] Length of an Ed25519 signing (private) key in bytes. ```rust pub const SIGNING_KEY_LEN: usize; ``` Source line: `21`. ## ed25519::VERIFYING\_KEY\_LEN [#ed25519verifying_key_len] Length of an Ed25519 verifying (public) key in bytes. ```rust pub const VERIFYING_KEY_LEN: usize; ``` Source line: `23`. ## ed25519::SIGNATURE\_LEN [#ed25519signature_len] Length of an Ed25519 signature in bytes. ```rust pub const SIGNATURE_LEN: usize; ``` Source line: `25`. ## ed25519::Keypair [#ed25519keypair] An Ed25519 keypair, suitable for both Rust and WASM contexts. Holds the 32-byte signing key and the derived 32-byte verifying key. The signing key bytes are zeroized when this struct is dropped. # Security [#security] `Debug` deliberately redacts the signing key. Do not log a \[`Keypair`] in any way that could expose `signing_key`. ```rust pub struct Keypair { } ``` Source line: `36`. ## ed25519::Keypair::signing\_key\_bytes [#ed25519keypairsigning_key_bytes] Returns a copy of the 32-byte signing (private) key bytes. The returned array should be wiped after use. ```rust #[inline] pub fn signing_key_bytes(&self) -> [u8; SIGNING_KEY_LEN]; ``` Source line: `61`. ## ed25519::Keypair::verifying\_key\_bytes [#ed25519keypairverifying_key_bytes] Returns a copy of the 32-byte verifying (public) key bytes. ```rust #[inline] pub fn verifying_key_bytes(&self) -> [u8; VERIFYING_KEY_LEN]; ``` Source line: `67`. ## ed25519::generate\_keypair [#ed25519generate_keypair] Generates a fresh Ed25519 keypair using the OS / WASM host CSPRNG. # Examples [#examples] ``` let kp = openagent_crypto_wasm::ed25519::generate_keypair(); assert_eq!(kp.signing_key_bytes().len(), 32); assert_eq!(kp.verifying_key_bytes().len(), 32); ``` ```rust pub fn generate_keypair() -> Keypair; ``` Source line: `81`. ## ed25519::keypair\_from\_signing\_key [#ed25519keypair_from_signing_key] Constructs an Ed25519 keypair from raw signing-key bytes. The verifying key is computed deterministically from the signing key. # Errors [#errors] \[`CryptoError::InvalidLength`] if `signing_key` is not exactly \[`SIGNING_KEY_LEN`] bytes. ```rust pub fn keypair_from_signing_key(signing_key: &[u8]) -> Result; ``` Source line: `102`. ## ed25519::public\_from\_private [#ed25519public_from_private] Derives the Ed25519 verifying (public) key from a signing (private) key. # Errors [#errors-1] \[`CryptoError::InvalidLength`] if `signing_key` is not exactly 32 bytes. ```rust pub fn public_from_private(signing_key: &[u8]) -> Result<[u8; VERIFYING_KEY_LEN], CryptoError>; ``` Source line: `119`. ## ed25519::sign [#ed25519sign] Signs `message` with the supplied 32-byte Ed25519 signing key. Returns the 64-byte detached signature. # Errors [#errors-2] \[`CryptoError::InvalidLength`] if `signing_key` is not exactly 32 bytes. ```rust pub fn sign(signing_key: &[u8], message: &[u8]) -> Result<[u8; SIGNATURE_LEN], CryptoError>; ``` Source line: `131`. ## ed25519::verify [#ed25519verify] Verifies an Ed25519 signature against the given verifying key and message. Returns `Ok(())` on success. # Errors [#errors-3] * \[`CryptoError::InvalidLength`] if either `verifying_key` or `signature` has the wrong length. * \[`CryptoError::InvalidPublicKey`] if `verifying_key` is not on the curve. * \[`CryptoError::SignatureInvalid`] if verification fails. ```rust pub fn verify(verifying_key: &[u8], message: &[u8], signature: &[u8]) -> Result<(), CryptoError>; ``` Source line: `150`. # openagent-crypto-wasm · encoding URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/encoding Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/encoding.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/encoding.rs`. SHA-256: `9f8b44e6dae5524119b6fdf05def6dc7db8eb9b7165257052594db7899c03449`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## encoding::encode [#encodingencode] Encodes raw bytes as multibase base58btc with the `z` prefix. # Examples [#examples] ``` let s = openagent_crypto_wasm::encoding::encode(&[0xDE, 0xAD, 0xBE, 0xEF]); assert!(s.starts_with('z')); ``` ```rust pub fn encode(bytes: &[u8]) -> String; ``` Source line: `19`. ## encoding::decode [#encodingdecode] Decodes a multibase base58btc string (must start with `z`) into raw bytes. # Errors [#errors] \[`CryptoError::MultibaseFailed`] if: * The input is empty or does not start with `'z'` * The base58btc payload is malformed ```rust pub fn decode(input: &str) -> Result, CryptoError>; ``` Source line: `33`. # openagent-crypto-wasm · error URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/error Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/error.rs`. SHA-256: `45f418c13364d1919337da58b6082b122998ab707bc834816dca8bc90ea1d57f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::CryptoError [#errorcryptoerror] Errors arising from `openagent-crypto-wasm` primitives. Construct via `?` from internal fallible operations. Match on the variant to discriminate failure modes; format with `Display` to surface the message. ```rust #[derive(Debug, Error)] pub enum CryptoError { /// A byte slice did not have the length required by the primitive. #[error("invalid byte length for {what}: expected {expected}, got {actual}")] InvalidLength { /// What was being constructed (e.g. `"Ed25519 signing key"`). what: &'static str, /// Expected length in bytes. expected: usize, /// Actual length received. actual: usize, }, /// An Ed25519 signature failed verification. #[error("Ed25519 signature verification failed: {reason}")] SignatureInvalid { /// Why verification failed (algorithm-supplied reason). reason: String, }, /// An Ed25519 public key could not be constructed from the supplied bytes. #[error("invalid Ed25519 public key: {reason}")] InvalidPublicKey { /// Why the public key was rejected. reason: String, }, /// HKDF expansion failed (typically: requested OKM exceeds 255*HashLen). #[error("HKDF-SHA256 {stage} failed: {reason}")] HkdfFailed { /// `"extract"` or `"expand"`. stage: &'static str, /// Underlying failure reason. reason: String, }, /// AEAD encryption or decryption failed (auth tag mismatch or bad input). #[error("AEAD {algorithm} {operation} failed: {reason}")] AeadFailed { /// `"AES-256-GCM"` or `"XChaCha20-Poly1305"`. algorithm: &'static str, /// `"encrypt"` or `"decrypt"`. operation: &'static str, /// Underlying failure reason. reason: String, }, /// Argon2id password hashing or verification failed. #[error("Argon2id {operation} failed: {reason}")] PasswordHashFailed { /// `"hash"` or `"verify"`. operation: &'static str, /// Underlying failure reason. reason: String, }, /// JCS (RFC 8785) canonicalization failed (typically: invalid JSON input). #[error("JCS canonicalization failed: {reason}")] JcsFailed { /// Underlying failure reason. reason: String, }, /// Multibase encoding or decoding failed. #[error("multibase {operation} failed: {reason}")] MultibaseFailed { /// `"encode"` or `"decode"`. operation: &'static str, /// Underlying failure reason. reason: String, }, /// FROST trusted-dealer key generation failed. #[error("FROST keygen failed for {min_signers}-of-{max_signers}: {reason}")] FrostKeygenFailed { /// Threshold `t`. min_signers: u16, /// Total participants `n`. max_signers: u16, /// Underlying failure reason. reason: String, }, /// FROST round-1 commitment, round-2 share, or aggregation step failed. #[error("FROST {stage} failed: {reason}")] FrostStageFailed { /// One of `"round1"`, `"round2"`, `"aggregate"`, `"verify"`. stage: &'static str, /// Underlying failure reason. reason: String, }, /// FROST participant selection was rejected (wrong count, OOB index, duplicate). #[error("FROST participant selection invalid: {reason}")] FrostInvalidParticipants { /// Why the selection was rejected. reason: String, }, /// A serialization/deserialization step failed. #[error("serialization failed for {what}: {reason}")] SerializationFailed { /// What was being (de)serialized. what: &'static str, /// Underlying failure reason. reason: String, }, /// The OS / WASM-host CSPRNG was unavailable or returned an error. #[error("system random number generator failed: {reason}")] RngFailed { /// Underlying failure reason. reason: String, }, } ``` Source line: `18`. # openagent-crypto-wasm · frost URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/frost Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/frost.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/frost.rs`. SHA-256: `9167fd0ac7d830b71fc393a2a12a7cd68ca017d28ed5c0be720f47ebb172e745`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## frost::KeyShareBundle [#frostkeysharebundle] A complete bundle of FROST key shares produced by \[`trusted_keygen`]. Contains every participant's serialized [`KeyPackage`](frost::keys::KeyPackage) and the shared [`PublicKeyPackage`](frost::keys::PublicKeyPackage). In production deployments, the dealer SHOULD distribute exactly one `key_packages[i]` entry to participant `i` and then destroy the bundle. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct KeyShareBundle { /// Threshold `t` — minimum number of signers required. pub min_signers: u16, /// Total participants `n`. pub max_signers: u16, /// One serialized `KeyPackage` per participant, in identifier order. pub key_packages: Vec>, /// Serialized `PublicKeyPackage` shared by every participant. pub public_key_package: Vec, /// Group verifying (public) key, raw 32 bytes. pub group_public_key: Vec } ``` Source line: `47`. ## frost::Round1Output [#frostround1output] Output of \[`sign_round1`] for a single participant. Contains the participant's `nonces` (kept secret, used in round 2) and `commitments` (sent to the coordinator and broadcast to other signers). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Round1Output { /// Serialized `SigningNonces` — KEEP SECRET on the participant's machine. pub nonces: Vec, /// Serialized `SigningCommitments` — broadcast to all signers + coordinator. pub commitments: Vec } ``` Source line: `65`. ## frost::ParticipantCommitments [#frostparticipantcommitments] A pairing of (participant identifier, that participant's serialized commitments). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ParticipantCommitments { /// 1-based participant identifier (matches the position in `key_packages`). pub identifier: u16, /// Serialized `SigningCommitments` from `sign_round1`. pub commitments: Vec } ``` Source line: `74`. ## frost::ParticipantShare [#frostparticipantshare] A pairing of (participant identifier, that participant's signature share). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ParticipantShare { /// 1-based participant identifier (matches the position in `key_packages`). pub identifier: u16, /// Serialized `SignatureShare` from `sign_round2`. pub share: Vec } ``` Source line: `83`. ## frost::trusted\_keygen [#frosttrusted_keygen] Generates a t-of-n FROST key share bundle via the trusted-dealer protocol. # Arguments [#arguments] * `min_signers` — threshold `t`. Must be >= 2. * `max_signers` — total participants `n`. Must be >= `min_signers`. # Errors [#errors] * \[`CryptoError::FrostKeygenFailed`] if the parameters are invalid or the underlying FROST keygen fails. * \[`CryptoError::SerializationFailed`] if any serialized output cannot be produced (should never happen with valid keygen output). ```rust pub fn trusted_keygen(min_signers: u16, max_signers: u16) -> Result; ``` Source line: `103`. ## frost::sign\_round1 [#frostsign_round1] Round-1 of the FROST protocol for a single participant. Generates that participant's signing nonces and commitments. The nonces MUST be kept secret and passed verbatim into \[`sign_round2`]. The commitments are broadcast to all other selected signers and to the coordinator. # Errors [#errors-1] * \[`CryptoError::SerializationFailed`] if the input key package cannot be parsed or the outputs cannot be serialized. ```rust pub fn sign_round1(serialized_key_package: &[u8]) -> Result; ``` Source line: `191`. ## frost::sign\_round2 [#frostsign_round2] Round-2 of the FROST protocol for a single participant. Given the participant's serialized key package, their secret nonces from round 1, the message to sign, and the aggregated commitments from all signers, produces this participant's signature share. # Arguments [#arguments-1] * `serialized_key_package` — this participant's key package bytes. * `serialized_nonces` — the `nonces` field from this participant's \[`Round1Output`]. * `message` — the message bytes being signed. * `commitments` — every selected signer's commitments (including this one), tagged with their 1-based identifier. # Errors [#errors-2] * \[`CryptoError::SerializationFailed`] for any deserialization failure. * \[`CryptoError::FrostStageFailed`] (stage = `"round2"`) if the round-2 signing operation rejects the inputs. ```rust pub fn sign_round2( serialized_key_package: &[u8], serialized_nonces: &[u8], message: &[u8], commitments: &[ParticipantCommitments], ) -> Result, CryptoError>; ``` Source line: `242`. ## frost::aggregate [#frostaggregate] Aggregates per-participant signature shares into a single Ed25519 signature. # Arguments [#arguments-2] * `message` — the same message bytes that were signed in round 2. * `commitments` — every selected signer's commitments (must match the set used in round 2). * `shares` — every selected signer's `SignatureShare` from round 2. * `serialized_public_key_package` — the bundle's `public_key_package` field. Returns a 64-byte Ed25519 signature. # Errors [#errors-3] * \[`CryptoError::SerializationFailed`] for any deserialization failure. * \[`CryptoError::FrostStageFailed`] (stage = `"aggregate"`) if FROST aggregation fails. ```rust pub fn aggregate( message: &[u8], commitments: &[ParticipantCommitments], shares: &[ParticipantShare], serialized_public_key_package: &[u8], ) -> Result, CryptoError>; ``` Source line: `292`. ## frost::verify [#frostverify] Verifies a FROST-Ed25519 threshold signature against the group public key. FROST produces standard Ed25519 signatures, so this is a straight delegate to \[`crate::ed25519::verify`]. Provided here for API symmetry with the rest of the FROST module. # Errors [#errors-4] * \[`CryptoError::FrostStageFailed`] (stage = `"verify"`) on any verification failure (we wrap the underlying Ed25519 error so callers can branch on the FROST-specific stage if needed). ```rust pub fn verify( message: &[u8], signature: &[u8], group_public_key: &[u8], ) -> Result<(), CryptoError>; ``` Source line: `351`. # openagent-crypto-wasm · hkdf_sha256 URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/hkdf_sha256 Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/hkdf_sha256.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/hkdf_sha256.rs`. SHA-256: `150f18f8e76586b7619205c3804ac25284d3c64360f906764ee4bd462fdebc1a`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## hkdf\_sha256::PRK\_LEN [#hkdf_sha256prk_len] Length of the HKDF-SHA256 PRK output (== HashLen). ```rust pub const PRK_LEN: usize; ``` Source line: `17`. ## hkdf\_sha256::extract [#hkdf_sha256extract] Performs `HKDF-Extract(salt, IKM)`. Returns the 32-byte pseudo-random key. # Arguments [#arguments] * `salt` — optional salt; pass an empty slice for the "no salt" case (the HKDF will internally use 32 zero bytes per RFC 5869). * `ikm` — input keying material. ```rust pub fn extract(salt: &[u8], ikm: &[u8]) -> [u8; PRK_LEN]; ``` Source line: `28`. ## hkdf\_sha256::expand [#hkdf_sha256expand] Performs `HKDF-Expand(PRK, info, length)`. # Errors [#errors] * \[`CryptoError::InvalidLength`] if `prk` is not exactly 32 bytes. * \[`CryptoError::HkdfFailed`] if `length` exceeds `255 * HashLen` (8160 bytes for SHA-256), which is the maximum allowed by RFC 5869. ```rust pub fn expand(prk: &[u8], info: &[u8], length: usize) -> Result, CryptoError>; ``` Source line: `43`. ## hkdf\_sha256::derive [#hkdf_sha256derive] Convenience: combined `HKDF-Extract` + `HKDF-Expand` in one call. Equivalent to running \[`extract`] then \[`expand`] but avoids exposing the intermediate PRK to the caller. # Errors [#errors-1] \[`CryptoError::HkdfFailed`] if `length` exceeds `255 * HashLen`. ```rust pub fn derive(salt: &[u8], ikm: &[u8], info: &[u8], length: usize) -> Result, CryptoError>; ``` Source line: `68`. # openagent-crypto-wasm modules URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-crates-openagent-crypto-wasm). [Focused integration guide](/sdk/typescript). ## Modules [#modules] * [crate](/reference/rust/openagent-crypto-wasm/crate) — 15 declarations * [aead](/reference/rust/openagent-crypto-wasm/aead) — 8 declarations * [blake3\_hash](/reference/rust/openagent-crypto-wasm/blake3_hash) — 5 declarations * [ct](/reference/rust/openagent-crypto-wasm/ct) — 3 declarations * [ed25519](/reference/rust/openagent-crypto-wasm/ed25519) — 11 declarations * [encoding](/reference/rust/openagent-crypto-wasm/encoding) — 2 declarations * [error](/reference/rust/openagent-crypto-wasm/error) — 1 declarations * [frost](/reference/rust/openagent-crypto-wasm/frost) — 9 declarations * [hkdf\_sha256](/reference/rust/openagent-crypto-wasm/hkdf_sha256) — 4 declarations * [jcs](/reference/rust/openagent-crypto-wasm/jcs) — 2 declarations * [kdf\_password](/reference/rust/openagent-crypto-wasm/kdf_password) — 2 declarations * [sha](/reference/rust/openagent-crypto-wasm/sha) — 4 declarations * [x25519](/reference/rust/openagent-crypto-wasm/x25519) — 9 declarations * [wasm\_api](/reference/rust/openagent-crypto-wasm/wasm_api) — 39 declarations # openagent-crypto-wasm · jcs URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/jcs Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/jcs.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/jcs.rs`. SHA-256: `06d4f1069cf4f1bd1e99da710961198c3c22f15031fbecadd0bf8ff84a3cfbe6`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## jcs::canonicalize [#jcscanonicalize] Canonicalizes a UTF-8 JSON string into its JCS bytes. `input` MUST be a valid JSON document. Invalid JSON returns \[`CryptoError::JcsFailed`]. # Examples [#examples] ``` let bytes = openagent_crypto_wasm::jcs::canonicalize(r#"{"b":1,"a":2}"#).unwrap(); assert_eq!(bytes, br#"{"a":2,"b":1}"#); ``` ```rust pub fn canonicalize(input: &str) -> Result, CryptoError>; ``` Source line: `26`. ## jcs::canonicalize\_value [#jcscanonicalize_value] Canonicalizes a \[`serde_json::Value`] into its JCS bytes. Use this when you already have a parsed `serde_json::Value` (e.g. from a downstream Rust crate) so you don't pay the cost of re-parsing. ```rust pub fn canonicalize_value(value: &serde_json::Value) -> Result, CryptoError>; ``` Source line: `38`. # openagent-crypto-wasm · kdf_password URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/kdf_password Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/kdf_password.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/kdf_password.rs`. SHA-256: `c021bffeadff900136368ce8482ab55ccdec97252df3d516ed985b9deabe67ad`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## kdf\_password::hash\_password [#kdf_passwordhash_password] Hashes `password` with Argon2id and a fresh random salt. Returns the PHC-format encoded hash string (`$argon2id$v=19$m=...`). # Errors [#errors] \[`CryptoError::PasswordHashFailed`] if the underlying hasher fails. ```rust pub fn hash_password(password: &[u8]) -> Result; ``` Source line: `24`. ## kdf\_password::verify\_password [#kdf_passwordverify_password] Verifies `password` against a PHC-format encoded Argon2id hash. Returns `Ok(true)` on a valid match, `Ok(false)` on a mismatch, and \[`CryptoError::PasswordHashFailed`] only if the hash string is malformed. ```rust pub fn verify_password(password: &[u8], encoded_hash: &str) -> Result; ``` Source line: `41`. # openagent-crypto-wasm · sha URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/sha Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/sha.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/sha.rs`. SHA-256: `2336d7624b2af848b3f708a8182c87c46da2ec140dd6237e0fa1c1a4807bb622`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## sha::SHA256\_LEN [#shasha256_len] Length of a SHA-256 hash in bytes. ```rust pub const SHA256_LEN: usize; ``` Source line: `10`. ## sha::SHA512\_LEN [#shasha512_len] Length of a SHA-512 hash in bytes. ```rust pub const SHA512_LEN: usize; ``` Source line: `12`. ## sha::sha256 [#shasha256] Computes the SHA-256 hash of `data`. ```rust pub fn sha256(data: &[u8]) -> [u8; SHA256_LEN]; ``` Source line: `15`. ## sha::sha512 [#shasha512] Computes the SHA-512 hash of `data`. ```rust pub fn sha512(data: &[u8]) -> [u8; SHA512_LEN]; ``` Source line: `25`. # openagent-crypto-wasm · wasm_api URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/wasm_api Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/wasm_api.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/wasm_api.rs`. SHA-256: `c567a5871c7879f19bf7b1be000244cb4f8d41f9f677a3d02d617dd4db9bfd6f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] ``` ## wasm\_api::WasmKeypair [#wasm_apiwasmkeypair] JS-friendly Ed25519 keypair: `{ signing_key, verifying_key }` as `Uint8Array` byte arrays. Returned by \[`ed25519_generate_keypair`]. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] #[derive(Clone)] pub struct WasmKeypair { } ``` Source line: `50`. ## wasm\_api::WasmKeypair::signing\_key [#wasm_apiwasmkeypairsigning_key] 32-byte signing (private) key. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen(getter)] pub fn signing_key(&self) -> Vec; ``` Source line: `59`. ## wasm\_api::WasmKeypair::verifying\_key [#wasm_apiwasmkeypairverifying_key] 32-byte verifying (public) key. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen(getter)] pub fn verifying_key(&self) -> Vec; ``` Source line: `65`. ## wasm\_api::WasmX25519Keypair [#wasm_apiwasmx25519keypair] JS-friendly X25519 keypair: `{ secret_key, public_key }`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] #[derive(Clone)] pub struct WasmX25519Keypair { } ``` Source line: `73`. ## wasm\_api::WasmX25519Keypair::secret\_key [#wasm_apiwasmx25519keypairsecret_key] 32-byte secret (private) key. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen(getter)] pub fn secret_key(&self) -> Vec; ``` Source line: `82`. ## wasm\_api::WasmX25519Keypair::public\_key [#wasm_apiwasmx25519keypairpublic_key] 32-byte public key. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen(getter)] pub fn public_key(&self) -> Vec; ``` Source line: `88`. ## wasm\_api::ed25519\_generate\_keypair [#wasm_apied25519_generate_keypair] Generates a fresh Ed25519 keypair using the host CSPRNG. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn ed25519_generate_keypair() -> WasmKeypair; ``` Source line: `99`. ## wasm\_api::ed25519\_sign [#wasm_apied25519_sign] Signs `message` with the supplied 32-byte Ed25519 signing key. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn ed25519_sign(signing_key: &[u8], message: &[u8]) -> Result, JsError>; ``` Source line: `109`. ## wasm\_api::ed25519\_verify [#wasm_apied25519_verify] Verifies an Ed25519 signature. Throws if verification fails. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn ed25519_verify( verifying_key: &[u8], message: &[u8], signature: &[u8], ) -> Result<(), JsError>; ``` Source line: `117`. ## wasm\_api::ed25519\_public\_from\_private [#wasm_apied25519_public_from_private] Derives the Ed25519 verifying key from a signing key. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn ed25519_public_from_private(signing_key: &[u8]) -> Result, JsError>; ``` Source line: `127`. ## wasm\_api::x25519\_generate\_keypair [#wasm_apix25519_generate_keypair] Generates a fresh X25519 keypair using the host CSPRNG. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn x25519_generate_keypair() -> WasmX25519Keypair; ``` Source line: `139`. ## wasm\_api::x25519\_diffie\_hellman [#wasm_apix25519_diffie_hellman] Computes the X25519 raw shared secret. Callers MUST run this through HKDF before using it as keying material. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn x25519_diffie_hellman( secret_key: &[u8], peer_public_key: &[u8], ) -> Result, JsError>; ``` Source line: `150`. ## wasm\_api::hkdf\_sha256\_extract [#wasm_apihkdf_sha256_extract] `HKDF-Extract(salt, IKM)` — returns the 32-byte PRK. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn hkdf_sha256_extract(salt: &[u8], ikm: &[u8]) -> Vec; ``` Source line: `165`. ## wasm\_api::hkdf\_sha256\_expand [#wasm_apihkdf_sha256_expand] `HKDF-Expand(PRK, info, length)`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn hkdf_sha256_expand(prk: &[u8], info: &[u8], length: usize) -> Result, JsError>; ``` Source line: `171`. ## wasm\_api::hkdf\_sha256\_derive [#wasm_apihkdf_sha256_derive] Combined extract + expand HKDF-SHA256 derivation. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn hkdf_sha256_derive( salt: &[u8], ikm: &[u8], info: &[u8], length: usize, ) -> Result, JsError>; ``` Source line: `177`. ## wasm\_api::blake3\_hash\_bytes [#wasm_apiblake3_hash_bytes] BLAKE3 hash of `data`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn blake3_hash_bytes(data: &[u8]) -> Vec; ``` Source line: `192`. ## wasm\_api::blake3\_keyed\_hash [#wasm_apiblake3_keyed_hash] BLAKE3 keyed hash. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn blake3_keyed_hash(key: &[u8], data: &[u8]) -> Result, JsError>; ``` Source line: `198`. ## wasm\_api::blake3\_derive\_key [#wasm_apiblake3_derive_key] BLAKE3 KDF mode: `derive_key(context, key_material)`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn blake3_derive_key(context: &str, key_material: &[u8]) -> Vec; ``` Source line: `206`. ## wasm\_api::sha256 [#wasm_apisha256] SHA-256 hash of `data`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn sha256(data: &[u8]) -> Vec; ``` Source line: `212`. ## wasm\_api::sha512 [#wasm_apisha512] SHA-512 hash of `data`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn sha512(data: &[u8]) -> Vec; ``` Source line: `218`. ## wasm\_api::aes256gcm\_encrypt [#wasm_apiaes256gcm_encrypt] AES-256-GCM encryption. Returns `ciphertext || tag`. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn aes256gcm_encrypt( key: &[u8], nonce: &[u8], plaintext: &[u8], aad: &[u8], ) -> Result, JsError>; ``` Source line: `228`. ## wasm\_api::aes256gcm\_decrypt [#wasm_apiaes256gcm_decrypt] AES-256-GCM decryption. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn aes256gcm_decrypt( key: &[u8], nonce: &[u8], ciphertext: &[u8], aad: &[u8], ) -> Result, JsError>; ``` Source line: `239`. ## wasm\_api::xchacha20poly1305\_encrypt [#wasm_apixchacha20poly1305_encrypt] XChaCha20-Poly1305 encryption. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn xchacha20poly1305_encrypt( key: &[u8], nonce: &[u8], plaintext: &[u8], aad: &[u8], ) -> Result, JsError>; ``` Source line: `250`. ## wasm\_api::xchacha20poly1305\_decrypt [#wasm_apixchacha20poly1305_decrypt] XChaCha20-Poly1305 decryption. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn xchacha20poly1305_decrypt( key: &[u8], nonce: &[u8], ciphertext: &[u8], aad: &[u8], ) -> Result, JsError>; ``` Source line: `261`. ## wasm\_api::argon2id\_hash\_password [#wasm_apiargon2id_hash_password] Hashes `password` with Argon2id, returning a PHC-format string. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn argon2id_hash_password(password: &[u8]) -> Result; ``` Source line: `276`. ## wasm\_api::argon2id\_verify\_password [#wasm_apiargon2id_verify_password] Verifies a password against a PHC-format Argon2id hash. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn argon2id_verify_password(password: &[u8], encoded_hash: &str) -> Result; ``` Source line: `282`. ## wasm\_api::jcs\_canonicalize [#wasm_apijcs_canonicalize] JCS canonicalization (RFC 8785) of a JSON string. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn jcs_canonicalize(json: &str) -> Result, JsError>; ``` Source line: `292`. ## wasm\_api::multibase\_base58btc\_encode [#wasm_apimultibase_base58btc_encode] Multibase base58btc encode. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn multibase_base58btc_encode(bytes: &[u8]) -> String; ``` Source line: `298`. ## wasm\_api::multibase\_base58btc\_decode [#wasm_apimultibase_base58btc_decode] Multibase base58btc decode. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn multibase_base58btc_decode(input: &str) -> Result, JsError>; ``` Source line: `304`. ## wasm\_api::ct\_eq [#wasm_apict_eq] Constant-time byte equality. Returns `false` for slices of differing length. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn ct_eq(a: &[u8], b: &[u8]) -> bool; ``` Source line: `310`. ## wasm\_api::random\_bytes [#wasm_apirandom_bytes] Returns `n` cryptographically random bytes. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn random_bytes(n: usize) -> Result, JsError>; ``` Source line: `316`. ## wasm\_api::frost\_trusted\_keygen [#wasm_apifrost_trusted_keygen] Generates a t-of-n FROST key share bundle (trusted dealer). Returns a JSON string of [`KeyShareBundle`](crate::frost::KeyShareBundle). ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn frost_trusted_keygen(min_signers: u16, max_signers: u16) -> Result; ``` Source line: `333`. ## wasm\_api::frost\_sign\_round1 [#wasm_apifrost_sign_round1] FROST round 1 for a single participant. Returns JSON of [`Round1Output`](crate::frost::Round1Output). ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn frost_sign_round1(serialized_key_package: &[u8]) -> Result; ``` Source line: `340`. ## wasm\_api::frost\_sign\_round2 [#wasm_apifrost_sign_round2] FROST round 2 for a single participant. `commitments_json` is a JSON array of [`ParticipantCommitments`](crate::frost::ParticipantCommitments). ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn frost_sign_round2( serialized_key_package: &[u8], serialized_nonces: &[u8], message: &[u8], commitments_json: &str, ) -> Result, JsError>; ``` Source line: `350`. ## wasm\_api::frost\_aggregate [#wasm_apifrost_aggregate] FROST aggregation: combine signature shares into a 64-byte Ed25519 signature. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn frost_aggregate( message: &[u8], commitments_json: &str, shares_json: &str, serialized_public_key_package: &[u8], ) -> Result, JsError>; ``` Source line: `369`. ## wasm\_api::frost\_verify [#wasm_apifrost_verify] Verifies a FROST signature. Throws on failure. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn frost_verify( message: &[u8], signature: &[u8], group_public_key: &[u8], ) -> Result<(), JsError>; ``` Source line: `389`. ## wasm\_api::version [#wasm_apiversion] Returns the crate version string. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn version() -> String; ``` Source line: `399`. ## wasm\_api::act\_verify [#wasm_apiact_verify] Verifies an ACT envelope against the trusted key set and policy, and returns the claims as a JSON string. This is the full normative procedure from `agent-capability-token`, not a re-implementation: envelope decode, version/algorithm checks, Ed25519 signature verification (checked **before** any claim, so an attacker cannot plant unauthenticated claim content), temporal checks with leeway, and issuer/audience/scope policy. Arguments: * `token_bytes`: the ACT envelope bytes (CBOR). * `trusted_keys`: concatenated raw 32-byte Ed25519 public keys (exactly 32 bytes each, any count > 0). Keys are tried in order; `kid` is a hint for audit, never authoritative for selection. * `expected_issuer` / `expected_audience`: the policy bindings. Both are required, deliberately: a verifier that does not bind the token's intended audience accepts tokens meant for someone else. * `required_scopes`: each entry a `service:resource:action` scope string the token must grant; wildcards in the GRANT expand, in the REQUEST are literal. * `leeway_seconds`: symmetric clock-skew allowance on temporal checks. * `now_unix_seconds`: 0 for the system clock, or a pinned time for tests and for replaying a decision at a known instant. Errors (thrown on the JS side) are the canonical `ActError` reasons, so a forged token reports distinctly from an expired one and an unimplemented format version distinctly from both. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn act_verify( token_bytes: &[u8], trusted_keys: &[u8], expected_issuer: &str, expected_audience: &str, required_scopes: Vec, leeway_seconds: i64, now_unix_seconds: i64, ) -> Result; ``` Source line: `436`. ## wasm\_api::act\_decode\_unverified [#wasm_apiact_decode_unverified] Decodes an ACT envelope's claims WITHOUT verifying the signature, for diagnostics and tooling. The returned string is prefixed so callers cannot accidentally treat the contents as verified. Never use this for authorization: unverified claims are attacker controlled. Authorization decisions go through \[`act_verify`]. ```rust #[cfg(feature = "wasm")] #[cfg_attr(docsrs, doc(cfg(feature = "wasm")))] #[wasm_bindgen] pub fn act_decode_unverified(token_bytes: &[u8]) -> Result; ``` Source line: `497`. # openagent-crypto-wasm · x25519 URL: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/x25519 Markdown: https://docs.openagent.id/reference/rust/openagent-crypto-wasm/x25519.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-crypto-wasm/src/x25519.rs`. SHA-256: `c3377cf2c8c6a2f73d789a2ae207d9fdc9c28dd61499daee727076477af34af6`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## x25519::SECRET\_KEY\_LEN [#x25519secret_key_len] Length of an X25519 secret (private) key in bytes. ```rust pub const SECRET_KEY_LEN: usize; ``` Source line: `15`. ## x25519::PUBLIC\_KEY\_LEN [#x25519public_key_len] Length of an X25519 public key in bytes. ```rust pub const PUBLIC_KEY_LEN: usize; ``` Source line: `17`. ## x25519::SHARED\_SECRET\_LEN [#x25519shared_secret_len] Length of an X25519 raw shared secret in bytes. ```rust pub const SHARED_SECRET_LEN: usize; ``` Source line: `19`. ## x25519::X25519Keypair [#x25519x25519keypair] An X25519 keypair (Curve25519, RFC 7748). The secret key is zeroized on drop. ```rust pub struct X25519Keypair { } ``` Source line: `24`. ## x25519::X25519Keypair::secret\_key\_bytes [#x25519x25519keypairsecret_key_bytes] Returns a copy of the 32-byte secret key bytes. ```rust #[inline] pub fn secret_key_bytes(&self) -> [u8; SECRET_KEY_LEN]; ``` Source line: `47`. ## x25519::X25519Keypair::public\_key\_bytes [#x25519x25519keypairpublic_key_bytes] Returns a copy of the 32-byte public key bytes. ```rust #[inline] pub fn public_key_bytes(&self) -> [u8; PUBLIC_KEY_LEN]; ``` Source line: `53`. ## x25519::generate\_keypair [#x25519generate_keypair] Generates a fresh X25519 keypair using the OS / WASM host CSPRNG. ```rust pub fn generate_keypair() -> X25519Keypair; ``` Source line: `59`. ## x25519::public\_from\_secret [#x25519public_from_secret] Derives an X25519 public key from a 32-byte secret key. # Errors [#errors] \[`CryptoError::InvalidLength`] if `secret_key` is not exactly 32 bytes. ```rust pub fn public_from_secret(secret_key: &[u8]) -> Result<[u8; PUBLIC_KEY_LEN], CryptoError>; ``` Source line: `77`. ## x25519::diffie\_hellman [#x25519diffie_hellman] Performs an X25519 Diffie-Hellman key exchange. Returns the raw 32-byte shared secret. Callers MUST process this through a KDF (e.g. \[`crate::hkdf_sha256`]) before using it as keying material. # Errors [#errors-1] \[`CryptoError::InvalidLength`] if either input is not 32 bytes. ```rust pub fn diffie_hellman( secret_key: &[u8], peer_public_key: &[u8], ) -> Result<[u8; SHARED_SECRET_LEN], CryptoError>; ``` Source line: `94`. # openagent-scim · crate URL: https://docs.openagent.id/reference/rust/openagent-scim/crate Markdown: https://docs.openagent.id/reference/rust/openagent-scim/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/scim/rust/src/lib.rs`. SHA-256: `67ea054f3b8534db37953673131ee30641cdcf2978c96438d9a814c5123bd6f5`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## mapping [#mapping] # openagent-scim [#openagent-scim] SCIM 2.0 provisioning bridge for OpenAgent — enterprise agent lifecycle management via RFC 7644. This crate provides: * Trait definitions for the SCIM provisioner * SCIM resource types (User + Agent extension) * OAS Agent \<-> SCIM User mapping functions The TypeScript implementation (`@openagentid/scim`) is the primary SDK. This Rust crate provides trait definitions and reference types for Rust-native integrations. ```rust pub mod mapping; ``` Source line: `15`. ## types [#types] ```rust pub mod types; ``` Source line: `16`. ## ::ScimError [#scimerror] Errors from the SCIM provisioner. ```rust #[derive(Debug, thiserror::Error)] pub enum ScimError { #[error("Agent not found: {did}")] NotFound { did: String }, #[error("Agent already exists: {did}")] Conflict { did: String }, #[error("Invalid input: {detail}")] InvalidInput { detail: String }, #[error("Store error: {0}")] Store(String), #[error("Deprovisioning cascade error: {step} — {detail}")] CascadeError { step: String, detail: String }, } ``` Source line: `23`. ## ::ScimResult [#scimresult] Result type for SCIM operations. ```rust pub type ScimResult = Result; ``` Source line: `41`. ## ::AgentStore [#agentstore] Storage interface for agent records. Implementations must return cloned/owned data — never hand out mutable references to internal state. ```rust #[async_trait] pub trait AgentStore: Send + Sync { async fn list(&self) -> ScimResult>; async fn find_by_did(&self, did: &str) -> ScimResult>; async fn find_by_user_name(&self, user_name: &str) -> ScimResult>; async fn find_by_external_id(&self, external_id: &str) -> ScimResult>; async fn create(&self, record: AgentRecord) -> ScimResult; async fn update(&self, did: &str, record: AgentRecord) -> ScimResult; async fn delete(&self, did: &str) -> ScimResult<()>; } ``` Source line: `48`. ## ::DidRevoker [#didrevoker] DID document revocation hook. ```rust #[async_trait] pub trait DidRevoker: Send + Sync { async fn revoke(&self, did: &str) -> ScimResult<()>; } ``` Source line: `60`. ## ::DelegationCascadeRevoker [#delegationcascaderevoker] Delegation tree cascade revocation hook. ```rust #[async_trait] pub trait DelegationCascadeRevoker: Send + Sync { async fn cascade_revoke(&self, did: &str) -> ScimResult<()>; } ``` Source line: `66`. ## ::ArsenalSessionInvalidator [#arsenalsessioninvalidator] Arsenal session invalidation hook. ```rust #[async_trait] pub trait ArsenalSessionInvalidator: Send + Sync { async fn invalidate_sessions(&self, did: &str) -> ScimResult<()>; } ``` Source line: `72`. ## ::AuditSink [#auditsink] Audit event sink. ```rust #[async_trait] pub trait AuditSink: Send + Sync { async fn emit(&self, event: AuditEvent) -> ScimResult<()>; } ``` Source line: `78`. ## ::ScimProvisioner [#scimprovisioner] The SCIM provisioner trait — core lifecycle operations. Implementations wire together storage, DID management, delegation cascade, Arsenal session control, and audit emission. ```rust #[async_trait] pub trait ScimProvisioner: Send + Sync { /// Create a new agent identity via SCIM. async fn create_agent(&self, params: CreateAgentParams) -> ScimResult; /// Replace an agent record (SCIM PUT). async fn replace_agent( &self, did: &str, params: CreateAgentParams, ) -> ScimResult; /// Partial update (SCIM PATCH). Receives the already-patched record. async fn update_agent(&self, did: &str, record: AgentRecord) -> ScimResult; /// Deprovision an agent — the killer feature. /// /// Execution order: /// 1. Revoke the agent's DID document /// 2. Cascade-revoke all delegation proofs /// 3. Invalidate all active Arsenal sessions /// 4. Delete the agent record from the store /// 5. Emit audit event async fn deprovision_agent(&self, did: &str) -> ScimResult<()>; /// Find agent by DID. async fn find_by_did(&self, did: &str) -> ScimResult>; /// List all agents. async fn list_agents(&self) -> ScimResult>; } ``` Source line: `87`. # openagent-scim modules URL: https://docs.openagent.id/reference/rust/openagent-scim Markdown: https://docs.openagent.id/reference/rust/openagent-scim.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-bridges-scim-rust). [Focused integration guide](/integrations/bridges). ## Modules [#modules] * [crate](/reference/rust/openagent-scim/crate) — 10 declarations * [mapping](/reference/rust/openagent-scim/mapping) — 6 declarations * [types](/reference/rust/openagent-scim/types) — 18 declarations # openagent-scim · mapping URL: https://docs.openagent.id/reference/rust/openagent-scim/mapping Markdown: https://docs.openagent.id/reference/rust/openagent-scim/mapping.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/scim/rust/src/mapping.rs`. SHA-256: `fb8f084d5f431f079aa7cf4b3fa6e4acf4721c80adec4890c714cf071aea56d3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## mapping::agent\_to\_scim\_resource [#mappingagent_to_scim_resource] Convert an internal `AgentRecord` into a SCIM `ScimAgentResource`. ```rust pub fn agent_to_scim_resource(agent: &AgentRecord, base_url: &str) -> ScimAgentResource; ``` Source line: `9`. ## mapping::scim\_resource\_to\_agent [#mappingscim_resource_to_agent] Convert a SCIM resource back to an internal `AgentRecord`. This is used when processing SCIM PUT requests that provide a full replacement resource. ```rust pub fn scim_resource_to_agent( resource: &ScimAgentResource, existing: &AgentRecord, ) -> AgentRecord; ``` Source line: `48`. ## mapping::derive\_did [#mappingderive_did] Derive a deterministic DID from namespace + userName. ```rust pub fn derive_did(namespace: &str, user_name: &str) -> String; ``` Source line: `72`. ## mapping::derive\_keypair\_fingerprint [#mappingderive_keypair_fingerprint] Derive a keypair fingerprint for a provisioned agent. ```rust pub fn derive_keypair_fingerprint(did: &str) -> String; ``` Source line: `83`. ## mapping::compute\_lineage\_depth [#mappingcompute_lineage_depth] Compute lineage depth: 1 if parent is HMR/MHR, otherwise derived. ```rust pub fn compute_lineage_depth(parent_did: &str, parent_depth: Option) -> u32; ``` Source line: `92`. ## mapping::parse\_conformance\_level [#mappingparse_conformance_level] Validate a conformance level string. ```rust pub fn parse_conformance_level(s: &str) -> Result; ``` Source line: `103`. # openagent-scim · types URL: https://docs.openagent.id/reference/rust/openagent-scim/types Markdown: https://docs.openagent.id/reference/rust/openagent-scim/types.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/scim/rust/src/types.rs`. SHA-256: `90751b9c8de304eb38dc8898876cbbdc4295ea101863ee05818abf122a152306`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## types::SCIM\_USER\_SCHEMA [#typesscim_user_schema] SCIM core User schema URN. ```rust pub const SCIM_USER_SCHEMA: &str; ``` Source line: `6`. ## types::OPENAGENT\_AGENT\_SCHEMA [#typesopenagent_agent_schema] OpenAgent agent extension schema URN. ```rust pub const OPENAGENT_AGENT_SCHEMA: &str; ``` Source line: `9`. ## types::SCIM\_LIST\_RESPONSE\_SCHEMA [#typesscim_list_response_schema] SCIM List Response schema URN. ```rust pub const SCIM_LIST_RESPONSE_SCHEMA: &str; ``` Source line: `12`. ## types::SCIM\_ERROR\_SCHEMA [#typesscim_error_schema] SCIM Error schema URN. ```rust pub const SCIM_ERROR_SCHEMA: &str; ``` Source line: `16`. ## types::SCIM\_PATCH\_OP\_SCHEMA [#typesscim_patch_op_schema] SCIM PatchOp schema URN. ```rust pub const SCIM_PATCH_OP_SCHEMA: &str; ``` Source line: `19`. ## types::ConformanceLevel [#typesconformancelevel] Conformance levels for OpenAgent agents. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum ConformanceLevel { L0, L1, L2, } ``` Source line: `23`. ## types::AgentExtension [#typesagentextension] The OpenAgent agent extension attribute group. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AgentExtension { pub parent_did: String, pub conformance_level: ConformanceLevel, pub scopes: Vec, pub lineage_depth: u32, pub created_via: String, pub keypair_fingerprint: String } ``` Source line: `38`. ## types::ScimMeta [#typesscimmeta] SCIM resource metadata. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScimMeta { pub resource_type: String, pub created: String, pub last_modified: String, pub location: String, pub version: String } ``` Source line: `50`. ## types::ScimAgentResource [#typesscimagentresource] Full SCIM User resource with agent extension. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScimAgentResource { pub schemas: Vec, pub id: String, #[serde(skip_serializing_if = "Option::is_none")] pub external_id: Option, pub user_name: String, pub display_name: String, pub active: bool, pub meta: ScimMeta, #[serde(rename = "urn:openagent:scim:1.0:Agent")] pub agent_extension: AgentExtension } ``` Source line: `61`. ## types::ScimListResponse [#typesscimlistresponse] SCIM List Response envelope. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScimListResponse { pub schemas: Vec, pub total_results: usize, pub start_index: usize, pub items_per_page: usize, #[serde(rename = "Resources")] pub resources: Vec } ``` Source line: `77`. ## types::ScimErrorResponse [#typesscimerrorresponse] SCIM Error response. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScimErrorResponse { pub schemas: Vec, pub status: String, #[serde(skip_serializing_if = "Option::is_none")] pub scim_type: Option, pub detail: String } ``` Source line: `89`. ## types::ScimErrorResponse::new [#typesscimerrorresponsenew] Create a new SCIM error response. ```rust pub fn new(status: u16, scim_type: impl Into, detail: impl Into) -> Self; ``` Source line: `99`. ## types::AgentRecord [#typesagentrecord] Internal agent record — the canonical representation of a provisioned agent. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AgentRecord { pub did: String, pub user_name: String, pub display_name: String, pub active: bool, pub parent_did: String, pub conformance_level: ConformanceLevel, pub scopes: Vec, pub lineage_depth: u32, pub created_via: String, pub keypair_fingerprint: String, pub created_at: String, pub updated_at: String, pub version: String, #[serde(skip_serializing_if = "Option::is_none")] pub external_id: Option } ``` Source line: `112`. ## types::CreateAgentParams [#typescreateagentparams] Parameters for creating a new agent via SCIM. ```rust #[derive(Debug, Clone)] pub struct CreateAgentParams { pub user_name: String, pub display_name: Option, pub parent_did: String, pub conformance_level: ConformanceLevel, pub scopes: Vec, pub external_id: Option } ``` Source line: `132`. ## types::AuditEvent [#typesauditevent] Audit event emitted during agent lifecycle operations. ```rust #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct AuditEvent { #[serde(rename = "type")] pub event_type: AuditEventType, pub did: String, pub timestamp: String, pub details: serde_json::Value } ``` Source line: `144`. ## types::AuditEventType [#typesauditeventtype] Audit event types. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub enum AuditEventType { #[serde(rename = "agent.created")] AgentCreated, #[serde(rename = "agent.updated")] AgentUpdated, #[serde(rename = "agent.deprovisioned")] AgentDeprovisioned, } ``` Source line: `154`. ## types::PatchOperation [#typespatchoperation] SCIM PATCH operation. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PatchOperation { pub op: PatchOp, #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, #[serde(skip_serializing_if = "Option::is_none")] pub value: Option } ``` Source line: `165`. ## types::PatchOp [#typespatchop] SCIM PATCH operation type. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PatchOp { Add, Replace, Remove, } ``` Source line: `176`. # openagent-oidc · bridge URL: https://docs.openagent.id/reference/rust/openagent-oidc/bridge Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/bridge.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/bridge.rs`. SHA-256: `db0ca0778211c56f2305ad437135aa8f90f539d82d69641a68f053e2fd1b3e6d`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## bridge::OidcBridge [#bridgeoidcbridge] The OIDC bridge — maps between human OIDC tokens and OAS agent identities. Thread-safe and cheaply cloneable (all internal state is behind `Arc`). # Example [#example] ```rust let bridge = OidcBridge::new(OidcConfig::single( ProviderConfig::new("okta", "https://dev-123.okta.com/oauth2/default") .with_audience("my-app"), ))?; // Flow 1: Human JWT -> Agent DID let agent = bridge.derive_agent_from_jwt(&jwt_string, "my-bot").await?; // Flow 2: Agent ACT -> JWT let jwt = bridge.act_to_jwt(&act_claims, &signing_key, Algorithm::EdDSA, None).await?; ``` ```rust #[derive(Debug, Clone)] pub struct OidcBridge { } ``` Source line: `45`. ## bridge::OidcBridge::new [#bridgeoidcbridgenew] Create a new OIDC bridge with the given configuration. # Errors [#errors] Returns \[`OidcBridgeError::Config`] if the configuration is invalid. ```rust pub fn new(config: OidcConfig) -> Result; ``` Source line: `57`. ## bridge::OidcBridge::config [#bridgeoidcbridgeconfig] Access the bridge configuration. ```rust pub fn config(&self) -> &OidcConfig; ``` Source line: `71`. ## bridge::OidcBridge::derive\_agent\_from\_jwt [#bridgeoidcbridgederive_agent_from_jwt] Derive an agent DID from a human's OIDC JWT. 1. Decodes the JWT header to find the algorithm and key ID. 2. Identifies the OIDC provider from the `iss` claim. 3. Fetches the provider's JWKS (cached, with rotation-aware refresh). 4. Validates the JWT (signature, issuer, audience, expiry). 5. Maps the JWT subject to an HMR DID. 6. Derives a child agent DID under that HMR. # Errors [#errors-1] Returns errors from any step in the chain (discovery, JWKS, validation, identity derivation). ```rust pub async fn derive_agent_from_jwt( &self, token: &str, agent_name: &str, ) -> Result; ``` Source line: `90`. ## bridge::OidcBridge::act\_to\_jwt [#bridgeoidcbridgeact_to_jwt] Wrap an Arsenal ACT into a standard JWT for services that speak OAuth2. The resulting JWT includes custom claims (`lineage_depth`, `parent_hmr`, `act`) alongside standard OAuth2 claims (`sub`, `iss`, `aud`, `scope`, `exp`). # Arguments [#arguments] * `claims` - Pre-built ACT JWT claims (use \[`build_act_claims`]). * `signing_key` - The key to sign the JWT with. * `algorithm` - Signing algorithm (e.g., `EdDSA`, `RS256`). * `kid` - Optional key ID for the JWT header. # Errors [#errors-2] Returns \[`OidcBridgeError::Signing`] if JWT encoding fails. ```rust pub fn act_to_jwt( &self, claims: &ActJwtClaims, signing_key: &EncodingKey, algorithm: Algorithm, kid: Option<&str>, ) -> Result; ``` Source line: `145`. ## bridge::OidcBridge::wrap\_act\_as\_jwt [#bridgeoidcbridgewrap_act_as_jwt] Convenience: build ACT claims and sign in one step. ```rust pub fn wrap_act_as_jwt( &self, agent_did: &str, bridge_issuer: &str, audience: Option<&str>, scopes: &[String], lineage_depth: u32, parent_hmr: &str, act_b64: &str, signing_key: &EncodingKey, algorithm: Algorithm, kid: Option<&str>, ) -> Result; ``` Source line: `156`. ## bridge::OidcBridge::exchange\_token [#bridgeoidcbridgeexchange_token] Execute an RFC 8693 token exchange. Validates the subject token (human JWT), derives an agent, and returns an ACT-wrapped JWT as the exchanged token. # Arguments [#arguments-1] * `request` - The token exchange request. * `signing_key` - Key for signing the response JWT. * `algorithm` - Signing algorithm. * `bridge_issuer` - Issuer claim for the response JWT. # Errors [#errors-3] Returns errors from request validation, JWT validation, or signing. ```rust pub async fn exchange_token( &self, request: &TokenExchangeRequest, signing_key: &EncodingKey, algorithm: Algorithm, bridge_issuer: &str, ) -> Result; ``` Source line: `199`. ## bridge::OidcBridge::exchange\_token\_simple [#bridgeoidcbridgeexchange_token_simple] Convenience: exchange a human JWT for agent scopes in one call. Combines Flow 1 and scope mapping without requiring the caller to construct a full \[`TokenExchangeRequest`]. ```rust pub async fn exchange_token_simple( &self, human_jwt: &str, requested_scopes: &[&str], signing_key: &EncodingKey, algorithm: Algorithm, bridge_issuer: &str, ) -> Result; ``` Source line: `259`. ## bridge::OidcBridge::validate\_jwt [#bridgeoidcbridgevalidate_jwt] Validate a JWT and return its claims without deriving an agent. Useful when you only need to verify the human's identity, not spawn an agent. ```rust pub async fn validate_jwt(&self, token: &str) -> Result; ``` Source line: `278`. ## bridge::OidcBridge::refresh\_all\_jwks [#bridgeoidcbridgerefresh_all_jwks] Force-refresh the JWKS cache for all configured providers. ```rust pub async fn refresh_all_jwks(&self); ``` Source line: `300`. # openagent-oidc · config URL: https://docs.openagent.id/reference/rust/openagent-oidc/config Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/config.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/config.rs`. SHA-256: `2965e6823b8dd3c0503f4826dcedefa6b7d85304ad090dc45f2e6e8be5a5268e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::ProviderConfig [#configproviderconfig] Configuration for a single OIDC provider (Okta, Auth0, Azure AD, etc.). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProviderConfig { /// Human-readable provider name (e.g. `"okta"`, `"azure"`). pub name: String, /// OIDC issuer URL (must match the `iss` claim in JWTs from this provider). pub issuer: String, /// Expected `aud` claim. Omit to skip audience validation (not recommended). pub audience: Option, /// Override for the JWKS URI. If `None`, auto-discovered from /// `{issuer}/.well-known/openid-configuration`. pub jwks_url: Option, /// Which JWT claim maps to the human identity (default: `"sub"`). #[serde(default = "default_hmr_claim")] pub hmr_claim: String, /// Mapping from OIDC scopes / roles to Arsenal-style scopes. /// /// Example: `{ "admin": ["*:*:*"], "agent-user": ["openai:chat:*"] }`. #[serde(default)] pub scope_mapping: HashMap> } ``` Source line: `16`. ## config::ProviderConfig::new [#configproviderconfignew] Create a minimal provider config with just issuer and audience. ```rust pub fn new(name: impl Into, issuer: impl Into) -> Self; ``` Source line: `42`. ## config::ProviderConfig::with\_audience [#configproviderconfigwith_audience] Set the expected audience. ```rust pub fn with_audience(mut self, audience: impl Into) -> Self; ``` Source line: `54`. ## config::ProviderConfig::with\_jwks\_url [#configproviderconfigwith_jwks_url] Set a custom JWKS URL (skip discovery). ```rust pub fn with_jwks_url(mut self, url: impl Into) -> Self; ``` Source line: `60`. ## config::ProviderConfig::with\_hmr\_claim [#configproviderconfigwith_hmr_claim] Set the JWT claim that identifies the human root. ```rust pub fn with_hmr_claim(mut self, claim: impl Into) -> Self; ``` Source line: `66`. ## config::ProviderConfig::with\_scope\_mapping [#configproviderconfigwith_scope_mapping] Add a scope mapping entry. ```rust pub fn with_scope_mapping(mut self, role: impl Into, scopes: Vec) -> Self; ``` Source line: `72`. ## config::ProviderConfig::validate [#configproviderconfigvalidate] Validate that the configuration is usable. ```rust pub fn validate(&self) -> Result<()>; ``` Source line: `78`. ## config::OidcConfig [#configoidcconfig] Top-level OIDC bridge configuration. Supports either a single provider (for simple setups) or multiple providers (for enterprises with several IdPs). The bridge routes JWTs to the correct provider based on the `iss` claim. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OidcConfig { /// List of OIDC providers. At least one is required. pub providers: Vec, /// OAS namespace for minted DIDs (default: `"openagent"`). #[serde(default = "default_namespace")] pub namespace: String, /// Default TTL in seconds for emitted JWTs (Flow 2). Default: 3600. #[serde(default = "default_jwt_ttl")] pub jwt_ttl_seconds: i64, /// HTTP client timeout in milliseconds for discovery / JWKS fetches. #[serde(default = "default_http_timeout_ms")] pub http_timeout_ms: u64 } ``` Source line: `99`. ## config::OidcConfig::single [#configoidcconfigsingle] Create a config with a single OIDC provider. ```rust pub fn single(provider: ProviderConfig) -> Self; ``` Source line: `127`. ## config::OidcConfig::multi [#configoidcconfigmulti] Create a config with multiple providers. ```rust pub fn multi(providers: Vec) -> Self; ``` Source line: `137`. ## config::OidcConfig::with\_namespace [#configoidcconfigwith_namespace] Override the OAS namespace. ```rust pub fn with_namespace(mut self, ns: impl Into) -> Self; ``` Source line: `147`. ## config::OidcConfig::with\_jwt\_ttl [#configoidcconfigwith_jwt_ttl] Override the JWT TTL for Flow 2 (ACT -> JWT). ```rust pub fn with_jwt_ttl(mut self, seconds: i64) -> Self; ``` Source line: `153`. ## config::OidcConfig::validate [#configoidcconfigvalidate] Validate the entire configuration. ```rust pub fn validate(&self) -> Result<()>; ``` Source line: `159`. ## config::OidcConfig::find\_provider [#configoidcconfigfind_provider] Find the provider whose issuer matches the given string. ```rust pub fn find_provider(&self, issuer: &str) -> Option<&ProviderConfig>; ``` Source line: `188`. # openagent-oidc · crate URL: https://docs.openagent.id/reference/rust/openagent-oidc/crate Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/lib.rs`. SHA-256: `e1b78269f34977b6ddbd8eb3685e0ace43ad061c633423ab5684a6c3f88bc039`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## bridge [#bridge] ```rust pub mod bridge; ``` Source line: `70`. ## config [#config] ```rust pub mod config; ``` Source line: `71`. ## discovery [#discovery] ```rust pub mod discovery; ``` Source line: `72`. ## error [#error] ```rust pub mod error; ``` Source line: `73`. ## exchange [#exchange] ```rust pub mod exchange; ``` Source line: `74`. ## jwks [#jwks] ```rust pub mod jwks; ``` Source line: `75`. ## jwt [#jwt] ```rust pub mod jwt; ``` Source line: `76`. ## mapping [#mapping] ```rust pub mod mapping; ``` Source line: `77`. ## pub use bridge::OidcBridge; [#pub-use-bridgeoidcbridge] ```rust pub use bridge::OidcBridge; ``` Source line: `80`. ## pub use config::\{OidcConfig, ProviderConfig}; [#pub-use-configoidcconfig-providerconfig] ```rust pub use config::{OidcConfig, ProviderConfig}; ``` Source line: `81`. ## pub use error::\{OidcBridgeError, Result}; [#pub-use-erroroidcbridgeerror-result] ```rust pub use error::{OidcBridgeError, Result}; ``` Source line: `82`. ## pub use exchange::\{TokenExchangeRequest, TokenExchangeResponse}; [#pub-use-exchangetokenexchangerequest-tokenexchangeresponse] ```rust pub use exchange::{TokenExchangeRequest, TokenExchangeResponse}; ``` Source line: `83`. ## pub use jwt::\{ActJwtClaims, ValidatedClaims}; [#pub-use-jwtactjwtclaims-validatedclaims] ```rust pub use jwt::{ActJwtClaims, ValidatedClaims}; ``` Source line: `84`. ## pub use mapping::DerivedAgent; [#pub-use-mappingderivedagent] ```rust pub use mapping::DerivedAgent; ``` Source line: `85`. ## ::VERSION [#version] Crate version, sourced from `Cargo.toml` at compile time. ```rust pub const VERSION: &str; ``` Source line: `88`. # openagent-oidc · discovery URL: https://docs.openagent.id/reference/rust/openagent-oidc/discovery Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/discovery.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/discovery.rs`. SHA-256: `ce5af3534455570d352ac8a1051bc8612a3debed502a0b3a8a2c46f47967a70e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## discovery::DiscoveryDocument [#discoverydiscoverydocument] Subset of the OpenID Connect Discovery document that we need. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DiscoveryDocument { /// The OIDC issuer identifier (MUST match the `issuer` in our config). pub issuer: String, /// URL of the authorization endpoint. #[serde(default)] pub authorization_endpoint: String, /// URL of the token endpoint. #[serde(default)] pub token_endpoint: String, /// URL of the JWKS endpoint. pub jwks_uri: String, /// Supported response types. #[serde(default)] pub response_types_supported: Vec, /// Supported subject identifier types. #[serde(default)] pub subject_types_supported: Vec, /// Supported ID token signing algorithms. #[serde(default)] pub id_token_signing_alg_values_supported: Vec, /// Supported scopes. #[serde(default)] pub scopes_supported: Vec, /// Token exchange endpoint (may differ from token_endpoint for some providers). #[serde(default)] pub token_exchange_endpoint: Option } ``` Source line: `18`. ## discovery::DiscoveryClient [#discoverydiscoveryclient] OIDC discovery client with per-issuer caching. Cache entries expire after the configured TTL (default: 1 hour). ```rust #[derive(Debug, Clone)] pub struct DiscoveryClient { } ``` Source line: `57`. ## discovery::DiscoveryClient::new [#discoverydiscoveryclientnew] Create a new discovery client. ```rust pub fn new(timeout: Duration, cache_ttl: Duration) -> Self; ``` Source line: `65`. ## discovery::DiscoveryClient::with\_defaults [#discoverydiscoveryclientwith_defaults] Create a discovery client with default settings (10s timeout, 1h cache TTL). ```rust pub fn with_defaults() -> Self; ``` Source line: `80`. ## discovery::DiscoveryClient::discover [#discoverydiscoveryclientdiscover] Fetch (or return cached) the discovery document for the given issuer. # Errors [#errors] Returns \[`OidcBridgeError::Discovery`] if the fetch or parse fails. ```rust pub async fn discover(&self, issuer: &str) -> Result; ``` Source line: `89`. ## discovery::DiscoveryClient::invalidate [#discoverydiscoveryclientinvalidate] Invalidate the cache for a specific issuer. ```rust pub async fn invalidate(&self, issuer: &str); ``` Source line: `149`. ## discovery::DiscoveryClient::invalidate\_all [#discoverydiscoveryclientinvalidate_all] Invalidate the entire cache. ```rust pub async fn invalidate_all(&self); ``` Source line: `155`. # openagent-oidc · error URL: https://docs.openagent.id/reference/rust/openagent-oidc/error Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/error.rs`. SHA-256: `337e5071fb79b843df2ddf7f81ac0d51e6114063ef68b75b13d3dfb4609dee56`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::Result [#errorresult] Result alias for OIDC bridge operations. ```rust pub type Result = std::result::Result; ``` Source line: `8`. ## error::OidcBridgeError [#erroroidcbridgeerror] Unified error type for OIDC bridge operations. ```rust #[derive(Debug, Error)] pub enum OidcBridgeError { /// OIDC discovery failed (network, parse, missing fields). #[error("oidc discovery error: {0}")] Discovery(String), /// JWKS fetch or parse error. #[error("jwks error: {0}")] Jwks(String), /// JWT validation failed (signature, claims, expiry). #[error("jwt validation error: {0}")] JwtValidation(String), /// No provider matched the JWT issuer claim. #[error("unknown issuer: {0}")] UnknownIssuer(String), /// DID mapping or derivation failed. #[error("identity mapping error: {0}")] Mapping(String), /// Token exchange error (RFC 8693). #[error("token exchange error: {0}")] Exchange(String), /// ACT-to-JWT signing error. #[error("signing error: {0}")] Signing(String), /// Configuration error (missing required fields, invalid values). #[error("configuration error: {0}")] Config(String), /// HTTP transport error. #[error("transport error: {0}")] Transport(String), /// Underlying OAS identity error. #[error("identity error: {0}")] Identity(String), /// JSON serialization/deserialization error. #[error("json error: {0}")] Json(#[from] serde_json::Error), } ``` Source line: `12`. ## error::OidcBridgeError::config [#erroroidcbridgeerrorconfig] Construct a configuration error. ```rust pub fn config(msg: impl Into) -> Self; ``` Source line: `60`. ## error::OidcBridgeError::discovery [#erroroidcbridgeerrordiscovery] Construct a discovery error. ```rust pub fn discovery(msg: impl Into) -> Self; ``` Source line: `65`. ## error::OidcBridgeError::jwks [#erroroidcbridgeerrorjwks] Construct a JWKS error. ```rust pub fn jwks(msg: impl Into) -> Self; ``` Source line: `70`. ## error::OidcBridgeError::jwt\_validation [#erroroidcbridgeerrorjwt_validation] Construct a JWT validation error. ```rust pub fn jwt_validation(msg: impl Into) -> Self; ``` Source line: `75`. ## error::OidcBridgeError::mapping [#erroroidcbridgeerrormapping] Construct a mapping error. ```rust pub fn mapping(msg: impl Into) -> Self; ``` Source line: `80`. ## error::OidcBridgeError::transport [#erroroidcbridgeerrortransport] Construct a transport error. ```rust pub fn transport(msg: impl Into) -> Self; ``` Source line: `85`. # openagent-oidc · exchange URL: https://docs.openagent.id/reference/rust/openagent-oidc/exchange Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/exchange.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/exchange.rs`. SHA-256: `eee1c1b9b3e003f6e61c96d3bca3af1e70494695d5060ca17447f4928ea16831`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## exchange::GRANT\_TYPE\_TOKEN\_EXCHANGE [#exchangegrant_type_token_exchange] Standard grant type for RFC 8693 Token Exchange. ```rust pub const GRANT_TYPE_TOKEN_EXCHANGE: &str; ``` Source line: `13`. ## exchange::TOKEN\_TYPE\_JWT [#exchangetoken_type_jwt] Standard token type for JWT subject tokens. ```rust pub const TOKEN_TYPE_JWT: &str; ``` Source line: `17`. ## exchange::TOKEN\_TYPE\_ACT [#exchangetoken_type_act] Custom token type for OpenAgent ACTs. ```rust pub const TOKEN_TYPE_ACT: &str; ``` Source line: `20`. ## exchange::TOKEN\_TYPE\_ACCESS [#exchangetoken_type_access] Standard token type for access tokens. ```rust pub const TOKEN_TYPE_ACCESS: &str; ``` Source line: `23`. ## exchange::TokenExchangeRequest [#exchangetokenexchangerequest] Token exchange request (RFC 8693 Section 2.1). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TokenExchangeRequest { /// Must be `urn:ietf:params:oauth:grant-type:token-exchange`. pub grant_type: String, /// The subject token (typically a human JWT). pub subject_token: String, /// Type of the subject token. pub subject_token_type: String, /// Desired type of the issued token. #[serde(skip_serializing_if = "Option::is_none")] pub requested_token_type: Option, /// Requested scopes for the exchanged token. #[serde(skip_serializing_if = "Option::is_none")] pub scope: Option, /// Target audience for the exchanged token. #[serde(skip_serializing_if = "Option::is_none")] pub audience: Option, /// Logical name of the target service. #[serde(skip_serializing_if = "Option::is_none")] pub resource: Option, /// Actor token (for delegation / impersonation scenarios). #[serde(skip_serializing_if = "Option::is_none")] pub actor_token: Option, /// Type of the actor token. #[serde(skip_serializing_if = "Option::is_none")] pub actor_token_type: Option } ``` Source line: `27`. ## exchange::TokenExchangeResponse [#exchangetokenexchangeresponse] Token exchange response (RFC 8693 Section 2.2). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TokenExchangeResponse { /// The issued token. pub access_token: String, /// Type of the issued token. pub issued_token_type: String, /// Token type (always `"Bearer"` for our use case). pub token_type: String, /// Lifetime of the token in seconds. pub expires_in: i64, /// Scope of the issued token. #[serde(skip_serializing_if = "Option::is_none")] pub scope: Option } ``` Source line: `56`. ## exchange::TokenExchangeRequest::new\_jwt\_to\_act [#exchangetokenexchangerequestnew_jwt_to_act] Create a new token exchange request for exchanging a human JWT for an ACT. ```rust pub fn new_jwt_to_act(subject_token: impl Into, scopes: &[&str]) -> Self; ``` Source line: `72`. ## exchange::TokenExchangeRequest::validate [#exchangetokenexchangerequestvalidate] Validate the request structure. ```rust pub fn validate(&self) -> Result<()>; ``` Source line: `91`. ## exchange::TokenExchangeRequest::requested\_scopes [#exchangetokenexchangerequestrequested_scopes] Parse requested scopes into a vector. ```rust pub fn requested_scopes(&self) -> Vec; ``` Source line: `133`. ## exchange::TokenExchangeResponse::success [#exchangetokenexchangeresponsesuccess] Build a successful token exchange response. ```rust pub fn success( access_token: impl Into, issued_token_type: impl Into, expires_in: i64, scope: Option, ) -> Self; ``` Source line: `143`. ## exchange::TokenExchangeError [#exchangetokenexchangeerror] RFC 8693 error response. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TokenExchangeError { /// Error code (per RFC 6749 Section 5.2). pub error: String, /// Human-readable error description. #[serde(skip_serializing_if = "Option::is_none")] pub error_description: Option } ``` Source line: `161`. ## exchange::TokenExchangeError::invalid\_request [#exchangetokenexchangeerrorinvalid_request] Create an `invalid_request` error. ```rust pub fn invalid_request(description: impl Into) -> Self; ``` Source line: `171`. ## exchange::TokenExchangeError::invalid\_grant [#exchangetokenexchangeerrorinvalid_grant] Create an `invalid_grant` error (e.g., JWT validation failed). ```rust pub fn invalid_grant(description: impl Into) -> Self; ``` Source line: `179`. ## exchange::TokenExchangeError::unsupported\_token\_type [#exchangetokenexchangeerrorunsupported_token_type] Create an `unsupported_token_type` error. ```rust pub fn unsupported_token_type(description: impl Into) -> Self; ``` Source line: `187`. ## exchange::TokenExchangeError::invalid\_target [#exchangetokenexchangeerrorinvalid_target] Create an `invalid_target` error. ```rust pub fn invalid_target(description: impl Into) -> Self; ``` Source line: `195`. # openagent-oidc modules URL: https://docs.openagent.id/reference/rust/openagent-oidc Markdown: https://docs.openagent.id/reference/rust/openagent-oidc.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-bridges-oidc-rust). [Focused integration guide](/integrations/bridges). ## Modules [#modules] * [crate](/reference/rust/openagent-oidc/crate) — 15 declarations * [bridge](/reference/rust/openagent-oidc/bridge) — 10 declarations * [config](/reference/rust/openagent-oidc/config) — 14 declarations * [discovery](/reference/rust/openagent-oidc/discovery) — 7 declarations * [error](/reference/rust/openagent-oidc/error) — 8 declarations * [exchange](/reference/rust/openagent-oidc/exchange) — 15 declarations * [jwks](/reference/rust/openagent-oidc/jwks) — 7 declarations * [jwt](/reference/rust/openagent-oidc/jwt) — 6 declarations * [mapping](/reference/rust/openagent-oidc/mapping) — 5 declarations # openagent-oidc · jwks URL: https://docs.openagent.id/reference/rust/openagent-oidc/jwks Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/jwks.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/jwks.rs`. SHA-256: `583b82e1c77b4208cb57a512763eaf62cbc3717254074494ff48e308a2abba22`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## jwks::JwksClient [#jwksjwksclient] JWKS client with per-URI caching and rotation-aware refresh. ```rust #[derive(Debug, Clone)] pub struct JwksClient { } ``` Source line: `28`. ## jwks::JwksClient::new [#jwksjwksclientnew] Create a new JWKS client. ```rust pub fn new(timeout: Duration, cache_ttl: Duration) -> Self; ``` Source line: `36`. ## jwks::JwksClient::with\_defaults [#jwksjwksclientwith_defaults] Create a client with default settings (10s timeout, 1h cache TTL). ```rust pub fn with_defaults() -> Self; ``` Source line: `51`. ## jwks::JwksClient::fetch\_jwks [#jwksjwksclientfetch_jwks] Fetch (or return cached) the JWKS for the given URI. # Errors [#errors] Returns \[`OidcBridgeError::Jwks`] on network or parse failure. ```rust pub async fn fetch_jwks(&self, jwks_uri: &str) -> Result; ``` Source line: `60`. ## jwks::JwksClient::refresh [#jwksjwksclientrefresh] Force-refresh the JWKS for the given URI (key rotation scenario). Call this when JWT signature verification fails — the IdP may have rotated keys since we last fetched the JWKS. ```rust pub async fn refresh(&self, jwks_uri: &str) -> Result; ``` Source line: `78`. ## jwks::JwksClient::select\_key [#jwksjwksclientselect_key] Select a \[`DecodingKey`] from the JWKS that matches the JWT header. Matches on `kid` (key ID) first, then falls back to `alg` matching if there is exactly one key for that algorithm. # Errors [#errors-1] Returns \[`OidcBridgeError::Jwks`] if no matching key is found. ```rust pub fn select_key(jwks: &JwkSet, header: &Header) -> Result; ``` Source line: `91`. ## jwks::JwksClient::invalidate [#jwksjwksclientinvalidate] Invalidate a specific JWKS cache entry. ```rust pub async fn invalidate(&self, jwks_uri: &str); ``` Source line: `178`. # openagent-oidc · jwt URL: https://docs.openagent.id/reference/rust/openagent-oidc/jwt Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/jwt.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/jwt.rs`. SHA-256: `3a1b313c20181eae9860c5525d156a1748a6859d586b20e6b1b6769905f36aab`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## jwt::ValidatedClaims [#jwtvalidatedclaims] Standard + custom claims extracted from a validated human JWT. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ValidatedClaims { /// Issuer (`iss` claim). pub issuer: String, /// Subject (`sub` claim) — typically the human user's unique ID. pub subject: String, /// Audience (`aud` claim), if present. #[serde(default)] pub audience: Vec, /// Expiration time (epoch seconds). pub exp: i64, /// Issued-at time (epoch seconds). #[serde(default)] pub iat: i64, /// The claim value that maps to the HMR (configurable, default `sub`). pub hmr_value: String, /// OIDC scopes or roles extracted from the token. #[serde(default)] pub scopes: Vec, /// All original claims (for custom mapping). #[serde(default)] pub raw_claims: HashMap } ``` Source line: `23`. ## jwt::decode\_jwt\_header [#jwtdecode_jwt_header] Decode the JWT header without validation (to extract `kid` and `alg`). # Errors [#errors] Returns \[`OidcBridgeError::JwtValidation`] if the header is malformed. ```rust pub fn decode_jwt_header(token: &str) -> Result
; ``` Source line: `81`. ## jwt::validate\_jwt [#jwtvalidate_jwt] Validate and decode a JWT using the given decoding key. Performs standard OIDC validation: issuer match, audience match (if configured), expiry check, signature verification. # Errors [#errors-1] Returns \[`OidcBridgeError::JwtValidation`] on any validation failure. ```rust pub fn validate_jwt( token: &str, key: &DecodingKey, algorithm: Algorithm, provider: &ProviderConfig, ) -> Result; ``` Source line: `95`. ## jwt::ActJwtClaims [#jwtactjwtclaims] Claims for an outbound JWT that wraps an Arsenal ACT (Flow 2). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ActJwtClaims { /// Subject: the agent's DID. pub sub: String, /// Issuer: the bridge's own issuer identifier. pub iss: String, /// Audience: the service that will consume this JWT. #[serde(skip_serializing_if = "Option::is_none")] pub aud: Option, /// Expiration (epoch seconds). pub exp: i64, /// Issued-at (epoch seconds). pub iat: i64, /// JWT ID for replay prevention. pub jti: String, /// Arsenal scope strings mapped from the ACT. pub scope: String, /// The agent's lineage depth (hops from HMR root). pub lineage_depth: u32, /// The parent HMR DID. pub parent_hmr: String, /// The serialized ACT (base64url-encoded). pub act: String } ``` Source line: `156`. ## jwt::sign\_act\_jwt [#jwtsign_act_jwt] Sign a JWT wrapping an Arsenal ACT for services that speak OAuth2. The resulting JWT can be introspected by standard OAuth2 resource servers. Custom claims (`lineage_depth`, `parent_hmr`, `act`) carry the agent identity metadata. # Arguments [#arguments] * `claims` - Pre-built ACT JWT claims. * `signing_key` - Ed25519 or RSA private key in PEM or DER format. * `algorithm` - The signing algorithm (e.g., `EdDSA`, `RS256`). * `kid` - Optional key ID to include in the JWT header. # Errors [#errors-2] Returns \[`OidcBridgeError::Signing`] if encoding fails. ```rust pub fn sign_act_jwt( claims: &ActJwtClaims, signing_key: &EncodingKey, algorithm: Algorithm, kid: Option<&str>, ) -> Result; ``` Source line: `196`. ## jwt::build\_act\_claims [#jwtbuild_act_claims] Build ACT JWT claims from the parts produced by the bridge. ```rust pub fn build_act_claims( agent_did: &str, bridge_issuer: &str, audience: Option<&str>, scopes: &[String], lineage_depth: u32, parent_hmr: &str, act_b64: &str, ttl_seconds: i64, ) -> ActJwtClaims; ``` Source line: `212`. # openagent-oidc · mapping URL: https://docs.openagent.id/reference/rust/openagent-oidc/mapping Markdown: https://docs.openagent.id/reference/rust/openagent-oidc/mapping.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/bridges/oidc/rust/src/mapping.rs`. SHA-256: `4fc3d6174d7e45f26946109f84ae2814a0a343d7123f69e1638b58e8d8adb8c8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## mapping::DerivedAgent [#mappingderivedagent] Result of deriving an agent DID from a human JWT. ```rust #[derive(Debug)] pub struct DerivedAgent { /// The agent's DID (`did:oas::agent:`). pub agent_did: String, /// The agent's Ed25519 keypair. pub agent_keypair: OasKeyPair, /// The agent's signed OAS document. pub agent_document: OasDocument, /// Cryptographic lineage proof (the agent's document contains this). pub lineage_proof: Option, /// The parent HMR DID. pub parent_hmr_did: String, /// The parent HMR's signed document. pub parent_document: OasDocument, /// The parent HMR's keypair (needed for further derivations). pub parent_keypair: OasKeyPair } ``` Source line: `22`. ## mapping::hmr\_identifier\_from\_claims [#mappinghmr_identifier_from_claims] Deterministic identifier for an HMR derived from an OIDC subject. Uses the issuer + subject to produce a stable, collision-resistant identifier so the same human always maps to the same HMR DID. ```rust pub fn hmr_identifier_from_claims(issuer: &str, hmr_value: &str) -> String; ``` Source line: `43`. ## mapping::derive\_agent\_from\_claims [#mappingderive_agent_from_claims] Derive an agent DID under a human's HMR from validated OIDC claims. This is the core of **Flow 1**: Human JWT -> Agent DID. 1. Maps the JWT subject to an HMR DID (deterministic). 2. Derives a child agent DID under that HMR using HKDF-SHA256. 3. Returns the agent's identity (DID, keypair, lineage proof, parent HMR). # Arguments [#arguments] * `namespace` - OAS namespace (e.g. `"openagent"`). * `claims` - Validated claims from the human's JWT. * `agent_name` - Name for the derived agent (e.g. `"my-bot"`). # Errors [#errors] Returns \[`OidcBridgeError::Mapping`] if HMR minting or child derivation fails. ```rust pub fn derive_agent_from_claims( namespace: &str, claims: &ValidatedClaims, agent_name: &str, ) -> Result; ``` Source line: `110`. ## mapping::map\_scopes [#mappingmap_scopes] Map OIDC scopes/roles to Arsenal capability scopes using the provider's scope mapping configuration. If the JWT contains scopes that are in the provider's `scope_mapping`, the corresponding Arsenal scopes are returned. Unmapped scopes are passed through as-is (useful when OIDC scopes already match Arsenal format). ```rust pub fn map_scopes( oidc_scopes: &[String], scope_mapping: &HashMap>, ) -> Vec; ``` Source line: `165`. ## mapping::lineage\_depth [#mappinglineage_depth] Compute the lineage depth from an OAS document. Derived from the OAS `LineageSection::generation` (number of derivation steps from the human root); documents without a lineage section report 0. ```rust pub fn lineage_depth(doc: &OasDocument) -> u32; ``` Source line: `194`. # openagent-server · authority URL: https://docs.openagent.id/reference/rust/openagent-server/authority Markdown: https://docs.openagent.id/reference/rust/openagent-server/authority.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/authority.rs`. SHA-256: `3c9c321ec47adf7eb3bc86427418bc9f67fca6ebf5f141fc75e6df5232e4cec3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## authority::LegacyLineageEvidence [#authoritylegacylineageevidence] Parsed legacy lineage retained strictly as migration/audit evidence. This type deliberately does not use an authority-oriented name. There is no authoritative lineage result type in the containment release; adding one requires a separately reviewed hardened verifier integration. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LegacyLineageEvidence { /// DID named as the subject by the legacy evidence. pub subject: String, /// Root DID reported by the legacy evidence. pub root: String, /// Reported path kind, e.g. `human_to_agent`. pub path_kind: String, /// Parser/source identifier. pub source: String, /// Reconstructed informational path, ordered root to subject. pub path: Vec, /// Finalized block reported by the source. pub finalized_block: u64, /// Scopes reported by the legacy evidence; never authorization grants. pub scopes: Vec, /// Reported generation/depth from root to subject. pub generation: u32, /// Reported root kind. #[serde(skip_serializing_if = "Option::is_none")] pub root_kind: Option, /// Optional org lineage root commitment. #[serde(skip_serializing_if = "Option::is_none")] pub org_root_commitment: Option, /// Optional expiry timestamp for the authority edge/path. #[serde(skip_serializing_if = "Option::is_none")] pub expires_at: Option } ``` Source line: `16`. ## authority::PrivilegedAuthorityRequest [#authorityprivilegedauthorityrequest] Request passed to a deployment-provided privileged authority verifier. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct PrivilegedAuthorityRequest { pub subject_did: String, pub required_path_kind: Option, pub required_scopes: Vec, pub min_finalized_block: Option } ``` Source line: `46`. ## authority::PrivilegedAuthorityVerifier [#authorityprivilegedauthorityverifier] Adapter trait for parsing legacy OAS/Sigil lineage evidence. The output is intentionally \[`LegacyLineageEvidence`], so an adapter cannot present the legacy profile as authoritative at compile time. ```rust #[async_trait] pub trait PrivilegedAuthorityVerifier: Send + Sync { async fn verify( &self, request: PrivilegedAuthorityRequest, ) -> Result; } ``` Source line: `58`. ## authority::MissingAuthorityVerifier [#authoritymissingauthorityverifier] Authority verifier used when no OAS/Sigil adapter is installed. ```rust pub struct MissingAuthorityVerifier; ``` Source line: `66`. ## authority::AuthorityError [#authorityauthorityerror] ```rust #[derive(Debug, thiserror::Error)] pub enum AuthorityError { #[error("legacy lineage evidence is informational and cannot authorize")] LegacyLineageNotAuthoritative, #[error("authoritative lineage verification is unavailable")] LineageVerificationUnavailable, #[error("privileged lineage authority is malformed: {0}")] Malformed(String), #[error("privileged lineage authority was rejected: {0}")] Rejected(String), } ``` Source line: `79`. ## authority::require\_authoritative\_lineage [#authorityrequire_authoritative_lineage] Rejects legacy lineage at a privileged authorization boundary. The arguments that formerly shaped structural acceptance remain on the API during migration so callers cannot accidentally remove an authorization gate. They are intentionally not consulted: no legacy field combination can satisfy the privilege predicate. ```rust pub fn require_authoritative_lineage( _subject_did: &str, _evidence: &LegacyLineageEvidence, _required_path_kind: Option<&str>, _required_scopes: &[String], ) -> Result; ``` Source line: `96`. # openagent-server · challenge URL: https://docs.openagent.id/reference/rust/openagent-server/challenge Markdown: https://docs.openagent.id/reference/rust/openagent-server/challenge.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/challenge.rs`. SHA-256: `2920c158061f341875b5b18dc7b452400506dc614b4bfda7f3e03c88ab021dd0`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## challenge::Challenge [#challengechallenge] A challenge issued to an unauthenticated agent. Per OPENAGENT-CORE-SPEC.md §4, the challenge is a JSON object with: * `type`: always "openagent-challenge-v1" * `nonce`: 32-byte hex string * `timestamp`: ISO 8601 UTC * `origin`: server origin * `realm`: optional realm string ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Challenge { #[serde(rename = "type")] pub challenge_type: String, pub nonce: String, pub timestamp: String, pub origin: String, #[serde(skip_serializing_if = "Option::is_none")] pub realm: Option } ``` Source line: `22`. ## challenge::Challenge::new [#challengechallengenew] Creates a new challenge with a cryptographically random nonce. ```rust pub fn new(origin: &str, realm: Option<&str>) -> Self; ``` Source line: `34`. ## challenge::Challenge::to\_jcs\_bytes [#challengechallengeto_jcs_bytes] Serializes this challenge using JCS (RFC 8785) for deterministic signing. ```rust pub fn to_jcs_bytes(&self) -> Result, serde_json::Error>; ``` Source line: `50`. ## challenge::Challenge::to\_base64url [#challengechallengeto_base64url] Encodes the challenge as base64url for the WWW-Authenticate header. ```rust pub fn to_base64url(&self) -> Result; ``` Source line: `57`. ## challenge::hex::encode [#challengehexencode] ```rust pub fn encode(bytes: &[u8]) -> String; ``` Source line: `65`. ## challenge::NonceStore [#challengenoncestore] Thread-safe nonce store with TTL-based expiration. Per OPENAGENT-CORE-SPEC.md §7: * Nonces are single-use (consumed atomically on verification) * Nonces expire after a configurable TTL (default 30 seconds) * Expired nonces are lazily cleaned up ```rust pub struct NonceStore { } ``` Source line: `86`. ## challenge::NonceStore::new [#challengenoncestorenew] ```rust pub fn new(ttl: Duration) -> Self; ``` Source line: `92`. ## challenge::NonceStore::issue [#challengenoncestoreissue] Issues a new challenge and stores its nonce. ```rust pub fn issue(&self, origin: &str, realm: Option<&str>) -> Challenge; ``` Source line: `100`. ## challenge::NonceStore::consume [#challengenoncestoreconsume] Consumes a nonce atomically, returning the original challenge if valid. Returns `None` if the nonce is unknown, already consumed, or expired. ```rust pub fn consume(&self, nonce: &str) -> Option; ``` Source line: `119`. # openagent-server · config URL: https://docs.openagent.id/reference/rust/openagent-server/config Markdown: https://docs.openagent.id/reference/rust/openagent-server/config.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/config.rs`. SHA-256: `f3287273cd30315d8e25093d429ce61c9652b3de24c912e28e60537d18be424c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::OpenAgentConfig [#configopenagentconfig] Configuration for the OpenAgent server middleware. ```rust #[derive(Debug, Clone)] pub struct OpenAgentConfig { /// Server origin for challenge generation (e.g., "https://api.example.com"). pub origin: String, /// Optional realm for challenge generation. pub realm: Option, /// Challenge nonce TTL. Default: 30 seconds. pub nonce_ttl: Duration, /// Session token TTL in seconds. Default: 900 (15 minutes). pub session_ttl_secs: i64, /// HMAC secret for signing session JWTs. Must be at least 32 bytes. pub session_secret: Vec, /// Minimum trust tier required for this service. Default: 0 (Anonymous). pub min_trust_tier: u8, /// Require privileged lineage authority for this service. /// /// During containment this is a deny-only gate because no hardened lineage /// verifier result type is available. pub require_privileged_authority: bool, /// Required authority path kind when privileged authority is required. pub required_authority_path: Option, /// Scopes that must be present in the privileged authority context. pub required_authority_scopes: Vec, /// Optional minimum finalized block for accepted authority context. pub min_authority_finalized_block: Option } ``` Source line: `9`. ## config::OpenAgentConfig::new [#configopenagentconfignew] Creates a new config with the given origin and session secret. All other fields use protocol defaults. ```rust pub fn new(origin: impl Into, session_secret: impl Into>) -> Self; ``` Source line: `48`. ## config::OpenAgentConfig::with\_realm [#configopenagentconfigwith_realm] Sets the optional realm. ```rust pub fn with_realm(mut self, realm: impl Into) -> Self; ``` Source line: `64`. ## config::OpenAgentConfig::with\_min\_trust\_tier [#configopenagentconfigwith_min_trust_tier] Sets the minimum trust tier. ```rust pub fn with_min_trust_tier(mut self, tier: u8) -> Self; ``` Source line: `70`. ## config::OpenAgentConfig::with\_nonce\_ttl [#configopenagentconfigwith_nonce_ttl] Sets the nonce TTL. ```rust pub fn with_nonce_ttl(mut self, ttl: Duration) -> Self; ``` Source line: `76`. ## config::OpenAgentConfig::with\_session\_ttl\_secs [#configopenagentconfigwith_session_ttl_secs] Sets the session token TTL. ```rust pub fn with_session_ttl_secs(mut self, secs: i64) -> Self; ``` Source line: `82`. ## config::OpenAgentConfig::with\_privileged\_authority [#configopenagentconfigwith_privileged_authority] Enables the deny-only privileged-lineage gate and pins the path kind. This method cannot restore legacy authorization. Requests remain denied until a separately reviewed hardened verifier API is introduced. ```rust pub fn with_privileged_authority(mut self, path_kind: impl Into) -> Self; ``` Source line: `91`. ## config::OpenAgentConfig::with\_required\_authority\_scopes [#configopenagentconfigwith_required_authority_scopes] Adds scopes that the privileged authority context must prove. ```rust pub fn with_required_authority_scopes(mut self, scopes: Vec) -> Self; ``` Source line: `98`. ## config::OpenAgentConfig::with\_min\_authority\_finalized\_block [#configopenagentconfigwith_min_authority_finalized_block] Sets the minimum finalized authority block. ```rust pub fn with_min_authority_finalized_block(mut self, block: u64) -> Self; ``` Source line: `104`. # openagent-server · crate URL: https://docs.openagent.id/reference/rust/openagent-server/crate Markdown: https://docs.openagent.id/reference/rust/openagent-server/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/lib.rs`. SHA-256: `c43f987d28dca0c03c3934d60c2f9f82ce7cc8a39cd25885a4e8ecd524ebbadc`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## authority [#authority] ```rust pub mod authority; ``` Source line: `25`. ## challenge [#challenge] ```rust pub mod challenge; ``` Source line: `26`. ## config [#config] ```rust pub mod config; ``` Source line: `27`. ## did\_key [#did_key] ```rust pub mod did_key; ``` Source line: `28`. ## error [#error] ```rust pub mod error; ``` Source line: `29`. ## l1feid\_client [#l1feid_client] ```rust pub mod l1feid_client; ``` Source line: `30`. ## layer [#layer] ```rust pub mod layer; ``` Source line: `31`. ## session [#session] ```rust pub mod session; ``` Source line: `32`. ## verify [#verify] ```rust pub mod verify; ``` Source line: `33`. ## pub use authority::\{ [#pub-use-authority] require\_authoritative\_lineage, AuthorityError, LegacyLineageEvidence, MissingAuthorityVerifier, PrivilegedAuthorityRequest, PrivilegedAuthorityVerifier, }; ```rust pub use authority::{ require_authoritative_lineage, AuthorityError, LegacyLineageEvidence, MissingAuthorityVerifier, PrivilegedAuthorityRequest, PrivilegedAuthorityVerifier, }; ``` Source line: `35`. ## pub use config::OpenAgentConfig; [#pub-use-configopenagentconfig] ```rust pub use config::OpenAgentConfig; ``` Source line: `39`. ## pub use l1feid\_client::L1feIdClient; [#pub-use-l1feid_clientl1feidclient] ```rust pub use l1feid_client::L1feIdClient; ``` Source line: `40`. ## pub use layer::OpenAgentLayer; [#pub-use-layeropenagentlayer] ```rust pub use layer::OpenAgentLayer; ``` Source line: `41`. # openagent-server · did_key URL: https://docs.openagent.id/reference/rust/openagent-server/did_key Markdown: https://docs.openagent.id/reference/rust/openagent-server/did_key.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/did_key.rs`. SHA-256: `af3d85cbe793c1528189111ecc157ee9f82bc378c3f446f9246a3baac5de7e62`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## did\_key::did\_key\_from\_ed25519 [#did_keydid_key_from_ed25519] Derives a `did:key` string from a raw 32-byte Ed25519 public key. Per the did:key method specification: 1. Prepend the Ed25519 multicodec prefix (0xed01) 2. Encode with base58btc (multibase prefix 'z') 3. Result: `did:key:z` # Arguments [#arguments] * `pubkey` - 32-byte Ed25519 public key # Returns [#returns] The `did:key:z...` string. ```rust pub fn did_key_from_ed25519(pubkey: &[u8; 32]) -> String; ``` Source line: `28`. ## did\_key::ed25519\_from\_did\_key [#did_keyed25519_from_did_key] Extracts the raw 32-byte Ed25519 public key from a `did:key` string. # Errors [#errors] Returns an error if the DID is not a valid `did:key` with Ed25519 multicodec prefix. ```rust pub fn ed25519_from_did_key(did: &str) -> Result<[u8; 32], DidKeyError>; ``` Source line: `41`. ## did\_key::parse\_pubkey\_base64url [#did_keyparse_pubkey_base64url] Parses a public key from the base64url-encoded segment of an Authorization header. ```rust pub fn parse_pubkey_base64url(encoded: &str) -> Result<[u8; 32], DidKeyError>; ``` Source line: `69`. ## did\_key::DidKeyError [#did_keydidkeyerror] Errors from did:key operations. ```rust #[derive(Debug, thiserror::Error)] pub enum DidKeyError { #[error("did:key must start with 'did:key:z'")] InvalidPrefix, #[error("invalid base58 encoding in did:key")] InvalidBase58, #[error("invalid base64url encoding")] InvalidBase64, #[error("decoded key length {actual} does not match expected {expected}")] InvalidLength { expected: usize, actual: usize }, #[error("unsupported multicodec prefix {found}; expected 0xed01 (Ed25519)")] UnsupportedCodec { found: String }, } ``` Source line: `88`. # openagent-server · error URL: https://docs.openagent.id/reference/rust/openagent-server/error Markdown: https://docs.openagent.id/reference/rust/openagent-server/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/error.rs`. SHA-256: `b02b125967dab737185e3e4f93279af42dab8cd530ffccc054abefd129a798d5`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::ErrorCode [#errorerrorcode] Error codes defined by the OpenAgent protocol. ```rust #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum ErrorCode { /// No Authorization header and no valid session token. AuthenticationRequired, /// Challenge nonce has expired (older than TTL window). ChallengeExpired, /// Signature verification failed against the challenge bytes. InvalidSignature, /// The key type in X-OpenAgent-Key-Type is not supported. UnsupportedKeyType, /// The nonce was already consumed or is not recognized. NonceUnknown, /// The agent's trust tier is below the route's minimum. TrustInsufficient, /// Legacy lineage evidence reached a privileged authorization boundary. LegacyLineageNotAuthoritative, /// No authoritative lineage verifier result is available. LineageVerificationUnavailable, /// Rate limit exceeded for this agent's trust tier. RateLimited, /// The Authorization header is present but malformed. MalformedRequest, /// Session token is expired or invalid. SessionExpired, /// Internal server error during verification. InternalError, } ``` Source line: `12`. ## error::OpenAgentError [#erroropenagenterror] Structured error response per OPENAGENT-CORE-SPEC.md §13. ```rust #[derive(Debug, Serialize)] pub struct OpenAgentError { pub error: ErrorCode, pub message: String, #[serde(skip_serializing_if = "Option::is_none")] pub details: Option, pub request_id: String } ``` Source line: `60`. ## error::OpenAgentError::new [#erroropenagenterrornew] ```rust pub fn new(code: ErrorCode, message: impl Into, request_id: impl Into) -> Self; ``` Source line: `69`. # openagent-server modules URL: https://docs.openagent.id/reference/rust/openagent-server Markdown: https://docs.openagent.id/reference/rust/openagent-server.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagents-openagent-id-crates-openagent-server). [Focused integration guide](/api-reference/openagent-server). ## Modules [#modules] * [crate](/reference/rust/openagent-server/crate) — 13 declarations * [authority](/reference/rust/openagent-server/authority) — 6 declarations * [challenge](/reference/rust/openagent-server/challenge) — 9 declarations * [config](/reference/rust/openagent-server/config) — 9 declarations * [did\_key](/reference/rust/openagent-server/did_key) — 4 declarations * [error](/reference/rust/openagent-server/error) — 3 declarations * [l1feid\_client](/reference/rust/openagent-server/l1feid_client) — 7 declarations * [layer](/reference/rust/openagent-server/layer) — 7 declarations * [session](/reference/rust/openagent-server/session) — 4 declarations * [verify](/reference/rust/openagent-server/verify) — 3 declarations # openagent-server · l1feid_client URL: https://docs.openagent.id/reference/rust/openagent-server/l1feid_client Markdown: https://docs.openagent.id/reference/rust/openagent-server/l1feid_client.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/l1feid_client.rs`. SHA-256: `d2a9626be9a57125eed115e7d03ffe2fa00f4b20d21d14ebf7b73f57f39b4578`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## l1feid\_client::L1feIdProvisionResponse [#l1feid_clientl1feidprovisionresponse] Response returned by `L1feIdClient::provision`. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct L1feIdProvisionResponse { /// The stable platform UUID for this agent. pub l1fe_id: String, /// Trust tier from the platform record (0-4). pub trust_tier: u8, /// True when a new record was created (HTTP 201), false when an existing /// record was returned (HTTP 200). pub is_new: bool } ``` Source line: `16`. ## l1feid\_client::L1feIdError [#l1feid_clientl1feiderror] Errors that can occur when calling L1feID. ```rust #[derive(Debug, thiserror::Error)] pub enum L1feIdError { #[error("L1feID service request failed: {0}")] Transport(String), #[error("L1feID service returned unexpected status {status}: {body}")] UnexpectedStatus { status: u16, body: String }, #[error("failed to deserialize L1feID response: {0}")] Deserialize(String), } ``` Source line: `28`. ## l1feid\_client::L1feIdClient [#l1feid_clientl1feidclient] HTTP client for the L1feID provisioning endpoint. The base URL is resolved from the first set of these env vars (see \[`L1feIdClient::from_env`]): * `LIFEID_SERVICE_URL` (canonical code-side name) * `L1FEID_API_URL` (deployment/ops contract used by k8s secrets) * `L1FEID_SERVICE_URL` (alternate spelling) If none are set, the in-cluster default (`http://l1feid.l1feid.svc.cluster.local:8090`) is used. ```rust #[derive(Debug, Clone)] pub struct L1feIdClient { } ``` Source line: `50`. ## l1feid\_client::L1feIdClient::new [#l1feid_clientl1feidclientnew] Creates a new client targeting `base_url`. The URL should NOT include a trailing slash. ```rust pub fn new(base_url: String) -> Self; ``` Source line: `75`. ## l1feid\_client::L1feIdClient::from\_env [#l1feid_clientl1feidclientfrom_env] Creates a client using the L1feID base URL from the environment. Resolution order (first non-empty wins): 1. `LIFEID_SERVICE_URL` 2. `L1FEID_API_URL` — ops/k8s secret key (must match deploys) 3. `L1FEID_SERVICE_URL` 4. in-cluster default `http://l1feid.l1feid.svc.cluster.local:8090` Accepting both `LIFEID_SERVICE_URL` and `L1FEID_API_URL` closes the historical mismatch where manifests injected `L1FEID_API_URL` while the binary only read `LIFEID_SERVICE_URL`. ```rust pub fn from_env() -> Self; ``` Source line: `94`. ## l1feid\_client::L1feIdClient::base\_url [#l1feid_clientl1feidclientbase_url] Returns the configured base URL (no trailing slash expected). ```rust #[must_use] pub fn base_url(&self) -> &str; ``` Source line: `102`. ## l1feid\_client::L1feIdClient::provision [#l1feid_clientl1feidclientprovision] Auto-provisions a platform identity record for `did`. This is idempotent: calling provision for a DID that already has a record returns the existing `l1fe_id` without modification. `initial_trust_tier` is only used during first-time creation. ```rust pub async fn provision( &self, did: &str, initial_trust_tier: u8, ) -> Result; ``` Source line: `112`. # openagent-server · layer URL: https://docs.openagent.id/reference/rust/openagent-server/layer Markdown: https://docs.openagent.id/reference/rust/openagent-server/layer.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/layer.rs`. SHA-256: `d3ed7de38e820ff9f645b974e5fb314d02837d9b4b7c79ffd1e6f1e9851dc0d3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## layer::OpenAgentState [#layeropenagentstate] Shared state for the OpenAgent middleware. ```rust pub struct OpenAgentState { pub config: OpenAgentConfig, pub nonce_store: NonceStore, pub l1feid_client: L1feIdClient, pub authority_verifier: Arc } ``` Source line: `30`. ## layer::OpenAgentLayer [#layeropenagentlayer] The Axum middleware layer. Attach to a router: ```rust use openagent_server::{OpenAgentConfig, OpenAgentLayer}; let config = OpenAgentConfig::new("https://api.example.com", b"my-secret-key-32-bytes-minimum!!"); let app = Router::new() .route("/api/data", get(handler)) .layer(OpenAgentLayer::new(config)); ``` ```rust #[derive(Clone)] pub struct OpenAgentLayer { } ``` Source line: `49`. ## layer::OpenAgentLayer::new [#layeropenagentlayernew] Creates a new layer with the L1feID client resolved via \[`crate::l1feid_client::L1feIdClient::from_env`] (`LIFEID_SERVICE_URL` / `L1FEID_API_URL` contract). ```rust pub fn new(config: OpenAgentConfig) -> Self; ``` Source line: `57`. ## layer::OpenAgentLayer::with\_l1feid\_client [#layeropenagentlayerwith_l1feid_client] Creates a new layer with an explicit L1feID client (useful for testing). ```rust pub fn with_l1feid_client(config: OpenAgentConfig, l1feid_client: L1feIdClient) -> Self; ``` Source line: `71`. ## layer::OpenAgentLayer::with\_authority\_verifier [#layeropenagentlayerwith_authority_verifier] Creates a new layer with an explicit privileged authority verifier. ```rust pub fn with_authority_verifier( config: OpenAgentConfig, authority_verifier: Arc, ) -> Self; ``` Source line: `84`. ## layer::OpenAgentLayer::with\_l1feid\_and\_authority\_verifier [#layeropenagentlayerwith_l1feid_and_authority_verifier] Creates a new layer with explicit L1feID and privileged authority clients. ```rust pub fn with_l1feid_and_authority_verifier( config: OpenAgentConfig, l1feid_client: L1feIdClient, authority_verifier: Arc, ) -> Self; ``` Source line: `101`. ## layer::OpenAgentMiddleware [#layeropenagentmiddleware] The middleware service that wraps the inner handler. ```rust #[derive(Clone)] pub struct OpenAgentMiddleware { } ``` Source line: `131`. # openagent-server · session URL: https://docs.openagent.id/reference/rust/openagent-server/session Markdown: https://docs.openagent.id/reference/rust/openagent-server/session.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/session.rs`. SHA-256: `9984fa2b50874326503665e883533b1999c40f51f154775fcd571f668069c348`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session::SessionClaims [#sessionsessionclaims] JWT claims for an OpenAgent session token. Per OPENAGENT-CORE-SPEC.md §12: * `sub`: the agent's DID (did:key or did:oas) * `iss`: the server origin * `iat`: issued-at timestamp (Unix seconds) * `exp`: expiration timestamp (Unix seconds) * `nonce`: the challenge nonce that was consumed * `trust_tier`: the agent's trust tier (0-4) * `l1fe_id`: the agent's L1feID platform UUID (None if L1feID was unreachable) * `lineage_authority`: optional legacy lineage evidence retained for migration ```rust #[derive(Debug, Serialize, Deserialize)] pub struct SessionClaims { pub sub: String, pub iss: String, pub iat: i64, pub exp: i64, pub nonce: String, pub trust_tier: u8, /// L1feID platform identifier. Absent when the L1feID service was /// unreachable during the initial provisioning call. #[serde(skip_serializing_if = "Option::is_none")] pub l1fe_id: Option, /// Legacy lineage evidence. Informational only; never forwarded as authority. #[serde(skip_serializing_if = "Option::is_none")] pub lineage_authority: Option } ``` Source line: `25`. ## session::issue\_session\_token [#sessionissue_session_token] Issues a JWT session token. # Arguments [#arguments] * `did` - The agent's DID * `origin` - The server origin (becomes `iss`) * `nonce` - The consumed challenge nonce * `trust_tier` - The agent's trust tier * `l1fe_id` - The agent's L1feID platform UUID (None if service unreachable) * `lineage_authority` - Optional informational legacy lineage evidence * `ttl_secs` - Token lifetime in seconds (default: 900 = 15 min) * `secret` - HMAC-SHA256 signing secret ```rust pub fn issue_session_token( did: &str, origin: &str, nonce: &str, trust_tier: u8, l1fe_id: Option<&str>, lineage_authority: Option, ttl_secs: i64, secret: &[u8], ) -> Result; ``` Source line: `53`. ## session::validate\_session\_token [#sessionvalidate_session_token] Validates a JWT session token and returns its claims. ```rust pub fn validate_session_token(token: &str, secret: &[u8]) -> Result; ``` Source line: `86`. ## session::SessionError [#sessionsessionerror] ```rust #[derive(Debug, thiserror::Error)] pub enum SessionError { #[error("session token has expired")] Expired, #[error("session token signature is invalid")] InvalidSignature, #[error("failed to encode session token: {0}")] EncodingFailed(String), #[error("session token validation failed: {0}")] ValidationFailed(String), } ``` Source line: `102`. # openagent-server · verify URL: https://docs.openagent.id/reference/rust/openagent-server/verify Markdown: https://docs.openagent.id/reference/rust/openagent-server/verify.md Declared module signatures, types, configuration, and source documentation. Source: `openagents/openagent.id/crates/openagent-server/src/verify.rs`. SHA-256: `701f627e8d8e41643d91a128e645b64af8cc52a955e2d62354d5bbe63714edcd`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## verify::parse\_authorization\_header [#verifyparse_authorization_header] Parses the `Authorization: OpenAgent .` header. Returns (signature\_bytes, public\_key\_bytes) on success. ```rust pub fn parse_authorization_header(header_value: &str) -> Result<(Vec, [u8; 32]), VerifyError>; ``` Source line: `14`. ## verify::verify\_ed25519 [#verifyverify_ed25519] Verifies an Ed25519 signature over JCS-canonicalized challenge bytes. # Arguments [#arguments] * `pubkey` - 32-byte Ed25519 public key * `signature_bytes` - 64-byte Ed25519 signature * `challenge_jcs_bytes` - The JCS-canonicalized challenge JSON ```rust pub fn verify_ed25519( pubkey: &[u8; 32], signature_bytes: &[u8], challenge_jcs_bytes: &[u8], ) -> Result<(), VerifyError>; ``` Source line: `57`. ## verify::VerifyError [#verifyverifyerror] ```rust #[derive(Debug, thiserror::Error)] pub enum VerifyError { #[error("malformed Authorization header: {0}")] MalformedHeader(String), #[error("invalid base64url encoding in {0}")] InvalidBase64(&'static str), #[error("public key length {actual} does not match expected {expected}")] InvalidKeyLength { expected: usize, actual: usize }, #[error("signature length {actual} does not match expected {expected}")] InvalidSignatureLength { expected: usize, actual: usize }, #[error("invalid Ed25519 public key: {0}")] InvalidPublicKey(String), #[error("Ed25519 signature verification failed")] SignatureInvalid, } ``` Source line: `82`. # openagent-skills-policy · audit URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/audit Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/audit.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/audit.rs`. SHA-256: `bcd120729293228acf0d04e5b12283d672de19108329b1136e444f3e455b609b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit::HASH\_LEN [#audithash_len] Length of a BLAKE3 hash in bytes. ```rust pub const HASH_LEN: usize; ``` Source line: `20`. ## audit::HashHex [#audithashhex] A hex-encoded hash (used for JSON-friendly serialization). ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct HashHex(String); ``` Source line: `25`. ## audit::HashHex::from\_bytes [#audithashhexfrom_bytes] Build from raw bytes. ```rust #[must_use] pub fn from_bytes(bytes: &[u8; HASH_LEN]) -> Self; ``` Source line: `30`. ## audit::HashHex::as\_str [#audithashhexas_str] Return the hex string. ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `36`. ## audit::Receipt [#auditreceipt] A single invocation receipt. Receipts are immutable. New invocations produce new receipts rather than mutating existing ones. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Receipt { /// Monotonically increasing sequence number, starting at 0. pub sequence: u64, /// Skill that was invoked. pub skill: String, /// DID of the invoking agent. pub agent: String, /// Session ID the invocation happened under. pub session: String, /// When the invocation was recorded (UTC, RFC 3339). pub invoked_at: String, /// Audit level applied when recording. pub audit_level: AuditLevel, /// Hash of the arguments (always present; the argument payload itself is /// only included when `audit_level = Full`). pub arguments_hash: HashHex, /// Full arguments JSON — only populated when `audit_level = Full`. #[serde(default, skip_serializing_if = "Option::is_none")] pub arguments: Option, /// Hash of the previous receipt in the chain (or zero for the first). pub previous_hash: HashHex, /// Hash of *this* receipt — computed over all fields above plus /// `previous_hash`. pub receipt_hash: HashHex } ``` Source line: `58`. ## audit::AuditChain [#auditauditchain] Append-only chain of invocation receipts. ```rust #[derive(Debug, Default, Clone)] pub struct AuditChain { } ``` Source line: `86`. ## audit::AuditChain::new [#auditauditchainnew] Create an empty chain. ```rust #[must_use] pub fn new() -> Self; ``` Source line: `94`. ## audit::AuditChain::len [#auditauditchainlen] Number of receipts in the chain. ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `100`. ## audit::AuditChain::is\_empty [#auditauditchainis_empty] Whether the chain is empty. ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `106`. ## audit::AuditChain::head [#auditauditchainhead] The current head hash (all-zero if the chain is empty). ```rust #[must_use] pub fn head(&self) -> HashHex; ``` Source line: `112`. ## audit::AuditChain::get [#auditauditchainget] Get a receipt by its sequence number. ```rust #[must_use] pub fn get(&self, sequence: u64) -> Option<&Receipt>; ``` Source line: `118`. ## audit::AuditChain::iter [#auditauditchainiter] Iterate over all receipts in order. ```rust pub fn iter(&self) -> impl Iterator; ``` Source line: `123`. ## audit::AuditChain::verify [#auditauditchainverify] Verify that every receipt's `receipt_hash` and `previous_hash` matches the recomputed chain. Returns `true` if intact. ```rust #[must_use] pub fn verify(&self) -> bool; ``` Source line: `130`. # openagent-skills-policy · crate URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/crate Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/lib.rs`. SHA-256: `6523cde71371235b5d154fb57f0ef3abba4272d7bb7702c13ea1e3cdf6648685`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## audit [#audit] ```rust pub mod audit; ``` Source line: `69`. ## did [#did] ```rust pub mod did; ``` Source line: `70`. ## engine [#engine] ```rust pub mod engine; ``` Source line: `72`. ## error [#error] ```rust pub mod error; ``` Source line: `73`. ## policy [#policy] ```rust pub mod policy; ``` Source line: `74`. ## rate [#rate] ```rust pub mod rate; ``` Source line: `75`. ## skills\_md [#skills_md] ```rust pub mod skills_md; ``` Source line: `76`. ## pub use audit::\{AuditChain, HashHex, Receipt}; [#pub-use-auditauditchain-hashhex-receipt] ```rust pub use audit::{AuditChain, HashHex, Receipt}; ``` Source line: `78`. ## pub use did::Did; [#pub-use-diddid] ```rust pub use did::Did; ``` Source line: `79`. ## pub use engine::\{arsenal\_error\_from, InvocationContext, SkillsPolicy}; [#pub-use-enginearsenal_error_from-invocationcontext-skillspolicy] ```rust pub use engine::{arsenal_error_from, InvocationContext, SkillsPolicy}; ``` Source line: `80`. ## pub use error::\{Result, SkillsPolicyError}; [#pub-use-errorresult-skillspolicyerror] ```rust pub use error::{Result, SkillsPolicyError}; ``` Source line: `81`. ## pub use policy::\{ [#pub-use-policy] AuditLevel, DefaultRule, RateLimit, SkillRule, SkillsPolicyDoc, TimeWindow, CURRENT\_VERSION, MAX\_SKILL\_RULES, }; ```rust pub use policy::{ AuditLevel, DefaultRule, RateLimit, SkillRule, SkillsPolicyDoc, TimeWindow, CURRENT_VERSION, MAX_SKILL_RULES, }; ``` Source line: `82`. ## pub use skills\_md::\{SkillEntry, SkillsManifest}; [#pub-use-skills_mdskillentry-skillsmanifest] ```rust pub use skills_md::{SkillEntry, SkillsManifest}; ``` Source line: `86`. # openagent-skills-policy · did URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/did Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/did.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/did.rs`. SHA-256: `c2b2af023a2d408322f60d815ccb05d1c39ed16728e03f7b612556db5fe37669`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## did::Did [#diddid] A Decentralized Identifier (DID) that identifies the agent a policy applies to. Format: `did::`. For L1fe agents this is typically `did:oas:l1fe:agent:`. ```rust #[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct Did(String); ``` Source line: `28`. ## did::Did::new [#diddidnew] Create a new DID with validation. # Errors [#errors] Returns \[`SkillsPolicyError::InvalidPolicy`] if the input does not look like a DID. ```rust pub fn new(input: impl Into) -> Result; ``` Source line: `36`. ## did::Did::as\_str [#diddidas_str] Return the raw DID string. ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `44`. # openagent-skills-policy · engine URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/engine Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/engine.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/engine.rs`. SHA-256: `9e55ac1b6524d85519315932929f89032d22db8f361634fcd7adc6b13a394abe`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## engine::InvocationContext [#engineinvocationcontext] Context passed into `can_invoke` / `record_invocation` describing who is attempting to use a skill, when, and with what arguments. ```rust #[derive(Debug, Clone)] pub struct InvocationContext { /// DID of the invoking agent. pub agent_did: Did, /// Session ID (opaque string — matches `arsenal-core::SessionId` shape). pub session_id: String, /// Arguments that will be passed to the skill. pub arguments: serde_json::Value, /// Wall-clock time of the attempted invocation (UTC). pub invoked_at: OffsetDateTime, /// Whether the caller has already collected human-in-the-loop consent. pub consent_granted: bool } ``` Source line: `31`. ## engine::InvocationContext::new [#engineinvocationcontextnew] Convenience constructor. `consent_granted` defaults to `false`. ```rust pub fn new( agent_did: Did, session_id: impl Into, arguments: serde_json::Value, ) -> Self; ``` Source line: `46`. ## engine::InvocationContext::with\_consent [#engineinvocationcontextwith_consent] Mark consent as granted (e.g. after a HITL approval flow). ```rust #[must_use] pub fn with_consent(mut self) -> Self; ``` Source line: `62`. ## engine::InvocationContext::with\_invoked\_at [#engineinvocationcontextwith_invoked_at] Override the invocation timestamp (primarily for testing). ```rust #[must_use] pub fn with_invoked_at(mut self, t: OffsetDateTime) -> Self; ``` Source line: `69`. ## engine::SkillsPolicy [#engineskillspolicy] Governance engine for agent skill invocations. ```rust pub struct SkillsPolicy { } ``` Source line: `76`. ## engine::SkillsPolicy::from\_yaml [#engineskillspolicyfrom_yaml] Parse a policy YAML document. # Errors [#errors] Returns \[`SkillsPolicyError::InvalidPolicy`] if the YAML is malformed or fails structural validation. ```rust pub fn from_yaml(yaml: &str) -> Result; ``` Source line: `101`. ## engine::SkillsPolicy::from\_file [#engineskillspolicyfrom_file] Load a policy YAML document from a file path. # Errors [#errors-1] Returns \[`SkillsPolicyError::Io`] on read failure, or any error from \[`SkillsPolicy::from_yaml`] on parse/validation failure. ```rust pub fn from_file(path: &Path) -> Result; ``` Source line: `119`. ## engine::SkillsPolicy::agent [#engineskillspolicyagent] The DID of the agent this policy applies to. ```rust #[must_use] pub fn agent(&self) -> &Did; ``` Source line: `129`. ## engine::SkillsPolicy::has\_rule [#engineskillspolicyhas_rule] Whether the policy has a per-skill rule for `skill`. ```rust #[must_use] pub fn has_rule(&self, skill: &str) -> bool; ``` Source line: `135`. ## engine::SkillsPolicy::can\_invoke [#engineskillspolicycan_invoke] Read-only check: can `ctx` invoke `skill` right now? This runs every policy dimension except the rate-limit *advance*. A successful return does not consume any rate-limit tokens — use `record_invocation` for that. # Errors [#errors-2] Returns a specific \[`SkillsPolicyError`] variant per failed dimension. ```rust pub fn can_invoke(&self, skill: &str, ctx: &InvocationContext) -> Result<()>; ``` Source line: `147`. ## engine::SkillsPolicy::record\_invocation [#engineskillspolicyrecord_invocation] Authorize and record an invocation. This runs `can_invoke`, then checks and advances the rate limiter, then appends a \[`Receipt`] to the hash-chained audit log. On any failure no state changes. # Errors [#errors-3] Returns the first dimension that failed. On rate-limit failure the caller gets `used` and `max` values to surface a friendly error. ```rust pub fn record_invocation( &mut self, skill: &str, ctx: &InvocationContext, ) -> Result; ``` Source line: `213`. ## engine::SkillsPolicy::audit\_chain [#engineskillspolicyaudit_chain] Borrow the audit chain for inspection (verification, export). ```rust #[must_use] pub fn audit_chain(&self) -> &AuditChain; ``` Source line: `281`. ## engine::SkillsPolicy::reset\_rate\_limit [#engineskillspolicyreset_rate_limit] Reset the rate-limit state for a single skill. ```rust pub fn reset_rate_limit(&mut self, skill: &str); ``` Source line: `286`. ## engine::arsenal\_error\_from [#enginearsenal_error_from] Used by integration with Arsenal: convert a `SkillsPolicyError` into an `arsenal_core::ArsenalError`. Kept behind the engine module so that downstream crates can depend on this without pulling the whole module graph. ```rust pub fn arsenal_error_from(err: &SkillsPolicyError) -> arsenal_core::ArsenalError; ``` Source line: `370`. # openagent-skills-policy · error URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/error Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/error.rs`. SHA-256: `e81853a8af43c13d6d09e8d0dac265acba3f37b22f391ecb0e909ef05828fcad`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::Result [#errorresult] Result alias for the skills policy engine. ```rust pub type Result = std::result::Result; ``` Source line: `12`. ## error::SkillsPolicyError [#errorskillspolicyerror] All errors produced by the skills policy engine. ```rust #[derive(Debug, Error)] pub enum SkillsPolicyError { /// The policy YAML failed to parse or validate. #[error("invalid policy document: {0}")] InvalidPolicy(String), /// Failed to read a file from disk. #[error("failed to read {path}: {source}")] Io { /// The path we tried to read. path: PathBuf, /// The underlying I/O error. #[source] source: std::io::Error, }, /// The skill name is not allowed under the current policy. /// /// This covers both explicit `deny_list` hits and the implicit deny from /// `default.allow: false` when the skill is not in any allow list. #[error("skill `{skill}` is not allowed by policy: {reason}")] NotAllowed { /// The skill name that was rejected. skill: String, /// Why it was rejected (e.g. "in deny_list", "no matching rule"). reason: String, }, /// The invocation exceeded the configured rate limit for this skill. #[error("rate limit exceeded for skill `{skill}`: {used}/{max} in {window_secs}s window")] RateLimitExceeded { /// The skill name. skill: String, /// How many invocations were observed in the window. used: u64, /// The maximum allowed in the window. max: u64, /// The window length in seconds. window_secs: u64, }, /// Arguments did not match the declared JSON Schema. #[error("argument constraints violated for skill `{skill}`: {details}")] ArgumentConstraint { /// The skill name. skill: String, /// Human-readable detail about the violation. details: String, }, /// The current time is outside any permitted time window. #[error("skill `{skill}` cannot be invoked at this time: outside allowed time windows")] OutsideTimeWindow { /// The skill name. skill: String, }, /// Human-in-the-loop consent is required and has not been granted. #[error("skill `{skill}` requires consent but none was provided")] ConsentRequired { /// The skill name. skill: String, }, /// The SKILLS.md file could not be parsed. #[error("failed to parse SKILLS.md: {0}")] InvalidSkillsMarkdown(String), } ``` Source line: `16`. # openagent-skills-policy modules URL: https://docs.openagent.id/reference/rust/openagent-skills-policy Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-crates-openagent-skills-policy-rust). [Focused integration guide](/features/skills-governance). ## Modules [#modules] * [crate](/reference/rust/openagent-skills-policy/crate) — 13 declarations * [audit](/reference/rust/openagent-skills-policy/audit) — 13 declarations * [did](/reference/rust/openagent-skills-policy/did) — 3 declarations * [engine](/reference/rust/openagent-skills-policy/engine) — 14 declarations * [error](/reference/rust/openagent-skills-policy/error) — 2 declarations * [policy](/reference/rust/openagent-skills-policy/policy) — 8 declarations * [rate](/reference/rust/openagent-skills-policy/rate) — 6 declarations * [skills\_md](/reference/rust/openagent-skills-policy/skills_md) — 8 declarations # openagent-skills-policy · policy URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/policy Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/policy.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/policy.rs`. SHA-256: `68313deafe836186c7c6805a142260bdd81f9f350dc30c0b1c4d900e29eaab6f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## policy::MAX\_SKILL\_RULES [#policymax_skill_rules] Maximum number of skill rules in a single policy document. Mirrors Arsenal's `MAX_RULES_PER_POLICY` to keep the two in lockstep. ```rust pub const MAX_SKILL_RULES: usize; ``` Source line: `21`. ## policy::CURRENT\_VERSION [#policycurrent_version] Current policy schema version. ```rust pub const CURRENT_VERSION: u32; ``` Source line: `24`. ## policy::AuditLevel [#policyauditlevel] How much detail to record for each invocation. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "snake_case")] pub enum AuditLevel { /// No audit event produced. None, /// Record only the skill name, DID, and a hash of the arguments. #[default] Hash, /// Record the full arguments JSON in the receipt. Full, } ``` Source line: `29`. ## policy::RateLimit [#policyratelimit] A rate limit for a single skill. The window is expressed as a human-friendly string (`1s`, `30m`, `1h`, `24h`) which the engine parses at load time. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RateLimit { /// Window length as a string (parsed to seconds at load time). pub window: String, /// Maximum invocations allowed within a single window. pub max: u64 } ``` Source line: `44`. ## policy::TimeWindow [#policytimewindow] A time window during which a skill may be invoked. Hours are interpreted in UTC. `start_hour` may be greater than `end_hour` to express an overnight window (e.g. 22..6). ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TimeWindow { /// Inclusive start hour in UTC (0..=23). pub start_hour: u8, /// Exclusive end hour in UTC (0..=24). 24 means midnight. pub end_hour: u8, /// Optional weekday filter (0=Sunday..6=Saturday). Empty = all days. #[serde(default)] pub weekdays: Vec } ``` Source line: `56`. ## policy::SkillRule [#policyskillrule] Per-skill policy rule. Every field is optional; the engine applies only what is present. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SkillRule { /// Whether the agent may invoke this skill at all. /// /// Defaults to `true` when the skill appears in the policy map. Use /// `allow: false` to explicitly deny while still documenting the rule. #[serde(default = "default_allow")] pub allow: bool, /// Rate limit applied to this skill. #[serde(default, skip_serializing_if = "Option::is_none")] pub rate_limit: Option, /// JSON Schema that invocation arguments must satisfy. /// /// Stored as a raw `serde_json::Value` to avoid premature compilation; /// the engine compiles and caches it at load time. #[serde(default, skip_serializing_if = "Option::is_none")] pub arg_constraints: Option, /// Time windows during which the skill may be invoked. Empty = always. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub time_windows: Vec, /// If `true`, the caller must supply a consent token alongside the /// invocation context. #[serde(default)] pub require_consent: bool, /// How much invocation detail to record in the audit chain. #[serde(default)] pub audit_level: AuditLevel } ``` Source line: `70`. ## policy::DefaultRule [#policydefaultrule] Default rule applied when a skill has no per-skill entry. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DefaultRule { /// Whether unknown skills are allowed by default. #[serde(default)] pub allow: bool, /// Default audit level for unknown skills. #[serde(default)] pub audit_level: AuditLevel } ``` Source line: `122`. ## policy::SkillsPolicyDoc [#policyskillspolicydoc] A skills policy document, as loaded from YAML. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SkillsPolicyDoc { /// Schema version. Must equal [`CURRENT_VERSION`]. pub version: u32, /// DID of the agent this policy applies to. pub agent: Did, /// Per-skill rules keyed by skill name. #[serde(default)] pub skills: BTreeMap, /// Default rule applied when a skill has no entry in `skills`. #[serde(default)] pub default: DefaultRule, /// Optional human-friendly description. #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option } ``` Source line: `142`. # openagent-skills-policy · rate URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/rate Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/rate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/rate.rs`. SHA-256: `97137171669e3ce11ad4761853f56ec30c9fcc38fcf99bee9d72ca15ed80b8a3`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## rate::RateLimiter [#rateratelimiter] In-memory GCRA rate limiter keyed by skill name. ```rust #[derive(Debug, Default)] pub struct RateLimiter { } ``` Source line: `23`. ## rate::RateLimitDecision [#rateratelimitdecision] Result of consulting the rate limiter. ```rust #[derive(Debug, Clone, Copy, PartialEq)] pub enum RateLimitDecision { /// The invocation is allowed; TAT has been advanced. Allowed, /// The invocation is denied. Contains the number of *conceptual* /// invocations already consumed in the window. Denied { /// How many are currently considered used in the window. used: u64, }, } ``` Source line: `30`. ## rate::RateLimiter::new [#rateratelimiternew] Create a fresh limiter with no state. ```rust #[must_use] pub fn new() -> Self; ``` Source line: `44`. ## rate::RateLimiter::used [#rateratelimiterused] Peek at the number of theoretical invocations currently in use for `skill`, for observability/debugging. ```rust #[must_use] pub fn used(&self, skill: &str, limit: &RateLimit, now: OffsetDateTime) -> u64; ``` Source line: `72`. ## rate::RateLimiter::reset [#rateratelimiterreset] Remove any stored state for the given skill. ```rust pub fn reset(&mut self, skill: &str); ``` Source line: `92`. ## rate::RateLimiter::snapshot [#rateratelimitersnapshot] Snapshot the current TATs — useful for persisting state. ```rust #[must_use] pub fn snapshot(&self) -> Vec<(String, f64)>; ``` Source line: `98`. # openagent-skills-policy · skills_md URL: https://docs.openagent.id/reference/rust/openagent-skills-policy/skills_md Markdown: https://docs.openagent.id/reference/rust/openagent-skills-policy/skills_md.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/crates/openagent-skills-policy/rust/src/skills_md.rs`. SHA-256: `65c4afba7eec3d10fb719b995d734e908301f151a660d58fe59b62f4a13e830e`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## skills\_md::SkillEntry [#skills_mdskillentry] A single skill entry discovered in a `SKILLS.md` file. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SkillEntry { /// Canonical skill name (the text of the `##` heading, trimmed). pub name: String, /// Human-readable description — all paragraphs beneath the heading, /// joined with blank lines. pub description: String } ``` Source line: `33`. ## skills\_md::SkillsManifest [#skills_mdskillsmanifest] A parsed `SKILLS.md` file. ```rust #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SkillsManifest { /// All skills discovered, in document order. pub skills: Vec } ``` Source line: `43`. ## skills\_md::SkillsManifest::from\_markdown [#skills_mdskillsmanifestfrom_markdown] Parse a `SKILLS.md` document from an in-memory string. # Errors [#errors] Returns \[`SkillsPolicyError::InvalidSkillsMarkdown`] if the document contains zero `##` skill headings or if a heading line is malformed. ```rust pub fn from_markdown(input: &str) -> Result; ``` Source line: `54`. ## skills\_md::SkillsManifest::from\_file [#skills_mdskillsmanifestfrom_file] Load and parse a `SKILLS.md` file from disk. # Errors [#errors-1] Returns \[`SkillsPolicyError::Io`] on read failure or \[`SkillsPolicyError::InvalidSkillsMarkdown`] on parse failure. ```rust pub fn from_file(path: &Path) -> Result; ``` Source line: `120`. ## skills\_md::SkillsManifest::len [#skills_mdskillsmanifestlen] Number of skills discovered. ```rust #[must_use] pub fn len(&self) -> usize; ``` Source line: `130`. ## skills\_md::SkillsManifest::is\_empty [#skills_mdskillsmanifestis_empty] Whether the manifest contains zero skills. ```rust #[must_use] pub fn is_empty(&self) -> bool; ``` Source line: `136`. ## skills\_md::SkillsManifest::get [#skills_mdskillsmanifestget] Return the skill entry with the given name, if any. ```rust #[must_use] pub fn get(&self, name: &str) -> Option<&SkillEntry>; ``` Source line: `142`. ## skills\_md::SkillsManifest::names [#skills_mdskillsmanifestnames] Iterate all skill names. ```rust pub fn names(&self) -> impl Iterator; ``` Source line: `147`. # openagent-sdk · act URL: https://docs.openagent.id/reference/rust/openagent-sdk/act Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/act.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/act.rs`. SHA-256: `68f5160930c131e508255fa8ae69bf8ca61b0d84f3c68cf5eb025e2a08b622be`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## act::ActVerifierBuilder [#actactverifierbuilder] Fluent ACT verifier, built by \[`verify`]. ```rust #[derive(Debug, Clone)] pub struct ActVerifierBuilder<'a> { } ``` Source line: `26`. ## act::verify [#actverify] Begin verifying an ACT envelope (CBOR bytes). ```rust pub fn verify(token: &[u8]) -> ActVerifierBuilder<'_>; ``` Source line: `37`. ## act::ActVerifierBuilder\<'a>::issuer [#actactverifierbuilderaissuer] Bind the expected issuer. Required: a verifier that does not name the issuer accepts anyone's tokens. ```rust pub fn issuer(mut self, iss: impl Into) -> Self; ``` Source line: `52`. ## act::ActVerifierBuilder\<'a>::for\_audience [#actactverifierbuilderafor_audience] Bind the audience this verifier answers for. Required: a token meant for another service must not pass here. ```rust pub fn for_audience(mut self, audience: impl Into) -> Self; ``` Source line: `59`. ## act::ActVerifierBuilder\<'a>::require\_scope [#actactverifierbuilderarequire_scope] Require a scope the token must grant. Wildcards in the grant expand; in the request they are literal. ```rust pub fn require_scope(mut self, scope: Scope) -> Self; ``` Source line: `66`. ## act::ActVerifierBuilder\<'a>::trusted\_keys [#actactverifierbuilderatrusted_keys] The trusted Ed25519 public keys (raw 32 bytes each). Required. ```rust pub fn trusted_keys(mut self, keys: impl IntoIterator) -> Self; ``` Source line: `72`. ## act::ActVerifierBuilder\<'a>::with\_leeway [#actactverifierbuilderawith_leeway] Allow `seconds` of clock skew on temporal checks. ```rust pub fn with_leeway(mut self, seconds: i64) -> Self; ``` Source line: `78`. ## act::ActVerifierBuilder\<'a>::at\_time [#actactverifierbuilderaat_time] Pin the verification clock (tests, decision replay). ```rust pub fn at_time(mut self, unix_seconds: i64) -> Self; ``` Source line: `84`. ## act::ActVerifierBuilder\<'a>::run [#actactverifierbuilderarun] Run verification. # Errors [#errors] Returns \[`OpenAgentError::Config`] for a missing policy binding, and \[`OpenAgentError::Verification`] carrying the canonical reason (signature, expiry, audience, scope, version - distinct on purpose) when the token itself fails. ```rust pub fn run(self) -> Result; ``` Source line: `97`. ## act::axum\_support [#actaxum_support] ```rust #[cfg(feature = "axum")] pub mod axum_support; ``` Source line: `127`. ## act::axum\_support::ActPolicy [#actaxum_supportactpolicy] The shared verifier policy. Cheap to clone (Arc inside). ```rust #[cfg(feature = "axum")] #[derive(Clone)] pub struct ActPolicy { } ``` Source line: `145`. ## act::axum\_support::ActPolicy::new [#actaxum_supportactpolicynew] Build a policy. Same bindings as the builder: issuer, audience, and at least one trusted key are required. ```rust #[cfg(feature = "axum")] pub fn new( issuer: impl Into, audience: impl Into, trusted_keys: Vec, ) -> Result; ``` Source line: `156`. ## act::axum\_support::ActPolicy::with\_scopes [#actaxum_supportactpolicywith_scopes] Require scopes on every request. ```rust #[cfg(feature = "axum")] pub fn with_scopes(mut self, scopes: Vec) -> Self; ``` Source line: `176`. ## act::axum\_support::ActPolicy::with\_leeway [#actaxum_supportactpolicywith_leeway] Allow clock skew. ```rust #[cfg(feature = "axum")] pub fn with_leeway(mut self, seconds: i64) -> Self; ``` Source line: `182`. ## act::axum\_support::ActContext [#actaxum_supportactcontext] Extractor: the verified claims of the request's ACT. ```rust #[cfg(feature = "axum")] pub struct ActContext(pub ActClaims); ``` Source line: `189`. # openagent-sdk · agent URL: https://docs.openagent.id/reference/rust/openagent-sdk/agent Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/agent.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/agent.rs`. SHA-256: `1538f167ae4c05d66cb606308a74ffbb53fe3171efcb40787d53077a38312219`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## agent::CreateAgentOptions [#agentcreateagentoptions] Options for creating a new agent in one call. Mirrors the JS / TS pattern of "one big options bag" so the call site stays flat. Most fields are optional and have sensible defaults. ```rust #[derive(Debug, Default)] pub struct CreateAgentOptions<'a> { /// Parent DID to derive this agent from. When `None`, a fresh Human Root /// (HMR) identity is minted under the configured namespace. pub parent: Option, /// Required: a short, human-readable name (becomes the DID identifier). pub name: &'a str, /// Default scopes the agent will request from the Arsenal broker. May be /// overridden per-credential-call. pub scopes: &'a [&'a str], /// Optional kind override (defaults to `"agent"` when deriving from a /// parent, or `"hmr"` when no parent is supplied). pub kind: Option<&'a str>, /// Optional derivation path. Defaults to `"/"`. pub derivation_path: Option<&'a str> } ``` Source line: `43`. ## agent::OpenAgent [#agentopenagent] A fully-constructed agent. `OpenAgent` is `Clone`-cheap (everything inside is `Arc`-shared) so the same agent handle can flow through every layer of an application. ```rust #[derive(Clone)] pub struct OpenAgent { } ``` Source line: `68`. ## agent::OpenAgent::from\_parts [#agentopenagentfrom_parts] Construct an \[`OpenAgent`] from already-built parts. Most callers should use \[`crate::builder::OpenAgentBuilder`] or \[`OpenAgent::create_agent`] instead. This constructor exists so test harnesses (and the builder itself) can wire pre-built components. The signature varies with the enabled Cargo features: `credentials` exists only with `arsenal`, `verifier` only with `aegis`. A subsystem left disabled is absent from the type, not silently stubbed. ```rust pub fn from_parts( record: AgentIdentityRecord, config: OpenAgentConfig, #[cfg(feature = "arsenal")] credentials: Option, #[cfg(feature = "aegis")] verifier: Option, skills: SkillsPolicyHandle, default_scopes: Vec, ) -> Self; ``` Source line: `93`. ## agent::OpenAgent::create\_agent [#agentopenagentcreate_agent] Create a new agent with default SDK configuration. This is the boring, batteries-included path: 1. If `parent` is supplied, derive a child identity under that parent. Otherwise mint a fresh HMR under the SDK's default namespace. 2. Skip the credentials layer (no broker is configured by default — use \[`crate::builder::OpenAgentBuilder::with_arsenal_client`] for that). 3. Skip the AEGIS verifier (same reason). 4. Use a deny-all default skills policy. # Errors [#errors] Returns \[`OpenAgentError::Identity`] if document construction fails. ```rust pub async fn create_agent(opts: CreateAgentOptions<'_>) -> Result; ``` Source line: `130`. ## agent::OpenAgent::create\_agent\_with\_config [#agentopenagentcreate_agent_with_config] Like \[`Self::create_agent`] but with a custom \[`OpenAgentConfig`]. # Errors [#errors-1] Returns \[`OpenAgentError::Identity`] if document construction fails. ```rust pub async fn create_agent_with_config( opts: CreateAgentOptions<'_>, config: OpenAgentConfig, ) -> Result; ``` Source line: `139`. ## agent::OpenAgent::document [#agentopenagentdocument] The agent's signed OAS Identity Document. ```rust pub fn document(&self) -> &OasDocument; ``` Source line: `187`. ## agent::OpenAgent::keypair [#agentopenagentkeypair] The agent's keypair (for advanced workflows — most users should not touch this). ```rust pub fn keypair(&self) -> &OasKeyPair; ``` Source line: `193`. ## agent::OpenAgent::did [#agentopenagentdid] The agent's `did:oas` string. ```rust pub fn did(&self) -> &str; ``` Source line: `198`. ## agent::OpenAgent::default\_scopes [#agentopenagentdefault_scopes] The default scopes the agent was created with. ```rust pub fn default_scopes(&self) -> &[String]; ``` Source line: `203`. ## agent::OpenAgent::config [#agentopenagentconfig] The SDK config snapshot in effect for this agent. ```rust pub fn config(&self) -> &OpenAgentConfig; ``` Source line: `208`. ## agent::OpenAgent::skills\_policy [#agentopenagentskills_policy] Skill policy handle for this agent. Returns a clone, so callers can move it into other layers without borrow-checking pain. ```rust pub fn skills_policy(&self) -> SkillsPolicyHandle; ``` Source line: `216`. ## agent::OpenAgent::with\_skills\_policy [#agentopenagentwith_skills_policy] Set (or replace) the skill policy on this agent. This rebuilds the inner `Arc` so the change is local to the returned clone — callers should reassign the returned value. ```rust pub fn with_skills_policy(self, policy: P) -> Self; ``` Source line: `224`. ## agent::OpenAgent::check\_skill [#agentopenagentcheck_skill] Quick check whether the named skill may be invoked by this agent. # Errors [#errors-2] Returns \[`OpenAgentError::SkillDenied`] if the skill is not allowed. ```rust pub fn check_skill(&self, skill: &str) -> Result<()>; ``` Source line: `250`. ## agent::OpenAgent::credentials\_for [#agentopenagentcredentials_for] Get a credentials handle scoped to a specific provider. `provider` is a logical name (e.g., `"openai"`, `"github"`) used by the SDK only for diagnostic logs — the actual scopes routed to the broker come from the agent's \[`Self::default_scopes`]. # Errors [#errors-3] Returns \[`OpenAgentError::Config`] if no credential client is wired in. ```rust #[cfg(feature = "arsenal")] pub async fn credentials_for(&self, provider: &str) -> Result; ``` Source line: `264`. ## agent::OpenAgent::verifier [#agentopenagentverifier] Reference to the AEGIS verifier (if configured). ```rust #[cfg(feature = "aegis")] pub fn verifier(&self) -> Option<&Verifier>; ``` Source line: `278`. ## agent::authenticate\_with\_verifier [#agentauthenticate_with_verifier] One-shot authentication helper at the crate level. `OpenAgent::authenticate` is the canonical entry point referenced in the README pitch. We expose it as an inherent method on the \[`OpenAgent`] type itself by re-exporting from \[`crate::lib`]. Verifies the supplied DID through an injected \[`Verifier`]. The DID is opaque — typically it comes from an `Authorization: Bearer` header or an `X-Openagent-DID` header on an inbound HTTP request. # Errors [#errors-4] Returns \[`OpenAgentError::Verification`] on pipeline failure or \[`OpenAgentError::Config`] if no verifier was supplied. ```rust #[cfg(feature = "aegis")] pub async fn authenticate_with_verifier( verifier: &Verifier, did: &str, ) -> Result; ``` Source line: `311`. # openagent-sdk · builder URL: https://docs.openagent.id/reference/rust/openagent-sdk/builder Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/builder.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/builder.rs`. SHA-256: `e0ecff2f40b0c2c8b5021827630f5991d14020c8561aee684e80447db77856a7`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## builder::OpenAgentBuilder [#builderopenagentbuilder] Fluent builder for an \[`OpenAgent`]. All setters consume `self` and return a new builder; the builder itself is `Default`-friendly so you can chain straight from a function call. Setters for a disabled Cargo feature are absent rather than ignored: a `with_arsenal_client` call cannot exist in a build that would discard the client. ```rust #[derive(Default)] pub struct OpenAgentBuilder { } ``` Source line: `36`. ## builder::OpenAgentBuilder::new [#builderopenagentbuildernew] Start a new builder with default config. ```rust pub fn new() -> Self; ``` Source line: `50`. ## builder::OpenAgentBuilder::config [#builderopenagentbuilderconfig] Replace the SDK config. ```rust pub fn config(mut self, config: OpenAgentConfig) -> Self; ``` Source line: `55`. ## builder::OpenAgentBuilder::with\_arsenal\_client [#builderopenagentbuilderwith_arsenal_client] Wire in an existing \[`ArsenalClient`]. Without this call, agents built by this builder cannot fetch credentials and \[`OpenAgent::credentials_for`] will return a \[`crate::errors::OpenAgentError::Config`]. ```rust #[cfg(feature = "arsenal")] pub fn with_arsenal_client(mut self, client: ArsenalClient) -> Self; ``` Source line: `66`. ## builder::OpenAgentBuilder::with\_aegis\_client [#builderopenagentbuilderwith_aegis_client] Wire in an existing \[`AegisClient`]. ```rust #[cfg(feature = "aegis")] pub fn with_aegis_client(mut self, client: AegisClient) -> Self; ``` Source line: `73`. ## builder::OpenAgentBuilder::with\_aegis\_registry [#builderopenagentbuilderwith_aegis_registry] Wire in an AEGIS plugin registry. The builder will materialise an \[`AegisClient`] from this when needed. ```rust #[cfg(feature = "aegis")] pub fn with_aegis_registry(mut self, registry: Arc) -> Self; ``` Source line: `81`. ## builder::OpenAgentBuilder::with\_skills\_policy [#builderopenagentbuilderwith_skills_policy] Wire in a custom skills policy. ```rust pub fn with_skills_policy(mut self, policy: P) -> Self; ``` Source line: `87`. ## builder::OpenAgentBuilder::with\_parent [#builderopenagentbuilderwith_parent] Provide a real parent identity (with its own keypair) so the new agent can be derived from it cryptographically. This is the production path. The convenience \[`crate::OpenAgent::create_agent`] mints a fresh transient root from the parent DID instead, which is useful for tests but not for long-lived deployments. ```rust pub fn with_parent(mut self, parent: AgentIdentityRecord) -> Self; ``` Source line: `99`. ## builder::OpenAgentBuilder::build [#builderopenagentbuilderbuild] Finish the build and produce an \[`OpenAgent`]. # Errors [#errors] Returns \[`OpenAgentError::Identity`] if document construction fails or \[`OpenAgentError::Config`] if the supplied options are invalid. ```rust pub async fn build(self, opts: CreateAgentOptions<'_>) -> Result; ``` Source line: `110`. # openagent-sdk · config URL: https://docs.openagent.id/reference/rust/openagent-sdk/config Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/config.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/config.rs`. SHA-256: `60a0684c92cb70612b9eda9b841a39dfed78ad80c39f2df3a6d8afbb7f1baa3c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::OpenAgentConfig [#configopenagentconfig] Top-level configuration for the OpenAgent SDK. Most users can call \[`OpenAgentConfig::default`] and never touch this type. Advanced users construct it via \[`crate::builder::OpenAgentBuilder`]. ```rust #[derive(Debug, Clone)] pub struct OpenAgentConfig { /// The OAS namespace used when minting new identities. Default: `"openagent"`. pub namespace: String, /// Optional Arsenal broker URL for credential proxying. /// When `None`, agents are created with identity only and credential /// fetching will return [`crate::errors::OpenAgentError::Config`]. pub broker_url: Option, /// Optional broker mTLS configuration. Required when `broker_url` is set /// in production. pub broker_mtls: Option, /// Default audience advertised on broker capability requests. pub default_audience: String, /// Default capability TTL in seconds. Default: 300 (5 minutes). pub default_ttl_seconds: i64, /// Whether to auto-renew capability tokens before expiry. Default: `true`. pub auto_renew: bool, /// Optional path to a key file for loading the SDK's master signing key. /// When `None`, a fresh ephemeral key is generated. pub key_file: Option } ``` Source line: `14`. ## config::BrokerMtlsConfig [#configbrokermtlsconfig] mTLS bundle for the Arsenal broker connection. All three fields are file paths to PEM-encoded material on disk. The SDK passes them through to \[`arsenal_sdk::ArsenalClientBuilder::broker_mtls`]. ```rust #[derive(Debug, Clone)] pub struct BrokerMtlsConfig { /// PEM-encoded client certificate chain. pub client_cert: PathBuf, /// PEM-encoded client private key. pub client_key: PathBuf, /// Optional PEM-encoded CA certificate to trust for the broker server. pub ca_cert: Option } ``` Source line: `60`. # openagent-sdk · crate URL: https://docs.openagent.id/reference/rust/openagent-sdk/crate Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/lib.rs`. SHA-256: `a08e99ea97d2d8baf98b88b5fc13588ae769ec424219aaba3b1cd1d7a78b22ae`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## act [#act] ```rust pub mod act; ``` Source line: `74`. ## agent [#agent] ```rust pub mod agent; ``` Source line: `75`. ## builder [#builder] ```rust pub mod builder; ``` Source line: `76`. ## config [#config] ```rust pub mod config; ``` Source line: `77`. ## credentials [#credentials] ```rust #[cfg(feature = "arsenal")] pub mod credentials; ``` Source line: `79`. ## errors [#errors] ```rust pub mod errors; ``` Source line: `80`. ## identity [#identity] ```rust pub mod identity; ``` Source line: `81`. ## skills [#skills] ```rust pub mod skills; ``` Source line: `82`. ## verification [#verification] ```rust #[cfg(feature = "aegis")] pub mod verification; ``` Source line: `84`. ## pub use agent::authenticate\_with\_verifier; [#pub-use-agentauthenticate_with_verifier] ```rust #[cfg(feature = "aegis")] pub use agent::authenticate_with_verifier; ``` Source line: `91`. ## pub use agent::\{CreateAgentOptions, OpenAgent}; [#pub-use-agentcreateagentoptions-openagent] ```rust pub use agent::{CreateAgentOptions, OpenAgent}; ``` Source line: `92`. ## pub use builder::OpenAgentBuilder; [#pub-use-builderopenagentbuilder] ```rust pub use builder::OpenAgentBuilder; ``` Source line: `93`. ## pub use config::\{BrokerMtlsConfig, OpenAgentConfig}; [#pub-use-configbrokermtlsconfig-openagentconfig] ```rust pub use config::{BrokerMtlsConfig, OpenAgentConfig}; ``` Source line: `94`. ## pub use credentials::CredentialClient; [#pub-use-credentialscredentialclient] ```rust #[cfg(feature = "arsenal")] pub use credentials::CredentialClient; ``` Source line: `96`. ## pub use errors::\{OpenAgentError, Result}; [#pub-use-errorsopenagenterror-result] ```rust pub use errors::{OpenAgentError, Result}; ``` Source line: `97`. ## pub use identity::\{AgentIdentityRecord, ParsedDid}; [#pub-use-identityagentidentityrecord-parseddid] ```rust pub use identity::{AgentIdentityRecord, ParsedDid}; ``` Source line: `98`. ## pub use skills::\{AllowListPolicy, SkillsPolicy, SkillsPolicyHandle}; [#pub-use-skillsallowlistpolicy-skillspolicy-skillspolicyhandle] ```rust pub use skills::{AllowListPolicy, SkillsPolicy, SkillsPolicyHandle}; ``` Source line: `99`. ## pub use verification::\{ [#pub-use-verification] authority\_context\_from\_oas, LineageAuthorityContext, VerifiedContext, Verifier, }; ```rust #[cfg(feature = "aegis")] pub use verification::{ authority_context_from_oas, LineageAuthorityContext, VerifiedContext, Verifier, }; ``` Source line: `101`. ## pub use arsenal\_sdk; [#pub-use-arsenal_sdk] The wrapped Arsenal SDK. ```rust #[cfg(feature = "arsenal")] pub use arsenal_sdk; ``` Source line: `111`. ## pub use oas\_sdk; [#pub-use-oas_sdk] The wrapped OAS SDK. ```rust pub use oas_sdk; ``` Source line: `113`. ## pub use openagent\_aegis\_sdk; [#pub-use-openagent_aegis_sdk] The wrapped AEGIS SDK. ```rust #[cfg(feature = "aegis")] pub use openagent_aegis_sdk; ``` Source line: `116`. ## sync [#sync] Synchronous helpers for CLI tooling. The OpenAgent SDK is async-first, but CLI tools and one-shot scripts usually want a blocking wrapper. The \[`sync`] module provides exactly that. ```rust pub mod sync; ``` Source line: `122`. ## sync::create\_agent [#synccreate_agent] Blocking equivalent of \[`crate::OpenAgent::create_agent`]. Builds a single-threaded tokio runtime, drives the async call to completion, and returns the result. Safe to call from any non-async context. # Errors [#errors-1] Propagates any \[`crate::OpenAgentError`] from the async path. ```rust pub fn create_agent(opts: CreateAgentOptions<'_>) -> Result; ``` Source line: `135`. # openagent-sdk · credentials URL: https://docs.openagent.id/reference/rust/openagent-sdk/credentials Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/credentials.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/credentials.rs`. SHA-256: `4031950119cf80c662cc8b3f1862a41b1ac6f38b25b9ef80e899de1c0645c042`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "arsenal")] ``` ## credentials::CredentialClient [#credentialscredentialclient] Builder-friendly handle to Arsenal-backed credentials for one agent. `CredentialClient` is `Clone` (via `Arc`) so multiple call sites in an agent can share one underlying broker connection. Internally it holds: * the \[`ArsenalClient`] (broker connection + identity), * the agent's default scopes, * the most-recently issued capability token (cached in the client itself), * a default audience hint for the broker. ```rust #[cfg(feature = "arsenal")] #[derive(Clone)] pub struct CredentialClient { } ``` Source line: `39`. ## credentials::CredentialClient::new [#credentialscredentialclientnew] Wrap an existing \[`ArsenalClient`] into a \[`CredentialClient`]. `default_scopes` are advertised on every capability request unless the caller passes more specific scopes via \[`Self::request_token`]. ```rust #[cfg(feature = "arsenal")] pub fn new( client: ArsenalClient, default_scopes: Vec, default_ttl_seconds: i64, ) -> Self; ``` Source line: `56`. ## credentials::CredentialClient::default\_scopes [#credentialscredentialclientdefault_scopes] Default scopes this credential client was constructed with. ```rust #[cfg(feature = "arsenal")] pub fn default_scopes(&self) -> &[String]; ``` Source line: `72`. ## credentials::CredentialClient::ensure\_session [#credentialscredentialclientensure_session] Ensure the underlying Arsenal session is open. Idempotent — safe to call from every entry point. The first call opens the session; subsequent calls are no-ops. # Errors [#errors] Returns \[`OpenAgentError::Credential`] if the broker rejects the session. ```rust #[cfg(feature = "arsenal")] pub async fn ensure_session(&self) -> Result<()>; ``` Source line: `85`. ## credentials::CredentialClient::request\_token [#credentialscredentialclientrequest_token] Request a capability token for the given scopes. If `scopes` is empty the client falls back to the default scopes supplied at construction. # Errors [#errors-1] Returns \[`OpenAgentError::Credential`] if the broker rejects the request or no scopes were configured. ```rust #[cfg(feature = "arsenal")] pub async fn request_token(&self, scopes: &[&str]) -> Result; ``` Source line: `109`. ## credentials::CredentialClient::get [#credentialscredentialclientget] Send an HTTP `GET` through the credential proxy. `url` and `headers` may contain `{{VARIABLE}}` placeholders; the broker resolves them server-side and the agent never sees the raw credential. # Errors [#errors-2] Returns \[`OpenAgentError::Credential`] or \[`OpenAgentError::Transport`] on broker / network failures. ```rust #[cfg(feature = "arsenal")] pub async fn get( &self, url: impl Into, headers: BTreeMap, ) -> Result; ``` Source line: `144`. ## credentials::CredentialClient::post [#credentialscredentialclientpost] Send an HTTP `POST` through the credential proxy. # Errors [#errors-3] Returns \[`OpenAgentError::Credential`] or \[`OpenAgentError::Transport`] on broker / network failures. ```rust #[cfg(feature = "arsenal")] pub async fn post( &self, url: impl Into, headers: BTreeMap, body: Vec, ) -> Result; ``` Source line: `158`. ## credentials::CredentialClient::inner [#credentialscredentialclientinner] Reference to the wrapped Arsenal client for advanced use cases. Drop down to this when the SDK doesn't expose what you need — but if you find yourself doing it often, file a feature request. ```rust #[cfg(feature = "arsenal")] pub fn inner(&self) -> &ArsenalClient; ``` Source line: `200`. # openagent-sdk · errors URL: https://docs.openagent.id/reference/rust/openagent-sdk/errors Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/errors.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/errors.rs`. SHA-256: `0d1f1eb2ffaa998919d2141ddf3cd565a7e235accc1a85ebfd2a844b66140155`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## errors::Result [#errorsresult] Result alias for OpenAgent SDK operations. ```rust pub type Result = std::result::Result; ``` Source line: `9`. ## errors::OpenAgentError [#errorsopenagenterror] Unified error type for the OpenAgent SDK. Wraps every error returned by the underlying OAS, Arsenal, and AEGIS layers so consumers don't need to learn three different error taxonomies. # Examples [#examples] ``` use openagent_sdk::errors::{OpenAgentError, Result}; fn example() -> Result<()> { // Errors from any wrapped SDK convert via `?`. Ok(()) } ``` ```rust #[derive(Debug, Error)] pub enum OpenAgentError { /// An error from the OAS identity layer. #[error("identity error: {0}")] Identity(#[from] oas_sdk::error::OasError), /// An error from the Arsenal capability/credential layer. #[cfg(feature = "arsenal")] #[error("credential error: {code:?}: {message}")] Credential { /// Numeric Arsenal error code. code: arsenal_core::error::ErrorCode, /// Human-readable description of what went wrong. message: String, }, /// An error from the AEGIS verification layer. #[error("verification error: {0}")] Verification(String), /// An error from the AEGIS authentication layer. #[error("authentication error: {0}")] Authentication(String), /// An error from the AEGIS policy / authorization layer. #[error("authorization error: {0}")] Authorization(String), /// An error from the AEGIS delegation layer. #[error("delegation error: {0}")] Delegation(String), /// A skill policy violation reported by the [`crate::skills`] layer. #[error("skill denied: {skill}: {reason}")] SkillDenied { /// Name of the skill that was denied. skill: String, /// Reason the skill is denied. reason: String, }, /// A configuration error in the SDK itself (missing parent, invalid scope, etc.). #[error("configuration error: {0}")] Config(String), /// An error in the underlying HTTP transport when proxying credentials. #[error("transport error: {0}")] Transport(String), /// A JSON serialization error from any of the layers. #[error("serialization error: {0}")] Json(#[from] serde_json::Error), } ``` Source line: `27`. ## errors::OpenAgentError::config [#errorsopenagenterrorconfig] Construct a configuration error from any displayable value. ```rust pub fn config(msg: impl Into) -> Self; ``` Source line: `82`. ## errors::OpenAgentError::transport [#errorsopenagenterrortransport] Construct a transport error from any displayable value. ```rust pub fn transport(msg: impl Into) -> Self; ``` Source line: `87`. # openagent-sdk · identity URL: https://docs.openagent.id/reference/rust/openagent-sdk/identity Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/identity.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/identity.rs`. SHA-256: `60b1590df92837c9a3fe12731f27f1d5dc40c693a5d1d6115c27ffb6eb3f0d01`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## identity::ParsedDid [#identityparseddid] A parsed `did:oas:::` triple. The OpenAgent SDK accepts DIDs as strings everywhere — this struct only exists internally so the wrapper code doesn't have to re-split the string. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParsedDid { /// The namespace component (e.g., `"l1fe"`, `"openagent"`). pub namespace: String, /// The entity kind (e.g., `"hmr"`, `"agent"`, `"tool"`). pub kind: String, /// The entity identifier. pub identifier: String } ``` Source line: `23`. ## identity::ParsedDid::parse [#identityparseddidparse] Parse a `did:oas:...` string. # Errors [#errors] Returns \[`OpenAgentError::Config`] if the DID is malformed. ```rust pub fn parse(did: &str) -> Result; ``` Source line: `38`. ## identity::ParsedDid::to\_did [#identityparseddidto_did] Render this triple back into the canonical DID string. ```rust pub fn to_did(&self) -> String; ``` Source line: `59`. ## identity::AgentIdentityRecord [#identityagentidentityrecord] A signed identity document plus its keypair. This is the OpenAgent SDK's analogue of \[`oas_sdk::identity::CreatedIdentity`] and \[`oas_sdk::lineage::DerivedIdentity`]. We collapse them into one type because consumers don't need to care which workflow produced the identity. ```rust #[derive(Debug)] pub struct AgentIdentityRecord { /// The signed OAS Identity Document. pub document: OasDocument, /// The Ed25519 keypair the document is signed with. pub keypair: OasKeyPair } ``` Source line: `87`. ## identity::mint\_human\_root [#identitymint_human_root] Mint a fresh Human Root (HMR) identity. Most apps don't call this directly — agents derive from a parent. This is exposed for tests and for the rare case of bootstrapping a new root. # Errors [#errors-1] Returns \[`OpenAgentError::Identity`] if document construction or signing fails inside OAS. ```rust pub fn mint_human_root(namespace: &str, identifier: &str) -> Result; ``` Source line: `121`. ## identity::derive\_agent [#identityderive_agent] Derive a child agent (or tool, skill, workflow) from a parent identity. Performs HKDF-SHA256 key derivation, builds the child document with a lineage section, and signs the document. The returned record can be used directly or registered with an \[`oas_lineage::provider::InMemoryProvider`] for chain verification. # Errors [#errors-2] Returns \[`OpenAgentError::Identity`] if any step inside \[`oas_sdk::lineage`] fails. ```rust pub fn derive_agent( parent_keypair: &OasKeyPair, parent_doc: &OasDocument, namespace: &str, kind: &str, identifier: &str, derivation_path: &str, ) -> Result; ``` Source line: `138`. ## identity::verify\_lineage\_chain [#identityverify_lineage_chain] Verify a document's lineage chain back to a human root. Provider must already contain every parent document on the chain (the OpenAgent SDK does not perform DID resolution; that lives in AEGIS). # Errors [#errors-3] Returns \[`OpenAgentError::Identity`] if any hop fails verification. ```rust pub fn verify_lineage_chain(document: &OasDocument, provider: &dyn DocumentProvider) -> Result<()>; ``` Source line: `167`. # openagent-sdk modules URL: https://docs.openagent.id/reference/rust/openagent-sdk Markdown: https://docs.openagent.id/reference/rust/openagent-sdk.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-sdks-rust). [Focused integration guide](/sdk/overview). ## Modules [#modules] * [crate](/reference/rust/openagent-sdk/crate) — 23 declarations * [act](/reference/rust/openagent-sdk/act) — 15 declarations * [agent](/reference/rust/openagent-sdk/agent) — 16 declarations * [builder](/reference/rust/openagent-sdk/builder) — 9 declarations * [config](/reference/rust/openagent-sdk/config) — 2 declarations * [credentials](/reference/rust/openagent-sdk/credentials) — 8 declarations * [errors](/reference/rust/openagent-sdk/errors) — 4 declarations * [identity](/reference/rust/openagent-sdk/identity) — 7 declarations * [skills](/reference/rust/openagent-sdk/skills) — 10 declarations * [verification](/reference/rust/openagent-sdk/verification) — 12 declarations # openagent-sdk · skills URL: https://docs.openagent.id/reference/rust/openagent-sdk/skills Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/skills.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/skills.rs`. SHA-256: `917d41de8f0984c4dfa386f7d56e170f11d91aedd10a4d8e91e2d8e6208cbf51`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## skills::SkillsPolicy [#skillsskillspolicy] Trait every skill policy must implement. A policy answers a single question: "is this agent allowed to invoke the named skill, given the current verified context?". Implementations may be pure (an in-memory allow-list) or remote (an HTTP call to a policy service); the SDK does not care. ```rust pub trait SkillsPolicy: Send + Sync { /// Return `Ok(())` if the skill is allowed, `Err` otherwise. fn can_invoke(&self, skill: &str) -> Result<()>; /// Return the set of skills currently allowed by this policy. /// /// Used by tooling and tests; the policy may return an empty set if it /// does not enumerate skills (e.g., a remote service). fn allowed_skills(&self) -> BTreeSet; } ``` Source line: `25`. ## skills::AllowListPolicy [#skillsallowlistpolicy] Default in-memory allow-list skill policy. `AllowListPolicy` lets callers register skill names up front and allow them by exact match. Useful for tests, CLI tools, and bootstrap before the real `openagent-skills-policy` crate is wired in. ```rust #[derive(Debug, Clone, Default)] pub struct AllowListPolicy { } ``` Source line: `42`. ## skills::AllowListPolicy::new [#skillsallowlistpolicynew] Create an empty policy that denies every skill. ```rust pub fn new() -> Self; ``` Source line: `48`. ## skills::AllowListPolicy::with\_skills [#skillsallowlistpolicywith_skills] Build a policy from an iterator of skill names. ```rust pub fn with_skills(skills: I) -> Self where I: IntoIterator, S: Into,; ``` Source line: `53`. ## skills::AllowListPolicy::allow [#skillsallowlistpolicyallow] Mutably add a skill to the allow-list. ```rust pub fn allow(&mut self, skill: impl Into); ``` Source line: `64`. ## skills::SkillsPolicyHandle [#skillsskillspolicyhandle] Cheap-to-clone facade returned by \[`crate::OpenAgent::skills_policy`]. Wraps an `Arc` so the same policy object can be shared across multiple agent handles without lifetime headaches. ```rust #[derive(Clone)] pub struct SkillsPolicyHandle { } ``` Source line: `91`. ## skills::SkillsPolicyHandle::new [#skillsskillspolicyhandlenew] Wrap any \[`SkillsPolicy`] implementation. ```rust pub fn new(policy: P) -> Self; ``` Source line: `97`. ## skills::SkillsPolicyHandle::from\_arc [#skillsskillspolicyhandlefrom_arc] Wrap an already-`Arc`'d policy (useful when sharing one policy across many `OpenAgent` instances). ```rust pub fn from_arc(policy: Arc) -> Self; ``` Source line: `105`. ## skills::SkillsPolicyHandle::can\_invoke [#skillsskillspolicyhandlecan_invoke] Return `Ok(())` if the named skill may be invoked, otherwise an error. ```rust pub fn can_invoke(&self, skill: &str) -> Result<()>; ``` Source line: `110`. ## skills::SkillsPolicyHandle::allowed\_skills [#skillsskillspolicyhandleallowed_skills] All skills currently allowed by the wrapped policy. ```rust pub fn allowed_skills(&self) -> BTreeSet; ``` Source line: `115`. # openagent-sdk · verification URL: https://docs.openagent.id/reference/rust/openagent-sdk/verification Markdown: https://docs.openagent.id/reference/rust/openagent-sdk/verification.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/sdks/rust/src/verification.rs`. SHA-256: `9244631fd8211d5e12d74a0e176f213441496c235ec2f2aee5d8900f20b58f7b`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. Module condition: ```rust #[cfg(feature = "aegis")] ``` ## verification::Verifier [#verificationverifier] Wraps an AEGIS client. The verifier owns its `AegisClient` (cheap-clone via `Arc` internally) and is meant to be shared across an entire process. Construction is async-free because AEGIS uses lazy in-memory stores by default. ```rust #[cfg(feature = "aegis")] #[derive(Clone)] pub struct Verifier { } ``` Source line: `29`. ## verification::Verifier::new [#verificationverifiernew] Build a verifier with the supplied plugin registry and AEGIS defaults. ```rust #[cfg(feature = "aegis")] pub fn new(registry: Arc) -> Self; ``` Source line: `35`. ## verification::Verifier::from\_client [#verificationverifierfrom_client] Wrap an existing \[`AegisClient`]. Use this when you've configured AEGIS with custom storage backends (e.g., PostgreSQL) or a non-default policy engine. ```rust #[cfg(feature = "aegis")] pub fn from_client(client: AegisClient) -> Self; ``` Source line: `45`. ## verification::Verifier::inner [#verificationverifierinner] Reference to the wrapped AEGIS client for advanced use. ```rust #[cfg(feature = "aegis")] pub fn inner(&self) -> &AegisClient; ``` Source line: `52`. ## verification::Verifier::verify [#verificationverifierverify] Verify a DID end-to-end and return a \[`VerifiedContext`]. Runs the full AEGIS verification pipeline: DID resolution, signature check, lineage walk back to a human root, revocation check, and liveness probe (subject to the configured TTL cache). # Errors [#errors] Returns \[`OpenAgentError::Verification`] if any pipeline stage fails. ```rust #[cfg(feature = "aegis")] pub async fn verify(&self, did: &str) -> Result; ``` Source line: `65`. ## verification::Verifier::authenticate [#verificationverifierauthenticate] Authenticate a credential and return the resulting AEGIS session ID. `identity_type` is `Human` for OAuth/Passkey/etc. and `Agent` for machine-to-machine flows. The two get different session lifetimes. # Errors [#errors-1] Returns \[`OpenAgentError::Authentication`] if no provider accepts the credential. ```rust #[cfg(feature = "aegis")] pub async fn authenticate( &self, credential: &AuthCredential, identity_type: IdentityType, ) -> Result; ``` Source line: `83`. ## verification::Verifier::authorize [#verificationverifierauthorize] Evaluate an authorization request against the registered policy engine. # Errors [#errors-2] Returns \[`OpenAgentError::Authorization`] if the policy engine errors (a *deny* decision is **not** an error — inspect \[`PolicyDecision`]). ```rust #[cfg(feature = "aegis")] pub async fn authorize(&self, request: &PolicyRequest) -> Result; ``` Source line: `98`. ## verification::LineageAuthorityContext [#verificationlineageauthoritycontext] Sigil-backed lineage authority attached by an OAS verifier. ```rust #[cfg(feature = "aegis")] #[derive(Debug, Clone, PartialEq, Eq)] pub struct LineageAuthorityContext { /// DID whose privileged authority was verified. pub subject: String, /// Backend/source identifier, normally `sigil_gal`. pub source: String, /// Finalized root DID for the verified path. pub root: String, /// Reconstructed finalized path, ordered root to caller. pub path: Vec, /// Sigil block height at which this authority was finalized. pub finalized_block: u64, /// Authority path kind, e.g. `human_to_agent`. pub path_kind: String, /// Scopes proven by this lineage path. pub scopes: Vec, /// Generation/depth from root to subject. pub generation: u32, /// Accepted root kind for this authority path. pub root_kind: Option, /// Optional org lineage root commitment for org-scoped authority. pub org_root_commitment: Option, /// Optional expiry timestamp for the authority edge/path. pub expires_at: Option } ``` Source line: `105`. ## verification::authority\_context\_from\_oas [#verificationauthority_context_from_oas] Convert an OAS privileged-authority verification into OpenAgent runtime auth context. This is the OpenAgent-side bridge for sensitive operations: callers provide an OAS document resolver and an authority source adapter, and OpenAgent receives a normalized context it can attach to ACT/request verification. ```rust #[cfg(feature = "aegis")] pub fn authority_context_from_oas( document: &OasDocument, provider: &dyn DocumentProvider, config: &VerifyConfig, authority_source: &dyn LineageAuthoritySource, path_kind: AuthorityPathKind, required_scopes: &[String], min_finalized_block: Option, ) -> Result; ``` Source line: `136`. ## verification::VerifiedContext [#verificationverifiedcontext] `VerifiedContext` is what callers get back from \[`crate::OpenAgent::authenticate`]. It bundles the DID that was verified, the raw AEGIS \[`VerificationResult`] for advanced use, and optional Sigil-backed lineage authority for privileged actions. ```rust #[cfg(feature = "aegis")] #[derive(Debug, Clone)] pub struct VerifiedContext { /// The DID that was verified. pub did: String, /// The raw AEGIS verification result (lineage chain, expiry, etc.). pub result: VerificationResult, /// OAS + Sigil authority proof required for privileged access. pub lineage_authority: Option } ``` Source line: `183`. ## verification::VerifiedContext::is\_valid [#verificationverifiedcontextis_valid] True if the verification considered the DID valid. Combines signature, lineage, revocation, and liveness into a single boolean. Use \[`Self::result`] for the breakdown. ```rust #[cfg(feature = "aegis")] pub fn is_valid(&self) -> bool; ``` Source line: `197`. ## verification::VerifiedContext::require\_privileged\_authority [#verificationverifiedcontextrequire_privileged_authority] Return the attached Sigil-backed authority or fail closed. ```rust #[cfg(feature = "aegis")] pub fn require_privileged_authority(&self) -> Result<&LineageAuthorityContext>; ``` Source line: `209`. # openagent-standalone modules URL: https://docs.openagent.id/reference/rust/openagent-standalone Markdown: https://docs.openagent.id/reference/rust/openagent-standalone.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagents-openagent-id-crates-openagent-standalone). [Focused integration guide](/api-reference/openagent-server). ## Modules [#modules] # openagent-weave · codec URL: https://docs.openagent.id/reference/rust/openagent-weave/codec Markdown: https://docs.openagent.id/reference/rust/openagent-weave/codec.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/codec.rs`. SHA-256: `c1222db288f0ca8462a02dae8e4f495fba541a82674aeb6ad504e0ecb43d27e8`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## codec::CborCodec [#codeccborcodec] CBOR codec for OpenAgent auth handshake messages. ```rust #[derive(Debug, Clone)] pub struct CborCodec { } ``` Source line: `28`. ## codec::CborCodec::new [#codeccborcodecnew] Creates a new codec with the given maximum message size. ```rust pub fn new(config: &WeaveAuthConfig) -> Self; ``` Source line: `34`. ## codec::encode\_frame [#codecencode_frame] Encode a CBOR message with a 4-byte big-endian length prefix. ```rust pub fn encode_frame(value: &T, max_size: usize) -> Result, WeaveAuthError>; ``` Source line: `50`. ## codec::decode\_frame [#codecdecode_frame] Decode a length-prefixed CBOR message from a byte buffer. ```rust pub fn decode_frame( data: &[u8], max_size: usize, ) -> Result; ``` Source line: `69`. # openagent-weave · config URL: https://docs.openagent.id/reference/rust/openagent-weave/config Markdown: https://docs.openagent.id/reference/rust/openagent-weave/config.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/config.rs`. SHA-256: `fe5a6919e4eb79da3f988e096b7a6fb5544d2f0a8812ba26cf610afd9b7fbca5`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## config::WeaveAuthConfig [#configweaveauthconfig] Configuration for the Weave OAAP protocol adapter. ```rust #[derive(Debug, Clone)] pub struct WeaveAuthConfig { /// Maximum size of a single CBOR-encoded message frame, in bytes. /// Prevents memory exhaustion from malicious peers. /// Default: 64 KiB. pub max_message_size: usize, /// How long to wait for each handshake round trip before timing out. /// Default: 30 seconds. pub handshake_timeout: Duration, /// How long an established session remains valid. /// Default: 1 hour. pub session_ttl: Duration, /// Maximum number of concurrent pending handshakes. /// Default: 128. pub max_pending_handshakes: usize, /// How long a challenge remains valid before the initiator must send PROVE. /// Default: 60 seconds. pub challenge_ttl: Duration } ``` Source line: `8`. ## config::WeaveAuthConfig::new [#configweaveauthconfignew] Creates a new config with default values. ```rust pub fn new() -> Self; ``` Source line: `45`. ## config::WeaveAuthConfig::with\_max\_message\_size [#configweaveauthconfigwith_max_message_size] Sets the maximum message size. ```rust pub fn with_max_message_size(mut self, size: usize) -> Self; ``` Source line: `50`. ## config::WeaveAuthConfig::with\_handshake\_timeout [#configweaveauthconfigwith_handshake_timeout] Sets the handshake timeout. ```rust pub fn with_handshake_timeout(mut self, timeout: Duration) -> Self; ``` Source line: `56`. ## config::WeaveAuthConfig::with\_session\_ttl [#configweaveauthconfigwith_session_ttl] Sets the session TTL. ```rust pub fn with_session_ttl(mut self, ttl: Duration) -> Self; ``` Source line: `62`. ## config::WeaveAuthConfig::with\_max\_pending\_handshakes [#configweaveauthconfigwith_max_pending_handshakes] Sets the maximum number of concurrent pending handshakes. ```rust pub fn with_max_pending_handshakes(mut self, max: usize) -> Self; ``` Source line: `68`. ## config::WeaveAuthConfig::with\_challenge\_ttl [#configweaveauthconfigwith_challenge_ttl] Sets the challenge TTL. ```rust pub fn with_challenge_ttl(mut self, ttl: Duration) -> Self; ``` Source line: `74`. # openagent-weave · crate URL: https://docs.openagent.id/reference/rust/openagent-weave/crate Markdown: https://docs.openagent.id/reference/rust/openagent-weave/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/lib.rs`. SHA-256: `f6ff34beea33ace1e6cf696d32d2ae99a199db8044efea61e6dad53ed3b486a9`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## codec [#codec] ```rust pub mod codec; ``` Source line: `44`. ## config [#config] ```rust pub mod config; ``` Source line: `45`. ## error [#error] ```rust pub mod error; ``` Source line: `46`. ## handler [#handler] ```rust pub mod handler; ``` Source line: `47`. ## peer\_auth [#peer_auth] ```rust pub mod peer_auth; ``` Source line: `48`. ## protocol [#protocol] ```rust pub mod protocol; ``` Source line: `49`. ## transport [#transport] ```rust pub mod transport; ``` Source line: `50`. ## pub use config::WeaveAuthConfig; [#pub-use-configweaveauthconfig] ```rust pub use config::WeaveAuthConfig; ``` Source line: `52`. ## pub use error::WeaveAuthError; [#pub-use-errorweaveautherror] ```rust pub use error::WeaveAuthError; ``` Source line: `53`. ## pub use handler::HandshakeHandler; [#pub-use-handlerhandshakehandler] ```rust pub use handler::HandshakeHandler; ``` Source line: `54`. ## pub use peer\_auth::\{PeerAuthState, PeerAuthStore}; [#pub-use-peer_authpeerauthstate-peerauthstore] ```rust pub use peer_auth::{PeerAuthState, PeerAuthStore}; ``` Source line: `55`. ## pub use protocol::\{ [#pub-use-protocol] HandshakeRequest, HandshakeResponse, WeaveAuthBehaviour, WeaveAuthEvent, OPENAGENT\_AUTH\_PROTOCOL, }; ```rust pub use protocol::{ HandshakeRequest, HandshakeResponse, WeaveAuthBehaviour, WeaveAuthEvent, OPENAGENT_AUTH_PROTOCOL, }; ``` Source line: `56`. ## pub use transport::WeaveTransport; [#pub-use-transportweavetransport] ```rust pub use transport::WeaveTransport; ``` Source line: `60`. # openagent-weave · error URL: https://docs.openagent.id/reference/rust/openagent-weave/error Markdown: https://docs.openagent.id/reference/rust/openagent-weave/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/error.rs`. SHA-256: `93dc23119a78ed4187935042cb3b6cce37c59b653a44c0b1390b9dfc3aa5f250`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::WeaveAuthError [#errorweaveautherror] Errors specific to the Weave/libp2p OAAP adapter. ```rust #[derive(Debug, Error)] pub enum WeaveAuthError { /// CBOR encoding or decoding failed. #[error("cbor codec error: {0}")] Codec(String), /// Message exceeds the configured maximum frame size. #[error("message too large: {size} bytes exceeds limit of {limit} bytes")] MessageTooLarge { /// Actual message size in bytes. size: usize, /// Configured maximum. limit: usize, }, /// No established auth session for the given peer. #[error("peer not authenticated: {peer_id}")] PeerNotAuthenticated { /// The libp2p peer ID. peer_id: String, }, /// A handshake is already in progress for this peer. #[error("handshake already in progress for peer: {peer_id}")] HandshakeInProgress { /// The libp2p peer ID. peer_id: String, }, /// The handshake timed out waiting for a response. #[error("handshake timeout after {elapsed_ms}ms")] Timeout { /// Milliseconds elapsed before timeout. elapsed_ms: u64, }, /// Received an unexpected message type for the current handshake state. #[error("unexpected message: expected {expected}, got {actual}")] UnexpectedMessage { /// What was expected. expected: String, /// What was received. actual: String, }, /// Error from the underlying OAAP protocol layer. #[error("auth protocol error: {0}")] Protocol(#[from] openagent_auth_protocol::AuthProtocolError), /// libp2p dial or connection error. #[error("connection error: {0}")] Connection(String), /// Internal error. #[error("internal error: {0}")] Internal(String), } ``` Source line: `8`. # openagent-weave · handler URL: https://docs.openagent.id/reference/rust/openagent-weave/handler Markdown: https://docs.openagent.id/reference/rust/openagent-weave/handler.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/handler.rs`. SHA-256: `2ad6b50295c742b7653914b2efde11a8675a44d569a7e2038e03a82f33dd3ea7`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## handler::HandshakeHandler [#handlerhandshakehandler] Orchestrates OAAP handshakes for both initiator and responder roles. The handler holds references to the peer auth store and session store, and coordinates the multi-step handshake against the swarm's `WeaveAuthBehaviour`. ```rust pub struct HandshakeHandler { } ``` Source line: `31`. ## handler::HandshakeHandler::new [#handlerhandshakehandlernew] Creates a new handler. ```rust pub fn new(config: WeaveAuthConfig, local_did: String) -> Self; ``` Source line: `41`. ## handler::HandshakeHandler::with\_session\_store [#handlerhandshakehandlerwith_session_store] Creates a handler with an external session store. ```rust pub fn with_session_store( config: WeaveAuthConfig, local_did: String, session_store: Arc, ) -> Self; ``` Source line: `51`. ## handler::HandshakeHandler::peer\_store [#handlerhandshakehandlerpeer_store] Returns a reference to the peer auth store. ```rust pub fn peer_store(&self) -> &PeerAuthStore; ``` Source line: `65`. ## handler::HandshakeHandler::local\_did [#handlerhandshakehandlerlocal_did] Returns the local DID. ```rust pub fn local_did(&self) -> &str; ``` Source line: `70`. ## handler::HandshakeHandler::initiate [#handlerhandshakehandlerinitiate] Initiate a handshake with a remote peer (Step 1: send PRESENT). Returns the `OutboundRequestId` for tracking the challenge response. ```rust pub fn initiate( &self, behaviour: &mut WeaveAuthBehaviour, peer: &PeerId, present: PresentMessage, ) -> Result; ``` Source line: `81`. ## handler::HandshakeHandler::handle\_challenge [#handlerhandshakehandlerhandle_challenge] Process a CHALLENGE response from the responder (received after PRESENT). Returns the challenge message for the caller to sign and build a PROVE. ```rust pub fn handle_challenge( &self, peer: &PeerId, challenge: &ChallengeMessage, ) -> Result<(), WeaveAuthError>; ``` Source line: `105`. ## handler::HandshakeHandler::send\_prove [#handlerhandshakehandlersend_prove] Send Step 3 (PROVE) to the responder. ```rust pub fn send_prove( &self, behaviour: &mut WeaveAuthBehaviour, peer: &PeerId, prove: ProveMessage, ) -> Result; ``` Source line: `132`. ## handler::HandshakeHandler::handle\_established [#handlerhandshakehandlerhandle_established] Process an ESTABLISHED response (received after PROVE). ```rust pub fn handle_established( &self, peer: &PeerId, established: &EstablishedMessage, ) -> Result<(), WeaveAuthError>; ``` Source line: `144`. ## handler::HandshakeHandler::handle\_present [#handlerhandshakehandlerhandle_present] Handle an inbound PRESENT request (Step 1 from a remote initiator). Returns a `ChallengeMessage` to send back. ```rust pub async fn handle_present( &self, peer: &PeerId, present: &PresentMessage, ) -> Result; ``` Source line: `186`. ## handler::HandshakeHandler::handle\_prove [#handlerhandshakehandlerhandle_prove] Handle an inbound PROVE request (Step 3 from a remote initiator). Returns an `EstablishedMessage` on success. ```rust pub async fn handle_prove( &self, peer: &PeerId, prove: &ProveMessage, ) -> Result; ``` Source line: `246`. ## handler::HandshakeHandler::respond [#handlerhandshakehandlerrespond] Respond to an inbound request on its response channel. ```rust pub fn respond( &self, behaviour: &mut WeaveAuthBehaviour, channel: ResponseChannel, response: HandshakeResponse, ) -> Result<(), WeaveAuthError>; ``` Source line: `322`. # openagent-weave modules URL: https://docs.openagent.id/reference/rust/openagent-weave Markdown: https://docs.openagent.id/reference/rust/openagent-weave.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-adapters-weave). [Focused integration guide](/integrations/adapters). ## Modules [#modules] * [crate](/reference/rust/openagent-weave/crate) — 13 declarations * [codec](/reference/rust/openagent-weave/codec) — 4 declarations * [config](/reference/rust/openagent-weave/config) — 7 declarations * [error](/reference/rust/openagent-weave/error) — 1 declarations * [handler](/reference/rust/openagent-weave/handler) — 12 declarations * [peer\_auth](/reference/rust/openagent-weave/peer_auth) — 13 declarations * [protocol](/reference/rust/openagent-weave/protocol) — 8 declarations * [transport](/reference/rust/openagent-weave/transport) — 5 declarations # openagent-weave · peer_auth URL: https://docs.openagent.id/reference/rust/openagent-weave/peer_auth Markdown: https://docs.openagent.id/reference/rust/openagent-weave/peer_auth.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/peer_auth.rs`. SHA-256: `1d288e2675cff08c6905e3ec68b20bf61d08dc8501d838e8954cb839871c0fe0`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## peer\_auth::PeerAuthState [#peer_authpeerauthstate] Authentication state for a single peer. ```rust #[derive(Debug, Clone)] pub struct PeerAuthState { /// The authenticated DID of the peer. pub did: String, /// The session ID from the ESTABLISHED step. pub session_id: String, /// When the session was established. pub established_at: Instant, /// When the session expires. pub expires_at: Instant, /// Current state of the handshake. pub phase: HandshakePhase } ``` Source line: `17`. ## peer\_auth::HandshakePhase [#peer_authhandshakephase] Which phase of the handshake this peer is in. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HandshakePhase { /// PRESENT sent, awaiting CHALLENGE. PresentSent, /// CHALLENGE issued by us, awaiting PROVE. ChallengeIssued, /// PROVE sent, awaiting ESTABLISHED. ProveSent, /// Handshake complete. Established, } ``` Source line: `32`. ## peer\_auth::PeerAuthState::is\_valid [#peer_authpeerauthstateis_valid] Returns `true` if the session is established and not expired. ```rust pub fn is_valid(&self) -> bool; ``` Source line: `45`. ## peer\_auth::PeerAuthState::is\_expired [#peer_authpeerauthstateis_expired] Returns `true` if the session has expired. ```rust pub fn is_expired(&self) -> bool; ``` Source line: `50`. ## peer\_auth::PeerAuthStore [#peer_authpeerauthstore] Thread-safe store for per-peer authentication state. Keyed by libp2p `PeerId`. Handles concurrent access from the swarm event loop and application code. ```rust #[derive(Debug, Clone, Default)] pub struct PeerAuthStore { } ``` Source line: `60`. ## peer\_auth::PeerAuthStore::new [#peer_authpeerauthstorenew] Creates a new empty peer auth store. ```rust pub fn new() -> Self; ``` Source line: `66`. ## peer\_auth::PeerAuthStore::put [#peer_authpeerauthstoreput] Record or update a peer's auth state. ```rust pub fn put(&self, peer: PeerId, state: PeerAuthState) -> Result<(), WeaveAuthError>; ``` Source line: `71`. ## peer\_auth::PeerAuthStore::get [#peer_authpeerauthstoreget] Retrieve a peer's auth state. ```rust pub fn get(&self, peer: &PeerId) -> Result, WeaveAuthError>; ``` Source line: `81`. ## peer\_auth::PeerAuthStore::remove [#peer_authpeerauthstoreremove] Remove a peer's auth state (on disconnect or session revocation). ```rust pub fn remove(&self, peer: &PeerId) -> Result<(), WeaveAuthError>; ``` Source line: `90`. ## peer\_auth::PeerAuthStore::is\_authenticated [#peer_authpeerauthstoreis_authenticated] Returns `true` if the peer has a valid, non-expired established session. ```rust pub fn is_authenticated(&self, peer: &PeerId) -> bool; ``` Source line: `100`. ## peer\_auth::PeerAuthStore::gc\_expired [#peer_authpeerauthstoregc_expired] Remove all expired sessions. Returns the number removed. ```rust pub fn gc_expired(&self) -> Result; ``` Source line: `108`. ## peer\_auth::PeerAuthStore::len [#peer_authpeerauthstorelen] Returns the number of peers in the store. ```rust pub fn len(&self) -> usize; ``` Source line: `119`. ## peer\_auth::PeerAuthStore::is\_empty [#peer_authpeerauthstoreis_empty] Returns `true` if the store has no entries. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `124`. # openagent-weave · protocol URL: https://docs.openagent.id/reference/rust/openagent-weave/protocol Markdown: https://docs.openagent.id/reference/rust/openagent-weave/protocol.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/protocol.rs`. SHA-256: `bd8735b2415d92f289459b6292df66aa1501a366a3ea8309a654f9093b07a8bd`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## protocol::OPENAGENT\_AUTH\_PROTOCOL [#protocolopenagent_auth_protocol] The protocol identifier for OpenAgent auth on libp2p. ```rust pub const OPENAGENT_AUTH_PROTOCOL: &str; ``` Source line: `21`. ## protocol::HandshakeRequest [#protocolhandshakerequest] A handshake request (sent by the initiator). Maps to Steps 1 (PRESENT) and 3 (PROVE) of the OAAP handshake. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub enum HandshakeRequest { /// Step 1: Initiator presents identity. Present(PresentMessage), /// Step 3: Initiator proves ownership of the DID private key. Prove(ProveMessage), } ``` Source line: `31`. ## protocol::HandshakeResponse [#protocolhandshakeresponse] A handshake response (sent by the responder). Maps to Steps 2 (CHALLENGE) and 4 (ESTABLISHED) of the OAAP handshake. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub enum HandshakeResponse { /// Step 2: Responder issues a challenge. Challenge(ChallengeMessage), /// Step 4: Authentication established. Established(EstablishedMessage), /// Error during handshake — the responder rejected the request. Error { /// Machine-readable error code. code: String, /// Human-readable reason. reason: String, }, } ``` Source line: `42`. ## protocol::WeaveAuthEvent [#protocolweaveauthevent] Events emitted by \[`WeaveAuthBehaviour`]. ```rust pub type WeaveAuthEvent = request_response::Event; ``` Source line: `61`. ## protocol::WeaveAuthBehaviour [#protocolweaveauthbehaviour] libp2p `NetworkBehaviour` for the OpenAgent auth protocol. This is a thin wrapper around `request_response::Behaviour` configured with the CBOR codec and the `/openagent/auth/1.0.0` protocol. Compose it into your swarm alongside other behaviours (Kademlia, Identify, etc.). # Example [#example] ```rust use openagent_weave::{WeaveAuthBehaviour, WeaveAuthConfig}; let config = WeaveAuthConfig::default(); let auth_behaviour = WeaveAuthBehaviour::new(config); // Include `auth_behaviour` in your composed NetworkBehaviour struct. ``` ```rust pub type WeaveAuthBehaviour = request_response::Behaviour; ``` Source line: `78`. ## protocol::new\_behaviour [#protocolnew_behaviour] Create a new \[`WeaveAuthBehaviour`] with the given configuration. Both inbound and outbound support is enabled so the node can both initiate and accept handshakes. ```rust pub fn new_behaviour(config: &WeaveAuthConfig) -> WeaveAuthBehaviour; ``` Source line: `84`. ## protocol::send\_request [#protocolsend_request] Send a handshake request to a specific peer. Returns the `OutboundRequestId` for correlating the response. ```rust pub fn send_request( behaviour: &mut WeaveAuthBehaviour, peer: &PeerId, request: HandshakeRequest, ) -> request_response::OutboundRequestId; ``` Source line: `100`. ## protocol::send\_response [#protocolsend_response] Send a handshake response for an inbound request. `channel` comes from the `request_response::Event::Message::Request` variant. ```rust pub fn send_response( behaviour: &mut WeaveAuthBehaviour, channel: request_response::ResponseChannel, response: HandshakeResponse, ) -> Result<(), HandshakeResponse>; ``` Source line: `111`. # openagent-weave · transport URL: https://docs.openagent.id/reference/rust/openagent-weave/transport Markdown: https://docs.openagent.id/reference/rust/openagent-weave/transport.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/weave/src/transport.rs`. SHA-256: `411d7607bb9534c7e74a73f86b1e2cb1e5bd20371a1fa3bf9743c5143e259ee6`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## transport::TransportCommand [#transporttransportcommand] A command sent from \[`WeaveTransport`] to the swarm event loop. ```rust #[derive(Debug)] pub enum TransportCommand { /// Send a request to a peer and receive the response asynchronously. SendRequest { /// Target peer. peer: PeerId, /// The handshake request to send. request: HandshakeRequest, /// Channel to receive the response. reply: oneshot::Sender>, }, } ``` Source line: `30`. ## transport::WeaveTransport [#transportweavetransport] `AuthTransport` implementation for Weave/libp2p. The transport sends commands through a channel that the swarm event loop consumes. This decouples the async transport API from the swarm poll loop. # Usage [#usage] ```rust use openagent_weave::{WeaveTransport, WeaveAuthConfig}; let (tx, rx) = tokio::sync::mpsc::channel(64); let transport = WeaveTransport::new(config, tx, peer_store); // In the swarm loop, consume `rx` and call the behaviour. ``` ```rust pub struct WeaveTransport { } ``` Source line: `57`. ## transport::WeaveTransport::new [#transportweavetransportnew] Creates a new Weave transport. ```rust pub fn new( config: WeaveAuthConfig, command_tx: mpsc::Sender, peer_store: PeerAuthStore, ) -> Self; ``` Source line: `68`. ## transport::WeaveTransport::register\_peer [#transportweavetransportregister_peer] Register a mapping from an endpoint/DID string to a libp2p `PeerId`. The `present` and `prove` methods accept an `endpoint` parameter. For Weave, this should be the peer's base58 PeerId or DID string. Register the mapping here so the transport knows where to route. ```rust pub async fn register_peer(&self, endpoint: &str, peer: PeerId); ``` Source line: `86`. ## transport::WeaveTransport::peer\_store [#transportweavetransportpeer_store] Returns the peer auth store. ```rust pub fn peer_store(&self) -> &PeerAuthStore; ``` Source line: `92`. # openagent-ws · client URL: https://docs.openagent.id/reference/rust/openagent-ws/client Markdown: https://docs.openagent.id/reference/rust/openagent-ws/client.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/client.rs`. SHA-256: `5b7d51d6bb8196d5dd39e33066f06351acf39ffd8fc5c6515ab90244d02e4405`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client::OpenAgentWsClient [#clientopenagentwsclient] Client-side OAAP WebSocket connector. Holds the client's identity material. Call [`connect`](Self::connect) to open a WebSocket, run the 4-step OAAP handshake, and receive an authenticated session. ```rust pub struct OpenAgentWsClient { } ``` Source line: `31`. ## client::OpenAgentWsClient::new [#clientopenagentwsclientnew] Creates a new client with the given identity. ```rust pub fn new(did: impl Into, signing_key: [u8; 32], verifying_key: [u8; 32]) -> Self; ``` Source line: `40`. ## client::OpenAgentWsClient::with\_timeout [#clientopenagentwsclientwith_timeout] Overrides the per-step handshake timeout (default: 5s). ```rust pub fn with_timeout(mut self, duration: Duration) -> Self; ``` Source line: `50`. ## client::OpenAgentWsClient::connect [#clientopenagentwsclientconnect] Opens a WebSocket connection to `url` and runs the 4-step OAAP handshake. Returns an \[`AuthenticatedSession`] on success. ```rust pub async fn connect(&self, url: &str) -> Result>; ``` Source line: `58`. # openagent-ws · crate URL: https://docs.openagent.id/reference/rust/openagent-ws/crate Markdown: https://docs.openagent.id/reference/rust/openagent-ws/crate.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/lib.rs`. SHA-256: `d6f1fc27284f118a123a7d0274dbc44542c94225a3b7b5c1dd2635d6276c4348`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## client [#client] ```rust pub mod client; ``` Source line: `56`. ## error [#error] ```rust pub mod error; ``` Source line: `57`. ## frame [#frame] ```rust pub mod frame; ``` Source line: `58`. ## server [#server] ```rust pub mod server; ``` Source line: `59`. ## session [#session] ```rust pub mod session; ``` Source line: `60`. ## transport [#transport] ```rust pub mod transport; ``` Source line: `61`. ## pub use client::OpenAgentWsClient; [#pub-use-clientopenagentwsclient] ```rust pub use client::OpenAgentWsClient; ``` Source line: `65`. ## pub use error::\{Result, WsError}; [#pub-use-errorresult-wserror] ```rust pub use error::{Result, WsError}; ``` Source line: `66`. ## pub use server::OpenAgentWsHandler; [#pub-use-serveropenagentwshandler] ```rust pub use server::OpenAgentWsHandler; ``` Source line: `67`. ## pub use session::AuthenticatedSession; [#pub-use-sessionauthenticatedsession] ```rust pub use session::AuthenticatedSession; ``` Source line: `68`. ## ::VERSION [#version] Crate version sourced from `Cargo.toml`. ```rust pub const VERSION: &str; ``` Source line: `71`. # openagent-ws · error URL: https://docs.openagent.id/reference/rust/openagent-ws/error Markdown: https://docs.openagent.id/reference/rust/openagent-ws/error.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/error.rs`. SHA-256: `3c5f2de60af23894205f0c60779c9c69b974b370ae0703181c36e6641099b82c`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## error::WsError [#errorwserror] Errors from the OpenAgent WebSocket adapter. ```rust #[derive(Debug, Error)] pub enum WsError { /// The WebSocket connection was closed before the handshake completed. #[error("WebSocket closed during OAAP handshake at step {step}")] HandshakeClosed { /// Which step (1-4) was in progress when the close occurred. step: u8, }, /// An unexpected frame type was received during the handshake. #[error("unexpected OAAP frame type: expected {expected}, got {actual}")] UnexpectedFrameType { /// Expected `oaap:*` type. expected: &'static str, /// Received type string. actual: String, }, /// A timeout expired waiting for a handshake response. #[error("OAAP handshake timed out at step {step} after {timeout_ms}ms")] HandshakeTimeout { /// Which step timed out. step: u8, /// Timeout duration in milliseconds. timeout_ms: u64, }, /// JSON serialization or deserialization failed. #[error("JSON error: {0}")] Json(#[from] serde_json::Error), /// The underlying WebSocket transport returned an error. #[error("WebSocket transport error: {0}")] Transport(String), /// A cryptographic operation failed during handshake or message processing. #[error("crypto error: {0}")] Crypto(#[from] openagent_crypto_wasm::CryptoError), /// Ed25519 signature verification failed on a handshake frame. #[error("OAAP authentication failed: {reason}")] AuthFailed { /// Why authentication was rejected. reason: String, }, /// The session has been invalidated or was never established. #[error("no active OAAP session")] NoSession, /// The session ID on an incoming message did not match the established session. #[error("session ID mismatch: expected {expected}, got {actual}")] SessionMismatch { /// Expected session ID (hex). expected: String, /// Received session ID (hex). actual: String, }, /// AEAD decryption of a message payload failed. #[error("message decryption failed: {0}")] DecryptionFailed(String), } ``` Source line: `9`. ## error::Result [#errorresult] Convenience alias. ```rust pub type Result = std::result::Result; ``` Source line: `79`. # openagent-ws · frame URL: https://docs.openagent.id/reference/rust/openagent-ws/frame Markdown: https://docs.openagent.id/reference/rust/openagent-ws/frame.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/frame.rs`. SHA-256: `1dd6eb684a375c0c9733fc171a312b0703495370fa7ed8cfc0a5ee9a886c250f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## frame::PresentFrame [#framepresentframe] Step 1: Client presents its DID and ephemeral X25519 public key. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PresentFrame { /// Always `"oaap:present"`. #[serde(rename = "type")] pub frame_type: String, /// The client's `did:oas:*` identifier. pub did: String, /// Client's ephemeral X25519 public key (hex-encoded, 64 chars). pub ephemeral_pub: String, /// Client's Ed25519 verifying key (hex-encoded, 64 chars). pub verifying_key: String, /// ISO-8601 timestamp of when the frame was created. pub timestamp: String } ``` Source line: `16`. ## frame::ChallengeFrame [#framechallengeframe] Step 2: Server responds with its own DID, ephemeral key, and a challenge nonce. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ChallengeFrame { /// Always `"oaap:challenge"`. #[serde(rename = "type")] pub frame_type: String, /// The server's `did:oas:*` identifier. pub did: String, /// Server's ephemeral X25519 public key (hex-encoded). pub ephemeral_pub: String, /// Server's Ed25519 verifying key (hex-encoded). pub verifying_key: String, /// Random challenge nonce (hex-encoded, 64 chars = 32 bytes). pub challenge: String, /// ISO-8601 timestamp. pub timestamp: String } ``` Source line: `32`. ## frame::ProveFrame [#frameproveframe] Step 3: Client proves identity by signing the challenge with its Ed25519 key. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProveFrame { /// Always `"oaap:prove"`. #[serde(rename = "type")] pub frame_type: String, /// Ed25519 signature over the challenge bytes (hex-encoded, 128 chars). pub signature: String, /// The challenge that was signed (echoed back for binding). pub challenge: String } ``` Source line: `50`. ## frame::EstablishedFrame [#frameestablishedframe] Step 4: Server confirms authentication and establishes the session. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EstablishedFrame { /// Always `"oaap:established"`. #[serde(rename = "type")] pub frame_type: String, /// The unique session identifier (hex-encoded, 32 bytes). pub session: String, /// Whether the session uses encrypted payloads. pub encrypted: bool, /// Ed25519 signature from the server over `session || client_ephemeral_pub` /// to prove the server is authentic (hex-encoded). pub signature: String } ``` Source line: `62`. ## frame::MessageFrame [#framemessageframe] Data frame sent after authentication is established. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MessageFrame { /// Always `"oaap:message"`. #[serde(rename = "type")] pub frame_type: String, /// Session identifier (hex-encoded). pub session: String, /// The payload — either plaintext (UTF-8) or base64-encoded ciphertext /// depending on whether the session is encrypted. pub payload: String, /// AES-256-GCM nonce (hex-encoded) — present only when encrypted. #[serde(skip_serializing_if = "Option::is_none")] pub nonce: Option, /// Monotonically increasing sequence number for replay protection. pub seq: u64 } ``` Source line: `79`. ## frame::TYPE\_PRESENT [#frametype_present] Wire value of the `type` field for \[`PresentFrame`] (handshake step 1). ```rust pub const TYPE_PRESENT: &str; ``` Source line: `107`. ## frame::TYPE\_CHALLENGE [#frametype_challenge] Wire value of the `type` field for \[`ChallengeFrame`] (handshake step 2). ```rust pub const TYPE_CHALLENGE: &str; ``` Source line: `109`. ## frame::TYPE\_PROVE [#frametype_prove] Wire value of the `type` field for \[`ProveFrame`] (handshake step 3). ```rust pub const TYPE_PROVE: &str; ``` Source line: `111`. ## frame::TYPE\_ESTABLISHED [#frametype_established] Wire value of the `type` field for \[`EstablishedFrame`] (handshake step 4). ```rust pub const TYPE_ESTABLISHED: &str; ``` Source line: `113`. ## frame::TYPE\_MESSAGE [#frametype_message] Wire value of the `type` field for \[`MessageFrame`] (post-handshake data). ```rust pub const TYPE_MESSAGE: &str; ``` Source line: `115`. # openagent-ws modules URL: https://docs.openagent.id/reference/rust/openagent-ws Markdown: https://docs.openagent.id/reference/rust/openagent-ws.md Public source declarations across the declared module tree. ## Task and package contract [#task-and-package-contract] [Package manifest, features, installation and entry points](/reference/packages/openagent-sdk-adapters-websocket-rust). [Focused integration guide](/integrations/adapters). ## Modules [#modules] * [crate](/reference/rust/openagent-ws/crate) — 11 declarations * [client](/reference/rust/openagent-ws/client) — 4 declarations * [error](/reference/rust/openagent-ws/error) — 2 declarations * [frame](/reference/rust/openagent-ws/frame) — 10 declarations * [server](/reference/rust/openagent-ws/server) — 5 declarations * [session](/reference/rust/openagent-ws/session) — 6 declarations * [transport](/reference/rust/openagent-ws/transport) — 5 declarations # openagent-ws · server URL: https://docs.openagent.id/reference/rust/openagent-ws/server Markdown: https://docs.openagent.id/reference/rust/openagent-ws/server.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/server.rs`. SHA-256: `3c53322097a362242fd8fbdab4d5b681606bb2c9f50a79a9d415da5013dbaf04`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## server::OpenAgentWsHandler [#serveropenagentwshandler] Server-side OAAP WebSocket handler. Holds the server's identity material. Call [`accept`](Self::accept) on each incoming WebSocket connection to run the 4-step authentication handshake. ```rust pub struct OpenAgentWsHandler { } ``` Source line: `32`. ## server::OpenAgentWsHandler::new [#serveropenagentwshandlernew] Creates a new handler with the server's identity. # Arguments [#arguments] * `did` — Server's `did:oas:*` identifier. * `signing_key` — 32-byte Ed25519 signing key. * `verifying_key` — 32-byte Ed25519 verifying key. ```rust pub fn new(did: impl Into, signing_key: [u8; 32], verifying_key: [u8; 32]) -> Self; ``` Source line: `48`. ## server::OpenAgentWsHandler::with\_encryption [#serveropenagentwshandlerwith_encryption] Sets whether sessions use encryption (default: `true`). ```rust pub fn with_encryption(mut self, encrypted: bool) -> Self; ``` Source line: `59`. ## server::OpenAgentWsHandler::with\_timeout [#serveropenagentwshandlerwith_timeout] Overrides the per-step handshake timeout (default: 5s). ```rust pub fn with_timeout(mut self, duration: Duration) -> Self; ``` Source line: `65`. ## server::OpenAgentWsHandler::accept [#serveropenagentwshandleraccept] Runs the 4-step OAAP handshake on an accepted WebSocket connection. Returns an \[`AuthenticatedSession`] on success. The caller should then use `session.send()` / `session.receive()` for all subsequent communication. # Errors [#errors] Returns \[`WsError`] if the handshake fails for any reason: timeout, unexpected frame, bad signature, transport error. ```rust pub async fn accept( &self, mut ws: WsServerStream, ) -> Result>; ``` Source line: `80`. # openagent-ws · session URL: https://docs.openagent.id/reference/rust/openagent-ws/session Markdown: https://docs.openagent.id/reference/rust/openagent-ws/session.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/session.rs`. SHA-256: `6a62576fb7175db89350d6f835a0a351a791eeaa23ac997d206d7bb3c5108b3f`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## session::AuthenticatedSession [#sessionauthenticatedsession] An authenticated WebSocket session with an optional encryption layer. Created by \[`crate::server::OpenAgentWsHandler::accept`] or \[`crate::client::OpenAgentWsClient::connect`] after a successful OAAP handshake. ```rust pub struct AuthenticatedSession { } ``` Source line: `34`. ## session::AuthenticatedSession\::session\_id\_hex [#sessionauthenticatedsessionssession_id_hex] Returns the hex-encoded session ID. ```rust pub fn session_id_hex(&self) -> String; ``` Source line: `108`. ## session::AuthenticatedSession\::peer\_did [#sessionauthenticatedsessionspeer_did] Returns the peer's DID. ```rust pub fn peer_did(&self) -> &str; ``` Source line: `113`. ## session::AuthenticatedSession\::is\_encrypted [#sessionauthenticatedsessionsis_encrypted] Returns whether this session uses encryption. ```rust pub fn is_encrypted(&self) -> bool; ``` Source line: `118`. ## session::AuthenticatedSession\::send [#sessionauthenticatedsessionssend] Sends a payload over the authenticated session. If the session was established with encryption, the payload is AES-256-GCM encrypted with a fresh random nonce. Otherwise, it is sent as plaintext. ```rust pub async fn send(&mut self, payload: &[u8]) -> Result<()>; ``` Source line: `133`. ## session::AuthenticatedSession\::receive [#sessionauthenticatedsessionsreceive] Receives the next message payload from the authenticated session. Validates session ID, verifies sequence ordering, and decrypts if the session is encrypted. ```rust pub async fn receive(&mut self) -> Result>; ``` Source line: `173`. # openagent-ws · transport URL: https://docs.openagent.id/reference/rust/openagent-ws/transport Markdown: https://docs.openagent.id/reference/rust/openagent-ws/transport.md Declared module signatures, types, configuration, and source documentation. Source: `openagent-sdk/adapters/websocket/rust/src/transport.rs`. SHA-256: `5d57dbb937bafb15a6c437c9b23cb383321f954c96469cb5d92ab2d3b49fb201`. This source reference follows declared modules and preserves feature attributes. It includes public declarations and implementation methods in those modules. Private-module exports and trait resolution still require the compiler; not every declaration is a crate-root import. Function bodies and constant values are omitted. Source comments describe their implementation context and are not a production deployment claim. ## transport::WsStream [#transportwsstream] The raw WebSocket stream type (over TCP, possibly TLS). ```rust pub type WsStream = WebSocketStream>; ``` Source line: `21`. ## transport::WsServerStream [#transportwsserverstream] The raw WebSocket stream type for a server-side accepted connection (plain TCP). ```rust pub type WsServerStream = WebSocketStream; ``` Source line: `24`. ## transport::OaapFrame [#transportoaapframe] Typed OAAP frames dispatched from the WebSocket. ```rust #[derive(Debug)] pub enum OaapFrame { /// Step 1: `oaap:present`. Present(PresentFrame), /// Step 2: `oaap:challenge`. Challenge(ChallengeFrame), /// Step 3: `oaap:prove`. Prove(ProveFrame), /// Step 4: `oaap:established`. Established(EstablishedFrame), /// Post-handshake data. Message(MessageFrame), } ``` Source line: `28`. ## transport::send\_frame [#transportsend_frame] Sends a serializable frame as a JSON text message. ```rust pub async fn send_frame(ws: &mut S, frame: &F) -> Result<()> where S: SinkExt + Unpin, S::Error: std::fmt::Display, F: serde::Serialize,; ``` Source line: `42`. ## transport::recv\_frame [#transportrecv_frame] Reads the next text frame from the WebSocket, deserializes and dispatches it. Binary frames are silently skipped. Ping/Pong are handled by tungstenite automatically. Close frames cause \[`WsError::HandshakeClosed`] with step = 0. ```rust pub async fn recv_frame(ws: &mut S) -> Result where S: StreamExt> + Unpin,; ``` Source line: `59`.