跳转至

English fallback

This translation is missing; the canonical English reference follows.

fuzzy1337.adapters.contracts

fuzzy1337.adapters.contracts

Provider-neutral contracts for governed security-tool adapters.

ImpactLevel

Bases: StrEnum

Declared maximum impact for a provider, independent from authorization.

源代码位于: fuzzy1337/adapters/contracts.py
24
25
26
27
28
29
30
31
class ImpactLevel(StrEnum):
    """Declared maximum impact for a provider, independent from authorization."""

    PASSIVE = "PASSIVE"
    SAFE = "SAFE"
    STANDARD = "STANDARD"
    ACTIVE = "ACTIVE"
    INTRUSIVE = "INTRUSIVE"

AdapterHealthState

Bases: StrEnum

Health state reported by an adapter without implying execution authority.

源代码位于: fuzzy1337/adapters/contracts.py
34
35
36
37
38
39
class AdapterHealthState(StrEnum):
    """Health state reported by an adapter without implying execution authority."""

    AVAILABLE = "available"
    DEGRADED = "degraded"
    UNAVAILABLE = "unavailable"

ExecutionState

Bases: StrEnum

Terminal executor state preserved for adapter normalization.

源代码位于: fuzzy1337/adapters/contracts.py
42
43
44
45
46
47
48
class ExecutionState(StrEnum):
    """Terminal executor state preserved for adapter normalization."""

    SUCCEEDED = "succeeded"
    FAILED = "failed"
    TIMED_OUT = "timed_out"
    CANCELLED = "cancelled"

AdapterDescriptor dataclass

Static provider declaration consumed by capability and policy layers.

源代码位于: fuzzy1337/adapters/contracts.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@dataclass(frozen=True, slots=True)
class AdapterDescriptor:
    """Static provider declaration consumed by capability and policy layers."""

    adapter_id: str
    display_name: str
    version: str
    capabilities: tuple[str, ...]
    maximum_impact: ImpactLevel
    required_privileges: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        """Validate provider declarations before an adapter can be registered."""

        RequireIdentifier(self.adapter_id, "adapter_id")
        RequireText(self.display_name, "display_name")
        RequireText(self.version, "version")
        if not isinstance(self.maximum_impact, ImpactLevel):
            raise ValueError("maximum_impact must be an ImpactLevel")
        if not self.capabilities:
            raise ValueError("capabilities must not be empty")
        object.__setattr__(
            self,
            "capabilities",
            UniqueIdentifiers(self.capabilities, "capabilities"),
        )
        object.__setattr__(
            self,
            "required_privileges",
            UniqueIdentifiers(self.required_privileges, "required_privileges"),
        )

    def Supports(self, capability: str) -> bool:
        """Return whether this provider declares a capability without authorizing it.

        Args:
            capability: Capability identifier to look up.

        Returns:
            True if declared, without implying authorization or runtime health.
        """

        return capability in self.capabilities

__post_init__() -> None

Validate provider declarations before an adapter can be registered.

源代码位于: fuzzy1337/adapters/contracts.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def __post_init__(self) -> None:
    """Validate provider declarations before an adapter can be registered."""

    RequireIdentifier(self.adapter_id, "adapter_id")
    RequireText(self.display_name, "display_name")
    RequireText(self.version, "version")
    if not isinstance(self.maximum_impact, ImpactLevel):
        raise ValueError("maximum_impact must be an ImpactLevel")
    if not self.capabilities:
        raise ValueError("capabilities must not be empty")
    object.__setattr__(
        self,
        "capabilities",
        UniqueIdentifiers(self.capabilities, "capabilities"),
    )
    object.__setattr__(
        self,
        "required_privileges",
        UniqueIdentifiers(self.required_privileges, "required_privileges"),
    )

Supports(capability: str) -> bool

Return whether this provider declares a capability without authorizing it.

参数:

名称 类型 描述 默认
capability str

Capability identifier to look up.

必需

返回:

类型 描述
bool

True if declared, without implying authorization or runtime health.

源代码位于: fuzzy1337/adapters/contracts.py
277
278
279
280
281
282
283
284
285
286
287
def Supports(self, capability: str) -> bool:
    """Return whether this provider declares a capability without authorizing it.

    Args:
        capability: Capability identifier to look up.

    Returns:
        True if declared, without implying authorization or runtime health.
    """

    return capability in self.capabilities

