benchling-toolkit 0.4.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.
Files changed (38) hide show
  1. benchling_toolkit/__init__.py +6 -0
  2. benchling_toolkit/api.py +219 -0
  3. benchling_toolkit/auth.py +133 -0
  4. benchling_toolkit/change_spec.py +436 -0
  5. benchling_toolkit/cli.py +840 -0
  6. benchling_toolkit/config.py +57 -0
  7. benchling_toolkit/credentials.py +257 -0
  8. benchling_toolkit/environment.py +188 -0
  9. benchling_toolkit/errors.py +104 -0
  10. benchling_toolkit/export.py +662 -0
  11. benchling_toolkit/keychain.py +323 -0
  12. benchling_toolkit/listing.py +487 -0
  13. benchling_toolkit/mcp_server.py +847 -0
  14. benchling_toolkit/models.py +290 -0
  15. benchling_toolkit/plans/__init__.py +13 -0
  16. benchling_toolkit/plans/base.py +60 -0
  17. benchling_toolkit/plans/document.py +298 -0
  18. benchling_toolkit/plans/fields.py +300 -0
  19. benchling_toolkit/plans/planner.py +318 -0
  20. benchling_toolkit/plans/repository.py +105 -0
  21. benchling_toolkit/plans/result_update.py +845 -0
  22. benchling_toolkit/plans/results.py +184 -0
  23. benchling_toolkit/plans/table.py +241 -0
  24. benchling_toolkit/py.typed +0 -0
  25. benchling_toolkit/redact.py +67 -0
  26. benchling_toolkit/runtime.py +82 -0
  27. benchling_toolkit/services.py +1206 -0
  28. benchling_toolkit/tls.py +10 -0
  29. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/list-parameters.json +32 -0
  30. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/contracts/openapi-manifest.json +48 -0
  31. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/change-spec.schema.json +173 -0
  32. benchling_toolkit-0.4.0.data/data/share/benchling-toolkit/schemas/envelope.schema.json +30 -0
  33. benchling_toolkit-0.4.0.dist-info/METADATA +576 -0
  34. benchling_toolkit-0.4.0.dist-info/RECORD +38 -0
  35. benchling_toolkit-0.4.0.dist-info/WHEEL +5 -0
  36. benchling_toolkit-0.4.0.dist-info/entry_points.txt +2 -0
  37. benchling_toolkit-0.4.0.dist-info/licenses/LICENSE +22 -0
  38. benchling_toolkit-0.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,290 @@
