agent-enrollment-protocol 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/PKG-INFO +84 -1
  2. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/README.md +83 -0
  3. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/pyproject.toml +5 -5
  4. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/__init__.py +3 -0
  5. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/client.py +16 -10
  6. agent_enrollment_protocol-0.3.0/src/agent_enrollment_protocol/agent/documents.py +70 -0
  7. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/types.py +7 -0
  8. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/__init__.py +16 -0
  9. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/constants.py +17 -0
  10. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/models.py +147 -2
  11. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/validation.py +17 -1
  12. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/service/service.py +147 -17
  13. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/service/types.py +10 -3
  14. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/.gitignore +0 -0
  15. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/LICENSE +0 -0
  16. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/examples/README.md +0 -0
  17. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/examples/agent_service.py +0 -0
  18. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/examples/hosted_platform.py +0 -0
  19. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/__init__.py +0 -0
  20. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/adapters/__init__.py +0 -0
  21. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/adapters/asgi.py +0 -0
  22. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/platform_provider.py +0 -0
  23. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/protected_resource.py +0 -0
  24. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/stores.py +0 -0
  25. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/agent/transport.py +0 -0
  26. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/assertions.py +0 -0
  27. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/claims.py +0 -0
  28. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/did_web.py +0 -0
  29. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/errors.py +0 -0
  30. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/http.py +0 -0
  31. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/inspect.py +0 -0
  32. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/core/openapi.py +0 -0
  33. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/platform/__init__.py +0 -0
  34. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/platform/document.py +0 -0
  35. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/platform/platform.py +0 -0
  36. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/platform/stores.py +0 -0
  37. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/platform/types.py +0 -0
  38. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/py.typed +0 -0
  39. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/service/__init__.py +0 -0
  40. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/service/credentials.py +0 -0
  41. {agent_enrollment_protocol-0.2.0 → agent_enrollment_protocol-0.3.0}/src/agent_enrollment_protocol/service/stores.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agent-enrollment-protocol
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Official Python SDK for the Agent Enrollment Protocol
5
5
  Project-URL: Documentation, https://www.aep.foundation/
6
6
  Project-URL: Issues, https://github.com/aep-foundation/aep-python/issues
@@ -274,6 +274,89 @@ the identity owner's credentials. Authorize that relationship explicitly rather
274
274
  every authenticated caller to verify every identity. Signing and identity management retain their
275
275
  owner checks.
276
276
 
277
+ ## Enrollment policy decisions
278
+
279
+ Policy callbacks receive the request and current time. They consult their own authoritative storage when needed; the SDK does not supply an existing-enrollment hint.
280
+
281
+ `EnrollmentDecision.owner_action_required`, `requirements_pending`, and `verification_pending` are optional. On initial enrollment, `None` defaults to false or an empty tuple. On repeated enrollment, `None` preserves the stored field; explicit booleans and tuples replace it, including `False` and `()` to clear it. Stored enrollment fields remain concrete values.
282
+
283
+ Repeated Enroll merges supplied claims without replacing the enrollment identity, creation time, lifecycle state, or issued credentials. Return `EnrollmentDecision(update_existing=False)` to leave the record unchanged, or a rejected decision to reject the request without mutating the record. Same-key retries replay their result without repeating policy effects.
284
+
285
+ ## Service Documents
286
+
287
+ Services advertise document descriptors through `ServiceOptions.service_documents` and include
288
+ `AEP_SERVICE_DOCUMENTS_EXTENSION` in `ServiceOptions.extensions`. Import the constant and models
289
+ from `agent_enrollment_protocol.core`:
290
+
291
+ ```python
292
+ from agent_enrollment_protocol.core import (
293
+ AEP_SERVICE_DOCUMENTS_EXTENSION,
294
+ DocumentRepresentation,
295
+ ServiceDocument,
296
+ )
297
+
298
+ terms = ServiceDocument(
299
+ id="terms",
300
+ type="terms_of_service",
301
+ title="Terms of service",
302
+ enrollment="required",
303
+ representations=(
304
+ DocumentRepresentation(media_type="text/html", url="https://service.example/terms"),
305
+ DocumentRepresentation(
306
+ media_type="application/json", url="https://service.example/terms.json"
307
+ ),
308
+ ),
309
+ )
310
+ # Include these in the application's ServiceOptions, alongside its verifier and stores:
311
+ # extensions=(AEP_SERVICE_DOCUMENTS_EXTENSION,), service_documents=(terms,)
312
+ ```
313
+
314
+ Inspect exposes at most seven documents with unique, case-sensitive IDs of up to 32 ASCII
315
+ characters. Each descriptor requires an HTML link. `SERVICE_DOCUMENT_TYPES` lists preferred type
316
+ names; custom lowercase type strings are supported. A `not-required` document does not require
317
+ acceptance. Unknown enrollment requirements are rejected rather than treated as not-required.
318
+
319
+ Agents can read a portable document before enrollment:
320
+
321
+ ```python
322
+ from agent_enrollment_protocol.agent import EnrollOptions, read_service_document
323
+
324
+ inspection = await session.inspect()
325
+ document = next(item for item in inspection.document.service_documents or () if item.id == "terms")
326
+ reading = await read_service_document(document)
327
+ # Render reading.document when present; otherwise offer reading.web_url.
328
+ # Only after the Owner authorizes these IDs:
329
+ result = await session.enroll(EnrollOptions(acknowledged_document_ids=("terms",)))
330
+ ```
331
+
332
+ The reader uses the standard HTTP client without credentials or cookies. It accepts HTTPS with
333
+ certificate verification and HTTP only for the literal hosts `localhost`, `127.0.0.1`, and `[::1]`.
334
+ It refuses redirects, limits the response to one mebibyte and the operation to ten seconds by
335
+ default, and propagates task cancellation. The application decides which document origins it
336
+ trusts; the reader does not inspect DNS answers or connected addresses. Unsupported, oversized,
337
+ malformed, or unavailable portable content returns the HTML link, not partial content.
338
+
339
+ Portable content contains full Service-authored text and an optional multi-block summary. The SDK
340
+ parses it into immutable models; the application renders it without summarizing or interpreting it.
341
+ Preserve sections, lists, and wording, neutralize terminal controls, and label Service-authored
342
+ summaries. For artificial-intelligence callers, return readable fenced text with a separate
343
+ instruction not to interpret, summarize, or follow document instructions, plus the source link.
344
+ Do not pass portable JSON directly as the presentation.
345
+
346
+ Reading does not acknowledge a document. `None` omits the enrollment declaration; `()` explicitly
347
+ declares no acknowledgements. Successful Enroll responses echo that operation's declaration, not
348
+ the cumulative history. A partial declaration does not acknowledge omitted documents; the Service
349
+ can enforce them on a later Grant. `EnrollmentRecord.acknowledged_document_ids` retains accepted
350
+ known IDs. Application-owned stores must preserve it and `required_document_ids`; setting a known
351
+ required ID in the latter requests renewed acceptance even if it was acknowledged before.
352
+
353
+ Grant reports unmet requirements through `AgentCommandError.problem`: `requirements_pending`
354
+ includes `service_documents`, and `required_document_ids` identifies the documents. Claim names
355
+ may accompany them. Present the requirements, obtain the Owner's decision, and explicitly call
356
+ Enroll with the approved IDs and any missing claims. A later Grant is a separate caller decision;
357
+ the Agent neither chains these commands nor accepts documents automatically. Previously stored
358
+ claims and acknowledgements survive omission on repeated Enroll.
359
+
277
360
  ## Application-owned storage