AdapterHealth dataclass

Observed adapter health and provider version at a bounded check boundary.

源代码位于: fuzzy1337/adapters/contracts.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@dataclass(frozen=True, slots=True)
class AdapterHealth:
    """Observed adapter health and provider version at a bounded check boundary."""

    adapter_id: str
    state: AdapterHealthState
    provider_version: str | None = None
    detail: str | None = None

    def __post_init__(self) -> None:
        """Reject ambiguous health values before callers act on them."""

        RequireIdentifier(self.adapter_id, "adapter_id")
        if not isinstance(self.state, AdapterHealthState):
            raise ValueError("state must be an AdapterHealthState")
        if self.provider_version is not None:
            RequireText(self.provider_version, "provider_version")
        if self.detail is not None:
            RequireText(self.detail, "detail")

__post_init__() -> None

Reject ambiguous health values before callers act on them.

源代码位于: fuzzy1337/adapters/contracts.py
299
300
301
302
303
304
305
306
307
308
def __post_init__(self) -> None:
    """Reject ambiguous health values before callers act on them."""

    RequireIdentifier(self.adapter_id, "adapter_id")
    if not isinstance(self.state, AdapterHealthState):
        raise ValueError("state must be an AdapterHealthState")
    if self.provider_version is not None:
        RequireText(self.provider_version, "provider_version")
    if self.detail is not None:
        RequireText(self.detail, "detail")

AdapterRequest dataclass

Approved capability request passed to an adapter for invocation preparation.

源代码位于: fuzzy1337/adapters/contracts.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
@dataclass(frozen=True, slots=True)
class AdapterRequest:
    """Approved capability request passed to an adapter for invocation preparation."""

    capability: str
    target_reference: str
    impact: ImpactLevel
    parameters: Mapping[str, object] = field(default_factory=dict)
    credential_references: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        """Validate request metadata while keeping credentials as opaque references."""

        RequireIdentifier(self.capability, "capability")
        RequireText(self.target_reference, "target_reference")
        if not isinstance(self.impact, ImpactLevel):
            raise ValueError("impact must be an ImpactLevel")
        object.__setattr__(self, "parameters", FreezeMapping(self.parameters))
        object.__setattr__(
            self,
            "credential_references",
            UniqueReferences(self.credential_references, "credential_references"),
        )

__post_init__() -> None

Validate request metadata while keeping credentials as opaque references.

源代码位于: fuzzy1337/adapters/contracts.py
321
322
323
324
325
326
327
328
329
330
331
332
333
def __post_init__(self) -> None:
    """Validate request metadata while keeping credentials as opaque references."""

    RequireIdentifier(self.capability, "capability")
    RequireText(self.target_reference, "target_reference")
    if not isinstance(self.impact, ImpactLevel):
        raise ValueError("impact must be an ImpactLevel")
    object.__setattr__(self, "parameters", FreezeMapping(self.parameters))
    object.__setattr__(
        self,
        "credential_references",
        UniqueReferences(self.credential_references, "credential_references"),
    )

AdapterInvocation dataclass

Prepared non-secret command metadata owned by a future executor boundary.

源代码位于: fuzzy1337/adapters/contracts.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
@dataclass(frozen=True, slots=True)
class AdapterInvocation:
    """Prepared non-secret command metadata owned by a future executor boundary."""

    adapter_id: str
    request: AdapterRequest
    argv: tuple[str, ...]
    timeout_seconds: int
    provider_version: str | None = None

    def __post_init__(self) -> None:
        """Require a bounded explicit argv without invoking a process."""

        RequireIdentifier(self.adapter_id, "adapter_id")
        arguments = tuple(self.argv)
        if not arguments:
            raise ValueError("argv must contain an executable")
        for argument in arguments:
            RequireText(argument, "argv entry")
        if (
            isinstance(self.timeout_seconds, bool)
            or not isinstance(self.timeout_seconds, int)
            or self.timeout_seconds < 1
        ):
            raise ValueError("timeout_seconds must be a positive integer")
        if self.provider_version is not None:
            RequireText(self.provider_version, "provider_version")
        object.__setattr__(self, "argv", arguments)

