# @eka-care/medassist-core

TypeScript SDK for real-time medical chatbot experiences: session management, WebSocket connectivity, messaging, and media handling.

## Installation

```bash
npm install @eka-care/medassist-core
```

## Quick start

```typescript
import { SynapseSDK, SYNAPSE_REALTIME_EVENTS } from "@eka-care/medassist-core";

const sdk = new SynapseSDK({
  agentId: "agent-123",
  environment: "production",
  userId: "user-456",
  callbacks: {
    onSessionRefreshed: (session) => console.log("session refreshed", session),
    onError: (error) => console.error("synapse error", error),
  },
});

// Optional: pass existing session to resume
const existing = {
  session_id: localStorage.getItem("synapse-session-id") ?? undefined,
  session_token: localStorage.getItem("synapse-session-token") ?? undefined,
};

const session = await sdk.startSession(
  existing?.session_id && existing?.session_token ? existing : undefined
);

if (session.session_token) {
  localStorage.setItem("synapse-session-id", session.session_id);
  localStorage.setItem("synapse-session-token", session.session_token);
}

sdk.sendMessage({ message: "Hello, doctor!" });

sdk.on(SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK, (data) => console.log("chunk", data));
sdk.on(SYNAPSE_REALTIME_EVENTS.END_OF_STREAM, () => console.log("stream done"));
sdk.off(SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK, handler);

sdk.endSession();
```

## Configuration

- **`agentId`** (required) – Platform agent identifier.
- **`environment`** – `"development"` or `"production"`; defaults to `"production"`.
- **`userId`** – Optional user identifier for analytics.
- **`overrides`** – Optional prompt, first message, or language overrides.
- **`callbacks`**
  - **`onSessionRefreshed(session)`** – Persist new credentials when the backend refreshes them.
  - **`onError(error)`** – Centralized error handling for UI or logging.

## Session lifecycle

1. **`startSession(existingSession?)`** – Creates or resumes a session; validates and refreshes when needed.
2. A WebSocket connection is established and authenticated with the session token.
3. Incoming server events are emitted via `SYNAPSE_REALTIME_EVENTS`.
4. **`endSession()`** – Closes the connection and clears in-memory state.

## Messaging API

- **`sendMessage(options)`** – Send text, files, or audio. Options: `message?`, `files?`, `audio?`, `tool_declined?`, `tool_id?`, `initial_prompts?`, `messageId?`, `hidden?`.
- **`sendFeedback(messageId, feedback, reason?)`** – Send feedback for a message.
- **`callTool(name, params?)`** – Invoke a tool by name with optional params.
- **`getSessionConfig()`** – Returns current session (e.g. `session_id`, `session_token`). Throws if session is not set.
- **`on(event, listener)`** / **`off(event, listener)`** – Subscribe to or remove realtime events.
- **`endSession()`** – Close the connection and cleanup.

## Audio

- **`startRecording({ onChunks, onError })`** – Start recording; `onChunks` receives audio metadata.
- **`endRecording()`** – Stop recording and send data over the socket.

## Realtime events

Use `SYNAPSE_REALTIME_EVENTS` for event names:

- `CONNECTED`
- `MESSAGE_CHUNK`
- `PROGRESS_MESSAGE`
- `TOOL_ESCALATION`
- `TIPS_MESSAGE`
- `INLINE_TEXT`
- `END_OF_STREAM`
- `ERROR`

Reserved events (e.g. `SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_EXPIRED`) are used for internal refresh handling.

## Project structure

```
packages/core/
├── src/
│   ├── Synapse.ts           # High-level SDK
│   ├── index.ts             # Public exports
│   ├── connection/          # WebSocket transport
│   ├── events/              # Realtime event types
│   ├── internal/            # HTTP client, errors, base connection
│   ├── media/               # File and audio helpers
│   ├── messages/            # MessageManager and types
│   ├── resources/           # Session and agent config
│   └── types/               # Shared types
└── README.md
```

For architecture details and advanced usage (e.g. `ConnectionFactory`, `MessageManager`), see the [main repository README](../../README.md).

## License

MIT
