# SDK

> **Preview**: Package names, class names, and parameters may change before official release.

***

## Installation

```bash
npm install @toani/control-sdk
```

**System Requirements (design target)**: Node.js >= 22.0.0

***

## Initialization

```typescript
import { ToaniControl } from '@toani/control-sdk';

const toaniControl = new ToaniControl({
  apiKey: process.env.TOANI_CONTROL_API_KEY!,
  tenantId: 'tenant_acme_corp',
  environment: 'sandbox', // 'production'
  webhookSecret: process.env.TOANI_CONTROL_WEBHOOK_SECRET, // recommended when validating HITL / async callbacks
});
```

| Parameter       | Description                                        |
| --------------- | -------------------------------------------------- |
| `apiKey`        | Enterprise tenant API key                          |
| `tenantId`      | Tenant identifier                                  |
| `environment`   | `sandbox` / `production`                           |
| `webhookSecret` | Validates server-side push signatures (if enabled) |

***

## Core Methods: Execution

### Synchronous Execution: `execute`

For low-latency read-only or **Tier 0** auto-approved write operations.

```typescript
const result = await toaniControl.execute({
  policyId: 'pol_wealth_mgmt_v2',
  userContext: { userId: 'user_123' }, // often needed for scenarios B/C
  service: 'schwab',
  action: 'read_balance',
  params: {},
  idempotencyKey: 'idem-2026-03-30-001',
  mode: 'sync', // optional; auto-inferred by policy by default
});
```

### Asynchronous Execution Plus HITL: `executeAsync`

For **Tier 1 / Tier 2**.

```typescript
const pending = await toaniControl.executeAsync({
  policyId: 'pol_wealth_mgmt_v2',
  userContext: { userId: 'user_123' },
  service: 'schwab',
  action: 'buy_stock',
  params: { ticker: 'AAPL', shares: 10 },
});
// { executionId, status: 'pending_hitl', hitlSentAt, ... }

const final = await toaniControl.waitForExecution(pending.executionId, {
  pollIntervalMs: 2000,
  timeoutMs: 120000,
});
```

### Pre-Authorized Batch: `createBatchAuthorization`

For **policy-allowed batch windows** (quota plus expiry).

```typescript
const batchAuth = await toaniControl.createBatchAuthorization({
  policyId: 'pol_defi_rebalance',
  validUntil: '2026-03-12T00:00:00Z',
  quota: { maxExecutions: 50, maxTotalUsd: 10_000 },
  userSignature: '<zkPassport-proof-or-admin-signature>',
});

await toaniControl.execute({
  batchAuthId: batchAuth.id,
  action: 'rebalance_portfolio',
  params: { target: 'SPY:60,BND:40' },
});
```

***

## Return Types (Conceptual)

```typescript
type ExecutionResult = {
  executionId: string;
  status: 'completed' | 'pending_hitl' | 'rejected' | 'failed';
  data?: unknown;
  proof: string; // Execution Receipt, offline-verifiable
  auditRef: string;
  hitlRequired?: boolean;
  hitlConfirmedAt?: string;
  policyId: string;
  policyVersion: number;
  durationMs: number;
};
```

***

## Audit and Proof Verification

```typescript
const history = await toaniControl.getExecutionHistory({
  policyId: 'pol_wealth_mgmt_v2',
  fromDate: '2026-01-01',
  toDate: '2026-03-31',
  status: 'completed',
});

const valid = await ToaniControl.verifyProof(result.proof, {
  expectedMrenclave: '0x...',
  expectedPolicy: 'pol_wealth_mgmt_v2',
});
```

***

## Error Codes (Design)

| Code                        | Meaning and Suggested Handling                              |
| --------------------------- | ----------------------------------------------------------- |
| `TC_POLICY_SCOPE_VIOLATION` | Action not in whitelist → inform user, do not blindly retry |
| `TC_CONSTRAINT_EXCEEDED`    | Quota or constraint reached → show limit information        |
| `TC_HITL_DENIED`            | User rejected → need new instruction to initiate again      |
| `TC_HITL_TIMEOUT`           | Approval timeout → can prompt user to re-initiate           |
| `TC_KYC_REQUIRED`           | Missing valid zkKYC → guide user through identity flow      |
| `TC_TOKEN_EXPIRED`          | Action Token expired → full flow retry                      |
| `TC_TOKEN_REPLAYED`         | Single-use Token reused → security alert                    |
| `TC_TEE_ATTESTATION_FAILED` | Attestation failure → stop retry, contact support           |
| `TC_CONNECTOR_FAILED`       | Downstream error → limited exponential backoff retry        |
| `TC_RATE_LIMITED`           | Rate limit reached → respect `Retry-After`                  |

***

## Preview Note

* SDK is not officially released; `npm install` may not yet be available.
* Sample code shows preview API; official release may differ.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.toani.ai/toani-control/getting-started/sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