__post_init__() -> None

Require a bounded explicit argv without invoking a process.

源代码位于: fuzzy1337/adapters/contracts.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def __post_init__(self) -> None:
    """Require a bounded explicit argv without invoking a process."""

    RequireIdentifier(self.adapter_id, "adapter_id")
    arguments = tuple(self.argv)
    if not arguments:
        raise ValueError("argv must contain an executable")
    for argument in arguments:
        RequireText(argument, "argv entry")
    if (
        isinstance(self.timeout_seconds, bool)
        or not isinstance(self.timeout_seconds, int)
        or self.timeout_seconds < 1
    ):
        raise ValueError("timeout_seconds must be a positive integer")
    if self.provider_version is not None:
        RequireText(self.provider_version, "provider_version")
    object.__setattr__(self, "argv", arguments)

EvidenceReference dataclass

Reference immutable raw evidence without embedding raw provider payloads.

源代码位于: fuzzy1337/adapters/contracts.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
@dataclass(frozen=True, slots=True)
class EvidenceReference:
    """Reference immutable raw evidence without embedding raw provider payloads."""

    role: str
    locator: str
    sha256: str
    media_type: str
    size_bytes: int

    def __post_init__(self) -> None:
        """Accept only relative, hash-addressed evidence references."""

        RequireIdentifier(self.role, "role")
        RequireText(self.locator, "locator")
        locator = PurePosixPath(self.locator)
        if (
            not self.locator
            or "\\" in self.locator
            or locator.is_absolute()
            or ".." in locator.parts
        ):
            raise ValueError("locator must be a relative evidence path")
        if not _SHA256_PATTERN.fullmatch(self.sha256):
            raise ValueError("sha256 must be a lowercase SHA-256 digest")
        RequireText(self.media_type, "media_type")
        if (
            isinstance(self.size_bytes, bool)
            or not isinstance(self.size_bytes, int)
            or self.size_bytes < 0
        ):
            raise ValueError("size_bytes must be a non-negative integer")

__post_init__() -> None

Accept only relative, hash-addressed evidence references.

源代码位于: fuzzy1337/adapters/contracts.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def __post_init__(self) -> None:
    """Accept only relative, hash-addressed evidence references."""

    RequireIdentifier(self.role, "role")
    RequireText(self.locator, "locator")
    locator = PurePosixPath(self.locator)
    if (
        not self.locator
        or "\\" in self.locator
        or locator.is_absolute()
        or ".." in locator.parts
    ):
        raise ValueError("locator must be a relative evidence path")
    if not _SHA256_PATTERN.fullmatch(self.sha256):
        raise ValueError("sha256 must be a lowercase SHA-256 digest")
    RequireText(self.media_type, "media_type")
    if (
        isinstance(self.size_bytes, bool)
        or not isinstance(self.size_bytes, int)
        or self.size_bytes < 0
    ):
        raise ValueError("size_bytes must be a non-negative integer")

AdapterExecution dataclass

Terminal executor outcome preserved before adapter parsing and normalization.

源代码位于: fuzzy1337/adapters/contracts.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
@dataclass(frozen=True, slots=True)
class AdapterExecution:
    """Terminal executor outcome preserved before adapter parsing and normalization."""

    state: ExecutionState
    exit_code: int | None
    duration_seconds: float

    def __post_init__(self) -> None:
        """Prevent failed, timed-out, or cancelled execution from becoming success."""

        if not isinstance(self.state, ExecutionState):
            raise ValueError("state must be an ExecutionState")
        if self.exit_code is not None and (
            isinstance(self.exit_code, bool) or not isinstance(self.exit_code, int)
        ):
            raise ValueError("exit_code must be an integer or None")
        if not math.isfinite(self.duration_seconds) or self.duration_seconds < 0:
            raise ValueError("duration_seconds must be a non-negative finite number")
        if self.state is ExecutionState.SUCCEEDED and self.exit_code != 0:
            raise ValueError("successful execution requires exit_code 0")
        if self.state is ExecutionState.FAILED and self.exit_code in (None, 0):
            raise ValueError("failed execution requires a non-zero exit_code")
        if self.state is ExecutionState.TIMED_OUT and self.exit_code == 0:
            raise ValueError("timed-out execution cannot report exit_code 0")
        if self.state is ExecutionState.CANCELLED and self.exit_code == 0:
            raise ValueError("cancelled execution cannot report exit_code 0")

