cap-sdk-python 2.17.0__tar.gz → 2.19.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 (127) hide show
  1. cap_sdk_python-2.19.0/PKG-INFO +700 -0
  2. cap_sdk_python-2.19.0/README.md +660 -0
  3. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/__init__.py +68 -0
  4. cap_sdk_python-2.19.0/cap/cancel.py +102 -0
  5. cap_sdk_python-2.19.0/cap/client.py +76 -0
  6. cap_sdk_python-2.19.0/cap/dispatch_fence.py +121 -0
  7. cap_sdk_python-2.19.0/cap/job_events.py +101 -0
  8. cap_sdk_python-2.19.0/cap/outcome.py +160 -0
  9. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/production_resource.py +15 -6
  10. cap_sdk_python-2.19.0/cap/resource_nats_kv.py +196 -0
  11. cap_sdk_python-2.19.0/cap/resource_registry.py +360 -0
  12. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/runtime.py +662 -120
  13. cap_sdk_python-2.19.0/cap/telemetry.py +366 -0
  14. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/testing.py +36 -2
  15. cap_sdk_python-2.19.0/cap_sdk_python.egg-info/PKG-INFO +700 -0
  16. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap_sdk_python.egg-info/SOURCES.txt +16 -0
  17. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap_sdk_python.egg-info/requires.txt +5 -0
  18. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/pyproject.toml +11 -2
  19. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_agent_worker_trust.py +4 -4
  20. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_artifact_verifier.py +20 -0
  21. cap_sdk_python-2.19.0/tests/test_cancel.py +375 -0
  22. cap_sdk_python-2.19.0/tests/test_dispatch_fence.py +363 -0
  23. cap_sdk_python-2.19.0/tests/test_handler_progress.py +476 -0
  24. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_heartbeat.py +19 -5
  25. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_imports.py +2 -1
  26. cap_sdk_python-2.19.0/tests/test_outcome.py +422 -0
  27. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_resource.py +72 -0
  28. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_publish_node_workflow_contract.py +25 -4
  29. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_publish_workflow_contract.py +5 -4
  30. cap_sdk_python-2.19.0/tests/test_resource_nats_kv.py +278 -0
  31. cap_sdk_python-2.19.0/tests/test_resource_registry.py +459 -0
  32. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_runtime_lifecycle.py +4 -4
  33. cap_sdk_python-2.19.0/tests/test_runtime_resources.py +431 -0
  34. cap_sdk_python-2.19.0/tests/test_runtime_telemetry.py +346 -0
  35. cap_sdk_python-2.19.0/tests/test_telemetry.py +516 -0
  36. cap_sdk_python-2.19.0/tests/test_testing.py +196 -0
  37. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_typing_contract.py +5 -1
  38. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_trust_adversarial.py +1 -1
  39. cap_sdk_python-2.17.0/PKG-INFO +0 -414
  40. cap_sdk_python-2.17.0/README.md +0 -378
  41. cap_sdk_python-2.17.0/cap/client.py +0 -45
  42. cap_sdk_python-2.17.0/cap_sdk_python.egg-info/PKG-INFO +0 -414
  43. cap_sdk_python-2.17.0/tests/test_testing.py +0 -46
  44. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/LICENSE +0 -0
  45. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/bus.py +0 -0
  46. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/constants.py +0 -0
  47. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/errors.py +0 -0
  48. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/handshake.py +0 -0
  49. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/heartbeat.py +0 -0
  50. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/metrics.py +0 -0
  51. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/middleware.py +0 -0
  52. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/packet_boundary.py +0 -0
  53. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/__init__.py +0 -0
  54. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/__init__.py +0 -0
  55. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/__init__.py +0 -0
  56. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/__init__.py +0 -0
  57. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/alert_pb2.py +0 -0
  58. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/alert_pb2_grpc.py +0 -0
  59. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/buspacket_pb2.py +0 -0
  60. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/buspacket_pb2_grpc.py +0 -0
  61. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/handshake_pb2.py +0 -0
  62. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/handshake_pb2_grpc.py +0 -0
  63. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/heartbeat_pb2.py +0 -0
  64. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/heartbeat_pb2_grpc.py +0 -0
  65. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/job_pb2.py +0 -0
  66. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/job_pb2_grpc.py +0 -0
  67. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/policy_pb2.py +0 -0
  68. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/policy_pb2_grpc.py +0 -0
  69. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/safety_pb2.py +0 -0
  70. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/pb/cordum/agent/v1/safety_pb2_grpc.py +0 -0
  71. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/production_events.py +0 -0
  72. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/production_replay.py +0 -0
  73. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/production_signing.py +0 -0
  74. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/production_validation.py +0 -0
  75. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/progress.py +0 -0
  76. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/py.typed +0 -0
  77. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/subjects.py +0 -0
  78. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/trust_signing.py +0 -0
  79. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/validate.py +0 -0
  80. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker.py +0 -0
  81. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust.py +0 -0
  82. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_async.py +0 -0
  83. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_build.py +0 -0
  84. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_codec.py +0 -0
  85. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_runtime.py +0 -0
  86. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_runtime_config.py +0 -0
  87. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_validate.py +0 -0
  88. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap/worker_trust_verify.py +0 -0
  89. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap_sdk_python.egg-info/dependency_links.txt +0 -0
  90. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/cap_sdk_python.egg-info/top_level.txt +0 -0
  91. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/setup.cfg +0 -0
  92. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_agent_trust_boundary.py +0 -0
  93. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_artifact_trust_smoke.py +0 -0
  94. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_artifacts.py +0 -0
  95. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_ci_workflow_contract.py +0 -0
  96. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_conformance.py +0 -0
  97. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_errors.py +0 -0
  98. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_generate_protos.py +0 -0
  99. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_handshake.py +0 -0
  100. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_handshake_fixture_acceptance.py +0 -0
  101. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_handshake_security_contract.py +0 -0
  102. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_metrics.py +0 -0
  103. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_middleware.py +0 -0
  104. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_payload_validation.py +0 -0
  105. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_admission.py +0 -0
  106. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_events.py +0 -0
  107. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_runtime_hardening.py +0 -0
  108. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_signing.py +0 -0
  109. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_wire_parser.py +0 -0
  110. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_production_worker_echo.py +0 -0
  111. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_progress.py +0 -0
  112. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_redis_tls.py +0 -0
  113. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_runtime.py +0 -0
  114. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_runtime_hardening.py +0 -0
  115. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_runtime_parallelism.py +0 -0
  116. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_sdk.py +0 -0
  117. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_trust_signing.py +0 -0
  118. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_trust_signing_unknown.py +0 -0
  119. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_validate.py +0 -0
  120. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_validate_release.py +0 -0
  121. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_failures.py +0 -0
  122. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_observability.py +0 -0
  123. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_security_boundary.py +0 -0
  124. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_trust.py +0 -0
  125. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_trust_codec.py +0 -0
  126. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_trust_low_level_adversarial.py +0 -0
  127. {cap_sdk_python-2.17.0 → cap_sdk_python-2.19.0}/tests/test_worker_trust_runtime.py +0 -0
