> ## Documentation Index
> Fetch the complete documentation index at: https://docs.thaliq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Changelog

> Historial de cambios y guia de migracion del SDK

## v1.1 (Actual)

### Nuevas features

<CardGroup cols={2}>
  <Card title="Feedback API" icon="thumbs-up">
    Califica respuestas del agente con thumbs up/down via `thaliq.agent.feedback()`.
  </Card>

  <Card title="Insights" icon="lightbulb">
    Recibe insights (warnings, oportunidades, logros) extraidos automaticamente del contexto.
  </Card>

  <Card title="Handoff a humano" icon="headset">
    Detecta cuando la conversacion es escalada a un agente humano con el evento `handoff`.
  </Card>

  <Card title="Nuevos eventos SSE" icon="bolt">
    4 nuevos tipos de evento: `message_stop`, `rate_limit`, `handoff`, `keepalive`.
  </Card>
</CardGroup>

### Nuevos eventos SSE

| Evento         | Descripcion                                                                                  |
| -------------- | -------------------------------------------------------------------------------------------- |
| `handoff`      | La conversacion fue escalada a un agente humano. Incluye `message`, `agentName?`, `reason?`. |
| `message_stop` | Generacion del modelo finalizada. Incluye `model` y `usage` (tokens).                        |
| `rate_limit`   | Rate limit del tenant excedido. Incluye `message` y `retryAfter` (segundos).                 |
| `keepalive`    | Ping periodico para mantener la conexion SSE abierta.                                        |

### Nuevo estado del stream

| Estado    | Descripcion                                     |
| --------- | ----------------------------------------------- |
| `handoff` | La conversacion fue escalada a un agente humano |

### Nuevo metodo: `feedback()`

```typescript theme={null}
await thaliq.agent.feedback({
  conversationId: 'conv-123',
  messageId: 'msg-456',         // De response.completed metadata
  feedback: 'positive',
});
```

### Insights en respuestas

```typescript theme={null}
const response = await thaliq.agent.chat('Resume mis finanzas');
console.log(response.insights);
// [{ type: 'warning', severity: 'high', title: '...', description: '...' }]
```

### ResponseMetadata mejorada

Se agrego `messageId` a `ResponseMetadata`:

```typescript theme={null}
interface ResponseMetadata {
  conversationId: string;
  messageId?: string;         // ← Nuevo en v1.1
  model: string;
  promptTokens: number;
  completionTokens: number;
  processingTimeMs: number;
  generatedAt: string;
}
```

### HITL: onReject `fallback`

Se agrego `fallback` como opcion de `onReject` en acciones HITL:

| `onReject` | Comportamiento                               |
| ---------- | -------------------------------------------- |
| `stop`     | El agente se detiene                         |
| `continue` | El agente continua sin la tool               |
| `fallback` | El agente ejecuta accion alternativa ← Nuevo |

***

## Migracion de v1.0 a v1.1

### Cambios no-breaking

Todos los cambios en v1.1 son **aditivos** — no hay breaking changes. Tu codigo existente sigue funcionando sin modificaciones.

### Recomendaciones

**1. Manejar nuevos eventos SSE**

Si tienes un `switch` sobre `event.type`, agrega casos para los nuevos eventos:

```typescript theme={null}
for await (const event of stream) {
  switch (event.type) {
    // ... casos existentes ...

    // Nuevos en v1.1:
    case 'handoff':
      showHandoffUI(event.message, event.agentName);
      break;
    case 'rate_limit':
      showRetryMessage(event.retryAfter);
      break;
    case 'message_stop':
      logUsage(event.model, event.usage);
      break;
  }
}
```

**2. Implementar feedback**

Aprovecha el nuevo `messageId` en `response.completed` para habilitar feedback:

```typescript theme={null}
if (event.type === 'response.completed' && event.metadata?.messageId) {
  enableFeedbackButtons(event.metadata.messageId);
}
```

**3. Consumir insights**

Las respuestas ahora incluyen `insights[]`. Si tu app muestra datos financieros, de productividad, o analiticos, renderizalos:

```typescript theme={null}
const response = await stream.finalResponse();
if (response.insights.length > 0) {
  showInsightsPanel(response.insights);
}
```

**4. Manejar handoff**

Si tu tenant tiene inbox habilitado con agentes humanos, maneja el evento `handoff`:

```typescript theme={null}
if (event.type === 'handoff') {
  disableChatInput();
  showMessage(`${event.agentName ?? 'Un agente'} tomara tu conversacion.`);
}
```

***

## Buenas practicas

### Consumo unico del stream

<Warning>
  El `AgentStream` solo puede ser consumido **una vez**. Esto es una restriccion de diseno para prevenir bugs.

  ```typescript theme={null}
  // ❌ Doble consumo — lanza StreamError
  const text = await stream.text();
  const response = await stream.finalResponse();

  // ✅ Usa finalResponse() que incluye todo
  const response = await stream.finalResponse();
  const text = response.message;
  const meta = response.metadata;
  const insights = response.insights;
  ```

  Esto aplica tanto a `stream()` como a `respondToAction()`.
</Warning>

### Reintentos y rate limits

El SDK reintenta automaticamente errores de servidor (5xx). Para rate limits (429), no reintenta pero emite el evento:

```typescript theme={null}
thaliq.on('rateLimit', (info) => {
  showToast(`Limite alcanzado. Reintenta en ${info.retryAfter}s`);
});
```

### Error boundaries

Envuelve las llamadas al SDK en bloques try/catch para manejar errores de red:

```typescript theme={null}
try {
  const stream = thaliq.agent.stream('Hola');
  for await (const event of stream) { /* ... */ }
} catch (error) {
  if (error instanceof ConnectionError) {
    showOfflineMessage();
  } else if (error instanceof TimeoutError) {
    showTimeoutMessage();
  }
}
```