1
+ """Pydantic models shared by the CLI, MCP server and planner: the JSON envelope,
2
+ environment config, entry snapshots and change-plan/journal records."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from datetime import UTC, datetime
7
+ from enum import Enum
8
+ from typing import Any, Generic, Literal, TypeVar, cast
9
+ from urllib.parse import urlsplit, urlunsplit
10
+
11
+ from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_serializer, field_validator
12
+ from pydantic import ValidationError as ModelValidationError
13
+
14
+ from .errors import BenchlingAgentError, ValidationError
15
+ from .redact import redact, redact_text
16
+
17
+ T = TypeVar("T")
18
+
19
+
20
+ class ErrorDetail(BaseModel):
21
+ """Serializable form of a BenchlingAgentError carried in a failed Envelope."""
22
+
23
+ code: str
24
+ message: str
25
+ retryable: bool = False
26
+ details: dict[str, Any] = Field(default_factory=dict)
27
+
28
+
29
+ class Envelope(BaseModel, Generic[T]):
30
+ """Stable JSON contract returned by both interfaces."""
31
+
32
+ schema_version: Literal["1.0"] = "1.0"
33
+ ok: bool
34
+ data: T | None = None
35
+ error: ErrorDetail | None = None
36
+ meta: dict[str, Any] = Field(default_factory=dict)
37
+
38
+ @classmethod
39
+ def success(cls, data: T, **meta: Any) -> Envelope[T]:
40
+ """Build an ok=True envelope wrapping data; extra kwargs become meta."""
41
+ return cls(ok=True, data=data, meta=meta)
42
+
43
+ @classmethod
44
+ def failure(cls, error: BenchlingAgentError, **meta: Any) -> Envelope[dict[str, Any]]:
45
+ """Build an ok=False envelope from an error; no data is included."""
46
+ details = redact(error.details)
47
+ if not isinstance(details, dict):
48
+ details = {}
49
+ redacted_meta = redact(meta)
50
+ return cast(
51
+ Envelope[dict[str, Any]],
52
+ cls(
53
+ ok=False,
54
+ error=ErrorDetail(
55
+ code=error.code,
56
+ message=redact_text(error.message),
57
+ retryable=error.retryable,
58
+ details=details,
59
+ ),
60
+ meta=redacted_meta if isinstance(redacted_meta, dict) else {},
61
+ ),
62
+ )
63
+
64
+
65
+ class AuthMethod(str, Enum):
66
+ """Supported ways of obtaining an API token."""
67
+
68
+ CLIENT_CREDENTIALS = "client_credentials"
69
+
70
+
71
+ _API_SUFFIXES = ("/api/v2", "/api/v3")
72
+
73
+
74
+ def prepare_tenant_url(value: object) -> object:
75
+ """Normalize a tenant URL string before it is parsed.
76
+
77
+ A bare host gets https://. A trailing /api/v2 or /api/v3 and a trailing
78
+ slash are removed. http:// is rejected with a message that does not echo
79
+ the input, which may contain credentials.
80
+ """
81
+ if not isinstance(value, str):
82
+ return value
83
+ text = value.strip()
84
+ if not text:
85
+ raise ValueError("Tenant URL is required")
86
+ if text.lower().startswith("http://"):
87
+ raise ValueError("Tenant URL must use https://, not http://")
88
+ if "://" not in text:
89
+ text = "https://" + text
90
+ elif not text.lower().startswith("https://"):
91
+ raise ValueError("Tenant URL must use https://")
92
+ parts = urlsplit(text)
93
+ path = parts.path.rstrip("/")
94
+ folded = path.casefold()
95
+ for suffix in _API_SUFFIXES:
96
+ if folded.endswith(suffix):
97
+ path = path[: -len(suffix)].rstrip("/")
98
+ break
99
+ return urlunsplit(("https", parts.netloc, path, parts.query, parts.fragment))
100
+
101
+
102
+ def explain_environment_error(exc: ModelValidationError, *, env: str) -> ValidationError:
103
+ """Turn a model failure into a field-specific error that does not echo the input."""
104
+ url_errors = [err for err in exc.errors() if "tenant_url" in err.get("loc", ())]
105
+ id_errors = [err for err in exc.errors() if "client_id" in err.get("loc", ())]
106
+ if url_errors:
107
+ return ValidationError(
108
+ _tenant_url_message(str(url_errors[0].get("msg", ""))),
109
+ details={"env": env, "field": "tenant_url"},
110
+ )
111
+ if id_errors:
112
+ return ValidationError("Invalid client ID", details={"env": env, "field": "client_id"})
113
+ return ValidationError(
114
+ "Invalid tenant URL. Expected https://host, a bare host, or a host ending in /api/v2 or /api/v3.",
115
+ details={"env": env, "field": "tenant_url"},
116
+ )
117
+
118
+
119
+ def _tenant_url_message(msg: str) -> str:
120
+ folded = msg.casefold()
121
+ if "not http://" in folded:
122
+ return "Tenant URL must use https://, not http://."
123
+ if "must use https" in folded:
124
+ return "Tenant URL must use https://."
125
+ if "credential" in folded:
126
+ return "Invalid tenant URL: user and password are not allowed."
127
+ if "only scheme and host" in folded or "path" in folded:
128
+ return (
129
+ "Invalid tenant URL: expected a host only. A trailing /api/v2 or /api/v3 "
130
+ "is removed; other paths are not allowed."
131
+ )
132
+ if "required" in folded:
133
+ return "Tenant URL is required."
134
+ return "Invalid tenant URL. Expected https://host, a bare host, or a host ending in /api/v2 or /api/v3."
135
+
136
+
137
+ class Environment(BaseModel):
138
+ """A named tenant configuration; holds no secrets, only the tenant URL and auth method."""
139
+
140
+ model_config = ConfigDict(extra="forbid")
141
+
142
+ name: str = Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
143
+ tenant_url: HttpUrl
144
+ auth_method: AuthMethod
145
+ client_id: str | None = None
146
+
147
+ @field_validator("tenant_url", mode="before")
148
+ @classmethod
149
+ def normalize_tenant_url(cls, value: object) -> object:
150
+ """Accept a bare host and a trailing /api/v2 or /api/v3; reject http://."""
151
+ return prepare_tenant_url(value)
152
+
153
+ @field_validator("tenant_url")
154
+ @classmethod
155
+ def strip_url_path(cls, value: HttpUrl) -> HttpUrl:
156
+ """Require a bare https://host URL; reject credentials, paths, queries and fragments."""
157
+ if value.scheme != "https":
158
+ raise ValueError("tenant_url must use HTTPS")
159
+ if value.username or value.password:
160
+ raise ValueError("tenant_url must not contain credentials")
161
+ if value.path not in {"", "/"} or value.query or value.fragment:
162
+ raise ValueError("tenant_url must contain only scheme and host")
163
+ return value
164
+
165
+ @field_validator("client_id")
166
+ @classmethod
167
+ def strip_client_id(cls, value: str | None) -> str | None:
168
+ """Trim whitespace; blank values become None."""
169
+ return value.strip() if value else None
170
+
171
+ @field_serializer("tenant_url")
172
+ def serialize_tenant_url(self, value: HttpUrl) -> str:
173
+ """Display and persist the host without a trailing slash."""
174
+ return str(value).rstrip("/")
175
+
176
+ @property
177
+ def base_url(self) -> str:
178
+ """Tenant URL without a trailing slash."""
179
+ return str(self.tenant_url).rstrip("/")
180
+
181
+
182
+ class TokenBundle(BaseModel):
183
+ """An access token with its expiry."""
184
+
185
+ access_token: str
186
+ expires_at: datetime
187
+ token_type: str = "Bearer"
188
+
189
+ def usable(self, skew_seconds: int = 60) -> bool:
190
+ """True if the token stays valid for more than skew_seconds; naive expiries are treated as UTC."""
191
+ now = datetime.now(UTC)
192
+ expires = self.expires_at
193
+ if expires.tzinfo is None:
194
+ expires = expires.replace(tzinfo=UTC)
195
+ return (expires - now).total_seconds() > skew_seconds
196
+
197
+
198
+ class CompletenessIssue(BaseModel):
199
+ """A reason part of an entry snapshot could not be retrieved."""
200
+
201
+ scope: str
202
+ reason: str
203
+ details: dict[str, Any] = Field(default_factory=dict)
204
+
205
+
206
+ class EntrySnapshot(BaseModel):
207
+ """Structured entry content pinned to one version_id.
208
+
209
+ completeness is "partial" when issues lists anything that was not retrieved.
210
+ """
211
+
212
+ model_config = ConfigDict(populate_by_name=True)
213
+
214
+ entry: dict[str, Any]
215
+ version_id: str
216
+ parts: list[dict[str, Any]]
217
+ sections: list[dict[str, Any]]
218
+ tables: dict[str, dict[str, Any]] = Field(default_factory=dict)
219
+ entry_schema: dict[str, Any] | None = Field(
220
+ default=None, validation_alias="schema", serialization_alias="schema"
221
+ )
222
+ fields: dict[str, Any] | None = None
223
+ result_tables: list[dict[str, Any]] = Field(default_factory=list)
224
+ results: list[dict[str, Any]] = Field(default_factory=list)
225
+ result_retrieval: dict[str, Any] = Field(default_factory=dict)
226
+ completeness: Literal["complete", "partial"] = "complete"
227
+ issues: list[CompletenessIssue] = Field(default_factory=list)
228
+
229
+
230
+ class PlanFamily(str, Enum):
231
+ """Kinds of change a plan can describe; each has its own planner."""
232
+
233
+ DOCUMENT = "document"
234
+ TABLE = "table"
235
+ FIELDS = "fields"
236
+ RESULTS = "results"
237
+
238
+
239
+ class PlanStatus(str, Enum):
240
+ """Lifecycle of a plan; UNKNOWN means the outcome of an apply could not be confirmed."""
241
+
242
+ PENDING = "pending"
243
+ APPLYING = "applying"
244
+ SUCCEEDED = "succeeded"
245
+ PARTIAL = "partial"
246
+ FAILED = "failed"
247
+ UNKNOWN = "unknown"
248
+
249
+
250
+ class ChangePlan(BaseModel):
251
+ """Immutable preview of a change: before/after/diff plus preconditions checked at apply time.
252
+
253
+ checksum guards against tampering with a stored plan.
254
+ """
255
+
256
+ model_config = ConfigDict(extra="forbid")
257
+
258
+ schema_version: Literal["1.0"] = "1.0"
259
+ id: str
260
+ created_at: datetime
261
+ env: str
262
+ tenant_url: str
263
+ entry_id: str
264
+ family: PlanFamily
265
+ request: dict[str, Any]
266
+ before: dict[str, Any]
267
+ after: dict[str, Any]
268
+ diff: dict[str, Any]
269
+ preconditions: dict[str, Any]
270
+ guarantees: list[str] = Field(default_factory=list)
271
+ warnings: list[str] = Field(default_factory=list)
272
+ checksum: str
273
+
274
+
275
+ class JournalEvent(BaseModel):
276
+ """One timestamped stage transition recorded while applying a plan."""
277
+
278
+ at: datetime
279
+ stage: str
280
+ status: str
281
+ details: dict[str, Any] = Field(default_factory=dict)
282
+
283
+
284
+ class ChangeJournal(BaseModel):
285
+ """Append-only apply history for a plan, with its overall status and final result."""
286
+
287
+ plan_id: str
288
+ status: PlanStatus = PlanStatus.PENDING
289
+ events: list[JournalEvent] = Field(default_factory=list)
290
+ result: dict[str, Any] | None = None
@@ -0,0 +1,13 @@
1
+ """Change planning and guarded application, split by change family."""
2
+
3
+ from .planner import ChangePlanner
4
+ from .repository import SAFE_ID, PlanRepository, canonical_json, checksum_for, json_diff
5
+
6
+ __all__ = [
7
+ "SAFE_ID",
8
+ "ChangePlanner",
9
+ "PlanRepository",
10
+ "canonical_json",
11
+ "checksum_for",
12
+ "json_diff",
13
+ ]
@@ -0,0 +1,60 @@
1
+ """Shared base class for the per-family planners."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from typing import Any
7
+
8
+ from ..api import BenchlingAPI
9
+ from ..errors import (
10
+ ConflictError,
11
+ )
12
+ from ..models import (
13
+ ChangeJournal,
14
+ JournalEvent,
15
+ )
16
+ from ..services import (
17
+ BenchlingService,
18
+ )
19
+ from .repository import PlanRepository
20
+
21
+
22
+ def write_event_details(response: dict[str, Any], **extra: Any) -> dict[str, Any]:
23
+ """Journal payload for one write: the response body and its raw HTTP status."""
24
+ status = getattr(response, "status_code", None)
25
+ details: dict[str, Any] = {"response": dict(response), **extra}
26
+ if isinstance(status, int):
27
+ details["http_status"] = status
28
+ return details
29
+
30
+
31
+ # before, after, preconditions, guarantees, warnings
32
+ PlanParts = tuple[dict[str, Any], dict[str, Any], dict[str, Any], list[str], list[str]]
33
+
34
+
35
+ class PlannerBase:
36
+ """Holds the service, API and repository that every planner mixin relies on."""
37
+
38
+ def __init__(
39
+ self,
40
+ service: BenchlingService,
41
+ api: BenchlingAPI,
42
+ repository: PlanRepository,
43
+ ) -> None:
44
+ self.service = service
45
+ self.api = api
46
+ self.repository = repository
47
+
48
+ def _expect(self, actual: Any, expected: Any, label: str) -> None:
49
+ if actual != expected:
50
+ raise ConflictError(
51
+ f"{label.capitalize()} changed after the plan was created",
52
+ details={"expected": expected, "actual": actual},
53
+ )
54
+
55
+ def _event(
56
+ self, journal: ChangeJournal, stage: str, status: str, details: dict[str, Any]
57
+ ) -> None:
58
+ journal.events.append(
59
+ JournalEvent(at=datetime.now(UTC), stage=stage, status=status, details=details)
60
+ )
@@ -0,0 +1,298 @@
1
+ """Document-part change planning."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ..errors import (
8
+ BenchlingAgentError,
9
+ UnsupportedError,
10
+ ValidationError,
11
+ )
12
+ from ..models import (
13
+ ChangeJournal,
14
+ ChangePlan,
15
+ )
16
+ from ..services import (
17
+ entry_version,
18
+ is_section,
19
+ part_content,
20
+ part_type,
21
+ )
22
+ from .base import PlannerBase, PlanParts, write_event_details
23
+
24
+
25
+ class DocumentPlanning(PlannerBase):
26
+ """Planning and applying of document-part changes."""
27
+
28
+ async def _plan_document(self, entry_id: str, request: dict[str, Any]) -> PlanParts:
29
+ snapshot = await self.service.get_entry(entry_id, full=True)
30
+ operation = request.get("operation")
31
+ parts = snapshot["parts"]
32
+ by_id = {part.get("id"): part for part in parts}
33
+ version_id = snapshot["version_id"]
34
+ if operation == "insert":
35
+ before, after = self._plan_insert(request, version_id, by_id)
36
+ elif operation == "delete":
37
+ before, after = self._plan_delete(request, version_id, parts)
38
+ elif operation == "move":
39
+ before, after = self._plan_move(request, version_id, parts, by_id)
40
+ elif operation == "replace_text":
41
+ before, after = self._plan_replace_text(request, version_id, by_id)
42
+ else:
43
+ raise ValidationError(
44
+ "Unknown document operation",
45
+ details={"supported": ["insert", "delete", "move", "replace_text"]},
46
+ )
47
+ return (
48
+ before,
49
+ after,
50
+ {
51
+ "entry_version": version_id,
52
+ "part_ids": [part.get("id") for part in parts if part.get("id")],
53
+ },
54
+ ["server-enforced document version check"],
55
+ (
56
+ ["Text replacement requires two versioned requests and can partially complete"]
57
+ if operation == "replace_text"
58
+ else []
59
+ ),
60
+ )
61
+
62
+ def _plan_insert(
63
+ self, request: dict[str, Any], version_id: str, by_id: dict[Any, Any]
64
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
65
+ """Validate an insert and return its before/after states."""
66
+ new_parts = request.get("parts")
67
+ position = request.get("position", "end_of_document")
68
+ if not isinstance(new_parts, list) or not new_parts:
69
+ raise ValidationError("Document insert requires a non-empty parts list")
70
+ if any(
71
+ not isinstance(part, dict) or not isinstance(part.get("contentType"), str)
72
+ for part in new_parts
73
+ ):
74
+ raise ValidationError("Every inserted document part requires a contentType")
75
+ if position not in {"beginning_of_document", "end_of_document"} and position not in by_id:
76
+ raise ValidationError("Insert position is not a document part")
77
+ before = {"version_id": version_id, "position": position, "parts": []}
78
+ after = {"version_id": "changes_on_apply", "position": position, "parts": new_parts}
79
+ return before, after
80
+
81
+ def _plan_delete(
82
+ self, request: dict[str, Any], version_id: str, parts: list[dict[str, Any]]
83
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
84
+ """Validate a part-range delete and return its before/after states."""
85
+ first = request.get("from_part_id")
86
+ last = request.get("to_part_id", first)
87
+ selected = self._part_range(parts, first, last)
88
+ before = {"version_id": version_id, "parts": selected}
89
+ after = {"version_id": "changes_on_apply", "parts": []}
90
+ return before, after
91
+
92
+ def _plan_move(
93
+ self,
94
+ request: dict[str, Any],
95
+ version_id: str,
96
+ parts: list[dict[str, Any]],
97
+ by_id: dict[Any, Any],
98
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
99
+ """Validate a part-range move and return its before/after states."""
100
+ first = request.get("from_part_id")
101
+ last = request.get("to_part_id", first)
102
+ selected = self._part_range(parts, first, last)
103
+ destination = request.get("position")
104
+ if (
105
+ destination not in {"beginning_of_document", "end_of_document"}
106
+ and destination not in by_id
107
+ ):
108
+ raise ValidationError("Move destination is not a document part")
109
+ if destination in {part.get("id") for part in selected}:
110
+ raise ValidationError("Move destination cannot be inside the source range")
111
+ reordered = self._parts_after_move(parts, selected, destination)
112
+ if reordered and not is_section(reordered[0]):
113
+ raise ValidationError(
114
+ "Entry must start with a section",
115
+ details={
116
+ "position": destination,
117
+ "first_part_id": reordered[0].get("id"),
118
+ "first_type": part_type(reordered[0]),
119
+ },
120
+ )
121
+ before = {"version_id": version_id, "parts": selected}
122
+ after = {"version_id": "changes_on_apply", "position": destination, "parts": selected}
123
+ return before, after
124
+
125
+ def _plan_replace_text(
126
+ self, request: dict[str, Any], version_id: str, by_id: dict[Any, Any]
127
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
128
+ """Validate a text replacement and return its before/after states."""
129
+ original = by_id.get(request.get("part_id"))
130
+ if not original:
131
+ raise ValidationError("Text replacement target was not found")
132
+ if part_type(original).split(".")[-1] not in {"TextDocumentContent", "DocumentPartText"}:
133
+ raise UnsupportedError("replace_text only supports text document parts")
134
+ if not isinstance(request.get("text"), str):
135
+ raise ValidationError("replace_text requires text")
136
+ before = {"version_id": version_id, "part": original}
137
+ content = part_content(original)
138
+ replacement = {
139
+ "contentType": "text",
140
+ "text": request["text"],
141
+ "formats": request.get("formats", content.get("formats", [])),
142
+ "links": request.get("links", content.get("links", [])),
143
+ "mentions": request.get("mentions", content.get("mentions", [])),
144
+ "indentation": request.get("indentation", content.get("indentation", 0)),
145
+ }
146
+ after = {"version_id": "changes_on_apply", "part": replacement}
147
+ return before, after
148
+
149
+ async def _apply_document(self, plan: ChangePlan, journal: ChangeJournal) -> dict[str, Any]:
150
+ current = await self.api.request("GET", f"/entry/{plan.entry_id}")
151
+ version = entry_version(current)
152
+ self._expect(version, plan.preconditions["entry_version"], "entry version")
153
+ request = plan.request
154
+ operation = request["operation"]
155
+ if operation == "replace_text":
156
+ return await self._apply_replace_text(plan, journal, version)
157
+
158
+ mutation = self._parts_mutation(operation, request, version)
159
+ response = await self.api.request(
160
+ "PATCH", f"/entry/{plan.entry_id}", json={"partsMutation": mutation}
161
+ )
162
+ self._event(journal, operation, "succeeded", write_event_details(response))
163
+ if operation == "insert":
164
+ discovered = await self._discover_new_part_ids(
165
+ plan.entry_id, plan.preconditions.get("part_ids", [])
166
+ )
167
+ changed_part_ids = discovered["ids"]
168
+ else:
169
+ discovered = {"complete": True, "ids": []}
170
+ changed_part_ids = [
171
+ part.get("id") for part in plan.before.get("parts", []) if part.get("id")
172
+ ]
173
+ return {
174
+ "operation": operation,
175
+ "response": response,
176
+ "changed_part_ids": changed_part_ids,
177
+ "part_id_discovery": discovered,
178
+ }
179
+
180
+ async def _apply_replace_text(
181
+ self, plan: ChangePlan, journal: ChangeJournal, version: str
182
+ ) -> dict[str, Any]:
183
+ """Replace text by inserting the new part, then deleting the original (two requests)."""
184
+ target = plan.request["part_id"]
185
+ insertion = {
186
+ "operationType": "insert",
187
+ "version": version,
188
+ "position": target,
189
+ "parts": [plan.after["part"]],
190
+ }
191
+ first = await self.api.request(
192
+ "PATCH", f"/entry/{plan.entry_id}", json={"partsMutation": insertion}
193
+ )
194
+ self._event(journal, "insert_replacement", "succeeded", write_event_details(first))
195
+ self.repository.save_journal(journal)
196
+ updated = await self.api.request("GET", f"/entry/{plan.entry_id}")
197
+ next_version = entry_version(updated)
198
+ deletion = {
199
+ "operationType": "delete",
200
+ "version": next_version,
201
+ "sourceRange": {"start": target, "end": target},
202
+ }
203
+ second = await self.api.request(
204
+ "PATCH", f"/entry/{plan.entry_id}", json={"partsMutation": deletion}
205
+ )
206
+ self._event(journal, "delete_original", "succeeded", write_event_details(second))
207
+ discovered = await self._discover_new_part_ids(
208
+ plan.entry_id, plan.preconditions.get("part_ids", [])
209
+ )
210
+ return {
211
+ "operations": [first, second],
212
+ "changed_part_ids": [target, *discovered["ids"]],
213
+ "part_id_discovery": discovered,
214
+ }
215
+
216
+ def _parts_mutation(
217
+ self, operation: str, request: dict[str, Any], version: str
218
+ ) -> dict[str, Any]:
219
+ """Build the partsMutation payload for an insert, delete or move."""
220
+ if operation == "insert":
221
+ return {
222
+ "operationType": "insert",
223
+ "version": version,
224
+ "position": request.get("position", "end_of_document"),
225
+ "parts": request["parts"],
226
+ }
227
+ if operation == "delete":
228
+ return {
229
+ "operationType": "delete",
230
+ "version": version,
231
+ "sourceRange": {
232
+ "start": request["from_part_id"],
233
+ "end": request.get("to_part_id", request["from_part_id"]),
234
+ },
235
+ }
236
+ return {
237
+ "operationType": "move",
238
+ "version": version,
239
+ "sourceRange": {
240
+ "start": request["from_part_id"],
241
+ "end": request.get("to_part_id", request["from_part_id"]),
242
+ },
243
+ "destinationPosition": request["position"],
244
+ }
245
+
246
+ def _parts_after_move(
247
+ self,
248
+ parts: list[dict[str, Any]],
249
+ selected: list[dict[str, Any]],
250
+ destination: Any,
251
+ ) -> list[dict[str, Any]]:
252
+ """Document order after a move. A part id inserts the range immediately before that part."""
253
+ selected_ids = {part.get("id") for part in selected}
254
+ remaining = [part for part in parts if part.get("id") not in selected_ids]
255
+ if destination == "beginning_of_document":
256
+ return [*selected, *remaining]
257
+ if destination == "end_of_document":
258
+ return [*remaining, *selected]
259
+ index = next(i for i, part in enumerate(remaining) if part.get("id") == destination)
260
+ return [*remaining[:index], *selected, *remaining[index:]]
261
+
262
+ def _part_range(
263
+ self, parts: list[dict[str, Any]], first: Any, last: Any
264
+ ) -> list[dict[str, Any]]:
265
+ ids = [part.get("id") for part in parts]
266
+ try:
267
+ start, end = ids.index(first), ids.index(last)
268
+ except ValueError as exc:
269
+ raise ValidationError("Document range contains an unknown part ID") from exc
270
+ if end < start:
271
+ raise ValidationError("Document range is reversed")
272
+ return parts[start : end + 1]
273
+
274
+ async def _discover_new_part_ids(
275
+ self, entry_id: str, previous_ids: list[str]
276
+ ) -> dict[str, Any]:
277
+ try:
278
+ current = [
279
+ item.get("id")
280
+ async for item in self.api.paginate(
281
+ f"/entry/{entry_id}/parts/items", params={"pageSize": 100}
282
+ )
283
+ if item.get("id")
284
+ ]
285
+ previous = set(previous_ids)
286
+ return {"complete": True, "ids": [item for item in current if item not in previous]}
287
+ except BenchlingAgentError as exc:
288
+ return {
289
+ "complete": False,
290
+ "ids": [],
291
+ "error": {"code": exc.code, "message": exc.message},
292
+ }
293
+ except Exception as exc:
294
+ return {
295
+ "complete": False,
296
+ "ids": [],
297
+ "error": {"code": "local_discovery_error", "type": type(exc).__name__},
298
+ }