Skip to content

Latest commit

 

History

History
246 lines (187 loc) · 17.4 KB

File metadata and controls

246 lines (187 loc) · 17.4 KB

Public API Design

Status

This document defines semantic responsibilities and API philosophy. Phase 1 introduces documented shells for this vocabulary; their presence does not implement the later-phase behavior described here or freeze pre-1.0 signatures.

Swift design principles

  • Use immutable value types for proposals, definitions, contexts, decisions, challenges, authorizations, and audit events.
  • Require Sendable for values crossing concurrency boundaries.
  • Use closed enums for security-critical outcomes and reject unknown decoded cases.
  • Use actors only to isolate genuinely shared mutable state; keep deterministic evaluation pure where possible.
  • Make invalid, missing, expired, and unverifiable states explicit; do not encode them as permissive defaults.
  • Avoid singleton registries, process-wide mutable policy, hidden clocks, and other global state.
  • Compose narrow protocols and initializers; do not introduce a dependency injection framework.
  • Use typed identifiers rather than interchangeable strings for security-relevant identities.
  • Provide documentation and pseudo-code or compilable examples for every public API as it is introduced.
  • Keep platform APIs out of the core module and behind adapter protocols.

Concept responsibilities

ToolDefinition

An immutable, versioned declaration registered by an authorized host path. It identifies one exact tool/version and owns its complete immutable schema, lifecycle, maximum capabilities, and typed metadata. It contains no parser, executable closure, endpoint, or implicit authority. Later authorization binds the exact definition and snapshot.

ToolProposal

An untrusted request to use a named/versioned tool with a closed host-parsed StructuredObject and declared provenance references. Creation is not schema validation. A proposal cannot carry authenticated identity, approval, or capabilities that the host has not supplied.

UserIntentEnvelope

A host-originated, authenticated binding between a subject and an intended action scope. It records identity, freshness, scope/constraints, context reference, and an identifier suitable for decision binding. It is not authoritative when constructed from model output or unauthenticated text.

Authorization

An immutable artifact representing narrowly scoped permission issued from one successful policy path. It binds the subject, tool/definition version, canonical arguments, capabilities, intent, policy/decision, confirmation when applicable, issuance/expiry, and single-use/idempotency identity. Possession alone is insufficient if verification or atomic consumption fails.

ApprovalChallenge

A safe-to-display, expiring request for host-mediated confirmation. It binds the canonical request, subject, decision, risk/capability summary, and challenge identity. Display content is derived from validated fields and cannot replace the underlying canonical binding. A response to one challenge is invalid for any changed request.

AuditEvent

An immutable, privacy-minimized record of a security transition: input acceptance/rejection, decision, challenge, authorization issuance, verification, consumption, or denial. It includes ordering/correlation data and tamper-evidence links but excludes secrets and raw prompts by default.

PolicyDecision

The deterministic result of evaluating one versioned policy against one complete immutable input set. Its outcome is deny, require confirmation, or allow; it also carries stable reason codes, policy/version identity, granted/required capabilities, obligations, and input commitments. It is evidence for authorization issuance, not itself an execution token.

Provenance

Structured origin and custody information for a proposal, argument, intent fact, or influence. It expresses source class, issuer, verification state, transformations, and references without converting claims into trust. Missing or unverifiable provenance is untrusted.

Influence

Evidence that content or a system may have shaped a proposal, such as retrieved text, tool output, memory, or another model. It enables policy to deny or escalate indirect prompt paths even when the influenced material is absent from final arguments.

Capability

A typed, versioned description of a privilege category or protected effect, optionally with normalized constraints. Requested/granted capability sets cannot exceed the registered definition, authenticated host authority, user intent, or policy. Unknown capabilities deny.

TrustClass

A closed, ordered only where explicitly specified classification of evidence or sources. It must not imply that trusted transport makes content trusted. Unknown values fail closed; no caller can create a higher class from model claims.

SecurityContext

A host-attested snapshot of authenticated subject, tenant, session, delegated authority, assurance, environment, and security-relevant constraints. It contains references rather than secrets and has explicit freshness/version semantics. Model output cannot construct or mutate it authoritatively.

Supporting conceptual types

  • CanonicalRequest: validated exact tool definition, complete schema, canonical arguments, reviewed argument-derived resources, and all applicable version bindings.
  • EvaluationInput: complete immutable bundle of canonical request, host authority, intent, provenance/influence, security context, registry/policy bindings, and explicit host-supplied comparison time.
  • DecisionReason: stable machine-readable reason code plus safe diagnostics; free text is never an authorization input.
  • ConfirmationResponse: host-attested response bound to an exact challenge and authenticated subject.
  • ConsumptionReceipt: future host evidence that one authorization was atomically consumed; Phase 6 deliberately defines no receipt or consumption operation.
  • IdempotencyKey: identity of one logical operation, distinct from a model-supplied retry label.