__post_init__() -> None

Prevent failed, timed-out, or cancelled execution from becoming success.

源代码位于: fuzzy1337/adapters/contracts.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def __post_init__(self) -> None:
    """Prevent failed, timed-out, or cancelled execution from becoming success."""

    if not isinstance(self.state, ExecutionState):
        raise ValueError("state must be an ExecutionState")
    if self.exit_code is not None and (
        isinstance(self.exit_code, bool) or not isinstance(self.exit_code, int)
    ):
        raise ValueError("exit_code must be an integer or None")
    if not math.isfinite(self.duration_seconds) or self.duration_seconds < 0:
        raise ValueError("duration_seconds must be a non-negative finite number")
    if self.state is ExecutionState.SUCCEEDED and self.exit_code != 0:
        raise ValueError("successful execution requires exit_code 0")
    if self.state is ExecutionState.FAILED and self.exit_code in (None, 0):
        raise ValueError("failed execution requires a non-zero exit_code")
    if self.state is ExecutionState.TIMED_OUT and self.exit_code == 0:
        raise ValueError("timed-out execution cannot report exit_code 0")
    if self.state is ExecutionState.CANCELLED and self.exit_code == 0:
        raise ValueError("cancelled execution cannot report exit_code 0")

AdapterReport dataclass

Executor-owned facts and raw-evidence references supplied to an adapter parser.

源代码位于: fuzzy1337/adapters/contracts.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
@dataclass(frozen=True, slots=True)
class AdapterReport:
    """Executor-owned facts and raw-evidence references supplied to an adapter parser."""

    invocation: AdapterInvocation
    execution: AdapterExecution
    evidence: tuple[EvidenceReference, ...]

    def __post_init__(self) -> None:
        """Freeze evidence ordering and reject ambiguous duplicate references."""

        evidence = tuple(self.evidence)
        locator_roles = tuple((item.locator, item.role) for item in evidence)
        if len(set(locator_roles)) != len(locator_roles):
            raise ValueError("evidence references must be unique by locator and role")
        object.__setattr__(self, "evidence", evidence)

__post_init__() -> None

Freeze evidence ordering and reject ambiguous duplicate references.

源代码位于: fuzzy1337/adapters/contracts.py
437
438
439
440
441
442
443
444
def __post_init__(self) -> None:
    """Freeze evidence ordering and reject ambiguous duplicate references."""

    evidence = tuple(self.evidence)
    locator_roles = tuple((item.locator, item.role) for item in evidence)
    if len(set(locator_roles)) != len(locator_roles):
        raise ValueError("evidence references must be unique by locator and role")
    object.__setattr__(self, "evidence", evidence)

NormalizedObservation dataclass

Provider-neutral observation envelope for a later Security Object Model update.

源代码位于: fuzzy1337/adapters/contracts.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
@dataclass(frozen=True, slots=True)
class NormalizedObservation:
    """Provider-neutral observation envelope for a later Security Object Model update."""

    kind: str
    subject_reference: str
    attributes: Mapping[str, object] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Freeze generic observation fields without assigning core schema semantics."""

        RequireIdentifier(self.kind, "kind")
        RequireText(self.subject_reference, "subject_reference")
        object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

__post_init__() -> None

Freeze generic observation fields without assigning core schema semantics.

源代码位于: fuzzy1337/adapters/contracts.py
455
456
457
458
459
460
def __post_init__(self) -> None:
    """Freeze generic observation fields without assigning core schema semantics."""

    RequireIdentifier(self.kind, "kind")
    RequireText(self.subject_reference, "subject_reference")
    object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

NormalizedFinding dataclass

Provider-neutral finding envelope backed by the enclosing raw evidence.

源代码位于: fuzzy1337/adapters/contracts.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
@dataclass(frozen=True, slots=True)
class NormalizedFinding:
    """Provider-neutral finding envelope backed by the enclosing raw evidence."""

    kind: str
    subject_reference: str
    summary: str
    attributes: Mapping[str, object] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Freeze generic finding attributes while retaining a human-readable summary."""

        RequireIdentifier(self.kind, "kind")
        RequireText(self.subject_reference, "subject_reference")
        RequireText(self.summary, "summary")
        object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

