benchlingtk 0.6.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 (46) hide show
  1. benchlingtk/__init__.py +6 -0
  2. benchlingtk/api.py +219 -0
  3. benchlingtk/auth.py +133 -0
  4. benchlingtk/change_spec.py +568 -0
  5. benchlingtk/cli.py +1291 -0
  6. benchlingtk/config.py +65 -0
  7. benchlingtk/credentials.py +264 -0
  8. benchlingtk/environment.py +260 -0
  9. benchlingtk/errors.py +104 -0
  10. benchlingtk/export.py +664 -0
  11. benchlingtk/issues.py +340 -0
  12. benchlingtk/keychain.py +323 -0
  13. benchlingtk/listing.py +506 -0
  14. benchlingtk/mcp_server.py +1221 -0
  15. benchlingtk/models.py +293 -0
  16. benchlingtk/plans/__init__.py +13 -0
  17. benchlingtk/plans/base.py +69 -0
  18. benchlingtk/plans/blobs.py +489 -0
  19. benchlingtk/plans/containers.py +171 -0
  20. benchlingtk/plans/document.py +300 -0
  21. benchlingtk/plans/entry.py +148 -0
  22. benchlingtk/plans/fields.py +314 -0
  23. benchlingtk/plans/planner.py +890 -0
  24. benchlingtk/plans/readback.py +290 -0
  25. benchlingtk/plans/repository.py +105 -0
  26. benchlingtk/plans/result_update.py +907 -0
  27. benchlingtk/plans/results.py +628 -0
  28. benchlingtk/plans/table.py +242 -0
  29. benchlingtk/py.typed +0 -0
  30. benchlingtk/redact.py +73 -0
  31. benchlingtk/runtime.py +82 -0
  32. benchlingtk/services.py +1802 -0
  33. benchlingtk/skill.py +64 -0
  34. benchlingtk/tls.py +10 -0
  35. benchlingtk-0.6.0.data/data/share/benchlingtk/SKILL.md +368 -0
  36. benchlingtk-0.6.0.data/data/share/benchlingtk/contracts/list-parameters.json +34 -0
  37. benchlingtk-0.6.0.data/data/share/benchlingtk/contracts/openapi-manifest.json +68 -0
  38. benchlingtk-0.6.0.data/data/share/benchlingtk/schemas/change-spec.schema.json +287 -0
  39. benchlingtk-0.6.0.data/data/share/benchlingtk/schemas/envelope.schema.json +30 -0
  40. benchlingtk-0.6.0.dist-info/METADATA +709 -0
  41. benchlingtk-0.6.0.dist-info/RECORD +46 -0
  42. benchlingtk-0.6.0.dist-info/WHEEL +5 -0
  43. benchlingtk-0.6.0.dist-info/entry_points.txt +2 -0
  44. benchlingtk-0.6.0.dist-info/licenses/LICENSE +202 -0
  45. benchlingtk-0.6.0.dist-info/licenses/NOTICE +2 -0
  46. benchlingtk-0.6.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,568 @@