Phase 2 Tool Registry API

  • ToolID accepts exact lowercase ASCII namespace syntax and never normalizes external input.
  • ToolVersion is a canonical positive integer generation used only for exact binding.
  • ToolDefinitionID identifies one immutable registered definition independently from tool/version identity.
  • ToolRegistryDraft accumulates definitions with value semantics and publishes only complete sets.
  • ToolRegistrySnapshot exposes deterministic ordered definitions and exact lookup from immutable state.
  • ToolDefinitionReference binds snapshot ID/version and the complete immutable definition value; it is an in-memory structural binding, not canonical serialization, a cryptographic commitment, or authorization.
  • ToolLookupResult is constructible only by the snapshot and records resolution, not permission.
  • ToolRegistryError exposes stable reasons and safe field/limit categories without raw rejected content.
  • ToolLifecycleState explicitly distinguishes active, deprecated, and retired definitions.
  • ToolSecurityMetadata is security-relevant classification; ToolDisplayMetadata and ToolDescriptiveMetadata are non-authoritative.
  • Capability describes a definition's maximum effect categories only. Phase 2 performs no authorization intersection.

The publication API deliberately accepts no ToolProposal, authentication claim, model output wrapper, clock, random source, persistence service, callback, endpoint, or executor. Calling publication is authority-sensitive host orchestration outside the core's ability to authenticate.

API flow constraints

The public surface should make the safe path natural:

  1. The host parses untrusted bytes without coercion and preserves duplicate field occurrences in an unvalidated proposal.
  2. Validation against a registry snapshot produces a canonical request or a typed rejection.
  3. Evaluation requires all authenticated and provenance inputs explicitly.
  4. A policy decision can be audited but cannot be passed directly to an executor.
  5. Phase 6 authorization issuance accepts only eligible allow decisions and rejects confirmation or other obligations it cannot prove satisfied.
  6. Host structural validation requires exact expectations; future consumption and execution remain separate and outside this API.

The API must not expose convenience initializers that synthesize trusted provenance, authenticated intent, allow decisions, or non-expiring/reusable authorization.

Phase 3 Schema and Canonical Request API

  • SchemaID, SchemaVersion, and SchemaReference identify one exact schema contract. CanonicalizationVersion is separate and has no inferred compatibility with schema versions.
  • FieldName and EnumCaseName are restricted exact lowercase ASCII values. Construction never trims, folds case, normalizes, or repairs.
  • FieldRequirement makes required versus optional presence explicit. Optional absence supplies no default; null is never accepted.
  • FieldKind is a finite inline closed vocabulary: ordinary string, reviewed resource identifier, Boolean, signed Int64, unsigned UInt64, closed enum, ordered array, and closed object.
  • StructuredObject uses [StructuredField], not a dictionary, to preserve duplicate occurrences for rejection. StructuredValue contains typed host-parsed values and has no parser or coercion API.
  • SchemaDefinition validates maximum depth and schema-node bounds at construction. ObjectSchema and EnumSchema reject duplicates and establish exact ordering.
  • SchemaValidator.canonicalRequest accepts only a non-publicly constructible ToolLookupResult, an exact matching schema, the exact ToolProposal, and an understood canonicalization version. Proposal tool/version must match the lookup before argument validation.
  • SchemaValidationError contains a stable reason, optional safe schema-derived path, and optional public limit. It never echoes rejected input.
  • CanonicalRequest has no public initializer, retains the exact snapshot-bound definition and schema plus resources derived only from resourceID nodes, and exposes no canonical field collection. Its canonicalBytes() method returns an independent copy of its opaque deterministic representation.

All Phase 3 types are immutable Sendable values. No actor is needed because schema construction, validation, and canonicalization have no shared mutable state.

Phase 4 Authenticated Binding API

  • Raw claims (HostAuthorityClaim, HostAttestationClaim, SecurityContextClaim, UserIntentClaim, ProvenanceClaim, InfluenceClaim, and InfluenceCollectionClaim) are public immutable data and never trusted merely because they were constructed.
  • HostAuthority, ValidatedHostAttestation, SecurityContext, UserIntentEnvelope, validated provenance/influence values, and EvaluationInput expose no public initializer. Narrow validators construct them after exact structural checks.
  • HostAuthorityValidator and HostAttestationValidator are authority-sensitive host integration APIs requiring the independently retained HostCapabilityBoundary. They implement no signature or caller authentication; applications must prevent model-controlled code from obtaining that boundary.
  • ValidityWindow uses explicit bounded EpochSeconds, inclusive not-before, and exclusive expiry. Every validation API requires explicit evaluation time.
  • IntentTarget is closed to an exact canonical request or an exact snapshot-bound definition. Intended capability scopes are nonempty; resource scopes may be exactly empty only for a genuinely resource-free request, bounded, sorted upper bounds—not grants.
  • SecurityContext contains closed unordered assurance and authentication-method classifications plus an optional separately attested delegation reference.
  • ValidatedProvenanceSet makes missing coverage unknown. hostVerified verifies a provenance record, not arbitrary content semantics, and is blocked by unsupported transformations.
  • ValidatedInfluenceSet stores bounded acyclic relationships and separate collection results. Validated complete status is constructible only with an exact collector attestation.
  • EvaluationInputValidator performs exact identity, request, scope, renewal, freshness, and lineage compatibility checks and returns no partial value. EvaluationInput has no decision or execution API.