__post_init__() -> None

Freeze generic finding attributes while retaining a human-readable summary.

源代码位于: fuzzy1337/adapters/contracts.py
472
473
474
475
476
477
478
def __post_init__(self) -> None:
    """Freeze generic finding attributes while retaining a human-readable summary."""

    RequireIdentifier(self.kind, "kind")
    RequireText(self.subject_reference, "subject_reference")
    RequireText(self.summary, "summary")
    object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

ObjectEnrichment dataclass

Generic object attribute enrichment without introducing provider-owned types.

源代码位于: fuzzy1337/adapters/contracts.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
@dataclass(frozen=True, slots=True)
class ObjectEnrichment:
    """Generic object attribute enrichment without introducing provider-owned types."""

    object_kind: str
    object_reference: str
    attributes: Mapping[str, object] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Keep object enrichment references typed and immutable."""

        RequireIdentifier(self.object_kind, "object_kind")
        RequireText(self.object_reference, "object_reference")
        object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

__post_init__() -> None

Keep object enrichment references typed and immutable.

源代码位于: fuzzy1337/adapters/contracts.py
489
490
491
492
493
494
def __post_init__(self) -> None:
    """Keep object enrichment references typed and immutable."""

    RequireIdentifier(self.object_kind, "object_kind")
    RequireText(self.object_reference, "object_reference")
    object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

RelationEnrichment dataclass

Generic relation attribute enrichment without mutating shared state directly.

源代码位于: fuzzy1337/adapters/contracts.py
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
@dataclass(frozen=True, slots=True)
class RelationEnrichment:
    """Generic relation attribute enrichment without mutating shared state directly."""

    relation_kind: str
    source_reference: str
    target_reference: str
    attributes: Mapping[str, object] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Keep relation references typed and immutable."""

        RequireIdentifier(self.relation_kind, "relation_kind")
        RequireText(self.source_reference, "source_reference")
        RequireText(self.target_reference, "target_reference")
        object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

__post_init__() -> None

Keep relation references typed and immutable.

源代码位于: fuzzy1337/adapters/contracts.py
506
507
508
509
510
511
512
def __post_init__(self) -> None:
    """Keep relation references typed and immutable."""

    RequireIdentifier(self.relation_kind, "relation_kind")
    RequireText(self.source_reference, "source_reference")
    RequireText(self.target_reference, "target_reference")
    object.__setattr__(self, "attributes", FreezeMapping(self.attributes))

AdapterResult dataclass

Normalized adapter output that remains separate from persistence and policy.

源代码位于: fuzzy1337/adapters/contracts.py
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
@dataclass(frozen=True, slots=True)
class AdapterResult:
    """Normalized adapter output that remains separate from persistence and policy."""

    report: AdapterReport
    observations: tuple[NormalizedObservation, ...] = ()
    findings: tuple[NormalizedFinding, ...] = ()
    object_enrichments: tuple[ObjectEnrichment, ...] = ()
    relation_enrichments: tuple[RelationEnrichment, ...] = ()

    def __post_init__(self) -> None:
        """Freeze result collections so downstream consumers receive stable evidence."""

        object.__setattr__(self, "observations", tuple(self.observations))
        object.__setattr__(self, "findings", tuple(self.findings))
        object.__setattr__(self, "object_enrichments", tuple(self.object_enrichments))
        object.__setattr__(self, "relation_enrichments", tuple(self.relation_enrichments))

__post_init__() -> None

Freeze result collections so downstream consumers receive stable evidence.

源代码位于: fuzzy1337/adapters/contracts.py
525
526
527
528
529
530
531
def __post_init__(self) -> None:
    """Freeze result collections so downstream consumers receive stable evidence."""

    object.__setattr__(self, "observations", tuple(self.observations))
    object.__setattr__(self, "findings", tuple(self.findings))
    object.__setattr__(self, "object_enrichments", tuple(self.object_enrichments))
    object.__setattr__(self, "relation_enrichments", tuple(self.relation_enrichments))

ToolAdapter

Bases: Protocol

Provider contract that cannot execute outside the future governed executor.