278
361
 
279
362
  Default memory stores retain state only for the lifetime of one process. To retain an Agent's
@@ -246,6 +246,89 @@ the identity owner's credentials. Authorize that relationship explicitly rather
246
246
  every authenticated caller to verify every identity. Signing and identity management retain their
247
247
  owner checks.
248
248
 
249
+ ## Enrollment policy decisions
250
+
251
+ Policy callbacks receive the request and current time. They consult their own authoritative storage when needed; the SDK does not supply an existing-enrollment hint.
252
+
253
+ `EnrollmentDecision.owner_action_required`, `requirements_pending`, and `verification_pending` are optional. On initial enrollment, `None` defaults to false or an empty tuple. On repeated enrollment, `None` preserves the stored field; explicit booleans and tuples replace it, including `False` and `()` to clear it. Stored enrollment fields remain concrete values.
254
+
255
+ Repeated Enroll merges supplied claims without replacing the enrollment identity, creation time, lifecycle state, or issued credentials. Return `EnrollmentDecision(update_existing=False)` to leave the record unchanged, or a rejected decision to reject the request without mutating the record. Same-key retries replay their result without repeating policy effects.
256
+
257
+ ## Service Documents
258
+
259
+ Services advertise document descriptors through `ServiceOptions.service_documents` and include
260
+ `AEP_SERVICE_DOCUMENTS_EXTENSION` in `ServiceOptions.extensions`. Import the constant and models
261
+ from `agent_enrollment_protocol.core`:
262
+
263
+ ```python
264
+ from agent_enrollment_protocol.core import (
265
+ AEP_SERVICE_DOCUMENTS_EXTENSION,
266
+ DocumentRepresentation,
267
+ ServiceDocument,
268
+ )
269
+
270
+ terms = ServiceDocument(
271
+ id="terms",
272
+ type="terms_of_service",
273
+ title="Terms of service",
274
+ enrollment="required",
275
+ representations=(
276
+ DocumentRepresentation(media_type="text/html", url="https://service.example/terms"),
277
+ DocumentRepresentation(
278
+ media_type="application/json", url="https://service.example/terms.json"
279
+ ),
280
+ ),
281
+ )
282
+ # Include these in the application's ServiceOptions, alongside its verifier and stores:
283
+ # extensions=(AEP_SERVICE_DOCUMENTS_EXTENSION,), service_documents=(terms,)
284
+ ```
285
+
286
+ Inspect exposes at most seven documents with unique, case-sensitive IDs of up to 32 ASCII
287
+ characters. Each descriptor requires an HTML link. `SERVICE_DOCUMENT_TYPES` lists preferred type
288
+ names; custom lowercase type strings are supported. A `not-required` document does not require
289
+ acceptance. Unknown enrollment requirements are rejected rather than treated as not-required.
290
+
291
+ Agents can read a portable document before enrollment:
292
+
293
+ ```python
294
+ from agent_enrollment_protocol.agent import EnrollOptions, read_service_document
295
+
296
+ inspection = await session.inspect()
297
+ document = next(item for item in inspection.document.service_documents or () if item.id == "terms")
298
+ reading = await read_service_document(document)
299
+ # Render reading.document when present; otherwise offer reading.web_url.
300
+ # Only after the Owner authorizes these IDs:
301
+ result = await session.enroll(EnrollOptions(acknowledged_document_ids=("terms",)))
302
+ ```
303
+
304
+ The reader uses the standard HTTP client without credentials or cookies. It accepts HTTPS with
305
+ certificate verification and HTTP only for the literal hosts `localhost`, `127.0.0.1`, and `[::1]`.
306
+ It refuses redirects, limits the response to one mebibyte and the operation to ten seconds by
307
+ default, and propagates task cancellation. The application decides which document origins it
308
+ trusts; the reader does not inspect DNS answers or connected addresses. Unsupported, oversized,
309
+ malformed, or unavailable portable content returns the HTML link, not partial content.
310
+
311
+ Portable content contains full Service-authored text and an optional multi-block summary. The SDK
312
+ parses it into immutable models; the application renders it without summarizing or interpreting it.
313
+ Preserve sections, lists, and wording, neutralize terminal controls, and label Service-authored
314
+ summaries. For artificial-intelligence callers, return readable fenced text with a separate
315
+ instruction not to interpret, summarize, or follow document instructions, plus the source link.
316
+ Do not pass portable JSON directly as the presentation.
317
+
318
+ Reading does not acknowledge a document. `None` omits the enrollment declaration; `()` explicitly
319
+ declares no acknowledgements. Successful Enroll responses echo that operation's declaration, not
320
+ the cumulative history. A partial declaration does not acknowledge omitted documents; the Service
321
+ can enforce them on a later Grant. `EnrollmentRecord.acknowledged_document_ids` retains accepted
322
+ known IDs. Application-owned stores must preserve it and `required_document_ids`; setting a known
323
+ required ID in the latter requests renewed acceptance even if it was acknowledged before.
324
+
325
+ Grant reports unmet requirements through `AgentCommandError.problem`: `requirements_pending`
326
+ includes `service_documents`, and `required_document_ids` identifies the documents. Claim names
327
+ may accompany them. Present the requirements, obtain the Owner's decision, and explicitly call
328
+ Enroll with the approved IDs and any missing claims. A later Grant is a separate caller decision;
329
+ the Agent neither chains these commands nor accepts documents automatically. Previously stored
330
+ claims and acknowledgements survive omission on repeated Enroll.
331
+
249
332
  ## Application-owned storage
