codemie-cdk-python 0.1.0__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.
- codemie_cdk_python-0.1.0.dist-info/METADATA +892 -0
- codemie_cdk_python-0.1.0.dist-info/RECORD +40 -0
- codemie_cdk_python-0.1.0.dist-info/WHEEL +4 -0
- codemie_cdk_python-0.1.0.dist-info/entry_points.txt +3 -0
- codemie_iac/__init__.py +49 -0
- codemie_iac/cli/__init__.py +17 -0
- codemie_iac/cli/__main__.py +24 -0
- codemie_iac/cli/commands/__init__.py +17 -0
- codemie_iac/cli/commands/apply.py +119 -0
- codemie_iac/cli/commands/plan.py +72 -0
- codemie_iac/cli/config_model.py +136 -0
- codemie_iac/cli/documents.py +59 -0
- codemie_iac/cli/env_file.py +62 -0
- codemie_iac/cli/exit_status.py +80 -0
- codemie_iac/cli/init_command.py +101 -0
- codemie_iac/cli/main.py +152 -0
- codemie_iac/cli/render.py +206 -0
- codemie_iac/cli/target_config.py +258 -0
- codemie_iac/credentials.py +99 -0
- codemie_iac/envelope.py +188 -0
- codemie_iac/plan_apply/__init__.py +70 -0
- codemie_iac/plan_apply/bulk_create.py +561 -0
- codemie_iac/plan_apply/credentials.py +306 -0
- codemie_iac/plan_apply/errors.py +223 -0
- codemie_iac/plan_apply/field_policy.py +188 -0
- codemie_iac/plan_apply/guards.py +221 -0
- codemie_iac/plan_apply/kinds.py +815 -0
- codemie_iac/plan_apply/lookup.py +313 -0
- codemie_iac/plan_apply/ordering.py +177 -0
- codemie_iac/plan_apply/single_apply.py +751 -0
- codemie_iac/resolver.py +61 -0
- codemie_iac/schema.py +106 -0
- codemie_iac/serializer.py +64 -0
- codemie_iac/specs/__init__.py +13 -0
- codemie_iac/specs/assistant.py +509 -0
- codemie_iac/specs/category.py +36 -0
- codemie_iac/specs/datasource.py +595 -0
- codemie_iac/specs/integration.py +103 -0
- codemie_iac/specs/skill.py +51 -0
- codemie_iac/specs/workflow.py +154 -0
|
@@ -0,0 +1,751 @@
|
|
|
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
|
+
"""Single-entity plan: diff a document against the live entity.
|
|
16
|
+
|
|
17
|
+
``diff`` compares the document spec with the live SDK object, restricted by a
|
|
18
|
+
``FieldPolicy``, and returns ``Difference`` / ``CannotCompare`` findings.
|
|
19
|
+
|
|
20
|
+
Comparison rules:
|
|
21
|
+
|
|
22
|
+
- Only fields that are in ``policy.comparable`` (and not in ``policy.deny``)
|
|
23
|
+
are compared; a field absent from the live view is not observable and is
|
|
24
|
+
skipped.
|
|
25
|
+
- Reference-shaped spec fields (``REFERENCE_FIELDS``) hold names/aliases
|
|
26
|
+
where the live entity holds platform ids, expanded integration objects or a
|
|
27
|
+
rendered workflow config. With a ``ResolveContext`` they are resolved the
|
|
28
|
+
way a write would resolve them and the resolved value is compared. Without
|
|
29
|
+
one they are ``CannotCompare`` (never silently skipped). Fields that carry
|
|
30
|
+
credential refs are compared with revealed values, but a ``Difference`` on
|
|
31
|
+
them is redacted.
|
|
32
|
+
- A field the document leaves unset (``None``) is not compared: the platform
|
|
33
|
+
may fill it (a slug, a default timezone) and a write never sends it. To clear
|
|
34
|
+
a field, author it empty (``""``, ``[]``).
|
|
35
|
+
- ``None``, ``""`` and empty collections are all "unset" and compare equal.
|
|
36
|
+
Live dicts are projected onto the document's keys, so server-added keys
|
|
37
|
+
inside nested objects are not differences.
|
|
38
|
+
- Credential-ref fields and live values that are masked (8 asterisks for
|
|
39
|
+
prompt variables, 10 for credentials) are ``CannotCompare``: never a
|
|
40
|
+
difference, never a match, and no value is ever put in the finding.
|
|
41
|
+
Credential refs are only checked for presence/resolvability.
|
|
42
|
+
- A masked value only makes a field uncomparable where the document looks at
|
|
43
|
+
it: the mask check runs on the live value projected onto the document's
|
|
44
|
+
keys, and per item for lists of equal length (one masked prompt variable
|
|
45
|
+
does not hide an edit of another). Integrations embedded in toolkits / MCP
|
|
46
|
+
servers are compared by id only.
|
|
47
|
+
- A comparable field the document authors but the live view cannot show (for
|
|
48
|
+
example a ``timezone`` when the datasource has no schedule) is
|
|
49
|
+
``CannotCompare``, never skipped.
|
|
50
|
+
- ``Plan.is_empty`` depends on differences only: a ``CannotCompare`` field
|
|
51
|
+
is unknowable, not a change, so it does not force a write. ``apply`` lists
|
|
52
|
+
such fields in ``ApplyResult.uncomparable`` and ``force=True`` writes anyway.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
import copy
|
|
56
|
+
from collections.abc import Mapping
|
|
57
|
+
from types import SimpleNamespace
|
|
58
|
+
from typing import Any
|
|
59
|
+
|
|
60
|
+
import yaml
|
|
61
|
+
from pydantic import BaseModel, ConfigDict, computed_field
|
|
62
|
+
|
|
63
|
+
from ..credentials import CredentialRef
|
|
64
|
+
from ..envelope import Document, DocumentKind
|
|
65
|
+
from .credentials import (
|
|
66
|
+
MCP_REF_FIELDS,
|
|
67
|
+
EnvCredentialResolver,
|
|
68
|
+
ProviderSecretLookup,
|
|
69
|
+
SecretValue,
|
|
70
|
+
)
|
|
71
|
+
from .bulk_create import (
|
|
72
|
+
ResolveContext,
|
|
73
|
+
build_resolved,
|
|
74
|
+
check_credentials,
|
|
75
|
+
check_references,
|
|
76
|
+
)
|
|
77
|
+
from .errors import PLATFORM_ERRORS, ApplyError, PlatformRejectionError
|
|
78
|
+
from .field_policy import FieldPolicy, policy_for
|
|
79
|
+
from .guards import (
|
|
80
|
+
guard_datasource_identity,
|
|
81
|
+
guard_name,
|
|
82
|
+
guard_project,
|
|
83
|
+
with_default_project,
|
|
84
|
+
guard_supported,
|
|
85
|
+
)
|
|
86
|
+
from .kinds import adapter_for, created_id
|
|
87
|
+
from .lookup import NameLookup
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"REFERENCE_FIELDS",
|
|
91
|
+
"ApplyResult",
|
|
92
|
+
"CannotCompare",
|
|
93
|
+
"Difference",
|
|
94
|
+
"Plan",
|
|
95
|
+
"SingleEntityPlanner",
|
|
96
|
+
"diff",
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
REFERENCE_FIELDS = frozenset(
|
|
100
|
+
{
|
|
101
|
+
"categories",
|
|
102
|
+
"assistant_ids",
|
|
103
|
+
"skill_ids",
|
|
104
|
+
"toolkits",
|
|
105
|
+
"mcp_servers",
|
|
106
|
+
"yaml_config",
|
|
107
|
+
"setting_id",
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
#: Skill categories are a fixed list of values, not Category entities.
|
|
111
|
+
_VALUE_CATEGORY_KINDS = frozenset({DocumentKind.SKILL})
|
|
112
|
+
_ID_LIST_FIELDS = frozenset({"categories", "assistant_ids", "skill_ids"})
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
_INTEGRATION_FIELDS = frozenset({"toolkits", "mcp_servers"})
|
|
116
|
+
#: Comparable fields the live view may legitimately omit (the timezone is only
|
|
117
|
+
#: exposed alongside a schedule); authored but absent means ``CannotCompare``.
|
|
118
|
+
_OPTIONAL_LIVE_FIELDS = frozenset({"cron_expression", "timezone"})
|
|
119
|
+
_REDACTED = "[redacted]"
|
|
120
|
+
_UNRESOLVABLE = "unresolvable credential reference"
|
|
121
|
+
_PROJECT_FIELDS = {
|
|
122
|
+
DocumentKind.ASSISTANT: "project",
|
|
123
|
+
DocumentKind.SKILL: "project",
|
|
124
|
+
DocumentKind.WORKFLOW: "project",
|
|
125
|
+
DocumentKind.INTEGRATION: "project_name",
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
_MASK_LENGTHS = frozenset({8, 10})
|
|
129
|
+
_NESTED_DATASOURCE_KEYS = (
|
|
130
|
+
"code",
|
|
131
|
+
"git_faq",
|
|
132
|
+
"jira",
|
|
133
|
+
"confluence",
|
|
134
|
+
"azure_devops_wiki",
|
|
135
|
+
"azure_devops_work_item",
|
|
136
|
+
"xwiki",
|
|
137
|
+
"svn",
|
|
138
|
+
"sharepoint",
|
|
139
|
+
"xray",
|
|
140
|
+
"provider",
|
|
141
|
+
)
|
|
142
|
+
_WORKFLOW_FIELDS = {"name", "description", "mode", "shared", "icon_url"}
|
|
143
|
+
#: Fields an omitted value clears on the platform (see ``_clear_omitted_icon``),
|
|
144
|
+
#: so an omitted one is compared; any other omitted field is left to the platform.
|
|
145
|
+
_CLEARED_WHEN_OMITTED = frozenset({"icon_url"})
|
|
146
|
+
_EMBEDDING_MODEL_TYPES = frozenset({"knowledge_base_sharepoint"})
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class Difference(BaseModel):
|
|
150
|
+
model_config = ConfigDict(extra="forbid")
|
|
151
|
+
|
|
152
|
+
field: str
|
|
153
|
+
document_value: Any
|
|
154
|
+
live_value: Any
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class CannotCompare(BaseModel):
|
|
158
|
+
"""A field that could not be compared; ``reason`` never holds a value."""
|
|
159
|
+
|
|
160
|
+
model_config = ConfigDict(extra="forbid")
|
|
161
|
+
|
|
162
|
+
field: str
|
|
163
|
+
reason: str
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class Plan(BaseModel):
|
|
167
|
+
model_config = ConfigDict(extra="forbid")
|
|
168
|
+
|
|
169
|
+
differences: list[Difference] = []
|
|
170
|
+
cannot_compare: list[CannotCompare] = []
|
|
171
|
+
|
|
172
|
+
@computed_field # type: ignore[prop-decorator]
|
|
173
|
+
@property
|
|
174
|
+
def is_empty(self) -> bool:
|
|
175
|
+
return not self.differences
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# --- normalisation ---------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _is_mask(value: Any) -> bool:
|
|
182
|
+
return (
|
|
183
|
+
isinstance(value, str) and len(value) in _MASK_LENGTHS and set(value) == {"*"}
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _has_mask(value: Any) -> bool:
|
|
188
|
+
if isinstance(value, Mapping):
|
|
189
|
+
return any(_has_mask(v) for v in value.values())
|
|
190
|
+
if isinstance(value, list):
|
|
191
|
+
return any(_has_mask(v) for v in value)
|
|
192
|
+
return _is_mask(value)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _canon(value: Any) -> Any:
|
|
196
|
+
"""Canonical form: every empty value becomes None and empties are dropped."""
|
|
197
|
+
if isinstance(value, Mapping):
|
|
198
|
+
items = {k: _canon(v) for k, v in value.items()}
|
|
199
|
+
value = {k: v for k, v in items.items() if v is not None}
|
|
200
|
+
elif isinstance(value, list):
|
|
201
|
+
value = [_canon(v) for v in value]
|
|
202
|
+
return value if value not in ("", [], {}) else None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _project(document_value: Any, live_value: Any) -> Any:
|
|
206
|
+
"""Restrict ``live_value`` to the shape (keys) of ``document_value``."""
|
|
207
|
+
if isinstance(document_value, dict) and isinstance(live_value, Mapping):
|
|
208
|
+
return {k: _project(v, live_value.get(k)) for k, v in document_value.items()}
|
|
209
|
+
if (
|
|
210
|
+
isinstance(document_value, list)
|
|
211
|
+
and isinstance(live_value, list)
|
|
212
|
+
and len(document_value) == len(live_value)
|
|
213
|
+
):
|
|
214
|
+
return [_project(d, v) for d, v in zip(document_value, live_value)]
|
|
215
|
+
return live_value
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _flatten_live(live: Mapping[str, Any]) -> dict[str, Any]:
|
|
219
|
+
"""Merge datasource sub-objects into the top level (top level wins)."""
|
|
220
|
+
flat = dict(live)
|
|
221
|
+
for key in _NESTED_DATASOURCE_KEYS:
|
|
222
|
+
sub = flat.get(key)
|
|
223
|
+
if isinstance(sub, Mapping):
|
|
224
|
+
for name, value in sub.items():
|
|
225
|
+
if flat.get(name) is None:
|
|
226
|
+
flat[name] = value
|
|
227
|
+
if "google_doc_link" in flat:
|
|
228
|
+
flat.setdefault("google_doc", flat["google_doc_link"])
|
|
229
|
+
if flat.get("type") in _EMBEDDING_MODEL_TYPES:
|
|
230
|
+
# The backend stores the model at the top level as ``embeddings_model``;
|
|
231
|
+
# these documents call it ``embedding_model``.
|
|
232
|
+
flat.setdefault("embedding_model", flat.get("embeddings_model"))
|
|
233
|
+
if isinstance(flat.get("provider"), Mapping):
|
|
234
|
+
# Provider settings are split server-side into base and create params.
|
|
235
|
+
provider = flat["provider"]
|
|
236
|
+
flat.setdefault(
|
|
237
|
+
"settings",
|
|
238
|
+
{
|
|
239
|
+
**(provider.get("base_params") or {}),
|
|
240
|
+
**(provider.get("create_params") or {}),
|
|
241
|
+
},
|
|
242
|
+
)
|
|
243
|
+
return flat
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _document_values(document: Document, all_fields: bool = False) -> dict[str, Any]:
|
|
247
|
+
spec = document.spec
|
|
248
|
+
if document.meta.kind is DocumentKind.WORKFLOW:
|
|
249
|
+
values = spec.workflow.model_dump(mode="json", include=_WORKFLOW_FIELDS)
|
|
250
|
+
values["start_hint"] = spec.start_hint
|
|
251
|
+
if all_fields:
|
|
252
|
+
values["yaml_config"] = "workflow" # always a reference field
|
|
253
|
+
return values
|
|
254
|
+
return spec.model_dump(mode="json")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# --- credentials -----------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _credential_finding(
|
|
261
|
+
field: str, refs: list[CredentialRef], resolver: EnvCredentialResolver
|
|
262
|
+
) -> CannotCompare:
|
|
263
|
+
if all(resolver.is_resolvable(ref) for ref in refs):
|
|
264
|
+
reason = "credential reference; live value is masked and cannot be compared"
|
|
265
|
+
else:
|
|
266
|
+
reason = f"{_UNRESOLVABLE}; live value is masked and cannot be compared"
|
|
267
|
+
return CannotCompare(field=field, reason=reason)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _credential_findings(
|
|
271
|
+
document: Document, resolver: EnvCredentialResolver
|
|
272
|
+
) -> list[CannotCompare]:
|
|
273
|
+
spec = document.spec
|
|
274
|
+
findings: list[CannotCompare] = []
|
|
275
|
+
entries = getattr(spec, "credential_values", None)
|
|
276
|
+
if entries:
|
|
277
|
+
findings.append(
|
|
278
|
+
_credential_finding("credential_values", [e.ref for e in entries], resolver)
|
|
279
|
+
)
|
|
280
|
+
nested = SimpleNamespace(
|
|
281
|
+
mcp_servers=getattr(spec, "mcp_servers", None),
|
|
282
|
+
workflow=getattr(spec, "workflow", None),
|
|
283
|
+
)
|
|
284
|
+
refs = resolver.collect_refs(nested)
|
|
285
|
+
if refs:
|
|
286
|
+
field = "mcp_servers" if hasattr(spec, "mcp_servers") else "yaml_config"
|
|
287
|
+
findings.append(_credential_finding(field, refs, resolver))
|
|
288
|
+
token = getattr(spec, "access_token", None)
|
|
289
|
+
if token is not None:
|
|
290
|
+
findings.append(_credential_finding("access_token", [token], resolver))
|
|
291
|
+
return findings
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _datasource_secret_view(spec: Any, settings: Any) -> SimpleNamespace:
|
|
295
|
+
"""The spec attributes the datasource secret table reads, nothing else."""
|
|
296
|
+
return SimpleNamespace(
|
|
297
|
+
type=getattr(spec, "type", None),
|
|
298
|
+
name=getattr(spec, "name", None),
|
|
299
|
+
provider_name=getattr(spec, "provider_name", None),
|
|
300
|
+
toolkit_id=getattr(spec, "toolkit_id", None),
|
|
301
|
+
settings=settings,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _settings_findings(
|
|
306
|
+
document: Document,
|
|
307
|
+
live_view: Mapping[str, Any],
|
|
308
|
+
resolver: EnvCredentialResolver,
|
|
309
|
+
) -> list[Difference | CannotCompare]:
|
|
310
|
+
"""Provider ``settings``, compared one key at a time: a key holding an
|
|
311
|
+
``env:`` reference, or masked on the live side, is reported on its own and
|
|
312
|
+
never hides the other keys."""
|
|
313
|
+
spec = document.spec
|
|
314
|
+
settings = getattr(spec, "settings", None)
|
|
315
|
+
if not settings or "settings" not in live_view:
|
|
316
|
+
return []
|
|
317
|
+
live_settings = live_view["settings"] or {}
|
|
318
|
+
findings: list[Difference | CannotCompare] = []
|
|
319
|
+
for key, value in settings.items():
|
|
320
|
+
field = f"settings.{key}"
|
|
321
|
+
refs = resolver.collect_refs(_datasource_secret_view(spec, {key: value}))
|
|
322
|
+
if refs:
|
|
323
|
+
findings.append(_credential_finding(field, refs, resolver))
|
|
324
|
+
continue
|
|
325
|
+
finding = _compare_field(field, value, live_settings.get(key))
|
|
326
|
+
if finding is not None:
|
|
327
|
+
findings.append(finding)
|
|
328
|
+
return findings
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# --- reference fields ----------------------------------------------------------
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _ids(value: Any) -> list[str]:
|
|
335
|
+
ids = []
|
|
336
|
+
for item in value or []:
|
|
337
|
+
if isinstance(item, Mapping):
|
|
338
|
+
item = item.get("id")
|
|
339
|
+
elif not isinstance(item, str):
|
|
340
|
+
item = getattr(item, "id", None)
|
|
341
|
+
ids.append(str(item))
|
|
342
|
+
return sorted(ids)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _load_yaml(value: Any) -> Any:
|
|
346
|
+
if not isinstance(value, str):
|
|
347
|
+
return value
|
|
348
|
+
try:
|
|
349
|
+
return yaml.safe_load(value)
|
|
350
|
+
except yaml.YAMLError:
|
|
351
|
+
return value
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
_INTEGRATION_KEYS = frozenset({"settings", "mcp_connect_auth_token"})
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _integrations_by_id(value: Any) -> Any:
|
|
358
|
+
"""Reduce every embedded integration to its id.
|
|
359
|
+
|
|
360
|
+
The backend embeds the whole integration (with masked ``credential_values``
|
|
361
|
+
and non-sensitive settings) in toolkits / MCP servers; the document only
|
|
362
|
+
references one, so only its identity is comparable.
|
|
363
|
+
"""
|
|
364
|
+
if isinstance(value, list):
|
|
365
|
+
return [_integrations_by_id(v) for v in value]
|
|
366
|
+
if not isinstance(value, Mapping):
|
|
367
|
+
return value
|
|
368
|
+
return {
|
|
369
|
+
k: {"id": v.get("id")}
|
|
370
|
+
if k in _INTEGRATION_KEYS and isinstance(v, Mapping)
|
|
371
|
+
else _integrations_by_id(v)
|
|
372
|
+
for k, v in value.items()
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _without_key(value: Any, key: str) -> Any:
|
|
377
|
+
if isinstance(value, list):
|
|
378
|
+
return [_without_key(v, key) for v in value]
|
|
379
|
+
if isinstance(value, Mapping):
|
|
380
|
+
return {k: _without_key(v, key) for k, v in value.items() if k != key}
|
|
381
|
+
return value
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _toolkit_view(value: Any) -> Any:
|
|
385
|
+
"""Toolkits as compared: integrations by id, and without ``settings_config``,
|
|
386
|
+
which the backend recomputes on every read (it is true when a tool needs
|
|
387
|
+
settings and has no integration pinned), so a document cannot author it."""
|
|
388
|
+
return _without_key(_integrations_by_id(value), "settings_config")
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _normalise_reference(field: str, resolved: Any, live: Any) -> tuple[Any, Any]:
|
|
392
|
+
if field in _ID_LIST_FIELDS:
|
|
393
|
+
return _ids(resolved), _ids(live)
|
|
394
|
+
if field == "toolkits":
|
|
395
|
+
return _toolkit_view(resolved), _toolkit_view(live)
|
|
396
|
+
if field in _INTEGRATION_FIELDS:
|
|
397
|
+
return _integrations_by_id(resolved), _integrations_by_id(live)
|
|
398
|
+
if field == "yaml_config":
|
|
399
|
+
return _load_yaml(resolved), _load_yaml(live)
|
|
400
|
+
return resolved, live
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _mask_mcp_servers(config: Any) -> Any:
|
|
404
|
+
"""A workflow configuration with the credential-bearing parts of every MCP
|
|
405
|
+
server (assistant-level and tool-level) replaced by a placeholder."""
|
|
406
|
+
if not isinstance(config, Mapping):
|
|
407
|
+
return config
|
|
408
|
+
masked = copy.deepcopy(dict(config))
|
|
409
|
+
assistants = masked.get("assistants") or []
|
|
410
|
+
if isinstance(assistants, dict):
|
|
411
|
+
assistants = list(assistants.values())
|
|
412
|
+
servers = [
|
|
413
|
+
server
|
|
414
|
+
for assistant in assistants
|
|
415
|
+
if isinstance(assistant, dict)
|
|
416
|
+
for server in assistant.get("mcp_servers") or []
|
|
417
|
+
if isinstance(server, dict)
|
|
418
|
+
]
|
|
419
|
+
servers += [
|
|
420
|
+
tool["mcp_server"]
|
|
421
|
+
for tool in masked.get("tools") or []
|
|
422
|
+
if isinstance(tool, dict) and isinstance(tool.get("mcp_server"), dict)
|
|
423
|
+
]
|
|
424
|
+
for server in servers:
|
|
425
|
+
for key in MCP_REF_FIELDS:
|
|
426
|
+
if server.get(key) is not None:
|
|
427
|
+
server[key] = _REDACTED
|
|
428
|
+
return masked
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _redact(finding: Difference | CannotCompare | None, redact: bool):
|
|
432
|
+
if redact and isinstance(finding, Difference):
|
|
433
|
+
return Difference(
|
|
434
|
+
field=finding.field, document_value=_REDACTED, live_value=_REDACTED
|
|
435
|
+
)
|
|
436
|
+
return finding
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _reference_fields(document: Document) -> frozenset[str]:
|
|
440
|
+
if document.meta.kind in _VALUE_CATEGORY_KINDS:
|
|
441
|
+
return REFERENCE_FIELDS - {"categories"}
|
|
442
|
+
return REFERENCE_FIELDS
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _reference_findings(
|
|
446
|
+
document: Document,
|
|
447
|
+
live_view: Mapping[str, Any],
|
|
448
|
+
policy: FieldPolicy,
|
|
449
|
+
ctx: ResolveContext | None,
|
|
450
|
+
credential_fields: set[str],
|
|
451
|
+
unresolvable_fields: set[str],
|
|
452
|
+
) -> list[Difference | CannotCompare]:
|
|
453
|
+
reference_fields = _reference_fields(document)
|
|
454
|
+
present = {
|
|
455
|
+
f
|
|
456
|
+
for f, v in _document_values(document, all_fields=True).items()
|
|
457
|
+
if f in reference_fields and _canon(v) is not None
|
|
458
|
+
}
|
|
459
|
+
if ctx is None:
|
|
460
|
+
return [
|
|
461
|
+
CannotCompare(field=f, reason="references not resolved; cannot compare")
|
|
462
|
+
for f in sorted(present - credential_fields)
|
|
463
|
+
]
|
|
464
|
+
resolved = build_resolved(document, ctx)
|
|
465
|
+
findings: list[Difference | CannotCompare] = []
|
|
466
|
+
for field in sorted(reference_fields & resolved.keys()):
|
|
467
|
+
if field not in policy.comparable or field not in live_view:
|
|
468
|
+
continue
|
|
469
|
+
if field in unresolvable_fields: # already reported as CannotCompare
|
|
470
|
+
continue
|
|
471
|
+
redact = field in credential_fields
|
|
472
|
+
pair = _normalise_reference(field, resolved[field], live_view[field])
|
|
473
|
+
finding = _redact(_compare_field(field, *pair), redact)
|
|
474
|
+
if field == "yaml_config" and isinstance(finding, Difference):
|
|
475
|
+
finding = Difference(
|
|
476
|
+
field=field,
|
|
477
|
+
document_value=_mask_mcp_servers(finding.document_value),
|
|
478
|
+
live_value=_mask_mcp_servers(finding.live_value),
|
|
479
|
+
)
|
|
480
|
+
if finding is not None and not (redact and isinstance(finding, CannotCompare)):
|
|
481
|
+
findings.append(finding)
|
|
482
|
+
return findings
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
# --- diff ------------------------------------------------------------------
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _comparable_part(document_value: Any, live_value: Any) -> tuple[Any, Any, bool]:
|
|
489
|
+
"""``(document, live, hidden)`` with the masked parts left out.
|
|
490
|
+
|
|
491
|
+
Lists of equal length are cut per item; anything else is all or nothing.
|
|
492
|
+
``hidden`` says that something the document authors could not be seen.
|
|
493
|
+
"""
|
|
494
|
+
if (
|
|
495
|
+
isinstance(document_value, list)
|
|
496
|
+
and isinstance(live_value, list)
|
|
497
|
+
and len(document_value) == len(live_value)
|
|
498
|
+
):
|
|
499
|
+
pairs = [
|
|
500
|
+
(d, v)
|
|
501
|
+
for d, v in zip(document_value, live_value)
|
|
502
|
+
if not _has_mask(_project(d, v))
|
|
503
|
+
]
|
|
504
|
+
hidden = len(pairs) < len(document_value)
|
|
505
|
+
return [d for d, _ in pairs], [v for _, v in pairs], hidden
|
|
506
|
+
if _has_mask(_project(document_value, live_value)):
|
|
507
|
+
return None, None, True
|
|
508
|
+
return document_value, live_value, False
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _compare_field(
|
|
512
|
+
field: str, document_value: Any, live_value: Any
|
|
513
|
+
) -> Difference | CannotCompare | None:
|
|
514
|
+
document, live, hidden = _comparable_part(document_value, live_value)
|
|
515
|
+
if _canon(document) != _canon(_project(document, live)):
|
|
516
|
+
return Difference(
|
|
517
|
+
field=field, document_value=document_value, live_value=live_value
|
|
518
|
+
)
|
|
519
|
+
if hidden:
|
|
520
|
+
return CannotCompare(field=field, reason="live value is masked")
|
|
521
|
+
return None
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _unobservable_findings(
|
|
525
|
+
document: Document, live_view: Mapping[str, Any], policy: FieldPolicy
|
|
526
|
+
) -> list[CannotCompare]:
|
|
527
|
+
"""Authored raw-only fields the live view did not carry (never skipped)."""
|
|
528
|
+
values = _document_values(document)
|
|
529
|
+
return [
|
|
530
|
+
CannotCompare(
|
|
531
|
+
field=field, reason="not returned by the live view; cannot compare"
|
|
532
|
+
)
|
|
533
|
+
for field in sorted(_OPTIONAL_LIVE_FIELDS & policy.comparable)
|
|
534
|
+
if field not in live_view and _canon(values.get(field)) is not None
|
|
535
|
+
]
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def diff(
|
|
539
|
+
document: Document,
|
|
540
|
+
live: Any,
|
|
541
|
+
policy: FieldPolicy,
|
|
542
|
+
resolver: EnvCredentialResolver,
|
|
543
|
+
ctx: ResolveContext | None = None,
|
|
544
|
+
) -> list[Difference | CannotCompare]:
|
|
545
|
+
"""Findings between a document and its live entity.
|
|
546
|
+
|
|
547
|
+
``live`` is the live SDK object, or an already-comparable dict. ``ctx``
|
|
548
|
+
resolves reference fields for comparison; without it they are reported as
|
|
549
|
+
``CannotCompare``.
|
|
550
|
+
"""
|
|
551
|
+
comparable = (
|
|
552
|
+
live if isinstance(live, Mapping) else adapter_for(document).to_comparable(live)
|
|
553
|
+
)
|
|
554
|
+
live_view = _flatten_live(comparable)
|
|
555
|
+
findings: list[Difference | CannotCompare] = _credential_findings(
|
|
556
|
+
document, resolver
|
|
557
|
+
)
|
|
558
|
+
credential_fields = {f.field for f in findings}
|
|
559
|
+
unresolvable = {f.field for f in findings if _UNRESOLVABLE in f.reason}
|
|
560
|
+
handled = {f.field for f in findings} | _reference_fields(document) | policy.deny
|
|
561
|
+
handled.add("settings") # compared per key below
|
|
562
|
+
for field, document_value in _document_values(document).items():
|
|
563
|
+
if field in handled or field not in policy.comparable or field not in live_view:
|
|
564
|
+
continue
|
|
565
|
+
if document_value is None and field not in _CLEARED_WHEN_OMITTED:
|
|
566
|
+
# not authored: the platform decides
|
|
567
|
+
continue
|
|
568
|
+
finding = _compare_field(field, document_value, live_view[field])
|
|
569
|
+
if finding is not None:
|
|
570
|
+
findings.append(finding)
|
|
571
|
+
findings.extend(_settings_findings(document, live_view, resolver))
|
|
572
|
+
findings.extend(_unobservable_findings(document, live_view, policy))
|
|
573
|
+
findings.extend(
|
|
574
|
+
_reference_findings(
|
|
575
|
+
document, live_view, policy, ctx, credential_fields, unresolvable
|
|
576
|
+
)
|
|
577
|
+
)
|
|
578
|
+
return findings
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _guard_project(document: Document, live: Mapping[str, Any], target: str) -> None:
|
|
582
|
+
"""Refuse to overwrite an entity that lives in another project."""
|
|
583
|
+
field = _PROJECT_FIELDS.get(document.meta.kind)
|
|
584
|
+
live_project = live.get(field) if field else None
|
|
585
|
+
if live_project is not None and live_project != target:
|
|
586
|
+
raise ApplyError(
|
|
587
|
+
"project_mismatch",
|
|
588
|
+
document.meta.kind.value,
|
|
589
|
+
document.meta.name,
|
|
590
|
+
f"live entity is in project {live_project!r}, not target {target!r}",
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
# --- planner / apply ---------------------------------------------------------
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
class _PlanCredentials:
|
|
598
|
+
"""Credentials for a read-only plan: an unset variable is not an error.
|
|
599
|
+
|
|
600
|
+
``credential_values`` are never compared, so a ref that cannot be resolved
|
|
601
|
+
only needs a placeholder to build the (compared) request body; the field
|
|
602
|
+
is reported as an "unresolvable credential reference" ``CannotCompare``.
|
|
603
|
+
"""
|
|
604
|
+
|
|
605
|
+
def __init__(self, inner: EnvCredentialResolver):
|
|
606
|
+
self._inner = inner
|
|
607
|
+
|
|
608
|
+
def is_resolvable(self, ref: CredentialRef) -> bool:
|
|
609
|
+
return self._inner.is_resolvable(ref)
|
|
610
|
+
|
|
611
|
+
def resolve(self, ref: CredentialRef) -> SecretValue:
|
|
612
|
+
if self._inner.is_resolvable(ref):
|
|
613
|
+
return self._inner.resolve(ref)
|
|
614
|
+
return SecretValue("")
|
|
615
|
+
|
|
616
|
+
def revealed_values(self) -> frozenset[str]:
|
|
617
|
+
return self._inner.revealed_values()
|
|
618
|
+
|
|
619
|
+
def collect_refs(self, spec: Any) -> list[CredentialRef]:
|
|
620
|
+
return self._inner.collect_refs(spec)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
class ApplyResult(BaseModel):
|
|
624
|
+
"""Outcome of a single-entity apply; ``id`` is returned, never stored."""
|
|
625
|
+
|
|
626
|
+
model_config = ConfigDict(extra="forbid")
|
|
627
|
+
|
|
628
|
+
id: str | None
|
|
629
|
+
created: bool
|
|
630
|
+
#: Fields the document authors that could not be compared; with an empty
|
|
631
|
+
#: plan nothing was written for them (see ``force``). Field names only.
|
|
632
|
+
uncomparable: list[str] = []
|
|
633
|
+
#: False only when an unchanged entity was left alone (empty plan, no write).
|
|
634
|
+
changed: bool = True
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
class SingleEntityPlanner:
|
|
638
|
+
"""Plans (and applies) one document against one live entity."""
|
|
639
|
+
|
|
640
|
+
def __init__(
|
|
641
|
+
self,
|
|
642
|
+
client: Any,
|
|
643
|
+
credentials: EnvCredentialResolver | None = None,
|
|
644
|
+
provider_secret_lookup: ProviderSecretLookup | None = None,
|
|
645
|
+
):
|
|
646
|
+
self._client = client
|
|
647
|
+
self._credentials = credentials or EnvCredentialResolver()
|
|
648
|
+
if provider_secret_lookup is not None:
|
|
649
|
+
self._credentials = self._credentials.with_provider_secret_lookup(
|
|
650
|
+
provider_secret_lookup
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
def _plan_credentials(self) -> "_PlanCredentials":
|
|
654
|
+
return _PlanCredentials(self._credentials)
|
|
655
|
+
|
|
656
|
+
def plan(self, document: Document, entity_id: str, target: str) -> Plan:
|
|
657
|
+
"""Diff ``document`` against the entity ``entity_id`` (one read, no writes)."""
|
|
658
|
+
document = with_default_project(document, target)
|
|
659
|
+
guard_name(document)
|
|
660
|
+
guard_project(document, target)
|
|
661
|
+
ctx = self._context(target, self._plan_credentials())
|
|
662
|
+
return self._plan(document, entity_id, target, ctx)
|
|
663
|
+
|
|
664
|
+
def _context(self, target: str, credentials: Any = None) -> ResolveContext:
|
|
665
|
+
lookup = NameLookup([], target, self._client)
|
|
666
|
+
return ResolveContext(lookup, credentials or self._credentials)
|
|
667
|
+
|
|
668
|
+
def _plan(
|
|
669
|
+
self, document: Document, entity_id: str, target: str, ctx: ResolveContext
|
|
670
|
+
) -> Plan:
|
|
671
|
+
guard_supported(document)
|
|
672
|
+
adapter = adapter_for(document)
|
|
673
|
+
live = adapter.get(self._client, document, entity_id)
|
|
674
|
+
guard_datasource_identity(document, live)
|
|
675
|
+
_guard_project(document, adapter.to_comparable(live), target)
|
|
676
|
+
policy = policy_for(document)
|
|
677
|
+
findings = diff(document, live, policy, self._credentials, ctx)
|
|
678
|
+
return Plan(
|
|
679
|
+
differences=[f for f in findings if isinstance(f, Difference)],
|
|
680
|
+
cannot_compare=[f for f in findings if isinstance(f, CannotCompare)],
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
def apply(
|
|
684
|
+
self,
|
|
685
|
+
document: Document,
|
|
686
|
+
entity_id: str | None,
|
|
687
|
+
target: str,
|
|
688
|
+
force: bool = False,
|
|
689
|
+
) -> ApplyResult:
|
|
690
|
+
"""Create (no ``entity_id``) or update the entity; never deletes.
|
|
691
|
+
|
|
692
|
+
References and credential refs are checked before anything is written
|
|
693
|
+
(references are looked up live, which is a read). An update with an empty plan sends no write, unless ``force``
|
|
694
|
+
is set; fields the plan could not compare (a rotated secret, a masked
|
|
695
|
+
value) are then not known to be unchanged, so they are listed in
|
|
696
|
+
``ApplyResult.uncomparable``. ``force`` writes the full document.
|
|
697
|
+
"""
|
|
698
|
+
document = with_default_project(document, target)
|
|
699
|
+
guard_supported(document)
|
|
700
|
+
guard_name(document)
|
|
701
|
+
guard_project(document, target)
|
|
702
|
+
ctx = self._context(target)
|
|
703
|
+
check_references([document], ctx)
|
|
704
|
+
check_credentials([document], ctx)
|
|
705
|
+
changed = None # unknown: write everything
|
|
706
|
+
if entity_id is not None:
|
|
707
|
+
plan = self._plan(document, entity_id, target, ctx)
|
|
708
|
+
if plan.is_empty and not force:
|
|
709
|
+
return ApplyResult(
|
|
710
|
+
id=entity_id,
|
|
711
|
+
created=False,
|
|
712
|
+
changed=False,
|
|
713
|
+
uncomparable=[c.field for c in plan.cannot_compare],
|
|
714
|
+
)
|
|
715
|
+
changed = frozenset(d.field for d in plan.differences) | frozenset(
|
|
716
|
+
c.field for c in plan.cannot_compare
|
|
717
|
+
)
|
|
718
|
+
resolved = build_resolved(document, ctx)
|
|
719
|
+
adapter = adapter_for(document)
|
|
720
|
+
try:
|
|
721
|
+
if entity_id is None:
|
|
722
|
+
response = adapter.create(self._client, document, resolved)
|
|
723
|
+
else:
|
|
724
|
+
extra = {}
|
|
725
|
+
if getattr(document.spec, "type", None) == "provider":
|
|
726
|
+
# The schema says which stored settings are secrets.
|
|
727
|
+
extra["secret_keys"] = self._credentials.provider_secret_keys(
|
|
728
|
+
document.spec
|
|
729
|
+
)
|
|
730
|
+
adapter.update(
|
|
731
|
+
self._client, document, entity_id, resolved, changed, **extra
|
|
732
|
+
)
|
|
733
|
+
except PLATFORM_ERRORS as exc:
|
|
734
|
+
# Raised below, outside the handler: the SDK error carries the
|
|
735
|
+
# request body, resolved credentials included.
|
|
736
|
+
rejection = PlatformRejectionError(
|
|
737
|
+
"platform_rejection",
|
|
738
|
+
document.meta.kind.value,
|
|
739
|
+
document.meta.name,
|
|
740
|
+
exc,
|
|
741
|
+
self._credentials.revealed_values(),
|
|
742
|
+
)
|
|
743
|
+
else:
|
|
744
|
+
rejection = None
|
|
745
|
+
if rejection is not None:
|
|
746
|
+
raise rejection
|
|
747
|
+
if entity_id is not None:
|
|
748
|
+
return ApplyResult(id=entity_id, created=False)
|
|
749
|
+
return ApplyResult(
|
|
750
|
+
id=created_id(adapter, self._client, document, response), created=True
|
|
751
|
+
)
|