源代码位于: fuzzy1337/adapters/contracts.py
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
@runtime_checkable
class ToolAdapter(Protocol):
    """Provider contract that cannot execute outside the future governed executor."""

    @property
    def Descriptor(self) -> AdapterDescriptor:
        """Return the immutable provider declaration.

        Returns:
            Immutable provider declaration and capability metadata.
        """

        ...

    def CheckHealth(self) -> AdapterHealth:
        """Return a bounded health result without claiming authorization.

        Implementations must bound the health probe and preserve unavailable/degraded states.

        Returns:
            Provider availability and version evidence, without permission to execute.
        """

        ...

    def PrepareInvocation(self, request: AdapterRequest) -> AdapterInvocation:
        """Prepare a bounded invocation from an already-approved request.

        Preparation must not start a process or resolve credential values into persisted
        metadata.

        Args:
            request: Capability request approved by upstream scope/policy.

        Returns:
            Explicit bounded argv and metadata for the governed executor.
        """

        ...

    def NormalizeReport(self, report: AdapterReport) -> AdapterResult:
        """Normalize an executor report without mutating shared security state.

        Normalization preserves failed execution and cannot mutate shared security state.

        Args:
            report: Executor-owned terminal facts and immutable raw-evidence references.

        Returns:
            Provider-neutral observations, findings and enrichment requests.
        """

        ...

Descriptor: AdapterDescriptor property

Return the immutable provider declaration.

返回:

类型 描述
AdapterDescriptor

Immutable provider declaration and capability metadata.

CheckHealth() -> AdapterHealth

Return a bounded health result without claiming authorization.

Implementations must bound the health probe and preserve unavailable/degraded states.

返回:

类型 描述
AdapterHealth

Provider availability and version evidence, without permission to execute.

源代码位于: fuzzy1337/adapters/contracts.py
548
549
550
551
552
553
554
555
556
557
def CheckHealth(self) -> AdapterHealth:
    """Return a bounded health result without claiming authorization.

    Implementations must bound the health probe and preserve unavailable/degraded states.

    Returns:
        Provider availability and version evidence, without permission to execute.
    """

    ...

PrepareInvocation(request: AdapterRequest) -> AdapterInvocation

Prepare a bounded invocation from an already-approved request.

Preparation must not start a process or resolve credential values into persisted metadata.

参数:

名称 类型 描述 默认
request AdapterRequest

Capability request approved by upstream scope/policy.

必需

返回:

类型 描述
AdapterInvocation

Explicit bounded argv and metadata for the governed executor.

源代码位于: fuzzy1337/adapters/contracts.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
def PrepareInvocation(self, request: AdapterRequest) -> AdapterInvocation:
    """Prepare a bounded invocation from an already-approved request.

    Preparation must not start a process or resolve credential values into persisted
    metadata.

    Args:
        request: Capability request approved by upstream scope/policy.

    Returns:
        Explicit bounded argv and metadata for the governed executor.
    """

    ...

NormalizeReport(report: AdapterReport) -> AdapterResult

Normalize an executor report without mutating shared security state.

Normalization preserves failed execution and cannot mutate shared security state.

参数:

名称 类型 描述 默认
report AdapterReport

Executor-owned terminal facts and immutable raw-evidence references.

必需

返回:

类型 描述
AdapterResult

Provider-neutral observations, findings and enrichment requests.

源代码位于: fuzzy1337/adapters/contracts.py
574
575
576
577
578
579
580
581
582
583
584
585
586
def NormalizeReport(self, report: AdapterReport) -> AdapterResult:
    """Normalize an executor report without mutating shared security state.

    Normalization preserves failed execution and cannot mutate shared security state.

    Args:
        report: Executor-owned terminal facts and immutable raw-evidence references.

    Returns:
        Provider-neutral observations, findings and enrichment requests.
    """

    ...

RequireIdentifier(value: str, field_name: str) -> None

Reject identifiers that cannot be used as stable machine-readable keys.

参数:

名称 类型 描述 默认
value str

Candidate lowercase machine identifier

必需
field_name str

Field label in validation errors.

必需

引发:

类型 描述
ValueError

The value fails the identifier grammar.