@@ -0,0 +1,700 @@
1
+ Metadata-Version: 2.4
2
+ Name: cap-sdk-python
3
+ Version: 2.19.0
4
+ Summary: CAP (Cordum Agent Protocol) Python SDK
5
+ Author-email: Cordum <eng@cordum.io>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/cordum-io/cap
8
+ Project-URL: Repository, https://github.com/cordum-io/cap
9
+ Project-URL: Issues, https://github.com/cordum-io/cap/issues
10
+ Keywords: cap,cordum,agent,protocol,sdk,ai
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: protobuf<7,>=6.31.1
21
+ Requires-Dist: grpcio<2,>=1.76.0
22
+ Requires-Dist: nats-py>=2.6.0
23
+ Requires-Dist: cryptography>=41.0.0
24
+ Requires-Dist: pydantic>=2.6.0
25
+ Requires-Dist: redis>=5.0.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: build<2,>=1.2; extra == "dev"
28
+ Requires-Dist: mypy<2,>=1.8; extra == "dev"
29
+ Requires-Dist: opentelemetry-api<2,>=1.41.1; extra == "dev"
30
+ Requires-Dist: opentelemetry-sdk<2,>=1.41.1; extra == "dev"
31
+ Requires-Dist: packaging>=23.2; extra == "dev"
32
+ Requires-Dist: pdoc>=14.0; extra == "dev"
33
+ Requires-Dist: PyYAML<7,>=6.0; extra == "dev"
34
+ Requires-Dist: pytest<9,>=8.0; extra == "dev"
35
+ Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "dev"
36
+ Requires-Dist: twine<7,>=5.0; extra == "dev"
37
+ Provides-Extra: otel
38
+ Requires-Dist: opentelemetry-api<2,>=1.41.1; extra == "otel"
39
+ Dynamic: license-file
40
+
41
+ # CAP Python SDK
42
+
43
+ Asyncio-first SDK with NATS helpers for CAP workers and clients. The supported
44
+ and CI-verified interpreter range is CPython 3.9 through 3.14.
45
+
46
+ ## Compatibility
47
+
48
+ - Python: `>=3.9` (tested on every minor release from 3.9 through 3.14).
49
+ - Protobuf runtime: `protobuf>=6.31.1,<7`.
50
+ - gRPC runtime: `grpcio>=1.76.0,<2`.
51
+
52
+ The protobuf modules are included in the wheel and sdist; consumers do not need
53
+ `protoc` or `grpcio-tools`. The minimum runtime versions match the headers in
54
+ the checked-in generated modules.
55
+
56
+ ## Consumer Quickstart (echo over NATS)
57
+
58
+ From an empty directory, install the released package and run an echo round-trip
59
+ against a running NATS server (`nats://127.0.0.1:4222`, or set `CAP_NATS_URL`).
60
+ This is the **direct-pool development-lab** wiring (worker on the submit subject,
61
+ no Scheduler/Safety Kernel); production submits through the governed
62
+ Scheduler/Safety path (see `docs/reference.md`).
63
+
64
+ ```bash
65
+ python -m venv .venv && . .venv/bin/activate
66
+ pip install cap-sdk-python==2.17.0 nats-py
67
+ # add echo.py below, then:
68
+ python echo.py
69
+ ```
70
+
71
+ <!-- cap-release:snippet:python-echo:python -->
72
+ ```python
73
+ import asyncio
74
+ import os
75
+
76
+ import nats
77
+ from cap import client, worker, SUBJECT_RESULT
78
+ from cap.pb.cordum.agent.v1 import buspacket_pb2, job_pb2
79
+
80
+ JOB_ID = "echo-1"
81
+
82
+
83
+ async def handle(req: job_pb2.JobRequest) -> job_pb2.JobResult:
84
+ return job_pb2.JobResult(
85
+ job_id=req.job_id,
86
+ status=job_pb2.JOB_STATUS_SUCCEEDED,
87
+ result_ptr=f"echo://{req.job_id}",
88
+ worker_id="echo-worker",
89
+ )
90
+
91
+
92
+ async def main() -> None:
93
+ url = os.environ.get("CAP_NATS_URL", "nats://127.0.0.1:4222")
94
+
95
+ # Dev-lab worker: consume submitted jobs directly (no Scheduler/Safety).
96
+ worker_task = asyncio.create_task(
97
+ worker.run_worker(nats_url=url, subject="sys.job.submit", handler=handle, sender_id="echo-worker")
98
+ )
99
+ await asyncio.sleep(0.5) # allow the worker subscription to register
100
+
101
+ nc = await nats.connect(url)
102
+ fut: asyncio.Future = asyncio.get_running_loop().create_future()
103
+
104
+ async def on_result(msg):
105
+ pkt = buspacket_pb2.BusPacket()
106
+ pkt.ParseFromString(msg.data)
107
+ if pkt.HasField("job_result") and pkt.job_result.job_id == JOB_ID and not fut.done():
108
+ fut.set_result(pkt.job_result)
109
+
110
+ await nc.subscribe(SUBJECT_RESULT, cb=on_result)
111
+ await nc.flush()
112
+
113
+ await client.submit_job(nc, job_pb2.JobRequest(job_id=JOB_ID, topic="job.echo"), JOB_ID, "echo-client", None)
114
+
115
+ try:
116
+ result = await asyncio.wait_for(fut, timeout=10)
117
+ except asyncio.TimeoutError:
118
+ raise SystemExit("timed out waiting for JobResult (no worker?)")
119
+ if result.status != job_pb2.JOB_STATUS_SUCCEEDED:
120
+ raise SystemExit(f"job {result.job_id} ended {result.status}")
121
+ print(f"job {result.job_id}: SUCCEEDED payload={result.result_ptr}")
122
+ await nc.drain()
123
+ worker_task.cancel()
124
+ try:
125
+ await worker_task
126
+ except asyncio.CancelledError:
127
+ pass
128
+
129
+
130
+ if __name__ == "__main__":
131
+ asyncio.run(main())
132
+ ```
133
+ <!-- cap-release:snippet-end -->
134
+
135
+ ## Quick Start
136
+ 1. Install:
137
+ ```bash
138
+ pip install -e .
139
+ ```
140
+
141
+ 2. Run a worker:
142
+ ```python
143
+ import asyncio
144
+ from cap import worker
145
+ from cap.pb.cordum.agent.v1 import job_pb2
146
+
147
+ async def handle(req: job_pb2.JobRequest):
148
+ return job_pb2.JobResult(
149
+ job_id=req.job_id,
150
+ status=job_pb2.JOB_STATUS_SUCCEEDED,
151
+ result_ptr=f"redis://res/{req.job_id}",
152
+ worker_id="worker-echo-1",
153
+ )
154
+
155
+ asyncio.run(worker.run_worker("nats://127.0.0.1:4222", "job.echo", handle))
156
+ ```
157
+
158
+ 3. Submit a job (client):
159
+ ```python
160
+ import asyncio
161
+ from cryptography.hazmat.primitives.asymmetric import ec
162
+ from cap import client
163
+ from cap.pb.cordum.agent.v1 import job_pb2
164
+ import nats
165
+
166
+ async def main():
167
+ nc = await nats.connect("nats://127.0.0.1:4222")
168
+ priv = ec.generate_private_key(ec.SECP256R1())
169
+ req = job_pb2.JobRequest(
170
+ job_id="job-echo-1",
171
+ topic="job.echo",
172
+ context_ptr="redis://ctx/job-echo-1",
173
+ )
174
+ await client.submit_job(nc, req, "trace-1", "client-py", priv)
175
+ await nc.drain()
176
+
177
+ asyncio.run(main())
178
+ ```
179
+
180
+ ## Files
181
+ - `cap/bus.py` — NATS connector.
182
+ - `cap/worker.py` — worker skeleton with handler hook.
183
+ - `cap/client.py` — publish JobRequest to `sys.job.submit`.
184
+ - `cap/pb/` — protobuf stubs (generated).
185
+
186
+ ## Defaults
187
+ - Subjects: `sys.job.submit`, `sys.job.result`, `sys.heartbeat`.
188
+ - Protocol version: `1`.
189
+ - Signing: `submit_job` and `run_worker` sign envelopes when given an `ec.EllipticCurvePrivateKey`. Signatures use deterministic protobuf serialization (map entries ordered by key) for cross-SDK verification. Generate a keypair with `cryptography`:
190
+ ```python
191
+ from cryptography.hazmat.primitives.asymmetric import ec
192
+ priv = ec.generate_private_key(ec.SECP256R1())
193
+ pub = priv.public_key()
194
+ ```
195
+ - Set `public_keys` on `run_worker` to verify incoming packets.
196
+ - Omit `public_keys` to accept unsigned packets.
197
+ - Pass `private_key=None` to `submit_job` if you want to send unsigned envelopes.
198
+
199
+ Swap out `cap.bus` if you need a different transport.
200
+
201
+ ## Testing
202
+
203
+ The `cap.testing` module lets you test handlers without running NATS or Redis.
204
+
205
+ ```python
206
+ from cap.testing import run_handler
207
+ from cap.pb.cordum.agent.v1 import job_pb2
208
+
209
+ async def test_echo():
210
+ result = await run_handler(
211
+ lambda ctx, data: {"echo": data["prompt"]},
212
+ {"prompt": "hello"},
213
+ topic="job.echo",
214
+ )
215
+ assert result.status == job_pb2.JOB_STATUS_SUCCEEDED
216
+ ```
217
+
218
+ - `run_handler(handler, input, **options)` — runs a single handler invocation and returns the `JobResult`.
219
+ - `create_test_agent(**options)` — returns `(agent, mock_nats, store)` pre-wired with `MockNATS` + `InMemoryBlobStore`.
220
+ - `MockNATS` — in-memory NATS mock for custom test setups. It accepts the worker-trust `reconnected_cb`/`disconnected_cb` connect options (stored as attributes) and answers every `request` with `asyncio.TimeoutError`, recorded in `requests`, so `create_test_agent(worker_trust_mode="warn", worker_trust=cfg)` starts without a session while `"enforce"` fails closed. `publish` also accepts the optional `headers=` mapping used by `telemetry=` agents and clients, and records it in `published_headers`.
221
+
222
+ ## Runtime (High-Level SDK)
223
+ The runtime hides NATS/Redis plumbing and gives you typed handlers.
224
+
225
+ ```python
226
+ import asyncio
227
+ from pydantic import BaseModel
228
+ from cap.runtime import Agent, Context
229
+
230
+ class Input(BaseModel):
231
+ prompt: str
232
+
233
+ class Output(BaseModel):
234
+ summary: str
235
+
236
+ agent = Agent(retries=2)
237
+
238
+ @agent.job("job.summarize", input_model=Input, output_model=Output)
239
+ async def summarize(ctx: Context, data: Input) -> Output:
240
+ return Output(summary=data.prompt[:140])
241
+
242
+ asyncio.run(agent.run())
243
+ ```
244
+
245
+ ### Authenticated worker trust
246
+
247
+ - `Agent` accepts `worker_trust_mode`, `worker_trust`, bounded timeout/retry/renewal tuning, or the `CORDUM_SDK_HANDSHAKE` mode. `warn`/`enforce` require a complete `WorkerTrustConfig` with enrolled identities, exact audience, active P-256 proof key, scheduler identity/pins, and SDK version.
248
+ - Omitting every trust option retains legacy `off` for source compatibility. Once configuration or tuning is present, mode is explicit and `off` rejects dormant material; use `warn` only for visible migration and `enforce` for fail-closed admission.
249
+ - Before handlers, the runtime uses bounded protobuf request/reply on `sys.worker.handshake.challenge` and `sys.worker.handshake.authenticate`, verifies the pinned scheduler, installs and attaches the opaque token, and renews with the current token. It never falls back to ISSUE; expired, revoked, superseded, wrong-audience, or binding-mismatched sessions are invalid.
250
+ - Enroll/rotate through an authenticated control plane: register only the public key, retain the private key in the worker, overlap scheduler pins, then revoke old authoritative key/session records.
251
+ - `build_challenge_request`, `build_authenticate`, trust codecs/signers/verifiers, and `handshake_payload` / `publish_handshake` support adapters and compatibility; they do not enroll keys, issue/revoke sessions, grant topics, or authenticate `sys.handshake`.
252
+ - Low-level `run_worker(..., session_token=...)` is caller-managed static compatibility only: it does not mint, renew, reauthenticate after reconnect, or observe revocation. Use high-level `Agent` with `warn`/`enforce` for authenticated worker trust. `warn` fails open only for transport availability errors; malformed, rejected, unpinned, expired, or otherwise invalid proofs stop trust admission.
253
+ - Never log key material, tokens, signatures, nonces, complete trust packets, or raw rejections; use bounded mode/phase/outcome/coarse-reason telemetry.
254
+
255
+ ### Failure and shutdown contract
256
+
257
+ - In both `run_worker()` and the high-level `Agent`, an ordinary handler
258
+ `Exception` produces exactly one `JOB_STATUS_FAILED` result with the generic
259
+ external message `handler failed`. In the `Agent`, a `cap.JobFailure`
260
+ publishes its own status and code instead (see below). Diagnostics use
261
+ bounded, newline-safe identifiers and the exception type without exposing
262
+ exception text. Logging and metrics hooks are best-effort and cannot block
263
+ the terminal result; the worker remains available for later jobs.
264
+ - `asyncio.CancelledError`, `KeyboardInterrupt`, and `SystemExit` remain control
265
+ flow and are not converted into job results.
266
+ - Cancelling `run_worker()` drains its NATS connection before exit.
267
+ - `Agent.run()` always enters cleanup without letting a cleanup error replace
268
+ cancellation or another primary failure. `Agent.close()` stops intake, stops
269
+ the heartbeat, waits for tracked handlers (retaining the live session for their
270
+ terminal results), drains NATS, and closes the blob
271
+ store. Each asynchronous cleanup stage has the `shutdown_timeout` deadline
272
+ (30 seconds by default), and later stages are still attempted after a timeout.
273
+ Pass `None` only to opt out of deadlines; zero and negative values are
274
+ rejected. Repeated or concurrent calls share the same cleanup operation.
275
+
276
+ #### Typed failures and error codes
277
+
278
+ In an `Agent` handler or middleware, raise `cap.JobFailure` to publish a
279
+ [spec/13](https://github.com/cordum-io/cap/blob/main/spec/13-error-codes.md)
280
+ error code instead of `handler failed`. For example, the handler above can
281
+ reject an empty prompt:
282
+
283
+ ```python
284
+ from cap import JobFailure
285
+
286
+ @agent.job("job.summarize", input_model=Input, output_model=Output)
287
+ async def summarize(ctx: Context, data: Input) -> Output:
288
+ if not data.prompt:
289
+ raise JobFailure("EMPTY_PROMPT", retryable=False)
290
+ return Output(summary=data.prompt[:140])
291
+ ```
292
+
293
+ - An `int` code sets `error_code_enum`. It must be an `ErrorCode` value other
294
+ than `ERROR_CODE_UNSPECIFIED`, or an application code in 1000-9999.
295
+ `error_code` stays empty, except for the spec/13 legacy strings:
296
+ - `ERROR_CODE_JOB_TIMEOUT`: `TIMEOUT`;
297
+ - `ERROR_CODE_SAFETY_DENIED`: `DENIED`;
298
+ - `ERROR_CODE_JOB_PERMISSION_DENIED`: `PERMISSION_DENIED`.
299
+ - A `str` code such as `"FRAMEWORK_ERROR"` sets `error_code` and leaves
300
+ `error_code_enum` at `ERROR_CODE_UNSPECIFIED`. It must match
301
+ `[A-Z][A-Z0-9_]{0,63}`. Any other code or `retryable` value, `bool` codes
302
+ included, raises `TypeError` or `ValueError` when the `JobFailure` is built;
303
+ inside a handler, that error is an ordinary exception.
304
+ - `retryable` selects the status:
305
+ - `retryable=None` (the default): `JOB_STATUS_FAILED`;
306
+ - `retryable=True`: `JOB_STATUS_FAILED_RETRYABLE`;
307
+ - `retryable=False`: `JOB_STATUS_FAILED_FATAL`.
308
+ - `error_message` is always `handler reported failure`, and the metrics hook's
309
+ `on_job_failed` gets the same text. The exception's arguments, its cause and
310
+ the input are never published. A subclass must call `JobFailure.__init__`;
311
+ one that does not publishes `handler failed`, still without a retry.
312
+ - The SDK never retries after a `JobFailure`: it publishes that outcome at
313
+ once, whatever `retries` says. An ordinary exception, an `output_model`
314
+ validation error included, still runs the handler up to `retries + 1` times;
315
+ if every attempt fails, the result is `handler failed`.
316
+ - The low-level `run_worker()` is unchanged. Its handlers build their own
317
+ `JobResult`, and a `JobFailure` raised there is an ordinary exception.
318
+
319
+ Failures the `Agent` detects itself publish `JOB_STATUS_FAILED` with an empty
320
+ `error_code` and fixed text, never exception text, input bytes or pointer text:
321
+
322
+ | Condition | `error_code_enum` | `error_message` |
323
+ |---|---|---|
324
+ | `context_ptr` is not a valid pointer | `ERROR_CODE_JOB_INVALID_INPUT` | `context pointer invalid` |
325
+ | a `resource_registry` is set and `context_ref` is missing | `ERROR_CODE_JOB_INVALID_INPUT` | `context ref required` |
326
+ | the registry refused `context_ref`, or `context_ptr` names other bytes | `ERROR_CODE_JOB_INVALID_INPUT` | `context ref refused` |
327
+ | context fetch raised or timed out | `ERROR_CODE_UNSPECIFIED` | `context fetch failed` |
328
+ | no context blob at the pointer | `ERROR_CODE_JOB_NOT_FOUND` | `context not found` |
329
+ | context over `max_context_bytes` | `ERROR_CODE_JOB_RESOURCE_EXHAUSTED` | `context exceeds max size` |
330
+ | context is not UTF-8 JSON | `ERROR_CODE_JOB_INVALID_INPUT` | `context decode failed` |
331
+ | `input_model` rejects the input | `ERROR_CODE_JOB_INVALID_INPUT` | `input validation failed` |
332
+ | handler, middleware or `output_model` raised on every attempt | `ERROR_CODE_UNSPECIFIED` | `handler failed` |
333
+ | output is not JSON-serializable | `ERROR_CODE_UNSPECIFIED` | `result encode failed` |
334
+ | result over `max_result_bytes` | `ERROR_CODE_JOB_RESOURCE_EXHAUSTED` | `result exceeds max size` |
335
+ | result write raised or timed out | `ERROR_CODE_UNSPECIFIED` | `result write failed` |
336
+
337
+ #### ResourceRef input and output
338
+
339
+ Pass an operator-built `cap.ResourceRegistry` to read job input from
340
+ `JobRequest.context_ref` and publish results as `JobResult.result_ref`:
341
+
342
+ ```python
343
+ from cap import Agent, InMemoryResourceBackend, ResourceBackendRegistration, ResourceRegistry
344
+
345
+ backend = InMemoryResourceBackend() # tests only: install a durable backend in production
346
+ registry = ResourceRegistry([ResourceBackendRegistration("memory", 2 * 1024 * 1024, backend, backend)])
347
+ agent = Agent(
348
+ resource_registry=registry,
349
+ result_backend_id="memory", # required with a registry
350
+ result_ref_ttl=3600.0, # seconds; the default
351
+ worker_trust_mode="enforce",
352
+ worker_trust=trust, # a cap.WorkerTrustConfig
353
+ )
354
+ ```
355
+
356
+ - Every resolve and externalize runs under the worker-trust tenant
357
+ (`worker_trust.tenant_id`) and the admitted job id. Neither comes from the
358
+ ref. `start()` raises `RuntimeError` before it connects when there is no
359
+ worker-trust configuration (mode `warn` or `enforce`). No Redis store is opened.
360
+ - Input comes only from `context_ref`. A `context_ptr` sent with it must name
361
+ the same Redis key (spec/19). A ref whose `media_type` is not
362
+ `application/json`, or whose `size_bytes` is over `max_context_bytes`, is
363
+ rejected before any fetch. The handler never runs for a missing, refused or
364
+ oversize ref, and `retries` never repeats the resolve.
365
+ - A ref over the backend's `max_bytes` publishes `context exceeds max size`. A
366
+ backend error or timeout publishes `context fetch failed`, and so does another
367
+ tenant's ref, which the backend cannot find. A non-JSON ref publishes
368
+ `context decode failed`, and any other registry error `context ref refused`.
369
+ - A SUCCEEDED result is externalized as `application/json` with purpose
370
+ `job-result`, expiring `result_ref_ttl` seconds later. It carries
371
+ `result_ref`, and `result_ptr` stays empty. A result over the backend's
372
+ `max_bytes` publishes `result exceeds max size`; any other failure
373
+ `result write failed`.
374
+ - Without `resource_registry`, `context_ptr` and `result_ptr` work as before.
375
+
376
+ For durable storage, install `cap.NatsKvResourceBackend` (resolver id `nats-kv`)
377
+ over a JetStream KV bucket that you provision:
378
+
379
+ ```python
380
+ import nats
381
+ from cap import NatsKvResourceBackend, ResourceRegistry
382
+
383
+ nc = await nats.connect(servers, user_credentials=creds) # your connection and credentials
384
+ kv = await nc.jetstream().key_value("cap-resources") # history 1, max_value_size set
385
+ backend = await NatsKvResourceBackend.open(kv)
386
+ registry = ResourceRegistry([backend.registration()])
387
+ ```
388
+
389
+ - `open()` refuses a bucket without `max_value_size`, or with one over 1 GiB,
390
+ and uses it as the backend's `max_bytes`. Set the bucket's `max_age` to at
391
+ least your longest `result_ref_ttl`, and keep the server's `max_payload` at or
392
+ above `max_value_size`. Entries have no per-entry TTL.
393
+ - URIs are `nats-kv://<bucket>/<tenant>/<sha256hex>`. Keys and values match the
394
+ Go backend in this repository (`internal/resourcekv`) byte for byte. A ref
395
+ names only the bucket and tenant, never a connection, credentials or path, and
396
+ another tenant's ref is refused before any fetch.
397
+
398
+ #### Cancellation and deadlines
399
+
400
+ Tags: cancellation, deadlines, worker-contract.
401
+
402
+ `Agent` subscribes to `sys.job.cancel` without a queue group or a handler slot.
403
+ It first checks whether the unverified job id is running locally (routing only,
404
+ not authority), then admits the cancel exactly like a request. CAP-PRODUCTION
405
+ requires the `sys.job.cancel` audience, session-bound trust and replay admission;
406
+ a set cancel identity must equal the verified envelope identity. The admitted
407
+ job id and the whole dispatch (dispatch id, attempt, assigned worker) must match
408
+ the running attempt. Empty dispatch matches only empty dispatch. Refused cancels
409
+ change nothing, and non-target workers do not consume shared replay entries.
410
+
411
+ `Agent(max_deadline=None)` keeps unbounded execution by default. A positive
412
+ `Budget.deadline_ms` gives `min(deadline_ms / 1000, max_deadline)` seconds, or the
413
+ budget alone when the maximum is `None`. A zero budget uses the maximum.
414
+ The maximum must be positive and finite; booleans and non-numbers are rejected.
415
+ The clock starts after input resolution, at handler start, and includes
416
+ middleware and retries. Result writes and publication still use `io_timeout`.
417
+ `Context.deadline` is that `time.monotonic()` instant, or `None`;
418
+ `Context.cancelled` is a read-only, thread-safe boolean set when cancel or
419
+ deadline stops the handler.
420
+
421
+ Cancellation publishes `JOB_STATUS_CANCELLED`, an empty `error_code`, enum
422
+ `UNSPECIFIED`, and `job cancelled`. Deadline expiry publishes `JOB_STATUS_FAILED`
423
+ (never status TIMEOUT), `ERROR_CODE_JOB_TIMEOUT`, `TIMEOUT`, and
424
+ `job deadline exceeded`. Cancel reason and requester text are never published or
425
+ logged. Exactly one terminal result is selected: the first observed event wins,
426
+ with completion before cancel before deadline when observed together. A cancel
427
+ before handler start skips the handler with execution time zero; an input
428
+ failure keeps its own outcome.
429
+
430
+ A synchronous handler blocks the event loop and cannot be pre-empted; its result
431
+ wins once it returns. Blocking work in `asyncio.to_thread` gets its terminal
432
+ result at the bound, while the thread finishes independently. A handler that
433
+ suppresses `CancelledError` keeps its slot until it returns; that outcome is
434
+ discarded. Once `close()` drains subscriptions, no further cancels are received.
435
+ The low-level `cap.worker.run_worker` is unchanged.
436
+
437
+ #### Progress and artifacts
438
+
439
+ Async `Agent` handlers can await ordered progress and registry-backed artifacts:
440
+
441
+ ```python
442
+ await context.report_progress("validated")
443
+ await context.attach_artifact("receipt", "text/plain", b"accepted")
444
+ ```
445
+
446
+ `report_progress(marker)` publishes one `JobProgress` on `sys.job.progress` with
447
+ the admitted job ID, status `JOB_STATUS_RUNNING`, `message=marker`, percent 0
448
+ and other fields unset. The marker is an exact `str`, 1-256 UTF-8 bytes, and
449
+ `str.isprintable()` must be true. CAP-PRODUCTION binds job identity and dispatch
450
+ and seals the envelope for audience `sys.job.progress` using the worker proof key.
451
+ Each call awaits publication under `io_timeout`; errors propagate. Markers go
452
+ out in call order before the terminal result.
453
+
454
+ `attach_artifact(name, media_type, content)` requires the operator
455
+ `resource_registry` and writes to `result_backend_id`, with purpose
456
+ `job-artifact:<name>` and expiry `now + result_ref_ttl`. It uses the worker-trust
457
+ tenant and admitted job ID, never identity from a resource reference. The exact
458
+ string name matches `[a-z0-9][a-z0-9._-]{0,63}`; media type is canonical lowercase
459
+ type/subtype without parameters, at most 127 bytes; content is nonempty exact
460
+ `bytes`. Invalid arguments raise `TypeError` or `ValueError` without publication
461
+ or latching a failure.
462
+
463
+ `Agent(max_artifacts=8, max_artifact_bytes=2 * 1024 * 1024)` bounds the count per
464
+ attempt and bytes per artifact. Count accepts integers 0..1000 and byte limit
465
+ accepts positive integers; bool and non-integers raise `ValueError`. A rejected
466
+ bound never writes content. Only a SUCCEEDED result includes `artifact_refs`,
467
+ in call order; `result_ref` is unchanged. Retries clear artifacts, but retain
468
+ progress already published and the first failure latch.
469
+
470
+ | Status | Error code | Fixed message |
471
+ | --- | --- | --- |
472
+ | `JOB_STATUS_FAILED` | `ERROR_CODE_JOB_RESOURCE_EXHAUSTED` | `artifact count exceeds max` |
473
+ | `JOB_STATUS_FAILED` | `ERROR_CODE_JOB_RESOURCE_EXHAUSTED` | `artifact exceeds max size` |
474
+ | `JOB_STATUS_FAILED` | `ERROR_CODE_JOB_RESOURCE_EXHAUSTED` | `artifact write failed` |
475
+
476
+ Count/size breaches, missing registries and write failures raise `JobFailure`
477
+ and latch the first row above. Registry size refusal uses the size row. The
478
+ latch overrides the handler outcome even if caught, so no SUCCEEDED result is
479
+ published. The raised failure contains no backend exception cause or context.
480
+
481
+ Hooks close synchronously when the final handler attempt ends, at terminal
482
+ publish entry, and during request cleanup. A call that runs after the handler's
483
+ final attempt ended is dropped. Closed or directly constructed, unbound contexts
484
+ still validate arguments, but publish and externalize nothing. Await hooks on
485
+ the event-loop thread: synchronous handlers cannot await them. `run_worker`
486
+ is unchanged. Tags: Python, progress, artifacts, ResourceRef.
487
+
488
+ #### Dispatch fencing and result replay
489
+
490
+ `Agent` fences every admitted `JobRequest` carrying a `DispatchIdentity`, in every
491
+ trust mode, before input resolution, cancellation registration or handler execution.
492
+ The dispatch id must be 1–128 UTF-8 bytes, `attempt >= 1`, the assigned worker must
493
+ match this Agent, and the job id must be at most 256 UTF-8 bytes. Invalid or foreign
494
+ dispatches are dropped. Admission still authenticates first; the trust mode decides
495
+ who can steer the fence. The digest is SHA-256 of deterministic `JobRequest` bytes.
496
+
497
+ | Stored state | Incoming dispatch | Decision |
498
+ | --- | --- | --- |
499
+ | unknown (including evicted) | valid dispatch | RUN |
500
+ | DONE | exact dispatch and digest, recorded result | REPLAY |
501
+ | DONE | exact dispatch and digest, no result | RUN |
502
+ | RUNNING | exact dispatch and digest | DROP (in flight) |
503
+ | any | same dispatch, different digest | DROP (conflicting dispatch) |
504
+ | RUNNING | attempt = active+1 | RUN (replaces entry) |
505
+ | RUNNING | attempt > active+1 | DROP (future attempt) |
506
+ | DONE | newer attempt, including a gap | RUN (replaces entry) |
507
+ | any | stale attempt, or same attempt with a different dispatch id | DROP |
508
+
509
+ The bound terminal result and trace id are recorded **before** result publication;
510
+ a failed publish can therefore be replayed. Replays keep the recorded trace id and
511
+ never invoke the handler, resolve input, register cancellation, update metrics or
512
+ record again. Production replays are re-bound and freshly sealed with the current
513
+ session. A verified production byte-identical duplicate may only replay an exact
514
+ recorded result; otherwise it is dropped silently, without claiming a dispatch. Interrupted
515
+ attempts finish without a result; a non-duplicate exact redelivery can run again.
516
+
517
+ `dispatch_fence_max_jobs=1024` accepts integers from 1 to 1,000,000;
518
+ `dispatch_fence_max_age=3600.0` accepts positive finite seconds (neither accepts bool).
519
+ Age is measured since the last write with a monotonic clock. Age and oldest-write
520
+ size eviction are checked on every store call. The store is **in memory**, per
521
+ process: eviction or restart forgets a job, not a durable exactly-once guarantee.
522
+ Other drops log a fixed reason and bounded job id, never request content; replays log at info.
523
+ Requests without `DispatchIdentity` remain unfenced, even in production; requiring
524
+ it for Go managed-worker parity is a follow-up. `run_worker` is unchanged.
525
+ For TCK probes, a distinct dispatch at attempt 1 needs a fresh job id, and the
526
+ future-attempt case must hold the active attempt RUNNING (DONE accepts newer gaps).
527
+
528
+ ### Middleware
529
+
530
+ Add cross-cutting concerns (logging, auth, metrics) without modifying handlers:
531
+
532
+ ```python
533
+ from cap.middleware import logging_middleware
534
+
535
+ # Built-in logging middleware
536
+ agent.use(logging_middleware())
537
+
538
+ # Custom middleware
539
+ async def timing(ctx, data, next_fn):
540
+ import time
541
+ start = time.monotonic()
542
+ result = await next_fn(ctx, data)
543
+ elapsed = time.monotonic() - start
544
+ print(f"job {ctx.job_id} took {elapsed:.3f}s")
545
+ return result
546
+
547
+ agent.use(timing)
548
+ ```
549
+
550
+ Middleware executes in registration order (FIFO). Each can inspect context,
551
+ measure timing, or short-circuit by returning without calling `next_fn`.
552
+
553
+ ### Redis TLS
554
+ The Python SDK provides `redis_ssl_context_from_env()` to build an `SSLContext` for secure Redis connections. It reads:
555
+ - `REDIS_TLS_CA` (or `SSL_CERT_FILE` fallback): Path to CA certificate.
556
+ - `REDIS_TLS_CERT` / `REDIS_TLS_KEY`: Path to client certificate/key pair.
557
+ - `REDIS_TLS_SERVER_NAME`: SNI server name override.
558
+ - `REDIS_TLS_INSECURE`: Set to `1` or `true` to skip certificate verification (dev only).
559
+
560
+ ### Environment
561
+ - `NATS_URL` (default `nats://127.0.0.1:4222`)
562
+ - `REDIS_URL` (default `redis://127.0.0.1:6379/0`)
563
+
564
+ ## Contributor and Release Verification
565
+
566
+ Run these commands from the repository root. Generated Python modules are
567
+ checked, never rewritten, by the pinned toolchain:
568
+
569
+ ```bash
570
+ python -m pip install -e "sdk/python[dev]"
571
+ python -m pytest -q sdk/python/tests --ignore=sdk/python/tests/integration
572
+
573
+ python -m pip install -r sdk/python/requirements-codegen.txt
574
+ python sdk/python/scripts/generate_protos.py --check
575
+ ```
576
+
577
+ The real-NATS test is mandatory in CI and never skips. Run it against an
578
+ explicit broker URL (CI and publishing pin NATS 2.12.6 by image digest):
579
+
580
+ ```bash
581
+ CAP_TEST_NATS_URL=nats://127.0.0.1:4222 \
582
+ python -m pytest -q sdk/python/tests/integration/test_worker_nats.py
583
+ ```
584
+
585
+ Build and verify the exact wheel/sdist pair in clean consumer environments:
586
+
587
+ ```bash
588
+ rm -rf dist/python
589
+ python -m build --outdir dist/python sdk/python
590
+ python -m twine check dist/python/*
591
+ python sdk/python/scripts/verify_artifacts.py \
592
+ --wheel dist/python/*.whl \
593
+ --sdist dist/python/*.tar.gz \
594
+ > dist/python/artifact-verification.json
595
+ ```
596
+
597
+ Before creating a release, bump the checked-in package version and require an
598
+ exact lowercase `v<version>` tag. Replace `<version>` below with the version in
599
+ `sdk/python/pyproject.toml`:
600
+
601
+ ```bash
602
+ python sdk/python/scripts/validate_release.py \
603
+ --tag "v<version>" \
604
+ --artifact-report dist/python/artifact-verification.json
605
+ ```
606
+
607
+ The publish workflow exports the tagged commit, builds once, records the exact
608
+ artifact inventory and SHA-256 checksums, and publishes only that verified
609
+ pair. Do not mutate generated code or package metadata during publishing, and
610
+ do not use a manual or `skip-existing` fallback.
611
+
612
+ ## Generating API Docs
613
+
614
+ Generate HTML API reference locally using [pdoc](https://pdoc.dev/):
615
+
616
+ ```bash
617
+ pip install cap-sdk-python[dev]
618
+ pdoc ./cap --output-dir docs
619
+ ```
620
+
621
+ Output is written to `docs/` (gitignored). Open `docs/index.html` to browse.
622
+
623
+ ## Observability
624
+
625
+ ### Structured Logging
626
+ The runtime Agent and Worker use `logging.Logger` (stdlib) for structured logging. All log calls include contextual fields (`job_id`, `trace_id`, `topic`, `sender_id`). Pass a custom logger or leave as default:
627
+
628
+ ```python
629
+ import logging
630
+ from cap.runtime import Agent
631
+
632
+ logger = logging.getLogger("my-agent")
633
+ logger.setLevel(logging.DEBUG)
634
+ agent = Agent(logger=logger)
635
+ ```
636
+
637
+ ### MetricsHook
638
+ Implement the `MetricsHook` protocol to integrate with Prometheus, OpenTelemetry, or any metrics system:
639
+
640
+ ```python
641
+ from cap.metrics import MetricsHook
642
+
643
+ class MetricsHook(Protocol):
644
+ def on_job_received(self, job_id: str, topic: str) -> None: ...
645
+ def on_job_completed(self, job_id: str, duration_ms: int, status: str) -> None: ...
646
+ def on_job_failed(self, job_id: str, error_msg: str) -> None: ...
647
+ def on_heartbeat_sent(self, worker_id: str) -> None: ...
648
+ ```
649
+
650
+ The default is `NoopMetrics` (zero overhead). Example Prometheus integration:
651
+
652
+ ```python
653
+ from cap.runtime import Agent
654
+
655
+ class PromMetrics:
656
+ def on_job_received(self, job_id, topic):
657
+ jobs_received.labels(topic=topic).inc()
658
+
659
+ def on_job_completed(self, job_id, duration_ms, status):
660
+ job_duration.labels(status=status).observe(duration_ms)
661
+
662
+ def on_job_failed(self, job_id, error_msg):
663
+ jobs_failed.inc()
664
+
665
+ def on_heartbeat_sent(self, worker_id):
666
+ pass
667
+
668
+ agent = Agent(metrics=PromMetrics())
669
+ ```
670
+
671
+ The `trace_id` is propagated through all log and metrics calls for distributed tracing correlation.
672
+
673
+ ### Trace context (OpenTelemetry)
674
+ `pip install "cap-sdk-python[otel]"` adds only `opentelemetry-api`. Install an OpenTelemetry SDK and exporter yourself; without one, spans are no-ops. The wire contract is `spec/interop/trace-context.md` in the CAP repository.
675
+
676
+ ```python
677
+ from opentelemetry import trace
678
+ from cap import telemetry
679
+ from cap.client import submit_job
680
+ from cap.runtime import Agent, Context
681
+
682
+ # Global TracerProvider and the W3C propagator, never the global propagator.
683
+ config = telemetry.from_opentelemetry()
684
+ tracer = trace.get_tracer("orders")
685
+ agent = Agent(telemetry=config)
686
+
687
+ @agent.job("job.orders.validate")
688
+ async def validate(ctx: Context, data):
689
+ with tracer.start_as_current_span("orders.validate", context=ctx.otel_context):
690
+ return {"ok": True}
691
+
692
+ # When telemetry is set, nc.publish must accept headers=.
693
+ await submit_job(nc, request, trace_id, sender_id, telemetry=config)
694
+ ```
695
+
696
+ - **Submit**: `submit_job` starts a `publish sys.job.submit` PRODUCER span, parented on `context=` (default: the current context), and sends its context in the lowercase `traceparent` and `tracestate` headers.
697
+ - **Process**: the Agent reads those headers only after CAP-PRODUCTION admission or legacy validation; a rejected packet starts no span. The CONSUMER `process` span is a child of a valid sender context and links to it; a missing or invalid `traceparent` starts a new root. The handler gets `ctx.otel_context`, which the runtime does not make current.
698
+ - **Result**: the `publish sys.job.result` span is a child of the process span, and its context goes out with the result. A handler error marks the process span `HANDLER_FAILED`; a failed publish marks its span `TRANSPORT_PUBLISH_FAILED`.
699
+ - **Never authority**: trace headers never select tenant, principal, key, policy or approval, and `baggage` is never read or sent.
700
+ - **Off by default**: with no `telemetry`, no headers are sent and no spans are started.