1
+ """Typed change specifications for the MCP plan_changes tool.
2
+
3
+ The CLI still passes the JSON object through to the planner. MCP validates the
4
+ same shapes first and returns a validation_error envelope when one does not match.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ from typing import Annotated, Any, Literal, TypeVar, cast
11
+
12
+ from pydantic import (
13
+ BaseModel,
14
+ ConfigDict,
15
+ Field,
16
+ TypeAdapter,
17
+ ValidationError,
18
+ field_validator,
19
+ model_validator,
20
+ )
21
+
22
+ from .errors import ValidationError as InputError
23
+
24
+ _STRICT = ConfigDict(extra="forbid", strict=True)
25
+
26
+
27
+ _T = TypeVar("_T")
28
+
29
+
30
+ def _omit(value: _T | None) -> _T:
31
+ """Reject JSON null for a field the caller may only omit."""
32
+ if value is None:
33
+ raise ValueError("null is not accepted; omit the field")
34
+ return value
35
+
36
+
37
+ class InsertedPart(BaseModel):
38
+ """One document part to insert. Other part fields are kept."""
39
+
40
+ model_config = ConfigDict(extra="allow", strict=True)
41
+
42
+ contentType: str = Field(min_length=1, description="Part content type, such as text.")
43
+
44
+
45
+ class DocumentInsert(BaseModel):
46
+ """Insert one or more document parts."""
47
+
48
+ model_config = _STRICT
49
+
50
+ operation: Literal["insert"] = Field(description="Insert one or more document parts.")
51
+ position: str = Field(
52
+ default="end_of_document",
53
+ min_length=1,
54
+ description=(
55
+ "Where to insert. beginning_of_document, end_of_document, or a part ID. "
56
+ "A part ID inserts immediately before that part. Defaults to end_of_document."
57
+ ),
58
+ )
59
+ parts: list[InsertedPart] = Field(
60
+ min_length=1,
61
+ description="Document parts to insert. Each part needs a contentType.",
62
+ )
63
+
64
+
65
+ class DocumentDelete(BaseModel):
66
+ """Delete one document part or a contiguous range."""
67
+
68
+ model_config = _STRICT
69
+
70
+ operation: Literal["delete"] = Field(description="Delete a range of document parts.")
71
+ from_part_id: str = Field(
72
+ min_length=1, description="First document part ID in the range to delete."
73
+ )
74
+ to_part_id: str | None = Field(
75
+ default=None,
76
+ min_length=1,
77
+ description="Last document part ID in the range. Omit it to delete only from_part_id.",
78
+ )
79
+
80
+ @field_validator("to_part_id")
81
+ @classmethod
82
+ def to_part_present(cls, value: str | None) -> str | None:
83
+ """Allow the field to be omitted, and reject JSON null."""
84
+ return _omit(value)
85
+
86
+
87
+ class DocumentMove(BaseModel):
88
+ """Move one document part or a contiguous range."""
89
+
90
+ model_config = _STRICT
91
+
92
+ operation: Literal["move"] = Field(description="Move a range of document parts.")
93
+ from_part_id: str = Field(
94
+ min_length=1, description="First document part ID in the range to move."
95
+ )
96
+ to_part_id: str | None = Field(
97
+ default=None,
98
+ min_length=1,
99
+ description="Last document part ID in the range. Omit it to move only from_part_id.",
100
+ )
101
+ position: str = Field(
102
+ min_length=1,
103
+ description=(
104
+ "Where to move the range. beginning_of_document, end_of_document, or a part ID. "
105
+ "A part ID moves the range immediately before that part."
106
+ ),
107
+ )
108
+
109
+ @field_validator("to_part_id")
110
+ @classmethod
111
+ def to_part_present(cls, value: str | None) -> str | None:
112
+ """Allow the field to be omitted, and reject JSON null."""
113
+ return _omit(value)
114
+
115
+
116
+ class DocumentReplaceText(BaseModel):
117
+ """Replace the text of one text document part."""
118
+
119
+ model_config = _STRICT
120
+
121
+ operation: Literal["replace_text"] = Field(
122
+ description="Replace the text of one text document part."
123
+ )
124
+ part_id: str = Field(min_length=1, description="Document part ID of the text part to replace.")
125
+ text: str = Field(description="Replacement text.")
126
+ formats: list[Any] | None = Field(
127
+ default=None,
128
+ description="Text formats to store. Omit to keep the part's current formats.",
129
+ )
130
+ links: list[Any] | None = Field(
131
+ default=None,
132
+ description="Links to store. Omit to keep the part's current links.",
133
+ )
134
+ mentions: list[Any] | None = Field(
135
+ default=None,
136
+ description="Mentions to store. Omit to keep the part's current mentions.",
137
+ )
138
+ indentation: int | None = Field(
139
+ default=None,
140
+ ge=0,
141
+ description="Indentation level, zero or greater. Omit to keep the current indentation.",
142
+ )
143
+
144
+ @field_validator("formats", "links", "mentions", "indentation")
145
+ @classmethod
146
+ def optional_present(cls, value: Any) -> Any:
147
+ """Allow these fields to be omitted, and reject JSON null."""
148
+ return _omit(value)
149
+
150
+
151
+ class CellUpdate(BaseModel):
152
+ """One unstructured-table cell write."""
153
+
154
+ model_config = _STRICT
155
+
156
+ row: int = Field(ge=0, description="Zero-based row index.")
157
+ column: int = Field(ge=0, description="Zero-based column index.")
158
+ value: Any = Field(description="New cell input. It is stored as text.")
159
+
160
+
161
+ class TableSetCells(BaseModel):
162
+ """Set the input of selected unstructured-table cells."""
163
+
164
+ model_config = _STRICT
165
+
166
+ operation: Literal["set_cells"] = Field(
167
+ description="Replace the input of selected unstructured-table cells."
168
+ )
169
+ table_part_id: str = Field(
170
+ min_length=1,
171
+ pattern=r"^docpart_",
172
+ description="Document part ID of the unstructured table. It starts with docpart_.",
173
+ )
174
+ updates: list[CellUpdate] = Field(
175
+ min_length=1,
176
+ description="Cells to write. Each item has row, column, and value.",
177
+ )
178
+
179
+
180
+ class TableAppendRows(BaseModel):
181
+ """Append rows to an unstructured table."""
182
+
183
+ model_config = _STRICT
184
+
185
+ operation: Literal["append_rows"] = Field(
186
+ description="Append rows to the end of an unstructured table."
187
+ )
188
+ table_part_id: str = Field(
189
+ min_length=1,
190
+ pattern=r"^docpart_",
191
+ description="Document part ID of the unstructured table. It starts with docpart_.",
192
+ )
193
+ rows: list[Any] = Field(
194
+ min_length=1,
195
+ description=(
196
+ "Rows to append. Each row is a list of cells or an object with a cells list. "
197
+ "The row must match the table width."
198
+ ),
199
+ )
200
+
201
+
202
+ class FieldValueInput(BaseModel):
203
+ """One schema field value. The only property is value."""
204
+
205
+ model_config = _STRICT
206
+
207
+ value: Any = Field(
208
+ description=(
209
+ "New field value, or null to clear an optional field. The type must match "
210
+ "the schema field."
211
+ )
212
+ )
213
+
214
+
215
+ class FieldChange(BaseModel):
216
+ """Update fields on the entry's assigned schema."""
217
+
218
+ model_config = _STRICT
219
+
220
+ schema_fields: dict[str, FieldValueInput] = Field(
221
+ min_length=1,
222
+ description=(
223
+ "Entry schema fields to update. Keys are V3 system names or field-definition "
224
+ "IDs. Each value is an object with a single value property."
225
+ ),
226
+ )
227
+
228
+
229
+ class AssayResultRecord(BaseModel):
230
+ """One new result record for a notebook table upload."""
231
+
232
+ model_config = _STRICT
233
+
234
+ schemaId: str = Field(
235
+ min_length=1,
236
+ description="Result schema ID. It must be the schema assigned to the table.",
237
+ )
238
+ projectId: str | None = Field(
239
+ default=None,
240
+ min_length=1,
241
+ description="Project ID for the new result, or null to leave it unscoped.",
242
+ )
243
+ fields: dict[str, FieldValueInput] = Field(
244
+ description=(
245
+ "Result fields. Keys are V3 system names or field-definition IDs. Each value "
246
+ "is an object with a single value property. On an attachment field, the value "
247
+ 'may be {"file": PATH} (optional blob_type RAW_FILE or VISUALIZATION, optional '
248
+ "mime_type) to upload that local file as a blob at apply and link its blob ID."
249
+ )
250
+ )
251
+
252
+ @model_validator(mode="before")
253
+ @classmethod
254
+ def omit_id(cls, data: Any) -> Any:
255
+ """Result ids are assigned by the server. A caller-supplied id is rejected."""
256
+ if isinstance(data, dict) and "id" in data:
257
+ raise ValueError("Notebook table uploads use server-assigned result IDs; omit id")
258
+ return data
259
+
260
+
261
+ class ResultUpload(BaseModel):
262
+ """Upload new result records to an explicit V2 result table."""
263
+
264
+ model_config = _STRICT
265
+
266
+ table_id: str = Field(
267
+ min_length=1,
268
+ pattern=r"^strtbl_",
269
+ description="V2 result table ID. It starts with strtbl_.",
270
+ )
271
+ assay_results: list[AssayResultRecord] = Field(
272
+ min_length=1,
273
+ description="New result records to upload to that table.",
274
+ )
275
+
276
+
277
+ class ResultUploadBatch(BaseModel):
278
+ """Upload records to one explicit V2 result table as part of a multi-table plan."""
279
+
280
+ model_config = _STRICT
281
+
282
+ table_id: str = Field(
283
+ min_length=1,
284
+ pattern=r"^strtbl_",
285
+ description="V2 result table ID. It starts with strtbl_.",
286
+ )
287
+ assay_results: list[AssayResultRecord] = Field(
288
+ min_length=1,
289
+ description="New result records to upload to this table.",
290
+ )
291
+
292
+
293
+ class MultiTableResultUpload(BaseModel):
294
+ """Upload records to several V2 result tables in one plan."""
295
+
296
+ model_config = _STRICT
297
+
298
+ batches: list[ResultUploadBatch] = Field(
299
+ min_length=1,
300
+ description="Table-specific result batches. Each table can contain at most 500 records.",
301
+ )
302
+
303
+
304
+ class ResultCsvUpdate(BaseModel):
305
+ """Update existing results from a CSV file and an explicit column map."""
306
+
307
+ model_config = _STRICT
308
+
309
+ operation: Literal["update"] = Field(description="Update existing results from a CSV file.")
310
+ csv_path: str = Field(
311
+ min_length=1,
312
+ description=(
313
+ "Path to a CSV file on this machine. An assay-result export writes a file "
314
+ "this planner can read."
315
+ ),
316
+ )
317
+ id_column: str = Field(
318
+ min_length=1,
319
+ description="CSV header that holds the result id. Export writes this column as id.",
320
+ )
321
+ column_map: dict[str, Annotated[str, Field(min_length=1)]] = Field(
322
+ min_length=1,
323
+ description=(
324
+ "CSV header to a field display name, system name, or field-definition id. "
325
+ "The plan resolves each one to a field-definition id. In an attachment column, "
326
+ "a cell file:PATH uploads that local file (relative to the CSV's folder)."
327
+ ),
328
+ )
329
+
330
+ @field_validator("column_map")
331
+ @classmethod
332
+ def column_names(cls, value: dict[str, str]) -> dict[str, str]:
333
+ """Reject a blank CSV header. The planner strips and checks the rest."""
334
+ if any(not key.strip() for key in value):
335
+ raise ValueError("column_map keys must be CSV column names")
336
+ return value
337
+
338
+
339
+ class EntryCreationSpecification(BaseModel):
340
+ """Create a notebook entry from a template in a folder."""
341
+
342
+ model_config = _STRICT
343
+
344
+ entry_template_id: str = Field(min_length=1, description="ID of the entry template to clone.")
345
+ folder_id: str = Field(min_length=1, description="ID of the destination folder.")
346
+ name: str = Field(min_length=1, description="Name of the new notebook entry.")
347
+ schema_fields: dict[str, FieldValueInput] | None = Field(
348
+ default=None,
349
+ min_length=1,
350
+ description=(
351
+ "Optional schema values using system names or field-definition IDs. "
352
+ "The plan resolves keys to field-definition IDs."
353
+ ),
354
+ )
355
+
356
+ @field_validator("schema_fields")
357
+ @classmethod
358
+ def schema_fields_present(cls, value: dict[str, Any] | None) -> dict[str, Any] | None:
359
+ """Allow schema_fields to be omitted, but not explicitly null."""
360
+ return _omit(value)
361
+
362
+
363
+ class ContainerCreate(BaseModel):
364
+ """Create one container after reviewing an immutable preview."""
365
+
366
+ model_config = _STRICT
367
+
368
+ operation: Literal["create"] = Field(description="Preview creation of a container.")
369
+ schema_id: str = Field(min_length=1, description="Container schema ID.")
370
+ name: str | None = Field(default=None, description="Optional container name.")
371
+ barcode: str | None = Field(default=None, description="Optional container barcode.")
372
+ project_id: str | None = Field(default=None, description="Optional project ID.")
373
+ parent_storage_id: str | None = Field(
374
+ default=None, description="Optional parent inventory or well coordinate."
375
+ )
376
+ fields: dict[str, Any] | None = Field(default=None, description="Container field values.")
377
+ restricted_sample_party_ids: list[str] | None = Field(
378
+ default=None, description="Optional restricted sample party IDs."
379
+ )
380
+ restriction_status: str | None = Field(
381
+ default=None, description="Optional RESTRICTED or UNRESTRICTED status."
382
+ )
383
+ sample_owner_ids: list[str] | None = Field(
384
+ default=None, description="Optional sample owner IDs."
385
+ )
386
+
387
+
388
+ class ContainerDestinationContent(BaseModel):
389
+ """One entity and optional concentration in the destination container."""
390
+
391
+ model_config = _STRICT
392
+
393
+ entity_id: str = Field(min_length=1, description="Entity ID in the destination contents.")
394
+ concentration: dict[str, Any] | None = Field(
395
+ default=None, description="Optional concentration measurement."
396
+ )
397
+
398
+
399
+ class ContainerTransfer(BaseModel):
400
+ """Transfer contents from one container into another after preview."""
401
+
402
+ model_config = _STRICT
403
+
404
+ operation: Literal["transfer"] = Field(description="Preview a container-to-container transfer.")
405
+ source_container_id: str = Field(min_length=1, description="Source container ID.")
406
+ destination_container_id: str = Field(min_length=1, description="Destination container ID.")
407
+ transfer_quantity: dict[str, Any] | None = Field(
408
+ default=None, description="Optional quantity to transfer from the source."
409
+ )
410
+ destination_contents: list[ContainerDestinationContent] = Field(
411
+ min_length=1, description="Destination contents after the transfer."
412
+ )
413
+ destination_quantity: dict[str, Any] | None = Field(
414
+ default=None, description="Optional desired destination quantity."
415
+ )
416
+ restricted_sample_party_ids: list[str] | None = Field(
417
+ default=None, description="Optional restricted sample party IDs."
418
+ )
419
+ restriction_status: str | None = Field(
420
+ default=None, description="Optional RESTRICTED or UNRESTRICTED status."
421
+ )
422
+ sample_owner_ids: list[str] | None = Field(
423
+ default=None, description="Optional sample owner IDs."
424
+ )
425
+
426
+
427
+ ChangeSpecification = (
428
+ DocumentInsert
429
+ | DocumentDelete
430
+ | DocumentMove
431
+ | DocumentReplaceText
432
+ | TableSetCells
433
+ | TableAppendRows
434
+ | FieldChange
435
+ | ResultUpload
436
+ | MultiTableResultUpload
437
+ | ResultCsvUpdate
438
+ | EntryCreationSpecification
439
+ | ContainerCreate
440
+ | ContainerTransfer
441
+ )
442
+
443
+ _BY_OPERATION: dict[str, type[BaseModel]] = {
444
+ "insert": DocumentInsert,
445
+ "delete": DocumentDelete,
446
+ "move": DocumentMove,
447
+ "replace_text": DocumentReplaceText,
448
+ "set_cells": TableSetCells,
449
+ "append_rows": TableAppendRows,
450
+ "update": ResultCsvUpdate,
451
+ "create": ContainerCreate,
452
+ "transfer": ContainerTransfer,
453
+ }
454
+
455
+ _SUPPORTED = [
456
+ "document: insert, delete, move, replace_text",
457
+ "table: set_cells, append_rows",
458
+ "fields: schema_fields",
459
+ "results upload: table_id and assay_results, or batches with table_id and assay_results",
460
+ "results update: operation update, csv_path, id_column, column_map",
461
+ "entry: entry_template_id, folder_id, name, optional schema_fields",
462
+ "containers create: operation create and schema_id",
463
+ "containers transfer: operation transfer, source_container_id and destination_container_id",
464
+ ]
465
+
466
+
467
+ def _inline_json_schema(schema: dict[str, Any]) -> dict[str, Any]:
468
+ """Copy a schema so every local $ref is replaced by its definition.
469
+
470
+ MCP publishes a parameter schema on its own. A $ref to a definition that lives
471
+ only inside this object does not resolve there.
472
+ """
473
+ definitions = schema.get("$defs", {})
474
+
475
+ def resolve(node: Any) -> Any:
476
+ if isinstance(node, dict):
477
+ ref = node.get("$ref")
478
+ if isinstance(ref, str) and ref.startswith("#/$defs/"):
479
+ target = cast(
480
+ dict[str, Any],
481
+ resolve(copy.deepcopy(definitions[ref.removeprefix("#/$defs/")])),
482
+ )
483
+ extras = {key: resolve(value) for key, value in node.items() if key != "$ref"}
484
+ return {**target, **extras}
485
+ return {key: resolve(value) for key, value in node.items() if key != "$defs"}
486
+ if isinstance(node, list):
487
+ return [resolve(item) for item in node]
488
+ return node
489
+
490
+ return cast(dict[str, Any], resolve(schema))
491
+
492
+
493
+ CHANGE_SPECIFICATION_SCHEMA: dict[str, Any] = _inline_json_schema(
494
+ TypeAdapter(ChangeSpecification).json_schema()
495
+ )
496
+
497
+
498
+ def _model_for(value: dict[str, Any]) -> type[BaseModel]:
499
+ """Pick the one shape this object is claiming to be."""
500
+ if "entry_template_id" in value or "folder_id" in value:
501
+ return EntryCreationSpecification
502
+ operation = value.get("operation")
503
+ if isinstance(operation, str) and operation in _BY_OPERATION:
504
+ return _BY_OPERATION[operation]
505
+ if any(key in value for key in ("csv_path", "id_column", "column_map")):
506
+ return ResultCsvUpdate
507
+ has_fields = "schema_fields" in value
508
+ has_results = "table_id" in value or "assay_results" in value
509
+ has_batches = "batches" in value
510
+ if has_fields and (has_results or has_batches):
511
+ raise InputError(
512
+ "Change specification mixes field updates and result records",
513
+ details={"supported": _SUPPORTED},
514
+ )
515
+ if has_batches:
516
+ return MultiTableResultUpload
517
+ if has_fields:
518
+ return FieldChange
519
+ if has_results:
520
+ return ResultUpload
521
+ raise InputError(
522
+ "Change specification does not match a supported shape",
523
+ details={"supported": _SUPPORTED},
524
+ )
525
+
526
+
527
+ def _error_details(exc: ValidationError) -> list[dict[str, Any]]:
528
+ """JSON-safe locations and messages. The rejected values are not included."""
529
+ details = []
530
+ for err in exc.errors():
531
+ details.append(
532
+ {
533
+ "path": ".".join(str(part) for part in err["loc"]),
534
+ "message": str(err["msg"]),
535
+ "type": str(err["type"]),
536
+ }
537
+ )
538
+ return details
539
+
540
+
541
+ def _error_message(exc: ValidationError) -> str:
542
+ """One sentence naming each invalid field."""
543
+ pieces = []
544
+ for err in exc.errors():
545
+ path = ".".join(str(part) for part in err["loc"]) or "specification"
546
+ pieces.append(f"{path}: {err['msg']}")
547
+ return "Change specification is invalid: " + "; ".join(pieces)
548
+
549
+
550
+ def parse_change_specification(value: Any) -> dict[str, Any]:
551
+ """Validate a plan_changes specification and return the planner's object.
552
+
553
+ Omitted optional fields stay omitted. JSON null is kept only for projectId
554
+ and for a field value, where null is meaningful.
555
+
556
+ Raises InputError when the value is not one of the supported shapes.
557
+ """
558
+ if not isinstance(value, dict):
559
+ raise InputError(
560
+ "Change specification must be an object",
561
+ details={"received": type(value).__name__},
562
+ )
563
+ model = _model_for(value)
564
+ try:
565
+ parsed = model.model_validate(value)
566
+ except ValidationError as exc:
567
+ raise InputError(_error_message(exc), details={"errors": _error_details(exc)}) from exc
568
+ return parsed.model_dump(mode="json", exclude_unset=True)