codemie-cdk-python 0.1.0rc0__py3-none-any.whl

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 (39) hide show
  1. codemie_cdk_python-0.1.0rc0.dist-info/METADATA +840 -0
  2. codemie_cdk_python-0.1.0rc0.dist-info/RECORD +39 -0
  3. codemie_cdk_python-0.1.0rc0.dist-info/WHEEL +4 -0
  4. codemie_cdk_python-0.1.0rc0.dist-info/entry_points.txt +3 -0
  5. codemie_iac/__init__.py +49 -0
  6. codemie_iac/cli/__init__.py +17 -0
  7. codemie_iac/cli/__main__.py +24 -0
  8. codemie_iac/cli/commands/__init__.py +17 -0
  9. codemie_iac/cli/commands/apply.py +119 -0
  10. codemie_iac/cli/commands/plan.py +72 -0
  11. codemie_iac/cli/documents.py +59 -0
  12. codemie_iac/cli/env_file.py +62 -0
  13. codemie_iac/cli/exit_status.py +80 -0
  14. codemie_iac/cli/main.py +118 -0
  15. codemie_iac/cli/render.py +206 -0
  16. codemie_iac/cli/target_config.py +230 -0
  17. codemie_iac/cli/token_client.py +42 -0
  18. codemie_iac/credentials.py +99 -0
  19. codemie_iac/envelope.py +188 -0
  20. codemie_iac/plan_apply/__init__.py +70 -0
  21. codemie_iac/plan_apply/bulk_create.py +561 -0
  22. codemie_iac/plan_apply/credentials.py +306 -0
  23. codemie_iac/plan_apply/errors.py +223 -0
  24. codemie_iac/plan_apply/field_policy.py +185 -0
  25. codemie_iac/plan_apply/guards.py +221 -0
  26. codemie_iac/plan_apply/kinds.py +815 -0
  27. codemie_iac/plan_apply/lookup.py +313 -0
  28. codemie_iac/plan_apply/ordering.py +177 -0
  29. codemie_iac/plan_apply/single_apply.py +751 -0
  30. codemie_iac/resolver.py +61 -0
  31. codemie_iac/schema.py +106 -0
  32. codemie_iac/serializer.py +64 -0
  33. codemie_iac/specs/__init__.py +13 -0
  34. codemie_iac/specs/assistant.py +509 -0
  35. codemie_iac/specs/category.py +36 -0
  36. codemie_iac/specs/datasource.py +595 -0
  37. codemie_iac/specs/integration.py +103 -0
  38. codemie_iac/specs/skill.py +51 -0
  39. codemie_iac/specs/workflow.py +154 -0