源代码位于: fuzzy1337/adapters/contracts.py
51
52
53
54
55
56
57
58
59
60
61
62
63
def RequireIdentifier(value: str, field_name: str) -> None:
    """Reject identifiers that cannot be used as stable machine-readable keys.

    Args:
        value: Candidate lowercase machine identifier
        field_name: Field label in validation errors.

    Raises:
        ValueError: The value fails the identifier grammar.
    """

    if not isinstance(value, str) or not _IDENTIFIER_PATTERN.fullmatch(value):
        raise ValueError(f"{field_name} must be a lowercase machine-readable identifier")

RequireText(value: str, field_name: str) -> None

Reject empty or multi-line user-visible contract text.

参数:

名称 类型 描述 默认
value str

Nonempty single-line text without NUL

必需
field_name str

Field label in validation errors.

必需

引发:

类型 描述
ValueError

The value is not valid nonempty single-line text.

源代码位于: fuzzy1337/adapters/contracts.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def RequireText(value: str, field_name: str) -> None:
    """Reject empty or multi-line user-visible contract text.

    Args:
        value: Nonempty single-line text without NUL
        field_name: Field label in validation errors.

    Raises:
        ValueError: The value is not valid nonempty single-line text.
    """

    if not isinstance(value, str) or not value or "\x00" in value or "\n" in value or "\r" in value:
        raise ValueError(f"{field_name} must be non-empty single-line text")

FreezeJson(value: object) -> object

Return a recursively immutable JSON-like value or fail closed.

No objects are persisted and no provider code is invoked.

参数:

名称 类型 描述 默认
value object

JSON scalars, string-keyed mappings or sequences to freeze.

必需

返回:

类型 描述
object

Scalars unchanged, sorted read-only mappings, or recursively frozen tuples.

引发:

类型 描述
ValueError

A key, number or nested value is outside the JSON contract.

源代码位于: fuzzy1337/adapters/contracts.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def FreezeJson(value: object) -> object:
    """Return a recursively immutable JSON-like value or fail closed.

    No objects are persisted and no provider code is invoked.

    Args:
        value: JSON scalars, string-keyed mappings or sequences to freeze.

    Returns:
        Scalars unchanged, sorted read-only mappings, or recursively frozen tuples.

    Raises:
        ValueError: A key, number or nested value is outside the JSON contract.
    """

    if value is None or isinstance(value, (bool, int, str)):
        return value

    if isinstance(value, float):
        if not math.isfinite(value):
            raise ValueError("contract metadata must not contain non-finite numbers")
        return value

    if isinstance(value, Mapping):
        frozen: dict[str, object] = {}
        for key, nested_value in value.items():
            if not isinstance(key, str) or not key:
                raise ValueError("contract metadata keys must be non-empty strings")
            frozen[key] = FreezeJson(nested_value)

        return MappingProxyType(dict(sorted(frozen.items())))

    if isinstance(value, (list, tuple)):
        return tuple(FreezeJson(item) for item in value)

    raise ValueError("contract metadata must contain JSON-compatible values")

FreezeMapping(value: Mapping[str, object]) -> Mapping[str, object]

Freeze a JSON object while retaining a read-only mapping contract.

参数:

名称 类型 描述 默认
value Mapping[str, object]

JSON object to copy into immutable nested structures.

必需

返回:

类型 描述
Mapping[str, object]

Read-only mapping with deterministic key order.

引发:

类型 描述
ValueError

The value is not a valid JSON object.

源代码位于: fuzzy1337/adapters/contracts.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def FreezeMapping(value: Mapping[str, object]) -> Mapping[str, object]:
    """Freeze a JSON object while retaining a read-only mapping contract.

    Args:
        value: JSON object to copy into immutable nested structures.

    Returns:
        Read-only mapping with deterministic key order.

    Raises:
        ValueError: The value is not a valid JSON object.
    """

    frozen = FreezeJson(value)
    if not isinstance(frozen, Mapping):
        raise ValueError("contract metadata must be a JSON object")
    return frozen

UniqueIdentifiers(values: tuple[str, ...], field_name: str) -> tuple[str, ...]

Validate a stable identifier collection without changing declaration order.

参数:

名称 类型 描述 默认
values tuple[str, ...]

Identifiers to validate in original order

必需
field_name str

Field label in validation errors.

必需

返回:

类型 描述
tuple[str, ...]

Validated identifiers as an ordered tuple.

引发:

类型 描述
ValueError

