# Infrastructure provider SDK — proposed contract v0.1

This interface is an implementation design, not an SDK release. It specifies the separation between creating a machine and managing what runs on the machine. The runtime operates identically for all admitted nodes; the provider adapter is optional. See MASTER_PRD §7 for product requirements and source references.

## Contract and invariants

- An installation is a trust boundary; every object is scoped to installation and provider account. Opaque provider IDs are not global identifiers. A `Node` is a locally authenticated identity; a `ProviderResource` is a provider's infrastructure record. Association is explicit and verified. A provider resource may exist without an enrolled node, and a node may exist without a provider resource.
- A `ProviderAccount` holds metadata and a reference to a customer-controlled credential, not a plaintext token. Customer provider runner fetches scoped signed commands, resolves credentials locally, invokes provider API and emits redacted results. Split discovery and mutation capabilities where available. Bootstrap trust is separate from provider credentials.
- SDK capability records are product/region/version-specific, with `tested_at`, `supported`, `reason`, and typed constraints. Support for one vendor product never implies support for all products. Native adapters are optional; generic enrollment must work without provider credentials.
- A quote is not a reservation and is not a final invoice. Amount is a decimal string or integer minor units, currency ISO 4217, interval (`hour`, `month`, `one_time`, etc.), setup fees, minimum commitment, renewal, tax inclusion/unknown, estimated bandwidth/egress and expiry. Unknown or unavailable price is explicit; do not auto-buy.
- Every paid create/resize, destructive reinstall, disk change, detach/delete, and public exposure is planned before apply. A plan includes action, target identity, exact request hash, expected generation, material changes, cost, risk, preconditions, ownership, approval policy, expiration and rollback/compensation. Reinstallation and node termination require separate approvals. A quote change invalidates approval; approval is not a permission to apply a different action. No arbitrary shell or user-supplied IaC passed through adapter.
- Mutations use idempotency keys bound to plan hash. Native idempotency where available, otherwise persist operation ID, unique tags and provider request correlation before call. After timeout, reconcile by provider ID/tag/status; never blindly retry a purchase. If ambiguous, block and alert. Provider asynchronous tasks survive runner restart. A resource not created by platform is protected by default.
- Secrets may appear in upstream responses: normalize and redact before storing/transmitting. Provider-specific extension data must be schema-validated and encrypted where appropriate; reject unknown secret-bearing fields. Never deliver provider API keys through cloud-init, SSH command text, app bindings or agent prompts.

## Types (language-neutral pseudocode)

```ts
type Ref = string; // opaque installation-scoped ID
type Money = { currency: string; amount: string; interval: 'hour'|'day'|'month'|'year'|'one_time'; tax: 'included'|'excluded'|'unknown' };
type Capability = {
  name: 'discover'|'quote'|'create'|'adopt'|'start'|'stop'|'reboot'|'rescue'|'reinstall'|'delete'|'resize'|'network'|'volume'|'snapshot'|'rdns';
  supported: boolean; product: string; region: string; reason?: string; testedAt?: string; constraints?: object;
};
type ProviderResource = {
  accountRef: Ref; providerId: string; product: string; region: string; sku: string;
  lifecycle: 'ordering'|'provisioning'|'ready'|'stopped'|'rescue'|'failed'|'unknown'|'deleted';
  addresses: string[]; architecture?: string; physicalCores?: number; vcpu?: number; memoryBytes?: number;
  disks?: object[]; accelerators?: object[]; nodeRef?: Ref; ownership: 'external'|'adopted'|'managed'; observedAt: string;
};
type Offer = { product: string; region: string; sku: string; architecture: string; cpuClass: string;
  memoryBytes: number; disks: object[]; accelerators: object[]; availability: 'available'|'unavailable'|'unknown';
  osImages: string[]; nativeMetadata: object; observedAt: string };
type Quote = { id: Ref; offerRef: Ref; prices: Money[]; commitment?: string; estimated: boolean;
  knownFees: Money[]; unknownFees: string[]; expiresAt: string; source: string };
type Plan = { id: Ref; action: string; accountRef: Ref; targetRef?: Ref; baseGeneration: number;
  canonicalRequestHash: string; quoteRef?: Ref; expectedCost?: Money[]; risks: string[];
  destructive: boolean; preconditions: object[]; approvalPolicy: string; expiresAt: string };
type Operation = { id: Ref; planRef: Ref; idempotencyKey: string; nativeTaskRef?: string; nativeResourceRef?: string;
  status: 'queued'|'running'|'pending'|'requires_user_action'|'ambiguous'|'succeeded'|'failed'|'blocked'|'canceled';
  retryAfterSeconds?: number; observedAt: string; safeToRetry: boolean; problem?: object; receiptRefs?: Ref[] };
interface InfrastructureProvider {
  describe(): ProviderDefinition;
  validateAccount(accountRef: Ref): AccountCheck;
  capabilities(accountRef: Ref, product: string, region?: string): Capability[];
  listRegions(accountRef: Ref): Page<Region>;
  listOffers(accountRef: Ref, filter: OfferFilter): Page<Offer>;
  quote(accountRef: Ref, offer: Offer, intent: CreateIntent): Quote;
  listResources(accountRef: Ref, cursor?: string): Page<ProviderResource>;
  getResource(accountRef: Ref, nativeResourceId: string): ProviderResource;
  planCreate(intent: CreateIntent, quoteRef: Ref): Plan;
  planAdopt(intent: AdoptIntent): Plan;
  planLifecycle(intent: LifecycleIntent): Plan;
  apply(plan: Plan, approval: SignedApproval, idempotencyKey: string): Operation;
  poll(operationRef: Ref): Operation;
  reconcile(operationRef: Ref): Operation;
  cancel(operationRef: Ref, approval: SignedApproval): Operation;
  exportReferences(accountRef: Ref): SanitizedExport;
}
```

