npm package: @paymanai/payman-typescript-ask-sdk
Description: Core TypeScript SDK for Payman workflows - logic only, no UI
Author: Payman
Latest version: 1.2.9

# Payman TypeScript Ask SDK

**Core TypeScript SDK for Payman workflows - Logic only, no UI components**

This package contains only the business logic for interacting with Payman workflows. Use this if you want to build your own custom UI or integrate Payman into existing applications without including the default UI components.

## Installation

```bash
npm install @paymanai/payman-typescript-ask-sdk
# or
yarn add @paymanai/payman-typescript-ask-sdk
# or
bun add @paymanai/payman-typescript-ask-sdk
```

## Features

- ✅ **`useChat` Hook** - React hook for managing chat state and streaming
- ✅ **`useVoice` Hook** - React hook for voice recognition (web and mobile)
- ✅ **Streaming Client** - Low-level streaming utilities
- ✅ **TypeScript Types** - Full type definitions
- ✅ **Cross-Platform** - Works in web and React Native
- ✅ **Zero UI Dependencies** - No UI libraries included

## Usage

### Basic Example with Custom UI

```typescript
import { useChat } from '@paymanai/payman-typescript-ask-sdk';

function MyCustomChat() {
  const {
    messages,
    sendMessage,
    isWaitingForResponse,
    resetSession,
  } = useChat({
    config: {
      api: {
        baseUrl: 'https://api.payman.ai',
        authToken: 'your-api-key',
      },
      workflowName: 'my-workflow',
      stage: 'DEV',
      sessionParams: {
        id: 'user-123',
        name: 'John Doe',
      },
    },
  });

  return (
    <div>
      {/* Your custom UI */}
      {messages.map((msg) => (
        <div key={msg.id}>{msg.content}</div>
      ))}
      
      <button
        onClick={() => sendMessage('Hello')}
        disabled={isWaitingForResponse}
      >
        Send
      </button>
    </div>
  );
}
```

### Direct Streaming API

```typescript
import { streamWorkflowEvents } from '@paymanai/payman-typescript-ask-sdk';

await streamWorkflowEvents(
  'https://api.payman.ai/api/workflows/ask/stream',
  {
    workflowName: 'my-workflow',
    userInput: 'Hello',
    sessionOwnerId: 'user-123',
    sessionOwnerLabel: 'John Doe',
  },
  {
    'x-yaak-api-key': 'your-api-key',
  },
  {
    onEvent: (event) => {
      console.log('Received event:', event);
    },
    onComplete: () => {
      console.log('Stream completed');
    },
    onError: (error) => {
      console.error('Stream error:', error);
    },
  }
);
```

## Voice Support

The SDK includes built-in voice recognition for both web and mobile platforms.

```typescript
import { useVoice } from '@paymanai/payman-typescript-ask-sdk';

function MyChat() {
  const {
    voiceState,
    transcribedText,
    isAvailable,
    isRecording,
    startRecording,
    stopRecording,
  } = useVoice(
    { lang: 'en-US' },
    {
      onResult: (transcript) => console.log('Transcript:', transcript),
    }
  );

  return (
    <div>
      <button onClick={startRecording} disabled={!isAvailable || isRecording}>
        Start Voice
      </button>
      <button onClick={stopRecording} disabled={!isRecording}>
        Stop Voice
      </button>
      <p>{transcribedText}</p>
    </div>
  );
}
```

**Platform Support:**
- **Web**: Uses browser's Web Speech API (Chrome, Edge, Safari)
- **React Native**: Uses `expo-speech-recognition` (iOS & Android). You must install it in your app: `npm install expo-speech-recognition` (or `yarn add expo-speech-recognition`). If the package is not installed, the voice button will show but `isAvailable` will be false and no permissions are requested.

**Voice UI layout (Ask UI / custom UIs):** When voice is enabled, show the voice control **beside** the send button (e.g. voice on the left, send on the right), not replacing it. Both should be visible so users can send text or use voice.

## API Reference

### `useChat(options)`

React hook for managing chat state.

**Parameters:**
- `config: ChatConfig` - Configuration object
  - `api.baseUrl: string` - API base URL
  - `api.authToken?: string` - Authentication token
  - `api.headers?: Record<string, string>` - Custom headers
  - `workflowName: string` - Workflow name
  - `stage?: WorkflowStage` - Environment stage (DEV, SANDBOX, PROD)
  - `sessionParams?: SessionParams` - Session owner information
- `callbacks?: ChatCallbacks` - Event callbacks

**Returns:**
- `messages: MessageDisplay[]` - Array of messages
- `sendMessage: (message: string) => Promise<void>` - Send a message
- `resetSession: () => void` - Reset the session
- `cancelStream: () => void` - Cancel current stream
- `isWaitingForResponse: boolean` - Loading state

### `useVoice(config?, callbacks?)`

React hook for voice recognition.

**Parameters:**
- `config?: VoiceConfig` - Voice configuration
  - `lang?: string` - Language (default: "en-US")
  - `interimResults?: boolean` - Enable interim results (default: true)
  - `continuous?: boolean` - Continuous mode (default: true)
  - `maxAlternatives?: number` - Max alternatives (default: 1)
  - `autoStopAfterSilence?: number` - Auto-stop after silence in ms (web only)
- `callbacks?: VoiceCallbacks` - Event callbacks
  - `onStart?: () => void` - Recording started
  - `onEnd?: () => void` - Recording ended
  - `onResult?: (transcript: string) => void` - New transcript
  - `onError?: (error: string) => void` - Error occurred
  - `onStateChange?: (state: VoiceState) => void` - State changed

**Returns:**
- `voiceState: VoiceState` - Current state ("idle" | "listening" | "processing" | "error")
- `transcribedText: string` - Current transcribed text
- `isAvailable: boolean` - Is voice available on this device/browser
- `isRecording: boolean` - Is currently recording
- `startRecording: () => Promise<void>` - Start voice recording
- `stopRecording: () => void` - Stop voice recording
- `requestPermissions: () => Promise<VoicePermissions>` - Request mic permissions
- `getPermissions: () => Promise<VoicePermissions>` - Check mic permissions
- `clearTranscript: () => void` - Clear transcribed text
- `reset: () => void` - Reset voice state

### `streamWorkflowEvents(url, body, headers, options)`

Low-level streaming function.

**Parameters:**
- `url: string` - API endpoint URL
- `body: Record<string, unknown>` - Request body
- `headers: Record<string, string>` - Request headers
- `options: StreamOptions` - Streaming options
  - `onEvent?: (event: StreamEvent) => void` - Event callback
  - `onComplete?: () => void` - Completion callback
  - `onError?: (error: Error) => void` - Error callback
  - `signal?: AbortSignal` - Abort signal

## TypeScript Types

All types are exported:

```typescript
import type {
  // Chat types
  ChatConfig,
  ChatCallbacks,
  MessageDisplay,
  StreamingStep,
  WorkflowStage,
  // Voice types
  VoiceConfig,
  VoiceCallbacks,
  VoiceState,
  VoicePermissions,
  UseVoiceReturn,
  // ... and more
} from '@paymanai/payman-typescript-ask-sdk';
```

## Related Packages

- **[@paymanai/payman-ask-sdk](../payman-ask-sdk)** - Full SDK with UI components (uses this package internally)

## License

MIT