# ArlopassClient

The core client class. Manages connection state, provider selection, and chat operations over the protocol transport.

```tsx
import { ArlopassClient } from "@arlopass/web-sdk";
```

---

### Constructor options

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| ` transport`<br>required | ` ArlopassTransport` | — | Transport implementation (provided by the browser extension via window.arlopass). |
| ` origin` | ` string` | "https://app.arlopass.local" | Origin URL for envelope metadata. Auto-set to window.location.origin when in a browser. |
| ` timeoutMs` | ` number` | `5000` | Default request timeout in milliseconds. |
| ` envelopeTtlMs` | ` number` | `60000` | Time-to-live for protocol envelopes. |
| ` protocolVersion` | ` string` | "1.0.0" | Protocol version string. |
| ` nonce` | ` string` | — | Nonce for envelope signatures. |
| ` now` | ` () => Date` | — | Clock function for envelope timestamps. Defaults to () => new Date(). |
| ` randomId` | ` () => string` | — | ID generator for request/correlation IDs. Defaults to crypto.randomUUID(). |
| ` defaultCapabilities` | ` readonly ProtocolCapability[]` | — | Capabilities to request during connect. |
| ` defaultProviderId` | ` string` | "provider.system" | Fallback provider ID for envelopes before selection. |
| ` defaultModelId` | ` string` | "model.default" | Fallback model ID for envelopes before selection. |
| ` tracing` | ` TelemetryTracing` | — | Optional tracing hook for observability. |

```tsx
const client = new ArlopassClient({
  transport,
  origin: window.location.origin,
});
```

---

### Properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| ` state` | ` ClientState` | — | Current connection state (readonly getter). |
| ` sessionId` | ` string | undefined` | — | Active session ID after connect, undefined before. |
| ` selectedProvider` | ` { providerId: string; modelId: string } | undefined` | — | Currently selected provider/model pair. |
| ` contextWindowSize` | ` number` | — | Context window size in tokens for the selected model. Falls back to 4096 for unknown models. |
| ` chat` | ` { send, stream }` | — | Chat operation namespace (see Methods below). |

---

### Methods

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| ` connect` | ` (options: ConnectOptions) => Promise<ConnectResult>` | — | Establish connection with the extension. Transitions state: disconnected → connecting → connected. |
| ` disconnect` | ` () => Promise<void>` | — | Disconnect and reset state to disconnected. |
| ` listProviders` | ` () => Promise<ListProvidersResult>` | — | Fetch available providers and models. Requires connected state. |
| ` selectProvider` | ` (input: SelectProviderInput) => Promise<SelectProviderResult>` | — | Select a provider/model pair. Requires connected state. |
| ` chat.send` | ` (input: ChatInput, options?: ChatOperationOptions) => Promise<ChatSendResult>` | — | Send messages and receive a complete response. Requires connected state + selected provider. |
| ` chat.stream` | ` (input: ChatInput, options?: ChatOperationOptions) => AsyncIterable<ChatStreamEvent>` | — | Send messages and stream the response as chunks. Supports AbortSignal via options.signal. |
| ` getContextInfo` | ` (messages: readonly ChatMessage[], reserveOutputTokens?: number) => ContextWindowInfo` | — | Compute context window usage for the selected model given a set of messages. Useful for token meters and "context full" warnings. |

```tsx
const client = new ArlopassClient({ transport: window.arlopass });

await client.connect({ appId: "com.example.myapp" });
const { providers } = await client.listProviders();
await client.selectProvider({ providerId: "openai", modelId: "gpt-4o" });
```

```tsx
// Non-streaming
const result = await client.chat.send({
  messages: [{ role: "user", content: "Hello" }],
});
console.log(result.message.content);

// Streaming
for await (const event of client.chat.stream({
  messages: [{ role: "user", content: "Hello" }],
})) {
  if (event.type === "chunk") process.stdout.write(event.delta);
}

// Context window info
const info = client.getContextInfo(messages);
console.log(
  `${info.usedTokens}/${info.maxTokens} (${Math.round(info.usageRatio * 100)}%)`,
);
console.log("Window size:", client.contextWindowSize);
```

---

### State machine

```text
// State machine transitions:
//
// disconnected ──connect()──→ connecting ──success──→ connected
//                                  │                      │
//                                  └──fail──→ failed      ├──degraded
//                                                         │
// connected ──disconnect()──→ disconnected       reconnecting
//                                                    │
//                                                    └──→ connected | failed
```