@@ -0,0 +1,313 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Name -> platform entity lookup for references between entities.
16
+
17
+ A reference is first resolved against the bundle (``ReferenceResolver``).
18
+ A name that is not in the bundle falls back to a read-only live lookup in the
19
+ target project. Anything that resolves nowhere (or ambiguously) is an
20
+ ``UnresolvedReferenceError``. Platform ids are only returned, never stored.
21
+ """
22
+
23
+ from collections.abc import Callable, Iterable, Iterator, Mapping
24
+ import time
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+
29
+ from ..envelope import Document, DocumentKind
30
+ from ..resolver import ReferenceResolutionError, ReferenceResolver
31
+ from .errors import ApplyError, UnresolvedReferenceError
32
+
33
+ __all__ = ["LIVE_FINDERS", "EntityKey", "NameLookup", "Reference"]
34
+
35
+ EntityKey = tuple[DocumentKind, str]
36
+
37
+ _PAGE_SIZE = 100
38
+ _MAX_PAGES = 50
39
+
40
+ #: A bundle entity without an id from its create (a datasource, an integration)
41
+ #: is looked up by name afterwards, and the platform may list it a moment later
42
+ #: (code and provider datasources are indexed in a background task). Poll for
43
+ #: about this long before giving up.
44
+ _ID_WAIT_ATTEMPTS = 30
45
+ _ID_WAIT_SECONDS = 1.0
46
+
47
+
48
+ def _wait(seconds: float) -> None:
49
+ time.sleep(seconds)
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Reference:
54
+ """A resolved reference.
55
+
56
+ ``id`` is the platform id; ``source`` is the bundle ``Document`` or the
57
+ live SDK object it came from.
58
+ """
59
+
60
+ id: str
61
+ source: Any
62
+
63
+
64
+ def _pages(fetch: Callable[[int], Any]) -> Iterator[Any]:
65
+ """Every item, paging until an empty page (a short page may just mean the
66
+ server caps ``per_page`` below ours). Raises rather than truncating."""
67
+ for page in range(_MAX_PAGES):
68
+ items = list(fetch(page))
69
+ if not items:
70
+ return
71
+ yield from items
72
+ raise ApplyError(
73
+ "lookup_truncated",
74
+ "lookup",
75
+ "pagination",
76
+ f"live lookup exceeded {_MAX_PAGES} pages; refusing to guess from a "
77
+ "truncated listing",
78
+ )
79
+
80
+
81
+ # The live assistant listing only returns assistants the calling user can see
82
+ # (shared in their projects, in projects they administer, or their own), so a
83
+ # missing assistant may exist but be invisible to the caller. Say so.
84
+ _VISIBILITY_NOTE: dict[DocumentKind, str] = {
85
+ DocumentKind.ASSISTANT: " (or it exists but is not visible to the current user)",
86
+ }
87
+
88
+
89
+ def _in_project(item: Any, target: str, attr: str) -> bool:
90
+ return getattr(item, attr, None) == target
91
+
92
+
93
+ def _named(items: Iterable[Any], name: str) -> list[Any]:
94
+ return [i for i in items if getattr(i, "name", None) == name]
95
+
96
+
97
+ def _find_assistants(client: Any, target: str, name: str) -> list[Any]:
98
+ # Not ``minimal_response``: its SDK model (``AssistantBase``) drops the
99
+ # ``project`` the backend sends, so no assistant would match the target.
100
+ items = _pages(
101
+ lambda p: client.assistants.list(
102
+ minimal_response=False,
103
+ page=p,
104
+ per_page=_PAGE_SIZE,
105
+ filters={"project": [target]},
106
+ )
107
+ )
108
+ return [i for i in _named(items, name) if _in_project(i, target, "project")]
109
+
110
+
111
+ def _find_skills(client: Any, target: str, name: str) -> list[Any]:
112
+ # ``search`` is a name-contains match; the exact name is checked below.
113
+ filters = {"project": [target], "search": name}
114
+ items = _pages(
115
+ lambda p: client.skills.list(
116
+ page=p, per_page=_PAGE_SIZE, filters=filters
117
+ ).skills
118
+ )
119
+ return [i for i in _named(items, name) if _in_project(i, target, "project")]
120
+
121
+
122
+ def _find_workflows(client: Any, target: str, name: str) -> list[Any]:
123
+ items = _pages(
124
+ lambda p: client.workflows.list(page=p, per_page=_PAGE_SIZE, projects=[target])
125
+ )
126
+ return [i for i in _named(items, name) if _in_project(i, target, "project")]
127
+
128
+
129
+ def _find_datasources(client: Any, target: str, name: str) -> list[Any]:
130
+ items = _pages(
131
+ lambda p: client.datasources.list(
132
+ page=p, per_page=_PAGE_SIZE, projects=[target]
133
+ )
134
+ )
135
+ return [i for i in _named(items, name) if _in_project(i, target, "project_name")]
136
+
137
+
138
+ def _find_integrations(client: Any, target: str, name: str) -> list[Any]:
139
+ """Integrations of the target project with alias ``name`` that the caller
140
+ can use. The project listing only shows a non-admin the projects they
141
+ administer, so ``list_available`` (project and user scopes, as the caller
142
+ may use them) is the one that finds a shared project integration."""
143
+ return [
144
+ i
145
+ for i in client.integrations.list_available()
146
+ if getattr(i, "alias", None) == name and _in_project(i, target, "project_name")
147
+ ]
148
+
149
+
150
+ def _find_categories(client: Any, target: str, name: str) -> list[Any]:
151
+ return _named(client.categories.get_categories(), name)
152
+
153
+
154
+ #: kind -> finder(client, target, name) -> matching live objects.
155
+ LIVE_FINDERS: dict[DocumentKind, Callable[[Any, str, str], list[Any]]] = {
156
+ DocumentKind.ASSISTANT: _find_assistants,
157
+ DocumentKind.SKILL: _find_skills,
158
+ DocumentKind.WORKFLOW: _find_workflows,
159
+ DocumentKind.DATASOURCE: _find_datasources,
160
+ DocumentKind.INTEGRATION: _find_integrations,
161
+ DocumentKind.CATEGORY: _find_categories,
162
+ }
163
+
164
+
165
+ def _integration_alias(document: Document) -> str | None:
166
+ return document.spec.alias
167
+
168
+
169
+ #: kind -> the name a *bundle* entity is known by on the platform, when that is
170
+ #: not its ``meta.name`` (an integration is found by its alias; the create
171
+ #: response carries no id, so it is looked up after it was created).
172
+ _LIVE_NAMES: dict[DocumentKind, Callable[[Document], str | None]] = {
173
+ DocumentKind.INTEGRATION: _integration_alias,
174
+ }
175
+
176
+
177
+ def _live_name(kind: DocumentKind, document: Document | None, name: str) -> str:
178
+ if document is None or kind not in _LIVE_NAMES:
179
+ return name
180
+ return _LIVE_NAMES[kind](document) or name
181
+
182
+
183
+ class NameLookup:
184
+ """Resolves ``(kind, name)`` references to platform ids.
185
+
186
+ ``bundle`` is the documents being applied; ``client`` (optional) enables
187
+ the live fallback in the ``target`` project. Without a client only the
188
+ bundle is consulted.
189
+ """
190
+
191
+ def __init__(self, bundle: Iterable[Document], target: str, client: Any = None):
192
+ self._resolver = ReferenceResolver(list(bundle))
193
+ self._target = target
194
+ self._client = client
195
+ # Live answers by (kind, name), so preflight, plan and write share one
196
+ # listing per value. Only ``find_live`` and ``require`` read it: a
197
+ # bundle entity looked up after its create must see the platform anew.
198
+ self._live_cache: dict[EntityKey, Any] = {}
199
+
200
+ @property
201
+ def target(self) -> str:
202
+ return self._target
203
+
204
+ @property
205
+ def client(self) -> Any:
206
+ return self._client
207
+
208
+ def in_bundle(self, kind: DocumentKind, name: str) -> Document | None:
209
+ """The bundle document for the reference; None if absent. Raises
210
+ ``UnresolvedReferenceError`` if ambiguous within the bundle."""
211
+ try:
212
+ return self._resolver.resolve(kind.value, name)
213
+ except ReferenceResolutionError as exc:
214
+ if exc.ambiguous:
215
+ raise self._error(kind, name, str(exc)) from exc
216
+ return None
217
+
218
+ def _cached_live(self, kind: DocumentKind, name: str) -> Any | None:
219
+ key = (kind, name)
220
+ if key not in self._live_cache:
221
+ self._live_cache[key] = self._live(kind, name)
222
+ return self._live_cache[key]
223
+
224
+ def _live(
225
+ self, kind: DocumentKind, name: str, document: Document | None = None
226
+ ) -> Any | None:
227
+ if self._client is None:
228
+ return None
229
+ matches = LIVE_FINDERS[kind](self._client, self._target, name)
230
+ # Alias uniqueness is per setting type: a bundle integration is the
231
+ # one of its own type, not a same-named one of another type.
232
+ if kind is DocumentKind.INTEGRATION and document is not None:
233
+ wanted = document.spec.setting_type
234
+ matches = [
235
+ m for m in matches if getattr(m, "setting_type", wanted) == wanted
236
+ ]
237
+ if len(matches) > 1:
238
+ raise self._error(
239
+ kind,
240
+ name,
241
+ f"ambiguous reference: {len(matches)} {kind.value} entities "
242
+ f"named {name!r} in project {self._target!r}",
243
+ )
244
+ return matches[0] if matches else None
245
+
246
+ @staticmethod
247
+ def _error(kind: DocumentKind, name: str, reason: str, referrer: str | None = None):
248
+ suffix = f" (referenced by {referrer})" if referrer else ""
249
+ return UnresolvedReferenceError(
250
+ "unresolved_reference", kind.value, name, reason + suffix
251
+ )
252
+
253
+ def find_live(self, kind: DocumentKind, name: str) -> Reference | None:
254
+ """The live entity named ``name`` in the target project, or ``None``
255
+ when there is none (or no client). Raises ``UnresolvedReferenceError``
256
+ if more than one matches."""
257
+ live = self._cached_live(kind, name)
258
+ entity_id = getattr(live, "id", None)
259
+ return Reference(entity_id, live) if entity_id else None
260
+
261
+ def require(
262
+ self, kind: DocumentKind, name: str, referrer: str | None = None
263
+ ) -> None:
264
+ """Preflight check: the reference exists in the bundle or live."""
265
+ if self.in_bundle(kind, name) is not None:
266
+ return
267
+ if self._cached_live(kind, name) is None:
268
+ raise self._error(
269
+ kind,
270
+ name,
271
+ f"no {kind.value} named {name!r} in the bundle or in "
272
+ f"project {self._target!r}" + _VISIBILITY_NOTE.get(kind, ""),
273
+ referrer,
274
+ )
275
+
276
+ def resolve(
277
+ self,
278
+ kind: DocumentKind,
279
+ name: str,
280
+ created: Mapping[EntityKey, str] | None = None,
281
+ ) -> Reference:
282
+ """Platform id of the reference.
283
+
284
+ ``created`` maps bundle entities already created in this run to their
285
+ ids. A bundle entity without a recorded id (e.g. a datasource, whose
286
+ create response carries none) is looked up live by name after create.
287
+ """
288
+ document = self.in_bundle(kind, name)
289
+ known = (created or {}).get((kind, name))
290
+ if known is not None and document is not None:
291
+ return Reference(known, document)
292
+ live_name = _live_name(kind, document, name)
293
+ live = self._live(kind, live_name, document)
294
+ if document is not None:
295
+ # Created in this run, so it exists: wait for the listing to show it.
296
+ for _ in range(_ID_WAIT_ATTEMPTS):
297
+ if getattr(live, "id", None):
298
+ break
299
+ _wait(_ID_WAIT_SECONDS)
300
+ live = self._live(kind, live_name, document)
301
+ entity_id = getattr(live, "id", None)
302
+ if not entity_id and document is not None:
303
+ raise self._error(
304
+ kind,
305
+ name,
306
+ f"{kind.value} {name!r} was created but is still not listed after "
307
+ f"{_ID_WAIT_ATTEMPTS * _ID_WAIT_SECONDS:.0f}s; apply the documents "
308
+ "that reference it once it is listed (applying the whole bundle "
309
+ "again would create it a second time)",
310
+ )
311
+ if not entity_id:
312
+ raise self._error(kind, name, f"no platform id for {kind.value} {name!r}")
313
+ return Reference(entity_id, live)
@@ -0,0 +1,177 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+
14
+ """Dependency ordering of a bundle's documents (create-only apply).
15
+
16
+ Only references to entities present in the bundle are ordering edges;
17
+ references to entities outside it are resolved by a live lookup elsewhere.
18
+ """
19
+
20
+ from collections.abc import Callable, Iterable, Iterator
21
+
22
+ from ..envelope import Document, DocumentKind
23
+ from .errors import ApplyError
24
+
25
+ __all__ = ["EDGE_EXTRACTORS", "DependencyGraph", "value_edges"]
26
+
27
+ Edge = tuple[DocumentKind, str]
28
+ _Key = tuple[DocumentKind, str]
29
+
30
+
31
+ def _assistant_integrations(spec) -> Iterator[str]:
32
+ for toolkit in spec.toolkits:
33
+ yield toolkit.settings
34
+ for tool in toolkit.tools:
35
+ yield tool.settings
36
+ for server in spec.mcp_servers:
37
+ yield server.settings
38
+ yield server.mcp_connect_auth_token
39
+ yield server.integration_alias
40
+
41
+
42
+ def _assistant_value_edges(spec) -> Iterator[Edge]:
43
+ for name in spec.skill_ids or ():
44
+ yield DocumentKind.SKILL, name
45
+
46
+
47
+ def _assistant_edges(doc: Document) -> Iterator[Edge]:
48
+ spec = doc.spec
49
+ for name in spec.assistant_ids:
50
+ yield DocumentKind.ASSISTANT, name
51
+ for ctx in spec.context:
52
+ yield DocumentKind.DATASOURCE, ctx.name
53
+ yield from _assistant_value_edges(spec)
54
+ for name in spec.categories:
55
+ yield DocumentKind.CATEGORY, name
56
+ for name in _assistant_integrations(spec):
57
+ if name:
58
+ yield DocumentKind.INTEGRATION, name
59
+
60
+
61
+ def _skill_edges(doc: Document) -> Iterator[Edge]:
62
+ # Skill categories are fixed values (``SkillCategory``), not Category entities.
63
+ return iter(())
64
+
65
+
66
+ def _agent_value_edges(assistant) -> Iterator[Edge]:
67
+ for name in assistant.skill_ids or ():
68
+ yield DocumentKind.SKILL, name
69
+ for name in assistant.datasource_ids or ():
70
+ yield DocumentKind.DATASOURCE, name
71
+
72
+
73
+ def _workflow_edges(doc: Document) -> Iterator[Edge]:
74
+ for assistant in doc.spec.workflow.assistants.values():
75
+ yield from _agent_value_edges(assistant)
76
+ if assistant.assistant_id:
77
+ yield DocumentKind.ASSISTANT, assistant.assistant_id
78
+ elif assistant.name and assistant.system_prompt is None:
79
+ # A name-only reference: ``WorkflowDefinition.to_yaml_config``
80
+ # resolves it to an assistant id when the workflow is rendered.
81
+ yield DocumentKind.ASSISTANT, assistant.name
82
+ aliases = [t.integration_alias for t in assistant.tools]
83
+ aliases += [s.integration_alias for s in assistant.mcp_servers]
84
+ for alias in aliases:
85
+ if alias:
86
+ yield DocumentKind.INTEGRATION, alias
87
+ for tool in doc.spec.workflow.tools:
88
+ aliases = [tool.integration_alias]
89
+ if tool.mcp_server is not None:
90
+ aliases.append(tool.mcp_server.integration_alias)
91
+ aliases += [a.integration_alias for a in tool.tool_access or []]
92
+ for alias in aliases:
93
+ if alias:
94
+ yield DocumentKind.INTEGRATION, alias
95
+
96
+
97
+ def _datasource_edges(doc: Document) -> Iterator[Edge]:
98
+ if doc.spec.setting_id:
99
+ yield DocumentKind.INTEGRATION, doc.spec.setting_id
100
+
101
+
102
+ EDGE_EXTRACTORS: dict[DocumentKind, Callable[[Document], Iterable[Edge]]] = {
103
+ DocumentKind.ASSISTANT: _assistant_edges,
104
+ DocumentKind.SKILL: _skill_edges,
105
+ DocumentKind.WORKFLOW: _workflow_edges,
106
+ DocumentKind.DATASOURCE: _datasource_edges,
107
+ }
108
+
109
+
110
+ def value_edges(doc: Document) -> set[Edge]:
111
+ """The edges of ``doc`` whose names may also be raw platform ids (skill and
112
+ datasource values), as opposed to names that must resolve."""
113
+ if doc.meta.kind is DocumentKind.ASSISTANT:
114
+ return set(_assistant_value_edges(doc.spec))
115
+ if doc.meta.kind is DocumentKind.WORKFLOW:
116
+ agents = doc.spec.workflow.assistants.values()
117
+ return {e for a in agents for e in _agent_value_edges(a)}
118
+ return set()
119
+
120
+
121
+ def _key(doc: Document) -> _Key:
122
+ return doc.meta.kind, doc.meta.name
123
+
124
+
125
+ class DependencyGraph:
126
+ """Dependency graph over a list of documents; dependencies sort first."""
127
+
128
+ def __init__(self, documents: Iterable[Document]):
129
+ self._docs: dict[_Key, Document] = {}
130
+ for doc in documents:
131
+ key = _key(doc)
132
+ if key in self._docs:
133
+ raise ApplyError(
134
+ "duplicate_document",
135
+ key[0].value,
136
+ key[1],
137
+ f"more than one {key[0].value} document named {key[1]!r}",
138
+ )
139
+ self._docs[key] = doc
140
+
141
+ def edges(self, doc: Document) -> list[Edge]:
142
+ """In-bundle dependencies of ``doc`` (deduplicated, stable order)."""
143
+ extractor = EDGE_EXTRACTORS.get(doc.meta.kind)
144
+ found = extractor(doc) if extractor else ()
145
+ unique = dict.fromkeys(e for e in found if e in self._docs)
146
+ return list(unique)
147
+
148
+ def order(self) -> list[Document]:
149
+ """Documents in dependency-first order; raises on a cycle."""
150
+ done: set[_Key] = set()
151
+ result: list[Document] = []
152
+ for key in self._docs:
153
+ self._visit(key, [], done, result)
154
+ return result
155
+
156
+ def _visit(
157
+ self, key: _Key, path: list[_Key], done: set[_Key], out: list[Document]
158
+ ) -> None:
159
+ if key in done:
160
+ return
161
+ if key in path:
162
+ self._raise_cycle(path[path.index(key) :] + [key])
163
+ doc = self._docs[key]
164
+ path.append(key)
165
+ for dep in self.edges(doc):
166
+ self._visit(dep, path, done, out)
167
+ path.pop()
168
+ done.add(key)
169
+ out.append(doc)
170
+
171
+ @staticmethod
172
+ def _raise_cycle(cycle: list[_Key]) -> None:
173
+ text = " -> ".join(name for _, name in cycle)
174
+ kind, name = cycle[0]
175
+ raise ApplyError(
176
+ "dependency_cycle", kind.value, name, f"dependency cycle: {text}"
177
+ )