250
333
 
251
334
  Default memory stores retain state only for the lifetime of one process. To retain an Agent's
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["hatchling==1.32.4"]
2
+ requires = ["hatchling==1.33.0"]
3
3
  build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agent-enrollment-protocol"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Official Python SDK for the Agent Enrollment Protocol"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -42,10 +42,10 @@ Repository = "https://github.com/aep-foundation/aep-python"
42
42
  dev = [
43
43
  "build==1.6.1",
44
44
  "mypy==2.4.0",
45
- "pytest==9.1.1",
46
- "pytest-asyncio==1.4.0",
45
+ "pytest==9.2.0",
46
+ "pytest-asyncio==1.4.1",
47
47
  "pytest-cov==7.1.0",
48
- "ruff==0.16.10",
48
+ "ruff==0.17.3",
49
49
  "twine==7.0.0",
50
50
  "uvicorn==0.54.0",
51
51
  ]
@@ -1,6 +1,7 @@
1
1
  """Agent-side enrollment, credential, and authentication workflows."""
2
2
 
3
3
  from .client import Agent, AgentOptions, ServiceSession
4
+ from .documents import DocumentReadResult, read_service_document
4
5
  from .platform_provider import (
5
6
  MemoryPlatformDiscoveryCache,
6
7
  PlatformAuthenticationHeaders,
@@ -64,6 +65,7 @@ __all__ = [
64
65
  "CredentialRecord",
65
66
  "CredentialStore",
66
67
  "CredentialUnavailableError",
68
+ "DocumentReadResult",
67
69
  "EnrollOptions",
68
70
  "EnrollmentStateError",
69
71
  "ExistingIdentityProvider",
@@ -100,4 +102,5 @@ __all__ = [
100
102
  "ServiceSession",
101
103
  "WaitOptions",
102
104
  "fetch_protected_resource",
105
+ "read_service_document",
103
106
  ]
@@ -15,6 +15,7 @@ from agent_enrollment_protocol.core import (
15
15
  AEP_AUTHENTICATION_METHOD_JWT,
16
16
  AEP_MEDIA_TYPE,
17
17
  AEP_PROBLEM_MEDIA_TYPE,
18
+ AEP_SERVICE_DOCUMENTS_EXTENSION,
18
19
  AEP_WELL_KNOWN_PATH,
19
20
  AepAssertionError,
20
21
  AepValidationError,
@@ -42,7 +43,6 @@ from agent_enrollment_protocol.core import (
42
43
  decode_jwt_unverified,
43
44
  did_web_document_url,
44
45
  media_type_essence,
45
- missing_required_claim_names,
46
46
  parse_json_model,
47
47
  render_authorization,
48
48
  require_service_origin_binding,
@@ -63,7 +63,6 @@ from .types import (
63
63
  AssertionSigner,
64
64
  AuthenticationOptions,
65
65
  BuiltInCredential,
66
- ClaimRequirementsError,
67
66
  CommandResult,
68
67
  CredentialRecord,
69
68
  CredentialStore,
@@ -295,14 +294,12 @@ class ServiceSession:
295
294
  async def enroll(self, options: EnrollOptions | None = None) -> CommandResult[EnrollResponse]:
296
295
  options = options or EnrollOptions()
297
296
  inspection, identity, signer = await self._command_context(Command.ENROLL)
298
- required = (
299
- inspection.document.claims.required
300
- if inspection.document.claims and inspection.document.claims.required
301
- else ()
302
- )
303
- missing = missing_required_claim_names(required, options.claims)
304
- if missing:
305
- raise ClaimRequirementsError(missing)
297
+ if options.acknowledged_document_ids is not None and (
298
+ inspection.document.extensions is None
299
+ or AEP_SERVICE_DOCUMENTS_EXTENSION
300
+ not in (inspection.document.extensions.supported or ())
301
+ ):
302
+ raise ValueError("Service does not advertise the Service Documents extension")
306
303
  key = await self._idempotency_key(inspection, Command.ENROLL.value, options.idempotency_key)
307
304
  request_data: dict[str, object] = {
308
305
  "agent_did": identity.agent_did,
@@ -310,6 +307,8 @@ class ServiceSession:
310
307
  }
311
308
  if options.claims is not None:
312
309
  request_data["claims"] = options.claims
310
+ if options.acknowledged_document_ids is not None:
311
+ request_data["acknowledged_document_ids"] = options.acknowledged_document_ids
313
312
  request = EnrollRequest.model_validate(request_data)
314
313
  result = await self._execute(
315
314
  inspection,
@@ -321,6 +320,13 @@ class ServiceSession:
321
320
  key,
322
321
  _parse_enroll_response,
323
322
  )
323
+ if (
324
+ result.body.status is not AgentStatus.REJECTED
325
+ and result.body.acknowledged_document_ids != options.acknowledged_document_ids
326
+ ):
327
+ raise AgentCommandError(
328
+ result.status, "AEP document acknowledgement does not match the request"
329
+ )
324
330
  self._authoritative_active_enrollment = result.body.status is AgentStatus.ACTIVE
325
331
  return result
326
332
 
@@ -0,0 +1,70 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import math
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ import httpx
9
+
10
+ from agent_enrollment_protocol.core import (
11
+ MAX_SERVICE_DOCUMENT_BYTES,
12
+ AepValidationError,
13
+ PortableServiceDocument,
14
+ ServiceDocument,
15
+ media_type_essence,
16
+ parse_portable_service_document,
17
+ )
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class DocumentReadResult:
22
+ descriptor: ServiceDocument
23
+ web_url: str
24
+ document: PortableServiceDocument | None = None
25
+ reason: Literal["not_advertised", "unavailable_or_unsupported"] | None = None
26
+
27
+
28
+ async def read_service_document(
29
+ descriptor: ServiceDocument, *, timeout: float = 10
30
+ ) -> DocumentReadResult:
31
+ if not math.isfinite(timeout) or timeout <= 0:
32
+ raise ValueError("document timeout must be positive and finite")
33
+ descriptor = ServiceDocument.model_validate(descriptor.to_wire())
34
+ web_url = next(
35
+ item.url for item in descriptor.representations if item.media_type == "text/html"
36
+ )
37
+ portable_url = next(
38
+ (item.url for item in descriptor.representations if item.media_type == "application/json"),
39
+ None,
40
+ )
41
+ if portable_url is None:
42
+ return DocumentReadResult(descriptor, web_url, reason="not_advertised")
43
+ try:
44
+ async with asyncio.timeout(timeout), httpx.AsyncClient(follow_redirects=False) as client:
45
+ request = httpx.Request(
46
+ "GET",
47
+ portable_url,
48
+ headers={"Accept": "application/json", "Accept-Encoding": "identity"},
49
+ )
50
+ response = await client.send(request, auth=None, follow_redirects=False, stream=True)
51
+ try:
52
+ if (
53
+ not response.is_success
54
+ or media_type_essence(response.headers.get("content-type", ""))
55
+ != "application/json"
56
+ or response.charset_encoding not in (None, "utf-8", "UTF-8")
57
+ or response.headers.get("content-encoding", "identity").lower() != "identity"
58
+ ):
59
+ raise ValueError("unsupported document response")
60
+ body = bytearray()
61
+ async for chunk in response.aiter_raw():
62
+ if len(body) + len(chunk) > MAX_SERVICE_DOCUMENT_BYTES:
63
+ raise ValueError("document exceeds one mebibyte")
64
+ body.extend(chunk)
65
+ document = parse_portable_service_document(bytes(body), descriptor.id)
66
+ return DocumentReadResult(descriptor, web_url, document=document)
67
+ finally:
68
+ await response.aclose()
69
+ except (TimeoutError, httpx.HTTPError, httpx.InvalidURL, ValueError, AepValidationError):
70
+ return DocumentReadResult(descriptor, web_url, reason="unavailable_or_unsupported")
@@ -148,6 +148,13 @@ class CommandResult(Generic[ResultT]):
148
148
  class EnrollOptions:
149
149
  claims: ClaimValues | None = None
150
150
  idempotency_key: str | None = None
151
+ acknowledged_document_ids: tuple[str, ...] | None = None
152
+
153
+ def __post_init__(self) -> None:
154
+ if self.acknowledged_document_ids is not None:
155
+ object.__setattr__(
156
+ self, "acknowledged_document_ids", tuple(self.acknowledged_document_ids)
157
+ )
151
158
 
152
159
 
153
160
  @dataclass(frozen=True, slots=True)
@@ -31,11 +31,14 @@ from .constants import (
31
31
  AEP_MEDIA_TYPE,
32
32
  AEP_PLATFORM_WELL_KNOWN_PATH,
33
33
  AEP_PROBLEM_MEDIA_TYPE,
34
+ AEP_SERVICE_DOCUMENTS_EXTENSION,
34
35
  AEP_SIGNING_ALGORITHMS,
35
36
  AEP_VERSION,
36
37
  AEP_WELL_KNOWN_PATH,
37
38
  DEFAULT_HTTP_ENDPOINT_BASE,
38
39
  MAX_ASSERTION_LIFETIME_SECONDS,
40
+ MAX_SERVICE_DOCUMENT_BYTES,
41
+ SERVICE_DOCUMENT_TYPES,
39
42
  )
40
43
  from .did_web import did_web_document_url, select_did_web_public_jwk
41
44
  from .errors import (
@@ -77,6 +80,7 @@ from .models import (
77
80
  Commands,
78
81
  ContactAddressPrimary,
79
82
  CoreConfiguration,
83
+ DocumentRepresentation,
80
84
  EnrollmentDecisionStatus,
81
85
  EnrollRequest,
82
86
  EnrollResponse,
@@ -112,10 +116,13 @@ from .models import (
112
116
  PlatformSignResponse,
113
117
  PlatformVerificationRequest,
114
118
  PlatformVerificationResponse,
119
+ PortableDocumentBlock,
120
+ PortableServiceDocument,
115
121
  ProblemDetails,
116
122
  ProtectedResourceAuthorization,
117
123
  RevokeRequest,
118
124
  RevokeResponse,
125
+ ServiceDocument,
119
126
  ServiceIdentity,
120
127
  SigningAlgorithm,
121
128
  StatusResponse,
@@ -132,6 +139,7 @@ from .validation import (
132
139
  ValidationResult,
133
140
  parse_json_model,
134
141
  parse_platform_sign_response,
142
+ parse_portable_service_document,
135
143
  validate_json_model,
136
144
  )
137
145
 
@@ -159,11 +167,14 @@ __all__ = [
159
167
  "AEP_MEDIA_TYPE",
160
168
  "AEP_PLATFORM_WELL_KNOWN_PATH",
161
169
  "AEP_PROBLEM_MEDIA_TYPE",
170
+ "AEP_SERVICE_DOCUMENTS_EXTENSION",
162
171
  "AEP_SIGNING_ALGORITHMS",
163
172
  "AEP_VERSION",
164
173
  "AEP_WELL_KNOWN_PATH",
165
174
  "DEFAULT_HTTP_ENDPOINT_BASE",
166
175
  "MAX_ASSERTION_LIFETIME_SECONDS",
176
+ "MAX_SERVICE_DOCUMENT_BYTES",
177
+ "SERVICE_DOCUMENT_TYPES",
167
178
  "AepAssertionError",
168
179
  "AepAuthorizationError",
169
180
  "AepError",
@@ -183,6 +194,7 @@ __all__ = [
183
194
  "Commands",
184
195
  "ContactAddressPrimary",
185
196
  "CoreConfiguration",
197
+ "DocumentRepresentation",
186
198
  "EnrollRequest",
187
199
  "EnrollResponse",
188
200
  "EnrollmentDecisionStatus",
@@ -223,10 +235,13 @@ __all__ = [
223
235
  "PlatformSigningConfiguration",
224
236
  "PlatformVerificationRequest",
225
237
  "PlatformVerificationResponse",
238
+ "PortableDocumentBlock",
239
+ "PortableServiceDocument",
226
240
  "ProblemDetails",
227
241
  "ProtectedResourceAuthorization",
228
242
  "RevokeRequest",
229
243
  "RevokeResponse",
244
+ "ServiceDocument",
230
245
  "ServiceIdentity",
231
246
  "SigningAlgorithm",
232
247
  "StatusResponse",
@@ -248,6 +263,7 @@ __all__ = [
248
263
  "parse_authorization",
249
264
  "parse_json_model",
250
265
  "parse_platform_sign_response",
266
+ "parse_portable_service_document",
251
267
  "render_authorization",
252
268
  "require_service_origin_binding",
253
269
  "resolve_openapi_security",
@@ -9,6 +9,23 @@ AEP_AUTHORIZATION_HEADER: Final = "AEP-Authorization"
9
9
  AEP_WELL_KNOWN_PATH: Final = "/.well-known/aep"
10
10
  DEFAULT_HTTP_ENDPOINT_BASE: Final = "/aep/"
11
11
  MAX_ASSERTION_LIFETIME_SECONDS: Final = 300
12
+ AEP_SERVICE_DOCUMENTS_EXTENSION: Final = "urn:aep:ext:aep-foundation:service-documents#v=1.0.0"
13
+ MAX_SERVICE_DOCUMENT_BYTES: Final = 1 << 20
14
+ SERVICE_DOCUMENT_TYPES: Final = (
15
+ "acceptable_use_policy",
16
+ "age_or_parental_consent",
17
+ "ai_data_use_policy",
18
+ "community_guidelines",
19
+ "cookie_policy",
20
+ "data_processing_agreement",
21
+ "data_retention_notice",
22
+ "electronic_signature_consent",
23
+ "privacy_policy",
24
+ "security_policy",
25
+ "subscription_terms",
26
+ "supplemental_terms",
27
+ "terms_of_service",
28
+ )
12
29
 
13
30
  AEP_COMMANDS: Final = ("inspect", "enroll", "grant", "revoke", "status")
14
31
  AEP_AUTHENTICATED_COMMANDS: Final = ("enroll", "grant", "revoke", "status")
@@ -9,6 +9,7 @@ from typing import Annotated, Any, ClassVar, Literal, Self
9
9
  from urllib.parse import urlsplit, urlunsplit
10
10
 
11
11
  from pydantic import (
12
+ AfterValidator,
12
13
  BaseModel,
13
14
  BeforeValidator,
14
15
  ConfigDict,
@@ -17,7 +18,7 @@ from pydantic import (
17
18
  model_validator,
18
19
  )
19
20
 
20
- from .constants import AEP_SIGNING_ALGORITHMS, AEP_VERSION
21
+ from .constants import AEP_SERVICE_DOCUMENTS_EXTENSION, AEP_SIGNING_ALGORITHMS, AEP_VERSION
21
22
 
22
23
  IDENTIFIER_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
23
24
  CLAIM_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$")
@@ -285,6 +286,129 @@ class ServiceIdentity(AepModel):
285
286
  return self
286
287
 
287
288
 
289
+ def _document_ids(values: tuple[str, ...]) -> tuple[str, ...]:
290
+ if (
291
+ len(values) > 7
292
+ or len(set(values)) != len(values)
293
+ or any(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}", value) is None for value in values)
294
+ ):
295
+ raise ValueError("expected at most seven unique document IDs of 1 to 32 ASCII characters")
296
+ return values
297
+
298
+
299
+ DocumentIds = Annotated[StringTuple, AfterValidator(_document_ids)]
300
+
301
+
302
+ DocumentTitle = Annotated[str, Field(min_length=1, max_length=256)]
303
+ DocumentText = Annotated[str, Field(min_length=1, max_length=16384)]
304
+ DocumentId = Annotated[str, Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9._-]{0,31}\z")]
305
+
306
+
307
+ class DocumentRepresentation(AepModel):
308
+ media_type: str = Field(pattern=r"^[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*\z")
309
+ url: str = Field(min_length=1, max_length=2048)
310
+
311
+ @model_validator(mode="after")
312
+ def validate_url(self) -> Self:
313
+ if not self.url.isascii() or any(ord(char) <= 32 or char in "\\\x7f" for char in self.url):
314
+ raise ValueError("document URL must be an ASCII URI without controls")
315
+ parsed = urlsplit(self.url)
316
+ if (
317
+ not parsed.hostname
318
+ or parsed.username is not None
319
+ or parsed.password is not None
320
+ or (
321
+ parsed.scheme != "https"
322
+ and not (
323
+ parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
324
+ )
325
+ )
326
+ ):
327
+ raise ValueError("document URL requires HTTPS or literal-loopback HTTP")
328
+ return self
329
+
330
+
331
+ class ServiceDocument(AepModel):
332
+ id: DocumentId
333
+ type: str = Field(min_length=1, max_length=64, pattern=r"^[a-z][a-z0-9_]*\z")
334
+ title: DocumentTitle
335
+ enrollment: Literal["required", "not-required"]
336
+ representations: Annotated[tuple[DocumentRepresentation, ...], BeforeValidator(_as_tuple)] = (
337
+ Field(min_length=1, max_length=8)
338
+ )
339
+
340
+ @model_validator(mode="after")
341
+ def validate_representations(self) -> Self:
342
+ media = [item.media_type for item in self.representations]
343
+ if "text/html" not in media or len(set(media)) != len(media):
344
+ raise ValueError("representations require HTML and distinct media types")
345
+ return self
346
+
347
+
348
+ class PortableDocumentBlock(AepModel):
349
+ type: Literal["paragraph", "section", "bulleted_list", "numbered_list"]
350
+ text: DocumentText | None = None
351
+ title: DocumentTitle | None = None
352
+ blocks: Annotated[tuple[PortableDocumentBlock, ...], BeforeValidator(_as_tuple)] | None = Field(
353
+ default=None, min_length=1
354
+ )
355
+ items: Annotated[tuple[DocumentText, ...], BeforeValidator(_as_tuple)] | None = Field(
356
+ default=None, min_length=1, max_length=128
357
+ )
358
+
359
+ @model_validator(mode="before")
360
+ @classmethod
361
+ def ignore_other_block_members(cls, value: Any) -> Any:
362
+ if not isinstance(value, dict):
363
+ return value
364
+ kind = value.get("type")
365
+ ignored = (
366
+ {"title", "blocks", "items"}
367
+ if kind == "paragraph"
368
+ else {"text", "items"}
369
+ if kind == "section"
370
+ else {"text", "title", "blocks"}
371
+ if kind in ("bulleted_list", "numbered_list")
372
+ else set()
373
+ )
374
+ return {key: item for key, item in value.items() if key not in ignored}
375
+
376
+ @model_validator(mode="after")
377
+ def validate_block(self) -> Self:
378
+ if self.type == "paragraph" and self.text is None:
379
+ raise ValueError("paragraph requires text")
380
+ if self.type == "section" and (self.title is None or self.blocks is None):
381
+ raise ValueError("section requires title and blocks")
382
+ if self.type in {"bulleted_list", "numbered_list"} and self.items is None:
383
+ raise ValueError("list requires items")
384
+ return self
385
+
386
+
387
+ class PortableServiceDocument(AepModel):
388
+ format: Literal["aep-service-document"]
389
+ version: Literal["1.0"]
390
+ id: DocumentId
391
+ summary: Annotated[tuple[PortableDocumentBlock, ...], BeforeValidator(_as_tuple)] | None = (
392
+ Field(default=None, min_length=1)
393
+ )
394
+ content: Annotated[tuple[PortableDocumentBlock, ...], BeforeValidator(_as_tuple)] = Field(
395
+ min_length=1
396
+ )
397
+
398
+ @model_validator(mode="after")
399
+ def validate_bounds(self) -> Self:
400
+ pending = [(item, 0) for item in (*(self.summary or ()), *self.content)]
401
+ count = 0
402
+ while pending:
403
+ block, depth = pending.pop()
404
+ count += 1
405
+ if count > 1024 or (block.type == "section" and depth >= 8):
406
+ raise ValueError("portable documents allow 1024 blocks and eight nested sections")
407
+ if block.type == "section":
408
+ pending.extend((item, depth + 1) for item in (block.blocks or ()))
409
+ return self
410
+
411
+
288
412
  class InspectDocument(AepModel):
289
413
  aep_version: str
290
414
  authentication: Authentication | None = None
@@ -296,9 +420,18 @@ class InspectDocument(AepModel):
296
420
  http: HttpConfiguration
297
421
  identity: Identity
298
422
  service: ServiceIdentity
423
+ service_documents: Annotated[tuple[ServiceDocument, ...], BeforeValidator(_as_tuple)] | None = (
424
+ Field(default=None, min_length=1, max_length=7)
425
+ )
299
426
 
300
427
  @model_validator(mode="after")
301
428
  def validate_document(self) -> Self:
429
+ if self.service_documents is not None:
430
+ _document_ids(tuple(item.id for item in self.service_documents))
431
+ if self.extensions is None or AEP_SERVICE_DOCUMENTS_EXTENSION not in (
432
+ self.extensions.supported or ()
433
+ ):
434
+ raise ValueError("Service Documents extension must be advertised")
302
435
  if VERSION_PATTERN.fullmatch(self.aep_version) is None:
303
436
  raise ValueError("aep_version must use major.minor syntax")
304
437
  if self.aep_version.split(".", 1)[0] != AEP_VERSION.split(".", 1)[0]:
@@ -377,6 +510,7 @@ class EnrollRequest(AepModel):
377
510
  agent_did: str = Field(min_length=1)
378
511
  claims: ClaimValues | None = None
379
512
  idempotency_key: str | None = Field(default=None, min_length=1)
513
+ acknowledged_document_ids: DocumentIds | None = None
380
514
 
381
515
 
382
516
  class LifecycleResponse(AepModel):
@@ -403,7 +537,7 @@ class LifecycleResponse(AepModel):
403
537
 
404
538
 
405
539
  class EnrollResponse(LifecycleResponse):
406
- pass
540
+ acknowledged_document_ids: DocumentIds | None = None
407
541
 
408
542
 
409
543
  class StatusResponse(LifecycleResponse):
@@ -488,9 +622,20 @@ class ProblemDetails(AepModel):
488
622
  owner_action_required: Literal["true"] | None = None
489
623
  verification_pending: StringTuple | None = None
490
624
  requirements_pending: StringTuple | None = None
625
+ required_document_ids: DocumentIds | None = None
491
626
 
492
627
  @model_validator(mode="after")
493
628
  def validate_problem(self) -> Self:
629
+ documents_pending = "service_documents" in (self.requirements_pending or ())
630
+ if (self.required_document_ids is not None or documents_pending) and (
631
+ not self.required_document_ids
632
+ or not documents_pending
633
+ or self.code != "requirements_unmet"
634
+ or self.status != 422
635
+ ):
636
+ raise ValueError(
637
+ "document requirements need IDs, service_documents and HTTP 422 requirements_unmet"
638
+ )
494
639
  if ERROR_CODE_PATTERN.fullmatch(self.code) is None:
495
640
  raise ValueError("code must use the registered AEP error-code syntax")
496
641
  if self.type != f"urn:aep:error:{self.code}":
@@ -6,8 +6,9 @@ from typing import Any, Generic, TypeVar, cast
6
6
 
7
7
  from pydantic import BaseModel, TypeAdapter, ValidationError
8
8
 
9
+ from .constants import MAX_SERVICE_DOCUMENT_BYTES
9
10
  from .errors import AepValidationError, ValidationIssue, validation_issues
10
- from .models import PlatformSignResponse
11
+ from .models import PlatformSignResponse, PortableServiceDocument
11
12
 
12
13
  ModelT = TypeVar("ModelT", bound=BaseModel)
13
14
  ValueT = TypeVar("ValueT")
@@ -49,6 +50,21 @@ def parse_platform_sign_response(data: str | bytes) -> PlatformSignResponse:
49
50
  )
50
51
 
51
52
 
53
+ def parse_portable_service_document(data: bytes, expected_id: str) -> PortableServiceDocument:
54
+ try:
55
+ if len(data) > MAX_SERVICE_DOCUMENT_BYTES:
56
+ raise ValueError("document exceeds one mebibyte")
57
+ text = data.decode("utf-8", errors="strict")
58
+ document = parse_json_model(text, PortableServiceDocument, "portable document")
59
+ if document.id != expected_id:
60
+ raise ValueError("document ID does not match its descriptor")
61
+ return document
62
+ except (ValueError, RecursionError) as error:
63
+ raise AepValidationError(
64
+ "Invalid portable document.", (ValidationIssue(path="$", message=str(error)),)
65
+ ) from error
66
+
67
+
52
68
  def _parse_json_value(data: str | bytes, value_type: Any, document_type: str) -> Any:
53
69
  _reject_duplicate_members(data, document_type)
54
70
  try:
@@ -18,6 +18,7 @@ from agent_enrollment_protocol.core import (
18
18
  AEP_GRANT_TYPE_BASIC,
19
19
  AEP_GRANT_TYPE_OAUTH_BEARER,
20
20
  AEP_PROBLEM_MEDIA_TYPE,
21
+ AEP_SERVICE_DOCUMENTS_EXTENSION,
21
22
  AEP_VERSION,
22
23
  AgentStatus,
23
24
  AssertionOperation,
@@ -29,6 +30,7 @@ from agent_enrollment_protocol.core import (
29
30
  Command,
30
31
  Commands,
31
32
  CoreConfiguration,
33
+ EnrollmentDecisionStatus,
32
34
  EnrollRequest,
33
35
  EnrollResponse,
34
36
  Extensions,
@@ -167,6 +169,8 @@ class Service:
167
169
  document_data["claims"] = options.claims
168
170
  if options.extensions:
169
171
  document_data["extensions"] = Extensions(supported=options.extensions)
172
+ if options.service_documents is not None:
173
+ document_data["service_documents"] = options.service_documents
170
174
  if self._authentication_methods:
171
175
  document_data["authentication"] = {"methods": self._authentication_methods}
172
176
  self._document = InspectDocument.model_validate(document_data)
@@ -205,22 +209,37 @@ class Service:
205
209
  return _problem("invalid_request", "Invalid request", 400)
206
210
 
207
211
  async def execute() -> ServiceResult[EnrollResponse]:
212
+ effective = request
213
+ if self._document.extensions is None or AEP_SERVICE_DOCUMENTS_EXTENSION not in (
214
+ self._document.extensions.supported or ()
215
+ ):
216
+ effective = parse_json_model(
217
+ json.dumps(
218
+ {
219
+ key: value
220
+ for key, value in request.to_wire().items()
221
+ if key != "acknowledged_document_ids"
222
+ }
223
+ ),
224
+ EnrollRequest,
225
+ "Enroll request",
226
+ )
208
227
  existing = await self._enrollment_store.find(claims.sub)
209
228
  if existing is not None:
210
- return _enrollment_result(existing, claims.sub)
229
+ return await self._update_enrollment(effective, existing)
211
230
  required = self._document.claims.required if self._document.claims else ()
212
- missing = missing_required_claim_names(required or (), request.claims)
213
- if missing:
214
- return _problem(
215
- "requirements_unmet",
216
- "Requirements unmet",
217
- 422,
218
- requirements_pending=missing,
219
- )
231
+ missing = missing_required_claim_names(required or (), effective.claims)
232
+ missing_documents = (
233
+ self._missing_document_ids(None)
234
+ if effective.acknowledged_document_ids is None
235
+ else ()
236
+ )
237
+ if missing or missing_documents:
238
+ return _document_requirements(missing, missing_documents)
220
239
 
221
240
  async def create() -> EnrollmentRecord:
222
241
  now = self._now()
223
- decision = await self._enrollment_policy.decide(request, now)
242
+ decision = await self._enrollment_policy.decide(effective, now)
224
243
  _validate_enrollment_decision(decision)
225
244
  identifier = self._identifier()
226
245
  if not identifier:
@@ -229,19 +248,24 @@ class Service:
229
248
  )
230
249
  return EnrollmentRecord(
231
250
  agent_did=claims.sub,
232
- claims=_accepted_claims(request.claims, self._document.claims),
251
+ claims=_accepted_claims(effective.claims, self._document.claims),
252
+ acknowledged_document_ids=(
253
+ ()
254
+ if decision.status is EnrollmentDecisionStatus.REJECTED
255
+ else self._accepted_document_ids((), effective.acknowledged_document_ids)
256
+ ),
233
257
  created_at=now,
234
258
  enrollment_id=identifier,
235
- owner_action_required=decision.owner_action_required,
236
- requirements_pending=tuple(decision.requirements_pending),
259
+ owner_action_required=decision.owner_action_required is True,
260
+ requirements_pending=tuple(decision.requirements_pending or ()),
237
261
  since=now,
238
262
  status=AgentStatus(decision.status.value),
239
263
  updated_at=now,
240
- verification_pending=tuple(decision.verification_pending),
264
+ verification_pending=tuple(decision.verification_pending or ()),
241
265
  )
242
266
 
243
267
  record, _ = await self._enrollment_store.find_or_create(claims.sub, create)
244
- return _enrollment_result(record, claims.sub)
268
+ return _enrollment_result(record, claims.sub, effective.acknowledged_document_ids)
245
269
 
246
270
  return await self._idempotent(
247
271
  claims.sub,
@@ -252,6 +276,86 @@ class Service:
252
276
  execute,
253
277
  )
254
278
 
279
+ async def _update_enrollment(
280
+ self, request: EnrollRequest, existing: EnrollmentRecord
281
+ ) -> ServiceResult[EnrollResponse]:
282
+ _validate_enrollment_record(existing, request.agent_did)
283
+ now = self._now()
284
+ decision = await self._enrollment_policy.decide(request, now)
285
+ _validate_enrollment_decision(decision)
286
+ if decision.status is EnrollmentDecisionStatus.REJECTED:
287
+ return _problem("enrollment_failed", "Enrollment failed", 403)
288
+ if not decision.update_existing:
289
+ return _enrollment_result(
290
+ existing, request.agent_did, request.acknowledged_document_ids
291
+ )
292
+ supplied = _accepted_claims(request.claims, self._document.claims)
293
+ merged = dict(existing.claims.to_wire()) if existing.claims is not None else {}
294
+ if supplied is not None:
295
+ merged.update(supplied.to_wire())
296
+ values = parse_json_model(json.dumps(merged), ClaimValues, "enrollment claims")
297
+ required = self._document.claims.required if self._document.claims else ()
298
+ missing = missing_required_claim_names(required or (), values)
299
+ missing_documents = (
300
+ self._missing_document_ids(existing)
301
+ if request.acknowledged_document_ids is None
302
+ else ()
303
+ )
304
+ if missing or missing_documents:
305
+ return _document_requirements(missing, missing_documents)
306
+ record = await self._enrollment_store.save(
307
+ replace(
308
+ existing,
309
+ claims=values,
310
+ acknowledged_document_ids=self._accepted_document_ids(
311
+ existing.acknowledged_document_ids, request.acknowledged_document_ids
312
+ ),
313
+ required_document_ids=tuple(
314
+ item
315
+ for item in existing.required_document_ids
316
+ if item not in (request.acknowledged_document_ids or ())
317
+ ),
318
+ owner_action_required=(
319
+ existing.owner_action_required
320
+ if decision.owner_action_required is None
321
+ else decision.owner_action_required
322
+ ),
323
+ requirements_pending=(
324
+ existing.requirements_pending
325
+ if decision.requirements_pending is None
326
+ else tuple(decision.requirements_pending)
327
+ ),
328
+ verification_pending=(
329
+ existing.verification_pending
330
+ if decision.verification_pending is None
331
+ else tuple(decision.verification_pending)
332
+ ),
333
+ updated_at=now,
334
+ )
335
+ )
336
+ return _enrollment_result(record, request.agent_did, request.acknowledged_document_ids)
337
+
338
+ def _missing_document_ids(self, record: EnrollmentRecord | None) -> tuple[str, ...]:
339
+ return tuple(
340
+ item.id
341
+ for item in (self._document.service_documents or ())
342
+ if item.enrollment == "required"
343
+ and (
344
+ record is None
345
+ or item.id not in record.acknowledged_document_ids
346
+ or item.id in record.required_document_ids
347
+ )
348
+ )
349
+
350
+ def _accepted_document_ids(
351
+ self, existing: tuple[str, ...], declared: tuple[str, ...] | None
352
+ ) -> tuple[str, ...]:
353
+ known = {item.id for item in (self._document.service_documents or ())}
354
+ return (
355
+ *existing,
356
+ *(item for item in (declared or ()) if item in known and item not in existing),
357
+ )
358
+
255
359
  async def status(self, options: CommandOptions) -> ServiceResult[StatusResponse]:
256
360
  claims = await self._authenticate_assertion(
257
361
  options, AssertionOperation.STATUS, resource=None
@@ -290,6 +394,11 @@ class Service:
290
394
  return _problem("unsupported_grant_type", "Unsupported grant type", 400)
291
395
  if record.status is not AgentStatus.ACTIVE:
292
396
  return _grant_lifecycle_problem(record)
397
+ required = self._document.claims.required if self._document.claims else ()
398
+ missing = missing_required_claim_names(required or (), record.claims)
399
+ missing_documents = self._missing_document_ids(record)
400
+ if missing or missing_documents:
401
+ return _document_requirements(missing, missing_documents)
293
402
  raw = await definition.handler.grant(
294
403
  request,
295
404
  GrantContext(
@@ -623,6 +732,7 @@ def _problem(
623
732
  requirements_pending: Sequence[str] = (),
624
733
  verification_pending: Sequence[str] = (),
625
734
  owner_action_required: bool = False,
735
+ required_document_ids: tuple[str, ...] = (),
626
736
  ) -> ServiceResult[Any]:
627
737
  data: dict[str, Any] = {
628
738
  "type": f"urn:aep:error:{code}",
@@ -636,6 +746,8 @@ def _problem(
636
746
  data["verification_pending"] = tuple(verification_pending)
637
747
  if owner_action_required:
638
748
  data["owner_action_required"] = "true"
749
+ if required_document_ids:
750
+ data["required_document_ids"] = required_document_ids
639
751
  problem = ProblemDetails.model_validate(data)
640
752
  headers = {"WWW-Authenticate": f'AEP reason="{code}"'} if status == 401 else {}
641
753
  return ServiceResult(
@@ -646,11 +758,29 @@ def _problem(
646
758
  )
647
759
 
648
760
 
649
- def _enrollment_result(record: EnrollmentRecord, agent_did: str) -> ServiceResult[EnrollResponse]:
761
+ def _document_requirements(
762
+ claims: tuple[str, ...], documents: tuple[str, ...]
763
+ ) -> ServiceResult[Any]:
764
+ return _problem(
765
+ "requirements_unmet",
766
+ "Requirements unmet",
767
+ 422,
768
+ requirements_pending=(*claims, "service_documents") if documents else claims,
769
+ owner_action_required=bool(documents),
770
+ required_document_ids=documents,
771
+ )
772
+
773
+
774
+ def _enrollment_result(
775
+ record: EnrollmentRecord, agent_did: str, declared: tuple[str, ...] | None = None
776
+ ) -> ServiceResult[EnrollResponse]:
650
777
  _validate_enrollment_record(record, agent_did)
778
+ data = _lifecycle_data(record)
779
+ if declared is not None and record.status is not AgentStatus.REJECTED:
780
+ data["acknowledged_document_ids"] = declared
651
781
  return ServiceResult(
652
782
  status=200,
653
- body=EnrollResponse.model_validate(_lifecycle_data(record)),
783
+ body=EnrollResponse.model_validate(data),
654
784
  )
655
785
 
656
786
 
@@ -23,6 +23,7 @@ from agent_enrollment_protocol.core import (
23
23
  OpenApiReference,
24
24
  ProblemDetails,
25
25
  RevokeRequest,
26
+ ServiceDocument,
26
27
  SigningAlgorithm,
27
28
  )
28
29
 
@@ -93,8 +94,12 @@ class EnrollmentRecord:
93
94
  status: AgentStatus
94
95
  updated_at: datetime
95
96
  verification_pending: tuple[str, ...]
97
+ acknowledged_document_ids: tuple[str, ...] = ()
98
+ required_document_ids: tuple[str, ...] = ()
96
99
 
97
100
  def __post_init__(self) -> None:
101
+ object.__setattr__(self, "acknowledged_document_ids", tuple(self.acknowledged_document_ids))
102
+ object.__setattr__(self, "required_document_ids", tuple(self.required_document_ids))
98
103
  if not self.agent_did or not self.enrollment_id:
99
104
  raise ValueError("AEP enrollment record requires Agent and enrollment identifiers")
100
105
  if any(
@@ -116,9 +121,10 @@ class EnrollmentStore(Protocol):
116
121
  @dataclass(frozen=True, slots=True)
117
122
  class EnrollmentDecision:
118
123
  status: EnrollmentDecisionStatus = EnrollmentDecisionStatus.ACTIVE
119
- owner_action_required: bool = False
120
- requirements_pending: tuple[str, ...] = ()
121
- verification_pending: tuple[str, ...] = ()
124
+ owner_action_required: bool | None = None
125
+ requirements_pending: tuple[str, ...] | None = None
126
+ verification_pending: tuple[str, ...] | None = None
127
+ update_existing: bool = True
122
128
 
123
129
 
124
130
  class EnrollmentPolicy(Protocol):
@@ -331,6 +337,7 @@ class ServiceOptions:
331
337
  maximum_assertion_lifetime: timedelta = timedelta(minutes=5)
332
338
  openapi: OpenApiReference | None = None
333
339
  replay_store: ReplayStore | None = None
340
+ service_documents: tuple[ServiceDocument, ...] | None = None
334
341
  signing_algorithms: tuple[SigningAlgorithm, ...] = (
335
342
  SigningAlgorithm.EDDSA,
336
343
  SigningAlgorithm.ES256,