All Phase 4 collections have public deterministic limits and output ordering. No actor is required because every transformation is pure over explicit values. The complete example is in Examples/PHASE_4.md.

Phase 5 Policy API

  • PolicyID, PolicyVersion, PolicySnapshotID, PolicySnapshotVersion, PolicyRuleID, and DecisionID are exact bounded values.
  • PolicyCondition is closed to unordered all, any, and typed predicates; PolicyRule validates and normalizes the full bounded tree.
  • PolicyScopeConstraint is an exact ceiling. Empty means none, not unrestricted.
  • PolicyDefinition sorts unique rules. PolicyDraft publishes immutable exact snapshots bound to the host capability boundary; lookup requires ID and version and rejects retired policy.
  • PolicyEvaluator.evaluate is a pure namespace operation over explicit values. It evaluates all rules and constructs the only evaluated PolicyDecision.
  • PolicyDecision has no public initializer. Its .allow outcome is evidence for possible Phase 6 processing, not an authorization or executable capability.

Every Phase 5 collection is bounded and deterministically ordered. No actor is needed because evaluation and publication are value transformations with no shared mutable state. See Examples/PHASE_5.md.

Phase 6 Authorization API

  • AuthorizationID, replay/consumption identities, versions, and generations are small validated immutable values.
  • Authorization and every authority-bearing subvalue expose only let properties and no public initializer. AuthorizationIssuer.issue is the only construction path.
  • Issuance accepts complete concrete Phase 4/5 values rather than protocols, closures, service locators, or hidden global state.
  • AuthorizationScopeClaim and AuthorizationLifetimeExpectation are explicitly non-authoritative host expectations. Constructing either grants nothing.
  • AuthorizationValidationContext is intentionally verbose: every security expectation is visible at the call site and exact equality is the contract.
  • AuthorizationValidator.validate requires explicit EpochSeconds and returns an immutable AuthorizationValidationResult; it does not consume or persist.
  • AuthorizationError contains only stable closed reasons, safe field categories, and public limits. It never returns raw arguments or rejected identifiers.

No actor is used because issuance and validation are pure deterministic value transformations. A future atomic consumption facility would own mutable isolation outside this Phase 6 API. See Examples/PHASE_6.md.

Errors and observability

Security failures should be typed and stable enough for policy, tests, and audit correlation. Public diagnostics must separate safe operator detail from user-facing messages and secret/raw input. Error recovery must require an explicit new evaluation when any bound input changes.

Evolution

Security-critical encodings, schemas, identifiers, policies, and artifacts require explicit versions. Forward compatibility does not mean accepting unknown fields or enums: a consumer that does not understand a version rejects it. Additive changes require a new understood schema/version or a field explicitly designated as non-security-relevant by the contract.

RC0.1 capability and structural APIs

  • HostCapabilityBoundary is a reference-identity capability retained by the host; authoritative values expose no method to recover it.
  • HostAuthorityScope is an immutable upper bound with nonempty capabilities and exact resources (including exact empty resource authority), never a default or grant.
  • ToolDefinition requires complete schema content. Identifier-only construction is unavailable.
  • FieldKind.resourceID is the reviewed resource-binding vocabulary. There is no generic key path, closure, parser hook, or caller-defined extractor.
  • Issuance and validation require the independently retained host boundary. Convenience overloads that derive it from an artifact are prohibited.
  • Collection-valued policy predicates reject empty operands at construction.

RC0.2 public API changes

  • ProposalAssessmentClaim, ProposalAssessmentReference, and its validator provide privacy-safe boundary-local continuity.
  • Phase 3 and Phase 4 validators require the independently retained boundary and exact assessment at each handoff.
  • HostAttestationValidator composes role-specific authorities sharing one exact domain and ceiling; policy publication requires a policy administrator.
  • PolicyEvaluator.evaluate independently requires the boundary, and decision binding retains complete exact snapshot and policy content.
  • AuthorizationIssuer.issue requires explicit issuedAt.
  • AuthorizationValidationContext requires an independently sourced expected authorizationID.
  • Validation returns a complete non-consuming AuthorizationConsumptionBinding.
  • .maximumEvaluationAgeSeconds replaces the ambiguous pre-1.0 freshness case.

Strong private boundary references are compared by === and cannot be recovered through public API. Custom Hashable implementations omit address-like boundary identity while equality still checks it; hash collisions imply neither equality nor authority.