re-cinq-agent-contracts 0.16.1__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.
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .coverage
5
+ dist/
6
+ .pytest_cache/
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: re-cinq-agent-contracts
3
+ Version: 0.16.1
4
+ Summary: Pydantic models and a client for the ai-agent-subsystem CRDs (Agent / Station / AgentDefinition / ModelCatalog / AgentSpawner). Types are generated from the D source so they cannot drift.
5
+ Project-URL: Homepage, https://github.com/re-cinq/ai-agent-subsystem
6
+ Project-URL: Documentation, https://re-cinq.github.io/ai-agent-subsystem/clients/python/
7
+ License-Expression: Apache-2.0
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: pydantic>=2.11
10
+ Provides-Extra: kubernetes
11
+ Requires-Dist: kubernetes>=30; extra == 'kubernetes'
12
+ Provides-Extra: test
13
+ Requires-Dist: kubernetes>=30; extra == 'test'
14
+ Requires-Dist: pytest-cov>=5; extra == 'test'
15
+ Requires-Dist: pytest>=8; extra == 'test'
16
+ Requires-Dist: pyyaml>=6; extra == 'test'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # re-cinq-agent-contracts (Python)
20
+
21
+ Pydantic models and a small client for the [ai-agent-subsystem](https://github.com/re-cinq/ai-agent-subsystem)
22
+ Custom Resources: **Agent**, **Station**, **AgentDefinition**, **ModelCatalog** and **AgentSpawner** (API group
23
+ `agents.re-cinq.com/v1beta1`).
24
+
25
+ The models are generated from the D structs that define the CRDs, the same source the CRD YAML and
26
+ the TypeScript, Go and Java contracts come from, so they cannot drift. CI fails if the committed
27
+ file stops matching the model, and a test decodes every manifest in `examples/` and fails on any
28
+ field the models do not know.
29
+
30
+ ## Install
31
+
32
+ ```sh
33
+ pip install "re-cinq-agent-contracts[kubernetes]"
34
+ ```
35
+
36
+ The `kubernetes` extra brings the official client the examples use. Versions follow the
37
+ subsystem's releases. Requires Python 3.10+ and Pydantic 2.11+.
38
+
39
+ ## Models
40
+
41
+ Every resource and nested type is a Pydantic model. Attributes are snake_case and accept either
42
+ name on input (`AgentSpec(station_ref=...)` or `AgentSpec.model_validate({"stationRef": ...})`).
43
+ Write the wire form with `model_dump(by_alias=True, exclude_none=True)`.
44
+
45
+ - A field left at `None` is omitted, so the API server applies the CRD's default.
46
+ - Free-form fields such as `StationSpec.template` are `Any`.
47
+ - Enums are `str` enums; an unknown value decodes to the first member, the same rule the controller
48
+ applies, so a newer cluster does not break an older client.
49
+ - Fields the models do not know are kept and written back, so reading and re-applying a resource
50
+ does not drop them.
51
+ - Each kind has `PLURAL` and `SHORT_NAMES`; `GROUP`, `VERSION` and `API_VERSION` are module constants.
52
+
53
+ ## Client
54
+
55
+ `AgentContractsClient` wraps the `kubernetes` package's `CustomObjectsApi` and works in one
56
+ namespace (`ai-agents` by default):
57
+
58
+ ```python
59
+ from kubernetes import client, config
60
+
61
+ from agent_contracts import Agent, AgentContractsClient, AgentSpec, ObjectMeta
62
+
63
+ config.load_config() # kubeconfig, or the pod's service account in a cluster
64
+ agents = AgentContractsClient(client.CustomObjectsApi())
65
+
66
+ run = agents.create_agent(Agent(
67
+ metadata=ObjectMeta(generate_name="story-writer-run-"),
68
+ spec=AgentSpec(station_ref="story-writer", parameters={"title": "The Last Lighthouse"}),
69
+ ))
70
+
71
+ finished = agents.wait_for_agent(run.metadata.name, timeout=1800)
72
+ print(finished.status.phase)
73
+ ```
74
+
75
+ | Method | Does |
76
+ | --- | --- |
77
+ | `create_agent` | Start one run. |
78
+ | `get_agent`, `find_agents` | Read one run, or list runs by label selector. |
79
+ | `wait_for_agent` | Poll until the run is `SUCCEEDED` or `FAILED`; `AgentNotFinishedError` after the timeout. |
80
+ | `get_model_catalog` | The models the subsystem can run with its configured keys. |
81
+ | `apply_agent_definition`, `apply_station` | Server-side apply a recipe or runtime (field manager `agent-contracts`, forced). |
82
+ | `is_terminal` | Whether a run has finished. |
83
+
84
+ ## Development
85
+
86
+ `make regen` from the repository root rewrites `src/agent_contracts/types_generated.py`; do not
87
+ edit it by hand. `make contracts-python` runs the tests with a 100% coverage gate on the client.
@@ -0,0 +1,69 @@
1
+ # re-cinq-agent-contracts (Python)
2
+
3
+ Pydantic models and a small client for the [ai-agent-subsystem](https://github.com/re-cinq/ai-agent-subsystem)
4
+ Custom Resources: **Agent**, **Station**, **AgentDefinition**, **ModelCatalog** and **AgentSpawner** (API group
5
+ `agents.re-cinq.com/v1beta1`).
6
+
7
+ The models are generated from the D structs that define the CRDs, the same source the CRD YAML and
8
+ the TypeScript, Go and Java contracts come from, so they cannot drift. CI fails if the committed
9
+ file stops matching the model, and a test decodes every manifest in `examples/` and fails on any
10
+ field the models do not know.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pip install "re-cinq-agent-contracts[kubernetes]"
16
+ ```
17
+
18
+ The `kubernetes` extra brings the official client the examples use. Versions follow the
19
+ subsystem's releases. Requires Python 3.10+ and Pydantic 2.11+.
20
+
21
+ ## Models
22
+
23
+ Every resource and nested type is a Pydantic model. Attributes are snake_case and accept either
24
+ name on input (`AgentSpec(station_ref=...)` or `AgentSpec.model_validate({"stationRef": ...})`).
25
+ Write the wire form with `model_dump(by_alias=True, exclude_none=True)`.
26
+
27
+ - A field left at `None` is omitted, so the API server applies the CRD's default.
28
+ - Free-form fields such as `StationSpec.template` are `Any`.
29
+ - Enums are `str` enums; an unknown value decodes to the first member, the same rule the controller
30
+ applies, so a newer cluster does not break an older client.
31
+ - Fields the models do not know are kept and written back, so reading and re-applying a resource
32
+ does not drop them.
33
+ - Each kind has `PLURAL` and `SHORT_NAMES`; `GROUP`, `VERSION` and `API_VERSION` are module constants.
34
+
35
+ ## Client
36
+
37
+ `AgentContractsClient` wraps the `kubernetes` package's `CustomObjectsApi` and works in one
38
+ namespace (`ai-agents` by default):
39
+
40
+ ```python
41
+ from kubernetes import client, config
42
+
43
+ from agent_contracts import Agent, AgentContractsClient, AgentSpec, ObjectMeta
44
+
45
+ config.load_config() # kubeconfig, or the pod's service account in a cluster
46
+ agents = AgentContractsClient(client.CustomObjectsApi())
47
+
48
+ run = agents.create_agent(Agent(
49
+ metadata=ObjectMeta(generate_name="story-writer-run-"),
50
+ spec=AgentSpec(station_ref="story-writer", parameters={"title": "The Last Lighthouse"}),
51
+ ))
52
+
53
+ finished = agents.wait_for_agent(run.metadata.name, timeout=1800)
54
+ print(finished.status.phase)
55
+ ```
56
+
57
+ | Method | Does |
58
+ | --- | --- |
59
+ | `create_agent` | Start one run. |
60
+ | `get_agent`, `find_agents` | Read one run, or list runs by label selector. |
61
+ | `wait_for_agent` | Poll until the run is `SUCCEEDED` or `FAILED`; `AgentNotFinishedError` after the timeout. |
62
+ | `get_model_catalog` | The models the subsystem can run with its configured keys. |
63
+ | `apply_agent_definition`, `apply_station` | Server-side apply a recipe or runtime (field manager `agent-contracts`, forced). |
64
+ | `is_terminal` | Whether a run has finished. |
65
+
66
+ ## Development
67
+
68
+ `make regen` from the repository root rewrites `src/agent_contracts/types_generated.py`; do not
69
+ edit it by hand. `make contracts-python` runs the tests with a 100% coverage gate on the client.
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "re-cinq-agent-contracts"
7
+ # release version: bumped in the release PR together with packages/agent-contracts/package.json
8
+ version = "0.16.1"
9
+ description = "Pydantic models and a client for the ai-agent-subsystem CRDs (Agent / Station / AgentDefinition / ModelCatalog / AgentSpawner). Types are generated from the D source so they cannot drift."
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ requires-python = ">=3.10"
13
+ dependencies = ["pydantic>=2.11"]
14
+
15
+ [project.optional-dependencies]
16
+ kubernetes = ["kubernetes>=30"]
17
+ test = ["pytest>=8", "pytest-cov>=5", "pyyaml>=6", "kubernetes>=30"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/re-cinq/ai-agent-subsystem"
21
+ Documentation = "https://re-cinq.github.io/ai-agent-subsystem/clients/python/"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/agent_contracts"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
28
+ addopts = "--cov=agent_contracts.client --cov-branch --cov-report=term-missing --cov-fail-under=100"
29
+ filterwarnings = ["error"]
@@ -0,0 +1,11 @@
1
+ """Types and a client for the ai-agent-subsystem Custom Resources."""
2
+
3
+ from agent_contracts.client import (
4
+ DEFAULT_NAMESPACE,
5
+ AgentContractsClient,
6
+ AgentNotFinishedError,
7
+ is_terminal,
8
+ )
9
+ from agent_contracts.types_generated import * # noqa: F403
10
+
11
+ __all__ = ["DEFAULT_NAMESPACE", "AgentContractsClient", "AgentNotFinishedError", "is_terminal"]
@@ -0,0 +1,19 @@
1
+ """The part of the ``kubernetes`` package the client calls, so any object with these methods works."""
2
+
3
+ from typing import Any, Protocol
4
+
5
+
6
+ class CustomObjects(Protocol):
7
+ """The part of ``kubernetes.client.CustomObjectsApi`` the client uses."""
8
+
9
+ def create_namespaced_custom_object(self, group: str, version: str, namespace: str, plural: str,
10
+ body: dict[str, Any], **kwargs: Any) -> Any: ...
11
+
12
+ def get_namespaced_custom_object(self, group: str, version: str, namespace: str, plural: str,
13
+ name: str, **kwargs: Any) -> Any: ...
14
+
15
+ def list_namespaced_custom_object(self, group: str, version: str, namespace: str, plural: str,
16
+ **kwargs: Any) -> Any: ...
17
+
18
+ def patch_namespaced_custom_object(self, group: str, version: str, namespace: str, plural: str,
19
+ name: str, body: Any, **kwargs: Any) -> Any: ...
@@ -0,0 +1,106 @@
1
+ """Creates and reads the subsystem's resources in one namespace through the official
2
+ ``kubernetes`` package's ``CustomObjectsApi``, or anything with the same four methods."""
3
+
4
+ import time
5
+ from collections.abc import Callable
6
+ from typing import Any, TypeVar
7
+
8
+ from agent_contracts.api import CustomObjects
9
+
10
+ from agent_contracts.types_generated import (
11
+ GROUP,
12
+ VERSION,
13
+ Agent,
14
+ AgentDefinition,
15
+ ModelCatalog,
16
+ Phase,
17
+ Station,
18
+ _Model,
19
+ )
20
+
21
+ DEFAULT_NAMESPACE = "ai-agents"
22
+
23
+ _FIELD_MANAGER = "agent-contracts"
24
+ _MODEL_CATALOG_NAME = "default"
25
+ _APPLY_PATCH = "application/apply-patch+yaml"
26
+
27
+ _Resource = TypeVar("_Resource", bound=_Model)
28
+
29
+
30
+ class AgentNotFinishedError(TimeoutError):
31
+ """A run did not reach a terminal phase before the timeout."""
32
+
33
+
34
+ def is_terminal(agent: Agent) -> bool:
35
+ """Whether a run has finished (Succeeded or Failed)."""
36
+ phase = agent.status.phase if agent.status else None
37
+ return phase in (Phase.SUCCEEDED, Phase.FAILED)
38
+
39
+
40
+ def _wire(resource: _Model) -> dict[str, Any]:
41
+ return resource.model_dump(by_alias=True, exclude_none=True, mode="json")
42
+
43
+
44
+ class AgentContractsClient:
45
+ """Typed calls for the Agent, Station, AgentDefinition and ModelCatalog resources."""
46
+
47
+ def __init__(self, api: CustomObjects, namespace: str | None = None) -> None:
48
+ self._api = api
49
+ self._namespace = namespace or DEFAULT_NAMESPACE
50
+
51
+ def create_agent(self, agent: Agent) -> Agent:
52
+ """Starts one run in the client's namespace."""
53
+ created = self._api.create_namespaced_custom_object(
54
+ GROUP, VERSION, self._namespace, Agent.PLURAL, _wire(agent))
55
+ return Agent.model_validate(created)
56
+
57
+ def get_agent(self, name: str) -> Agent:
58
+ """Reads one run; the API's 404 error propagates for an unknown name."""
59
+ return Agent.model_validate(self._api.get_namespaced_custom_object(
60
+ GROUP, VERSION, self._namespace, Agent.PLURAL, name))
61
+
62
+ def find_agents(self, label_selector: str) -> list[Agent]:
63
+ """Lists the runs matching a Kubernetes label selector such as ``team=web``."""
64
+ listed = self._api.list_namespaced_custom_object(
65
+ GROUP, VERSION, self._namespace, Agent.PLURAL, label_selector=label_selector)
66
+ return [Agent.model_validate(item) for item in listed.get("items") or []]
67
+
68
+ def get_model_catalog(self) -> ModelCatalog:
69
+ """Reads the models the subsystem can run (the controller's ``default`` ModelCatalog)."""
70
+ return ModelCatalog.model_validate(self._api.get_namespaced_custom_object(
71
+ GROUP, VERSION, self._namespace, ModelCatalog.PLURAL, _MODEL_CATALOG_NAME))
72
+
73
+ def apply_agent_definition(self, definition: AgentDefinition) -> AgentDefinition:
74
+ """Server-side applies an AgentDefinition, taking over fields other managers set."""
75
+ return self._apply(definition)
76
+
77
+ def apply_station(self, station: Station) -> Station:
78
+ """Server-side applies a Station, taking over fields other managers set."""
79
+ return self._apply(station)
80
+
81
+ def _apply(self, resource: _Resource) -> _Resource:
82
+ name = resource.metadata.name if resource.metadata else None
83
+ if not name:
84
+ raise ValueError(f"apply {resource.kind}: metadata.name is required")
85
+ body = _wire(resource)
86
+ body["metadata"] = {**body["metadata"], "namespace": self._namespace}
87
+ body["metadata"].pop("managedFields", None)
88
+ applied = self._api.patch_namespaced_custom_object(
89
+ GROUP, VERSION, self._namespace, type(resource).PLURAL, name, body,
90
+ field_manager=_FIELD_MANAGER, force=True, _content_type=_APPLY_PATCH)
91
+ return type(resource).model_validate(applied)
92
+
93
+ def wait_for_agent(self, name: str, timeout: float = 1200.0, interval: float = 2.0,
94
+ sleep: Callable[[float], None] = time.sleep,
95
+ clock: Callable[[], float] = time.monotonic) -> Agent:
96
+ """Polls the run until it is Succeeded or Failed, or raises AgentNotFinishedError after
97
+ ``timeout`` seconds."""
98
+ deadline = clock() + timeout
99
+ while True:
100
+ agent = self.get_agent(name)
101
+ if is_terminal(agent):
102
+ return agent
103
+ if clock() >= deadline:
104
+ raise AgentNotFinishedError(
105
+ f"agent {name} did not reach a terminal phase within {timeout:g}s")
106
+ sleep(interval)
@@ -0,0 +1,582 @@
1
+ # Code generated by ai-agent-tsgen from the agentcore CRD structs. DO NOT EDIT.
2
+ # Regenerate: make regen
3
+
4
+ from enum import Enum
5
+ from typing import Any, ClassVar
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+ GROUP = "agents.re-cinq.com"
10
+ VERSION = "v1beta1"
11
+ API_VERSION = "agents.re-cinq.com/v1beta1"
12
+
13
+
14
+ class _Model(BaseModel):
15
+ """Accepts wire names and Python names, and keeps fields it does not know."""
16
+
17
+ model_config = ConfigDict(validate_by_name=True, validate_by_alias=True, extra="allow")
18
+
19
+
20
+ class PermissionMode(str, Enum):
21
+ AUTO = "auto"
22
+ BYPASS = "bypass"
23
+
24
+ @classmethod
25
+ def _missing_(cls, value: object) -> "PermissionMode":
26
+ return next(iter(cls))
27
+
28
+
29
+ class McpTransport(str, Enum):
30
+ STDIO = "stdio"
31
+ HTTP = "http"
32
+ SSE = "sse"
33
+
34
+ @classmethod
35
+ def _missing_(cls, value: object) -> "McpTransport":
36
+ return next(iter(cls))
37
+
38
+
39
+ class OutputFormat(str, Enum):
40
+ TEXT = "text"
41
+ JSON = "json"
42
+ STREAM_JSON = "stream-json"
43
+
44
+ @classmethod
45
+ def _missing_(cls, value: object) -> "OutputFormat":
46
+ return next(iter(cls))
47
+
48
+
49
+ class SelectEvent(str, Enum):
50
+ TOOL_CALL = "tool_call"
51
+ MESSAGE = "message"
52
+ TOOL_RESULT = "tool_result"
53
+ RESULT = "result"
54
+ USAGE = "usage"
55
+
56
+ @classmethod
57
+ def _missing_(cls, value: object) -> "SelectEvent":
58
+ return next(iter(cls))
59
+
60
+
61
+ class SelectRole(str, Enum):
62
+ ASSISTANT = "assistant"
63
+ USER = "user"
64
+
65
+ @classmethod
66
+ def _missing_(cls, value: object) -> "SelectRole":
67
+ return next(iter(cls))
68
+
69
+
70
+ class SinkType(str, Enum):
71
+ STDOUT = "stdout"
72
+ HTTP = "http"
73
+ FILE = "file"
74
+
75
+ @classmethod
76
+ def _missing_(cls, value: object) -> "SinkType":
77
+ return next(iter(cls))
78
+
79
+
80
+ class ConcurrencyPolicy(str, Enum):
81
+ ALLOW = "Allow"
82
+ FORBID = "Forbid"
83
+ REPLACE = "Replace"
84
+
85
+ @classmethod
86
+ def _missing_(cls, value: object) -> "ConcurrencyPolicy":
87
+ return next(iter(cls))
88
+
89
+
90
+ class SpawnerConcurrencyPolicy(str, Enum):
91
+ ALLOW = "Allow"
92
+ FORBID = "Forbid"
93
+
94
+ @classmethod
95
+ def _missing_(cls, value: object) -> "SpawnerConcurrencyPolicy":
96
+ return next(iter(cls))
97
+
98
+
99
+ class Execution(str, Enum):
100
+ INTERACTIVE = "interactive"
101
+ BATCH = "batch"
102
+ REALTIME = "realtime"
103
+
104
+ @classmethod
105
+ def _missing_(cls, value: object) -> "Execution":
106
+ return next(iter(cls))
107
+
108
+
109
+ class BatchTimeoutAction(str, Enum):
110
+ FAIL = "fail"
111
+ FALLBACK = "fallback"
112
+
113
+ @classmethod
114
+ def _missing_(cls, value: object) -> "BatchTimeoutAction":
115
+ return next(iter(cls))
116
+
117
+
118
+ class Phase(str, Enum):
119
+ PENDING = "Pending"
120
+ RUNNING = "Running"
121
+ SUCCEEDED = "Succeeded"
122
+ FAILED = "Failed"
123
+
124
+ @classmethod
125
+ def _missing_(cls, value: object) -> "Phase":
126
+ return next(iter(cls))
127
+
128
+
129
+ class ObjectMeta(_Model):
130
+ name: str | None = Field(default=None, alias="name")
131
+ generate_name: str | None = Field(default=None, alias="generateName")
132
+ namespace: str | None = Field(default=None, alias="namespace")
133
+ uid: str | None = Field(default=None, alias="uid")
134
+ resource_version: str | None = Field(default=None, alias="resourceVersion")
135
+ creation_timestamp: str | None = Field(default=None, alias="creationTimestamp")
136
+ labels: dict[str, str] | None = Field(default=None, alias="labels")
137
+ annotations: dict[str, str] | None = Field(default=None, alias="annotations")
138
+ finalizers: list[str] | None = Field(default=None, alias="finalizers")
139
+ deletion_timestamp: str | None = Field(default=None, alias="deletionTimestamp")
140
+
141
+
142
+ class EnvVar(_Model):
143
+ name: str = Field(alias="name")
144
+ value: str = Field(alias="value")
145
+
146
+
147
+ class SecretRef(_Model):
148
+ name: str = Field(alias="name")
149
+ """Environment variable name to expose the secret as."""
150
+
151
+ ref: str = Field(alias="ref")
152
+ """Allowlisted secret-store key."""
153
+
154
+
155
+
156
+ class McpHeader(_Model):
157
+ name: str = Field(alias="name")
158
+ """HTTP header name, e.g. X-API-Key."""
159
+
160
+ ref: str = Field(alias="ref")
161
+ """Allowlisted secret-store key holding the header value."""
162
+
163
+
164
+
165
+ class McpServer(_Model):
166
+ name: str = Field(alias="name")
167
+ transport: McpTransport = Field(alias="transport")
168
+ command: str | None = Field(default=None, alias="command")
169
+ args: list[str] | None = Field(default=None, alias="args")
170
+ url: str | None = Field(default=None, alias="url")
171
+ headers_secret: str | None = Field(default=None, alias="headers_secret")
172
+ """Deprecated: use headers. Allowlisted secret-store key sent as the Authorization header."""
173
+
174
+ headers: list[McpHeader] | None = Field(default=None, alias="headers")
175
+ """http/sse: headers whose values come from the secret store."""
176
+
177
+ env: list[SecretRef] | None = Field(default=None, alias="env")
178
+ """stdio: environment variables for the server process whose values come from the secret store."""
179
+
180
+
181
+
182
+ class RepoRef(_Model):
183
+ name: str = Field(alias="name")
184
+ url: str = Field(alias="url")
185
+ ref: str | None = Field(default=None, alias="ref")
186
+ path: str | None = Field(default=None, alias="path")
187
+ token_secret: str | None = Field(default=None, alias="token_secret")
188
+
189
+
190
+ class ConversationRef(_Model):
191
+ source: str | None = Field(default=None, alias="source")
192
+ """Base URL the prior conversation state is fetched from."""
193
+
194
+ id: str | None = Field(default=None, alias="id")
195
+ """Conversation to continue; empty starts a fresh one."""
196
+
197
+ pin: str | None = Field(default=None, alias="pin")
198
+ """Id this run's state is saved as; empty means it is not saved."""
199
+
200
+ headers_secret: str | None = Field(default=None, alias="headers_secret")
201
+ """Secret holding the Authorization header for the fetch."""
202
+
203
+
204
+
205
+ class AgentResources(_Model):
206
+ env: list[EnvVar] | None = Field(default=None, alias="env")
207
+ secrets: list[SecretRef] | None = Field(default=None, alias="secrets")
208
+ mcp_servers: list[McpServer] | None = Field(default=None, alias="mcp_servers")
209
+ repos: list[RepoRef] | None = Field(default=None, alias="repos")
210
+ skills: list[str] | None = Field(default=None, alias="skills")
211
+ skills_source: str | None = Field(default=None, alias="skills_source")
212
+ conversation: ConversationRef | None = Field(default=None, alias="conversation")
213
+
214
+
215
+ class OutputSelector(_Model):
216
+ event: SelectEvent = Field(alias="event")
217
+ tool: str | None = Field(default=None, alias="tool")
218
+ role: SelectRole | None = Field(default=None, alias="role")
219
+ contains: str | None = Field(default=None, alias="contains")
220
+
221
+
222
+ class OutputSink(_Model):
223
+ type: SinkType = Field(alias="type")
224
+ url: str | None = Field(default=None, alias="url")
225
+ headers_secret: str | None = Field(default=None, alias="headers_secret")
226
+ path: str | None = Field(default=None, alias="path")
227
+
228
+
229
+ class WatchUpload(_Model):
230
+ url: str = Field(alias="url")
231
+ """URL the file is POSTed to; {agent} and {event} are expanded per run."""
232
+
233
+ headers_secret: str | None = Field(default=None, alias="headers_secret")
234
+ """Secret key holding the header block sent with the upload."""
235
+
236
+
237
+
238
+ class OutputWatch(_Model):
239
+ event: str = Field(alias="event")
240
+ """Event name raised when the file is produced."""
241
+
242
+ path: str = Field(alias="path")
243
+ """File to read; relative paths resolve against WORKSPACE_DIR."""
244
+
245
+ upload: WatchUpload | None = Field(default=None, alias="upload")
246
+ """Upload the file to a URL instead of inlining its content."""
247
+
248
+
249
+
250
+ class OutputSpec(_Model):
251
+ format: OutputFormat | None = Field(default=None, alias="format")
252
+ schema_: Any | None = Field(default=None, alias="schema")
253
+ """JSON Schema validating the result."""
254
+
255
+ select: list[OutputSelector] | None = Field(default=None, alias="select")
256
+ sinks: list[OutputSink] | None = Field(default=None, alias="sinks")
257
+ watch: list[OutputWatch] | None = Field(default=None, alias="watch")
258
+
259
+
260
+ class RunOutput(_Model):
261
+ """Where one run's output goes; sinks and select replace the AgentDefinition's when set, watch merges by event."""
262
+
263
+ sinks: list[OutputSink] | None = Field(default=None, alias="sinks")
264
+ """Sinks for this run; when set they replace the recipe's sinks."""
265
+
266
+ select: list[OutputSelector] | None = Field(default=None, alias="select")
267
+ """Which events reach the sinks; when set it replaces the recipe's selectors."""
268
+
269
+ watch: list[OutputWatch] | None = Field(default=None, alias="watch")
270
+ """Files this run produces. An entry replaces the recipe's watch of the same event (so a run can give a recipe's watch its own upload); other events are added."""
271
+
272
+
273
+
274
+ class PullRequestDelivery(_Model):
275
+ """Open a pull request from the run's work branch; the push happens outside the agent container."""
276
+
277
+ base: str = Field(alias="base")
278
+ """Branch the pull request merges into."""
279
+
280
+ title_template: str = Field(alias="titleTemplate")
281
+ """Pull request title; {placeholder} tokens are filled from the Agent's parameters."""
282
+
283
+ draft: bool | None = Field(default=None, alias="draft")
284
+ """Open the pull request as a draft."""
285
+
286
+ api_url: str | None = Field(default=None, alias="apiUrl")
287
+ """GitHub REST API base URL; defaults to https://api.github.com."""
288
+
289
+
290
+
291
+ class DeliverySpec(_Model):
292
+ """What happens to the run's work once the agent exits."""
293
+
294
+ pull_request: PullRequestDelivery | None = Field(default=None, alias="pullRequest")
295
+
296
+
297
+ class BatchSpec(_Model):
298
+ timeout_minutes: int | None = Field(default=None, alias="timeoutMinutes")
299
+ """Minutes to wait for the batch result before onTimeout applies."""
300
+
301
+ on_timeout: BatchTimeoutAction | None = Field(default=None, alias="onTimeout")
302
+ """fail marks the Agent Failed; fallback reruns the work as a CLI Job."""
303
+
304
+ max_tokens: int | None = Field(default=None, alias="maxTokens")
305
+ """Output token ceiling (max_tokens) for the batch request."""
306
+
307
+
308
+
309
+ class RealtimeSpec(_Model):
310
+ idle_timeout_minutes: int | None = Field(default=None, alias="idleTimeoutMinutes")
311
+ """Minutes without a prompt or a running turn after which the session ends and its conversation is saved."""
312
+
313
+
314
+
315
+ class AgentDefinitionSpec(_Model):
316
+ """The reusable recipe for a coding agent task."""
317
+
318
+ description: str | None = Field(default=None, alias="description")
319
+ """Human summary for operators."""
320
+
321
+ model: str | None = Field(default=None, alias="model")
322
+ """Model id (e.g. claude-sonnet-4-6). If omitted, the runtime default is used."""
323
+
324
+ prompt: str = Field(alias="prompt")
325
+ """Task template; {placeholder} tokens are filled from an Agent's parameters."""
326
+
327
+ allowed_tools: list[str] | None = Field(default=None, alias="allowed_tools")
328
+ disallowed_tools: list[str] | None = Field(default=None, alias="disallowed_tools")
329
+ permission_mode: PermissionMode | None = Field(default=None, alias="permission_mode")
330
+ max_turns: int | None = Field(default=None, alias="max_turns")
331
+ execution: Execution | None = Field(default=None, alias="execution")
332
+ batch: BatchSpec | None = Field(default=None, alias="batch")
333
+ realtime: RealtimeSpec | None = Field(default=None, alias="realtime")
334
+ resources: AgentResources | None = Field(default=None, alias="resources")
335
+ output: OutputSpec | None = Field(default=None, alias="output")
336
+ delivery: DeliverySpec | None = Field(default=None, alias="delivery")
337
+ tool_config: Any | None = Field(default=None, alias="tool_config")
338
+ """Raw passthrough for tool-specific knobs."""
339
+
340
+
341
+
342
+ class AgentDefinition(_Model):
343
+ PLURAL: ClassVar[str] = "agentdefinitions"
344
+ SHORT_NAMES: ClassVar[tuple[str, ...]] = ("agentdef", "ad", )
345
+
346
+ api_version: str = Field(default=API_VERSION, alias="apiVersion")
347
+ kind: str = "AgentDefinition"
348
+ metadata: ObjectMeta | None = Field(default=None, alias="metadata")
349
+ spec: AgentDefinitionSpec | None = Field(default=None, alias="spec")
350
+
351
+
352
+ class StationSpec(_Model):
353
+ """The runtime template that pairs a recipe with a Pod template."""
354
+
355
+ agent_def_ref: str = Field(alias="agentDefRef")
356
+ """Name of the AgentDefinition this Station runs."""
357
+
358
+ deadline_minutes: int | None = Field(default=None, alias="deadlineMinutes")
359
+ """Wall-clock limit per run; becomes the Job's activeDeadlineSeconds."""
360
+
361
+ successful_runs_history_limit: int | None = Field(default=None, alias="successfulRunsHistoryLimit")
362
+ failed_runs_history_limit: int | None = Field(default=None, alias="failedRunsHistoryLimit")
363
+ max_concurrent_runs: int | None = Field(default=None, alias="maxConcurrentRuns")
364
+ """Max Agents of this Station running at once; 0 is unlimited. A Pending Agent waits while at the limit."""
365
+
366
+ concurrency_policy: ConcurrencyPolicy | None = Field(default=None, alias="concurrencyPolicy")
367
+ """At the limit: Allow queues (default), Forbid caps at one, Replace cancels the oldest run for the new one."""
368
+
369
+ template: Any = Field(alias="template")
370
+ """Standard Kubernetes PodTemplateSpec; the container named "agent" is wired with the recipe."""
371
+
372
+
373
+
374
+ class Station(_Model):
375
+ PLURAL: ClassVar[str] = "stations"
376
+ SHORT_NAMES: ClassVar[tuple[str, ...]] = ("stn", )
377
+
378
+ api_version: str = Field(default=API_VERSION, alias="apiVersion")
379
+ kind: str = "Station"
380
+ metadata: ObjectMeta | None = Field(default=None, alias="metadata")
381
+ spec: StationSpec | None = Field(default=None, alias="spec")
382
+
383
+
384
+ class InputFile(_Model):
385
+ path: str = Field(alias="path")
386
+ """Destination, relative to WORKSPACE_DIR; must stay inside it."""
387
+
388
+ url: str = Field(alias="url")
389
+ """http(s) URL the file is downloaded from."""
390
+
391
+ headers_secret: str | None = Field(default=None, alias="headers_secret")
392
+ """Secret key holding the header block sent with the download."""
393
+
394
+
395
+
396
+ class AgentSpec(_Model):
397
+ """One run of a recipe in a Station. The AgentDefinition is the reusable recipe; what belongs to a single run (repos, conversation, output, secrets, env) can be given here and wins over the recipe's value when set, so one AgentDefinition serves many Agents."""
398
+
399
+ station_ref: str = Field(alias="stationRef")
400
+ """The Station to run in (which selects the recipe)."""
401
+
402
+ task_id: str | None = Field(default=None, alias="taskId")
403
+ """External id for correlation."""
404
+
405
+ model: str | None = Field(default=None, alias="model")
406
+ """Model id for this run; overrides the AgentDefinition's model."""
407
+
408
+ target_repo: str | None = Field(default=None, alias="targetRepo")
409
+ """GitHub repo in owner/name form."""
410
+
411
+ branch: str | None = Field(default=None, alias="branch")
412
+ parameters: dict[str, str] | None = Field(default=None, alias="parameters")
413
+ """Per-run values; fill the prompt {placeholder} tokens and pass to the agent."""
414
+
415
+ files: list[InputFile] | None = Field(default=None, alias="files")
416
+ """Files downloaded into the workspace before the agent starts; only references travel."""
417
+
418
+ resume_session: str | None = Field(default=None, alias="resumeSession")
419
+ """Session id of an earlier realtime run to continue: its saved conversation is restored and the definition's prompt is not sent."""
420
+
421
+ repos: list[RepoRef] | None = Field(default=None, alias="repos")
422
+ """Repositories to clone for this run; when set they replace the AgentDefinition's resources.repos."""
423
+
424
+ conversation: ConversationRef | None = Field(default=None, alias="conversation")
425
+ """Conversation to continue and the id to save under; each field set here wins over the same field of the AgentDefinition's resources.conversation."""
426
+
427
+ output: RunOutput | None = Field(default=None, alias="output")
428
+ """Where this run's output goes; see RunOutput for how each field combines with the AgentDefinition's output."""
429
+
430
+ secrets: list[SecretRef] | None = Field(default=None, alias="secrets")
431
+ """Secrets exposed to this run, such as per-run credentials; an entry replaces the AgentDefinition's resources.secrets entry of the same name, others are added."""
432
+
433
+ env: list[EnvVar] | None = Field(default=None, alias="env")
434
+ """Environment values for this run, such as ones derived from its inputs; an entry replaces the AgentDefinition's resources.env entry of the same name, others are added."""
435
+
436
+
437
+
438
+ class AgentStatus(_Model):
439
+ phase: Phase | None = Field(default=None, alias="phase")
440
+ job_name: str | None = Field(default=None, alias="jobName")
441
+ started_at: str | None = Field(default=None, alias="startedAt")
442
+ """RFC3339 timestamp when the run began."""
443
+
444
+ completed_at: str | None = Field(default=None, alias="completedAt")
445
+ """RFC3339 timestamp when the run ended."""
446
+
447
+ exit_code: int | None = Field(default=None, alias="exitCode")
448
+ output: str | None = Field(default=None, alias="output")
449
+ failure_reason: str | None = Field(default=None, alias="failureReason")
450
+ pr_url: str | None = Field(default=None, alias="prUrl")
451
+ """URL of the pull request the run opened (spec.delivery.pullRequest)."""
452
+
453
+ session_id: str | None = Field(default=None, alias="sessionId")
454
+ """Harness session id of this run; pass it as spec.resumeSession to continue the conversation."""
455
+
456
+ batch_id: str | None = Field(default=None, alias="batchId")
457
+ """Provider batch id while a batch-executed run is in flight."""
458
+
459
+ batch_provider: str | None = Field(default=None, alias="batchProvider")
460
+ """Provider the batch was submitted to."""
461
+
462
+ batch_fallback: bool | None = Field(default=None, alias="batchFallback")
463
+ """True once the batch timed out and the fallback Job started."""
464
+
465
+ batch_cleanup_attempts: int | None = Field(default=None, alias="batchCleanupAttempts")
466
+ """Failed attempts to delete the batch's provider-side objects."""
467
+
468
+
469
+
470
+ class Agent(_Model):
471
+ PLURAL: ClassVar[str] = "agents"
472
+ SHORT_NAMES: ClassVar[tuple[str, ...]] = ("agt", )
473
+
474
+ api_version: str = Field(default=API_VERSION, alias="apiVersion")
475
+ kind: str = "Agent"
476
+ metadata: ObjectMeta | None = Field(default=None, alias="metadata")
477
+ spec: AgentSpec | None = Field(default=None, alias="spec")
478
+ status: AgentStatus | None = Field(default=None, alias="status")
479
+
480
+
481
+ class ModelInfo(_Model):
482
+ id: str | None = Field(default=None, alias="id")
483
+ """Model id to set as an AgentDefinition's or Agent's model."""
484
+
485
+ display_name: str | None = Field(default=None, alias="displayName")
486
+ """The vendor's human-readable name for the model."""
487
+
488
+
489
+
490
+ class VendorModels(_Model):
491
+ vendor: str | None = Field(default=None, alias="vendor")
492
+ """Agent CLI vendor the subsystem routes these model ids to."""
493
+
494
+ provider: str | None = Field(default=None, alias="provider")
495
+ """Provider API whose list-models endpoint was queried."""
496
+
497
+ secret_refs: list[str] | None = Field(default=None, alias="secretRefs")
498
+ """agent-secrets keys that were queried; an AgentDefinition can run these models when its resources.secrets maps one of them."""
499
+
500
+ error: str | None = Field(default=None, alias="error")
501
+ """Why the last refresh could not list models with some of the keys; empty when every key answered."""
502
+
503
+ models: list[ModelInfo] | None = Field(default=None, alias="models")
504
+
505
+
506
+ class ModelCatalogStatus(_Model):
507
+ refreshed_at: str | None = Field(default=None, alias="refreshedAt")
508
+ """RFC3339 timestamp of the last refresh."""
509
+
510
+ vendors: list[VendorModels] | None = Field(default=None, alias="vendors")
511
+
512
+
513
+ class ModelCatalog(_Model):
514
+ """The models the subsystem can run, written by the controller from each vendor's list-models API."""
515
+
516
+ PLURAL: ClassVar[str] = "modelcatalogs"
517
+ SHORT_NAMES: ClassVar[tuple[str, ...]] = ("mc", )
518
+
519
+ api_version: str = Field(default=API_VERSION, alias="apiVersion")
520
+ kind: str = "ModelCatalog"
521
+ metadata: ObjectMeta | None = Field(default=None, alias="metadata")
522
+ status: ModelCatalogStatus | None = Field(default=None, alias="status")
523
+
524
+
525
+ class GitHubTrigger(_Model):
526
+ """Starts a run for each signed GitHub webhook delivery that matches."""
527
+
528
+ secret_ref: str = Field(alias="secretRef")
529
+ """Key in the agent-secrets Secret holding the webhook's HMAC secret."""
530
+
531
+ events: list[str] = Field(alias="events")
532
+ """Deliveries that start a run, as <X-GitHub-Event>.<action> (issues.labeled); an event without an action by its name alone."""
533
+
534
+ label: str | None = Field(default=None, alias="label")
535
+ """Only issues carrying this label start a run; for issues.labeled, only when it is the label just added."""
536
+
537
+ repository: str | None = Field(default=None, alias="repository")
538
+ """Only deliveries from this owner/name repository start a run."""
539
+
540
+
541
+
542
+ class AgentSpawnerSpec(_Model):
543
+ """Creates an Agent in a Station on a cron schedule, on GitHub webhook deliveries, or both."""
544
+
545
+ station_ref: str = Field(alias="stationRef")
546
+ """The Station each spawned Agent runs in."""
547
+
548
+ schedule: str | None = Field(default=None, alias="schedule")
549
+ """Five-field cron expression (minute hour day-of-month month day-of-week), evaluated in UTC."""
550
+
551
+ github: GitHubTrigger | None = Field(default=None, alias="github")
552
+ """Starts a run for each matching GitHub webhook delivery."""
553
+
554
+ parameters: dict[str, str] | None = Field(default=None, alias="parameters")
555
+ """Copied verbatim into every spawned Agent's spec.parameters."""
556
+
557
+ concurrency_policy: SpawnerConcurrencyPolicy | None = Field(default=None, alias="concurrencyPolicy")
558
+ """Allow starts a run on every tick; Forbid skips a tick while an Agent this spawner created is not finished."""
559
+
560
+ suspend: bool | None = Field(default=None, alias="suspend")
561
+ """True stops new runs; runs already started are left alone."""
562
+
563
+
564
+
565
+ class AgentSpawnerStatus(_Model):
566
+ last_schedule_time: str | None = Field(default=None, alias="lastScheduleTime")
567
+ """RFC3339 schedule time of the last tick handled, whether it created an Agent or was skipped."""
568
+
569
+ last_agent: str | None = Field(default=None, alias="lastAgent")
570
+ """Name of the last Agent this spawner created."""
571
+
572
+
573
+
574
+ class AgentSpawner(_Model):
575
+ PLURAL: ClassVar[str] = "agentspawners"
576
+ SHORT_NAMES: ClassVar[tuple[str, ...]] = ("asp", )
577
+
578
+ api_version: str = Field(default=API_VERSION, alias="apiVersion")
579
+ kind: str = "AgentSpawner"
580
+ metadata: ObjectMeta | None = Field(default=None, alias="metadata")
581
+ spec: AgentSpawnerSpec | None = Field(default=None, alias="spec")
582
+ status: AgentSpawnerStatus | None = Field(default=None, alias="status")
@@ -0,0 +1,57 @@
1
+ """An in-memory stand-in for kubernetes.client.CustomObjectsApi: stores objects per
2
+ (namespace, plural, name) and records every call."""
3
+
4
+ import copy
5
+ import inspect
6
+ from typing import Any
7
+
8
+ from kubernetes.client import CustomObjectsApi
9
+ from kubernetes.client.exceptions import ApiException
10
+
11
+
12
+ def _real_signature(method):
13
+ """Fails a call whose arguments the real CustomObjectsApi method would reject."""
14
+ real = inspect.signature(getattr(CustomObjectsApi, method.__name__))
15
+
16
+ def checked(self, *args, **kwargs):
17
+ real.bind(self, *args, **kwargs)
18
+ return method(self, *args, **kwargs)
19
+ return checked
20
+
21
+
22
+ class FakeCustomObjects:
23
+ def __init__(self) -> None:
24
+ self.objects: dict[tuple[str, str, str], dict[str, Any]] = {}
25
+ self.patches: list[dict[str, Any]] = []
26
+ self.generated = 0
27
+
28
+ @_real_signature
29
+ def create_namespaced_custom_object(self, group, version, namespace, plural, body, **kwargs):
30
+ stored = copy.deepcopy(body)
31
+ metadata = stored.setdefault("metadata", {})
32
+ if "name" not in metadata:
33
+ self.generated += 1
34
+ metadata["name"] = f"{metadata['generateName']}{self.generated}"
35
+ metadata["namespace"] = namespace
36
+ self.objects[(namespace, plural, metadata["name"])] = stored
37
+ return copy.deepcopy(stored)
38
+
39
+ @_real_signature
40
+ def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs):
41
+ if (namespace, plural, name) not in self.objects:
42
+ raise ApiException(status=404, reason="Not Found")
43
+ return copy.deepcopy(self.objects[(namespace, plural, name)])
44
+
45
+ @_real_signature
46
+ def list_namespaced_custom_object(self, group, version, namespace, plural, label_selector="", **kwargs):
47
+ key, _, value = label_selector.partition("=")
48
+ items = [copy.deepcopy(stored) for (space, kind, _), stored in self.objects.items()
49
+ if space == namespace and kind == plural
50
+ and stored.get("metadata", {}).get("labels", {}).get(key) == value]
51
+ return {"items": items}
52
+
53
+ @_real_signature
54
+ def patch_namespaced_custom_object(self, group, version, namespace, plural, name, body, **kwargs):
55
+ self.patches.append({"path": (group, version, namespace, plural, name), "body": body, **kwargs})
56
+ self.objects[(namespace, plural, name)] = copy.deepcopy(body)
57
+ return copy.deepcopy(body)
@@ -0,0 +1,143 @@
1
+ import pytest
2
+ from kubernetes.client.exceptions import ApiException
3
+
4
+ from agent_contracts import (
5
+ DEFAULT_NAMESPACE,
6
+ Agent,
7
+ AgentContractsClient,
8
+ AgentDefinition,
9
+ AgentDefinitionSpec,
10
+ AgentNotFinishedError,
11
+ AgentSpec,
12
+ AgentStatus,
13
+ ModelCatalog,
14
+ ModelCatalogStatus,
15
+ ModelInfo,
16
+ ObjectMeta,
17
+ Phase,
18
+ Station,
19
+ StationSpec,
20
+ VendorModels,
21
+ is_terminal,
22
+ )
23
+ from fake_api import FakeCustomObjects
24
+
25
+
26
+ def agent_named(name: str, phase: Phase, labels: dict[str, str] | None = None) -> Agent:
27
+ return Agent(
28
+ metadata=ObjectMeta(name=name, labels=labels),
29
+ spec=AgentSpec(station_ref="story-writer"),
30
+ status=AgentStatus(phase=phase),
31
+ )
32
+
33
+
34
+ @pytest.fixture
35
+ def api() -> FakeCustomObjects:
36
+ return FakeCustomObjects()
37
+
38
+
39
+ def test_create_agent_puts_the_run_in_the_client_namespace(api):
40
+ agents = AgentContractsClient(api)
41
+
42
+ created = agents.create_agent(Agent(metadata=ObjectMeta(generate_name="run-"),
43
+ spec=AgentSpec(station_ref="story-writer")))
44
+
45
+ assert created.model_dump(include={"metadata", "spec"}, exclude_none=True) == {
46
+ "metadata": {"name": "run-1", "generate_name": "run-", "namespace": DEFAULT_NAMESPACE},
47
+ "spec": {"station_ref": "story-writer"},
48
+ }
49
+ assert api.objects[(DEFAULT_NAMESPACE, "agents", "run-1")]["apiVersion"] == "agents.re-cinq.com/v1beta1"
50
+
51
+
52
+ def test_get_agent_raises_the_api_404_for_an_unknown_run(api):
53
+ with pytest.raises(ApiException, match="Not Found"):
54
+ AgentContractsClient(api).get_agent("missing")
55
+
56
+
57
+ def test_find_agents_returns_only_the_runs_matching_the_selector(api):
58
+ agents = AgentContractsClient(api, "team-a")
59
+ agents.create_agent(agent_named("web-1", Phase.RUNNING, {"team": "web"}))
60
+ agents.create_agent(agent_named("data-1", Phase.RUNNING, {"team": "data"}))
61
+
62
+ assert [found.metadata.name for found in agents.find_agents("team=web")] == ["web-1"]
63
+
64
+
65
+ def test_find_agents_returns_an_empty_list_when_the_api_lists_no_items(api):
66
+ api.list_namespaced_custom_object = lambda *args, **kwargs: {}
67
+
68
+ assert AgentContractsClient(api).find_agents("team=web") == []
69
+
70
+
71
+ def test_get_model_catalog_reads_the_default_catalog(api):
72
+ catalog = ModelCatalog(
73
+ metadata=ObjectMeta(name="default"),
74
+ status=ModelCatalogStatus(vendors=[VendorModels(vendor="claude", models=[ModelInfo(id="claude-opus-5-5")])]),
75
+ )
76
+ api.objects[(DEFAULT_NAMESPACE, "modelcatalogs", "default")] = catalog.model_dump(by_alias=True, exclude_none=True)
77
+
78
+ read = AgentContractsClient(api).get_model_catalog()
79
+
80
+ assert read.status.vendors[0].models[0].id == "claude-opus-5-5"
81
+
82
+
83
+ def test_apply_station_sends_a_forced_apply_patch_in_the_client_namespace(api):
84
+ station = Station(metadata=ObjectMeta(name="story-writer", managedFields=[{"manager": "kubectl"}]),
85
+ spec=StationSpec(agent_def_ref="story-writer", template={"spec": {}}))
86
+
87
+ applied = AgentContractsClient(api, "team-a").apply_station(station)
88
+
89
+ assert api.patches == [{
90
+ "path": ("agents.re-cinq.com", "v1beta1", "team-a", "stations", "story-writer"),
91
+ "body": {"apiVersion": "agents.re-cinq.com/v1beta1", "kind": "Station",
92
+ "metadata": {"name": "story-writer", "namespace": "team-a"},
93
+ "spec": {"agentDefRef": "story-writer", "template": {"spec": {}}}},
94
+ "field_manager": "agent-contracts", "force": True, "_content_type": "application/apply-patch+yaml",
95
+ }]
96
+ assert applied.spec.agent_def_ref == "story-writer"
97
+
98
+
99
+ def test_apply_agent_definition_returns_the_applied_definition(api):
100
+ definition = AgentDefinition(metadata=ObjectMeta(name="story-writer"),
101
+ spec=AgentDefinitionSpec(model="claude-opus-5-5", prompt="Write a story."))
102
+
103
+ applied = AgentContractsClient(api).apply_agent_definition(definition)
104
+
105
+ assert applied.spec.model == "claude-opus-5-5"
106
+
107
+
108
+ @pytest.mark.parametrize("metadata", [None, ObjectMeta(), ObjectMeta(name="")])
109
+ def test_apply_station_without_a_name_fails(api, metadata):
110
+ with pytest.raises(ValueError, match="^apply Station: metadata.name is required$"):
111
+ AgentContractsClient(api).apply_station(Station(metadata=metadata))
112
+
113
+
114
+ def test_wait_for_agent_returns_the_run_once_it_succeeds(api):
115
+ agents = AgentContractsClient(api)
116
+ agents.create_agent(agent_named("run-1", Phase.RUNNING))
117
+ stored = api.objects[(DEFAULT_NAMESPACE, "agents", "run-1")]
118
+
119
+ def finish(seconds: float) -> None:
120
+ stored["status"]["phase"] = "Succeeded"
121
+
122
+ assert agents.wait_for_agent("run-1", sleep=finish).status.phase == Phase.SUCCEEDED
123
+
124
+
125
+ def test_wait_for_agent_raises_once_the_timeout_passes_while_running(api):
126
+ agents = AgentContractsClient(api)
127
+ agents.create_agent(agent_named("run-1", Phase.RUNNING))
128
+ ticks = iter([0.0, 5.0, 11.0])
129
+
130
+ with pytest.raises(AgentNotFinishedError, match="^agent run-1 did not reach a terminal phase within 10s$"):
131
+ agents.wait_for_agent("run-1", timeout=10, sleep=lambda seconds: None, clock=lambda: next(ticks))
132
+
133
+
134
+ @pytest.mark.parametrize(("status", "terminal"), [
135
+ (None, False),
136
+ (AgentStatus(), False),
137
+ (AgentStatus(phase=Phase.PENDING), False),
138
+ (AgentStatus(phase=Phase.RUNNING), False),
139
+ (AgentStatus(phase=Phase.SUCCEEDED), True),
140
+ (AgentStatus(phase=Phase.FAILED), True),
141
+ ])
142
+ def test_is_terminal_is_true_only_for_succeeded_and_failed(status, terminal):
143
+ assert is_terminal(Agent(status=status)) is terminal
@@ -0,0 +1,66 @@
1
+ from pathlib import Path
2
+
3
+ import yaml
4
+ from pydantic import BaseModel
5
+
6
+ import agent_contracts
7
+ from agent_contracts import API_VERSION, Agent, PermissionMode, SecretRef, StationSpec
8
+
9
+ EXAMPLES = Path(__file__).resolve().parents[3] / "examples"
10
+ KINDS = {kind: getattr(agent_contracts, kind)
11
+ for kind in ("AgentDefinition", "Station", "Agent", "ModelCatalog", "AgentSpawner")}
12
+
13
+
14
+ def unknown_fields(model: BaseModel, path: str) -> list[str]:
15
+ """Every field the model kept only as an extra, outside metadata (which is a subset of Kubernetes')."""
16
+ found = [f"{path}.{name}" for name in (model.model_extra or {}) if path != ".metadata"]
17
+ for name in type(model).model_fields:
18
+ value = getattr(model, name)
19
+ children = value if isinstance(value, list) else list(value.values()) if isinstance(value, dict) else [value]
20
+ found += [field for child in children if isinstance(child, BaseModel)
21
+ for field in unknown_fields(child, f"{path}.{name}")]
22
+ return found
23
+
24
+
25
+ def test_every_example_manifest_decodes_without_unknown_fields():
26
+ decoded = []
27
+ for file in sorted(EXAMPLES.glob("*.yaml")):
28
+ for document in yaml.safe_load_all(file.read_text()):
29
+ if not document or "kind" not in document:
30
+ continue
31
+ resource = KINDS[document["kind"]].model_validate(document)
32
+ assert (resource.api_version, unknown_fields(resource, "")) == (API_VERSION, []), file.name
33
+ decoded.append(document["kind"])
34
+ assert decoded
35
+
36
+
37
+ def test_a_resource_round_trips_to_the_same_wire_document():
38
+ wire = {"apiVersion": API_VERSION, "kind": "Agent",
39
+ "metadata": {"name": "run-1", "ownerReferences": [{"name": "spawner"}]},
40
+ "spec": {"stationRef": "story-writer", "parameters": {"title": "a"}, "futureField": 1},
41
+ "status": {"phase": "Running"}}
42
+
43
+ assert Agent.model_validate(wire).model_dump(by_alias=True, exclude_none=True, mode="json") == wire
44
+
45
+
46
+ def test_an_unknown_enum_value_falls_back_to_the_first_member():
47
+ assert (PermissionMode("bogus"), PermissionMode("bypass")) == (PermissionMode.AUTO, PermissionMode.BYPASS)
48
+
49
+
50
+ def test_unset_fields_are_left_out_of_the_wire_document():
51
+ assert StationSpec(agent_def_ref="story-writer", template={}).model_dump(by_alias=True, exclude_none=True) == {
52
+ "agentDefRef": "story-writer", "template": {}}
53
+
54
+
55
+ def test_a_kind_carries_its_group_version_plural_and_short_names():
56
+ assert (Agent().api_version, Agent().kind, Agent.PLURAL, Agent.SHORT_NAMES) == (
57
+ "agents.re-cinq.com/v1beta1", "Agent", "agents", ("agt",))
58
+
59
+
60
+ def test_a_required_field_is_enforced():
61
+ try:
62
+ SecretRef(name="TOKEN")
63
+ except ValueError as error:
64
+ assert "ref" in str(error)
65
+ else:
66
+ raise AssertionError("SecretRef without ref validated")