An identifier is invalid or duplicated.

源代码位于: fuzzy1337/adapters/contracts.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def UniqueIdentifiers(values: tuple[str, ...], field_name: str) -> tuple[str, ...]:
    """Validate a stable identifier collection without changing declaration order.

    Args:
        values: Identifiers to validate in original order
        field_name: Field label in validation errors.

    Returns:
        Validated identifiers as an ordered tuple.

    Raises:
        ValueError: An identifier is invalid or duplicated.
    """

    normalized = tuple(values)
    for value in normalized:
        RequireIdentifier(value, field_name)

    if len(set(normalized)) != len(normalized):
        raise ValueError(f"{field_name} must contain unique values")
    return normalized

UniqueReferences(values: tuple[str, ...], field_name: str) -> tuple[str, ...]

Validate opaque non-secret references without assigning their semantics.

参数:

名称 类型 描述 默认
values tuple[str, ...]

Opaque non-secret reference strings

必需
field_name str

Field label in validation errors.

必需

返回:

类型 描述
tuple[str, ...]

Validated reference tuple in declaration order.

引发:

类型 描述
ValueError

A reference is invalid or duplicated.

源代码位于: fuzzy1337/adapters/contracts.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def UniqueReferences(values: tuple[str, ...], field_name: str) -> tuple[str, ...]:
    """Validate opaque non-secret references without assigning their semantics.

    Args:
        values: Opaque non-secret reference strings
        field_name: Field label in validation errors.

    Returns:
        Validated reference tuple in declaration order.

    Raises:
        ValueError: A reference is invalid or duplicated.
    """

    normalized = tuple(values)
    for value in normalized:
        RequireText(value, field_name)

    if len(set(normalized)) != len(normalized):
        raise ValueError(f"{field_name} must contain unique values")
    return normalized

JsonValue(value: object) -> object

Render one immutable contract value as deterministic JSON-compatible data.

参数:

名称 类型 描述 默认
value object

Contract dataclass, enum, mapping, sequence or JSON scalar.

必需

返回:

类型 描述
object

JSON-compatible data with sorted keys and list sequences.

引发:

类型 描述
ValueError

A key, number or value is outside the JSON contract.

源代码位于: fuzzy1337/adapters/contracts.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def JsonValue(value: object) -> object:
    """Render one immutable contract value as deterministic JSON-compatible data.

    Args:
        value: Contract dataclass, enum, mapping, sequence or JSON scalar.

    Returns:
        JSON-compatible data with sorted keys and list sequences.

    Raises:
        ValueError: A key, number or value is outside the JSON contract.
    """

    if isinstance(value, StrEnum):
        return value.value

    if is_dataclass(value) and not isinstance(value, type):
        return {field.name: JsonValue(getattr(value, field.name)) for field in fields(value)}

    if isinstance(value, Mapping):
        rendered: dict[str, object] = {}
        for key, nested_value in value.items():
            if not isinstance(key, str):
                raise ValueError("contract mappings must use string keys")
            rendered[key] = JsonValue(nested_value)

        return dict(sorted(rendered.items()))

    if isinstance(value, (list, tuple)):
        return [JsonValue(item) for item in value]

    if isinstance(value, float) and not math.isfinite(value):
        raise ValueError("contract values must not contain non-finite numbers")

    if value is None or isinstance(value, (bool, int, float, str)):
        return value

    raise ValueError("contract values must be JSON-compatible")

SerializeContract(value: object) -> str

Serialize a contract value with stable key order and no non-JSON numbers.

参数:

名称 类型 描述 默认
value object

Supported contract value to serialize.

必需

返回:

类型 描述
str

Compact deterministic JSON text with sorted keys.

引发:

类型 描述
ValueError

The value is outside the strict JSON contract.

源代码位于: fuzzy1337/adapters/contracts.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def SerializeContract(value: object) -> str:
    """Serialize a contract value with stable key order and no non-JSON numbers.

    Args:
        value: Supported contract value to serialize.

    Returns:
        Compact deterministic JSON text with sorted keys.

    Raises:
        ValueError: The value is outside the strict JSON contract.
    """

    return json.dumps(
        JsonValue(value),
        allow_nan=False,
        separators=(",", ":"),
        sort_keys=True,
    )