The actual Go/RPC implementation will use typed schemas, paginated results, version negotiation, deadlines, cancellation, errors and no arbitrary `object` fields at privilege boundaries. The above expresses semantics, not a compilable interface. `cancel` can be unsupported; it does not imply reimbursement or reversal of a completed order. Deleting an adapter/account record does not delete provider resources. A provider runner verifies the exact approval independently of central model output. Provider result states and local verification states are distinct.

## Bootstrap lifecycle

`requested → quoted → approval → ordering → provider_allocated → OS_preparing → enrollment_pending → admitted → baseline_verified → ready`. Exceptional states `requires_user_action`, `ambiguous`, `blocked`, `failed`, `quarantined`. The provisioning operation is not succeeded solely because a server ID exists. Verify node certificate, machine facts, intended roles, disk/ports, registry reachability, overlay where configured, time sync, runtime and functional probes. A node that cannot pass preflight is quarantined, not silently reformatted or automatically billed for a replacement. Polling uses capped backoff and provider rate limits; human instructions include only necessary safe context.

Generic host path uses the same enrollment handshake but no provider order. Enrollment grants are short-lived, single-use and scoped to intended installation/role; node generates its own private key and requests certificate. Customer authorizes installation with signed artifacts; confirm node identity, pin trust roots, then revoke bootstrap grant. Installer is resumable and dry-run capable; preflight never mutates. No persisted root SSH key in hosted service.

## Provider implementation matrix

| Adapter | Initial capabilities to implement | Specific caveat |
|---|---|---|
| generic-linux | preflight, enroll, local inventory, detach | no remote purchase or power claims |
| hetzner-cloud | list regions/types/images, quote, create, poll, link, power, delete | project token scopes; test capacity availability and billing |
| ovh-dedicated | inventory, quote/order where authorized, install compatible OS, poll, link, rescue/reboot where supported | region-specific API/account, commitment/setup, wipe approval |
| hetzner-robot | inventory/link, hardware and rescue/install capabilities verified per product | separate API; manual order acceptable until tested |
| digitalocean | regions/sizes/images, Droplet create/poll/link/power/delete | quote and storage/network support per resource |
| vultr | distinct cloud compute and bare-metal offers, create/poll/link | do not assume same API or power semantics across products |
| opentofu | approved module plan/apply/export with encrypted local state | no dual ownership or arbitrary HCL execution; lock state, pin providers |

Later community adapters: Scaleway, Akamai/Linode, Hostinger, Contabo, Leaseweb, UpCloud, hyperscaler VM APIs, Proxmox. Publish actual support only after conformance and sandbox/live tests. Native provider documentation links in PRD §22.

## Conformance suite

1. Capability discovery is accurate and can return unsupported without pretending success.
2. Account validation never leaks credentials, uses read-only scope if possible.
3. Stable product and region IDs; price normalization preserves commitment/currency/unknowns.
4. Plan dry-run creates no infrastructure. Altered or expired quote, plan, generation or signature denied.
5. Simulated timeout after provider-side create: reconcile returns same resource; no duplicate purchase.
6. Uncertain create with no unique match: blocked, visible ongoing cost risk, escalation.
7. Provider quota/rate-limit/auth/network error handled distinctly; retry caps honored.
8. Existing-resource adoption never triggers reboot, install, billing or deletion.
9. Destructive install/delete protected; unmanaged resources not deleted; cancel semantics truthful.
10. Node admission is independent of provider reported status; duplicate or replay enrollment denied.
11. Revoked integration does not stop running apps; provider actions unavailable.
12. Logs/telemetry/error payloads redacted; no cross-account reads/writes; plugin sandbox enforced.
13. Verify live authorized disposable test create and clean up; reconcile actual invoice or billing event where possible. Publish date, SKU, OS, region, limits and evidence.
14. Export references and detach preserving customer machine and workload; customer can continue manual management.
