@syrtis-ai/syrtis-javascript-client 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @syrtis-ai/syrtis-javascript-client
2
2
 
3
- Version: 2.0.0
3
+ Version: 3.0.0
4
4
 
5
5
  ## Table of Contents
6
6
 
@@ -8,11 +8,7 @@ Version: 2.0.0
8
8
  - [Usage](#usage)
9
9
  - [Suite Signature](#suite-signature)
10
10
 
11
- # @syrtis-ai/syrtis-javascript-client
12
-
13
- Version: 0.0.75
14
-
15
- ## Table of Contents
11
+ TypeScript client for the Syrtis public API: sessions, conversational messages (sync or async via live updates), history and entity hydration. It targets the versioned API (`2026-1` by default) and carries no server secret — authentication uses a bearer token, and realtime subscriptions rely on scoped, short-lived JWTs fetched from the API.
16
12
 
17
13
  ## Installation
18
14
 
@@ -26,18 +22,188 @@ npm install @syrtis-ai/syrtis-javascript-client
26
22
  import SyrtisClient from '@syrtis-ai/syrtis-javascript-client/Common/SyrtisClient';
27
23
 
28
24
  const client = new SyrtisClient({
25
+ host: 'https://api.syrtis.ai',
29
26
  bearerToken: 'your_token_here',
30
27
  });
31
28
  ```
32
29
 
33
- By default the client targets the latest API version. To pin a specific version:
30
+ By default the client targets the latest API version (`2026-1`). To pin a specific version:
34
31
 
35
32
  ```typescript
36
33
  const client = new SyrtisClient({
34
+ host: 'https://api.syrtis.ai',
37
35
  bearerToken: 'your_token_here',
36
+ apiVersion: SyrtisClient.API_VERSION_2025_3,
37
+ });
38
+ ```
39
+
40
+ ## Repositories
41
+
42
+ Entities are accessed through repositories, resolved from the entity class:
43
+
44
+ ```typescript
45
+ import Session from '@syrtis-ai/syrtis-javascript-client/Entity/Session';
46
+ import type SessionRepository from '@syrtis-ai/syrtis-javascript-client/Repository/SessionRepository';
47
+
48
+ const sessionRepository = client.getRepository(Session) as SessionRepository;
49
+ ```
50
+
51
+ ## Creating a session
52
+
53
+ ```typescript
54
+ const session = await sessionRepository.createSession({
55
+ scenarioSecureId: 'sce_…',
56
+ title: 'Support conversation', // optional
57
+ });
58
+ // session.secureId → use it for sendMessage / fetchHistory / subscribe
59
+ ```
60
+
61
+ ## Sending a message
62
+
63
+ `sendMessage` posts to `session/continue/{secureId}` and returns hydrated `Message[]` entities (the messages produced by the scenario):
64
+
65
+ ```typescript
66
+ const messages = await sessionRepository.sendMessage({
67
+ sessionSecureId: 'session_secure_id',
68
+ content: 'Hello',
69
+ });
70
+ ```
71
+
72
+ ### Synchronous mode
73
+
74
+ By default the API responds as soon as the request is accepted. With `sync: true`, the HTTP response is held until the whole scenario processing is done, so the returned messages include the full reply:
75
+
76
+ ```typescript
77
+ const messages = await sessionRepository.sendMessage({
78
+ sessionSecureId: 'session_secure_id',
79
+ content: 'Hello',
80
+ sync: true,
81
+ });
82
+ ```
83
+
84
+ Other supported options: `files`, `contentType`, `format`, `templateId`, `stamps`, `name`, `metadata`, `fileStamps`, `parentRequestSecureId`, `timeZone`.
85
+
86
+ ### Sending several messages in one request
87
+
88
+ All messages of a single `sendMessage` call belong to the same scenario request — the scenario processes them as one conversation turn (unlike two successive `sendMessage` calls, which create two turns). `content` is a shortcut for the first message; `messages` carries the others (or all of them), with the same defaults (`conversation`/`text`):
89
+
90
+ ```typescript
91
+ const reply = await sessionRepository.sendMessageAndWaitForReply({
92
+ sessionSecureId,
93
+ content: 'Hello',
94
+ messages: [
95
+ { content: 'Your name is Marion', name: 'CONTEXT_INSTRUCTION' },
96
+ ],
97
+ });
98
+ ```
99
+
100
+ ## Working with messages
101
+
102
+ `Message` exposes typed fields (`content`, `contentType`, `format`, `name`, `origin`, `dateCreated`, `versionMajor`, `versionMinor`) plus the discriminant constants used by the API (`Message.ORIGIN_*`, `Message.CONTENT_TYPE_*`, `Message.FORMAT_*`).
103
+
104
+ ```typescript
105
+ import Message from '@syrtis-ai/syrtis-javascript-client/Entity/Message';
106
+
107
+ // Conversational replies produced by the scenario (origin node + contentType conversation):
108
+ const lastReply = messages.filter(Message.isReply).at(-1);
109
+
110
+ // Find a scenario output by name:
111
+ const extracted = messages.find((m) => m.name === 'EXTRACTED_COMPANY');
112
+
113
+ // Structured content: for format 'json' messages, getParsedContent() returns the
114
+ // server-parsed object (metadata.formattedContent), falling back to JSON.parse(content).
115
+ // For other formats it returns the raw content.
116
+ const data = extracted?.getParsedContent();
117
+ ```
118
+
119
+ ## Async conversations (live updates)
120
+
121
+ No configuration is required: `subscribe()` fetches a scoped, short-lived Mercure subscriber JWT from the API (`session/subscribe-info/{secureId}`) and renews it automatically on reconnection. The API bearer token is enough.
122
+
123
+ Subscribe to a session — payloads are hydrated into entities, reconnection with backoff is automatic:
124
+
125
+ ```typescript
126
+ const connection = sessionRepository.subscribe({
127
+ sessionSecureId: 'session_secure_id',
128
+ onMessage: (message) => { /* hydrated Message */ },
129
+ onRequest: (request) => { /* hydrated Request */ },
130
+ onEvent: (liveEvent) => { /* every raw event: {entityType, event, data} */ },
131
+ onStatusChange: (status) => { /* connecting | open | error | closed */ },
132
+ });
133
+
134
+ connection.close(); // when done
135
+ ```
136
+
137
+ Send and wait for the scenario reply without holding the HTTP response:
138
+
139
+ ```typescript
140
+ const reply = await sessionRepository.sendMessageAndWaitForReply({
141
+ sessionSecureId: 'session_secure_id',
142
+ content: 'Hello',
143
+ timeoutMs: 60000, // default 120000; ERR_LIVE_UPDATES_REPLY_TIMEOUT on expiry
144
+ });
145
+ ```
146
+
147
+ By default the promise resolves on the first `Message.isReply` message; pass `isReply: (m) => ...` to customize.
148
+
149
+ To bypass the automatic JWT flow, pass `mercureHubUrl`/`mercureJwt` to the client constructor (static hub configuration), or inject a `liveUpdatesDriver` (any `LiveUpdatesDriverInterface` from `@wexample/js-api/Common/LiveUpdates/LiveUpdatesDriver`) for a custom transport. Both take precedence over the subscribe-info flow. `fetchSubscribeInfo(sessionSecureId)` is also available directly on the repository.
150
+
151
+ ## Fetching history
152
+
153
+ ```typescript
154
+ const { messages, hasMore } = await sessionRepository.fetchHistory({
155
+ sessionSecureId: 'session_secure_id',
156
+ page: 0,
157
+ length: 50,
38
158
  });
39
159
  ```
40
160
 
161
+ `hasMore` is computed server side (correct even with filters); it is `null` when the API did not paginate (no `length` requested).
162
+
163
+ Also supports `lastRequestSecureId`, `orderBy` and `orderDirection`.
164
+
165
+ Conversations are trees (message versions create branches). `lastRequestSecureId` selects which branch the history walks: it anchors the walk on that request and returns messages from its branch (the request and its ancestors). Without it, the walk starts from the latest request of the session. Side effect worth relying on: once anchored, pages are stable — messages sent after the anchor belong to descendant requests and never shift the pagination. For an infinite-scroll chat, capture the `requestSecureId` of the first batch and keep it as `lastRequestSecureId` for the following pages.
166
+
167
+ To display a chat history, filter conversational messages (both user and scenario):
168
+
169
+ ```typescript
170
+ const visible = messages.filter(Message.isConversation);
171
+ ```
172
+
173
+ ## Error handling
174
+
175
+ All API responses use the standard envelope `{ type, code, message?, data }`. Unwrapping is centralized in `@wexample/js-api`: when the server answers `type: 'error'`, repository calls throw an `ApiEnvelopeError` carrying the server error key.
176
+
177
+ ```typescript
178
+ import ApiEnvelopeError from '@wexample/js-api/Common/Errors/ApiEnvelopeError';
179
+
180
+ try {
181
+ await sessionRepository.sendMessage({ sessionSecureId, content, sync: true });
182
+ } catch (error) {
183
+ if (error instanceof ApiEnvelopeError) {
184
+ // error.code: server error key (e.g. 'ERR_INVALID_CREDENTIALS')
185
+ // error.responseCode: numeric code from the envelope
186
+ // error.envelope: raw response for inspection
187
+ }
188
+ throw error;
189
+ }
190
+ ```
191
+
192
+ To unwrap a raw call yourself:
193
+
194
+ ```typescript
195
+ import { unwrapApiEnvelope } from '@wexample/js-api/Common/ApiEnvelope';
196
+
197
+ const data = unwrapApiEnvelope<{ messages: unknown[] }>(await response.json());
198
+ ```
199
+
200
+ ## Extending entities
201
+
202
+ Entity fields are schema-driven and resolved through a Proxy. Two rules when adding code to an entity class:
203
+
204
+ - Prefer explicit methods (`getParsedContent()`) over computed getters.
205
+ - Inside a method, read schema fields with `this.getDataValue('field')` — the Proxy binds methods to the raw target, so `this.field` is not resolved there.
206
+
41
207
  # About us
42
208
 
43
209
  [Syrtis AI](https://syrtis.ai) helps organizations turn artificial intelligence from an idea into reliable, measurable systems. We are a team of engineers and practitioners focused on implementing AI services inside real businesses — from strategy and architecture to deployment, integration, and long-term operations. Our goal is simple: deliver AI that works in production, fits your constraints, and earns its keep.
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.0.0",
2
+ "version": "3.0.0",
3
3
  "type": "module",
4
4
  "name": "@syrtis-ai/syrtis-javascript-client",
5
5
  "scripts": {
@@ -13,7 +13,7 @@
13
13
  "access": "public"
14
14
  },
15
15
  "dependencies": {
16
- "@wexample/js-api": "^0.0.40"
16
+ "@wexample/js-api": "^1.0.0"
17
17
  },
18
18
  "files": [
19
19
  "src"
@@ -0,0 +1,57 @@
1
+ import type {
2
+ LiveUpdatesDriverConnectOptions,
3
+ LiveUpdatesDriverInterface,
4
+ } from '@wexample/js-api/Common/LiveUpdates/LiveUpdatesDriver';
5
+ import MercureLiveUpdatesDriver from '@wexample/js-api/Common/LiveUpdates/MercureLiveUpdatesDriver';
6
+ import type SessionRepository from '../Repository/SessionRepository.js';
7
+ import type { SessionSubscribeInfo } from '../Repository/SessionRepository.js';
8
+
9
+ // Renew the JWT slightly before its announced expiration.
10
+ const EXPIRATION_MARGIN_MS = 60000;
11
+
12
+ // Driver that fetches a scoped, short-lived Mercure subscriber JWT from the
13
+ // API (session/subscribe-info/{secureId}) before each connection, caching it
14
+ // until close to expiration. Reconnections automatically pick a fresh JWT.
15
+ export default class SessionSubscribeInfoDriver implements LiveUpdatesDriverInterface {
16
+ private cachedInfo: SessionSubscribeInfo | null = null;
17
+
18
+ constructor(
19
+ private readonly repository: SessionRepository,
20
+ private readonly sessionSecureId: string
21
+ ) {}
22
+
23
+ async connect(options: LiveUpdatesDriverConnectOptions): Promise<EventSource> {
24
+ const info = await this.getFreshSubscribeInfo();
25
+
26
+ return new MercureLiveUpdatesDriver({
27
+ hubUrl: info.hubUrl,
28
+ jwt: info.jwt,
29
+ // Authorization is carried by the scoped JWT in the URL, not by
30
+ // cookies — required for hubs answering Access-Control-Allow-Origin: *.
31
+ withCredentials: false,
32
+ }).connect(options);
33
+ }
34
+
35
+ private async getFreshSubscribeInfo(): Promise<SessionSubscribeInfo> {
36
+ if (this.cachedInfo && !this.isExpiringSoon(this.cachedInfo)) {
37
+ return this.cachedInfo;
38
+ }
39
+
40
+ this.cachedInfo = await this.repository.fetchSubscribeInfo(this.sessionSecureId);
41
+
42
+ return this.cachedInfo;
43
+ }
44
+
45
+ private isExpiringSoon(info: SessionSubscribeInfo): boolean {
46
+ if (!info.expiresAt) {
47
+ return true;
48
+ }
49
+
50
+ const expiresAtMs = Date.parse(info.expiresAt);
51
+ if (Number.isNaN(expiresAtMs)) {
52
+ return true;
53
+ }
54
+
55
+ return Date.now() >= expiresAtMs - EXPIRATION_MARGIN_MS;
56
+ }
57
+ }
@@ -1,12 +1,20 @@
1
1
  import type { ApiClientOptions } from '@wexample/js-api/Common/AbstractApiClient';
2
2
  import AbstractApiEntitiesClient from '@wexample/js-api/Common/AbstractApiEntitiesClient';
3
3
  import type { RepositoryClass } from '@wexample/js-api/Common/ApiEntityManager';
4
+ import LiveUpdatesError from '@wexample/js-api/Common/Errors/LiveUpdatesError';
5
+ import type { LiveUpdatesDriverInterface } from '@wexample/js-api/Common/LiveUpdates/LiveUpdatesDriver';
6
+ import MercureLiveUpdatesDriver from '@wexample/js-api/Common/LiveUpdates/MercureLiveUpdatesDriver';
4
7
  import getEntitySchemas from './entitySchemas.js';
5
8
  import generatedRepositories from './generatedRepositories.js';
6
9
 
7
10
  export type SyrtisClientOptions = Omit<ApiClientOptions, 'baseUrl'> & {
8
11
  host: string;
9
12
  apiVersion?: string;
13
+ // Live updates (async conversations). Provide both Mercure options, or
14
+ // inject a custom driver; when neither is set, subscribe() throws.
15
+ mercureHubUrl?: string;
16
+ mercureJwt?: string | null;
17
+ liveUpdatesDriver?: LiveUpdatesDriverInterface;
10
18
  };
11
19
 
12
20
  export default class SyrtisClient extends AbstractApiEntitiesClient {
@@ -14,14 +22,46 @@ export default class SyrtisClient extends AbstractApiEntitiesClient {
14
22
  static readonly API_VERSION_2026_1 = '2026-1';
15
23
  static readonly API_VERSION_DEFAULT = SyrtisClient.API_VERSION_2026_1;
16
24
 
25
+ private liveUpdatesDriver: LiveUpdatesDriverInterface | null;
26
+
17
27
  constructor(options: SyrtisClientOptions) {
18
- const { host, apiVersion, ...rest } = options;
28
+ const { host, apiVersion, mercureHubUrl, mercureJwt, liveUpdatesDriver, ...rest } = options;
19
29
  const version = apiVersion ?? SyrtisClient.API_VERSION_DEFAULT;
20
30
  const normalizedHost = host.endsWith('/') ? host : host + '/';
21
31
  super({
22
32
  ...rest,
23
33
  baseUrl: `${normalizedHost}api/${version}/`,
24
34
  });
35
+
36
+ this.liveUpdatesDriver =
37
+ liveUpdatesDriver ??
38
+ (mercureHubUrl
39
+ ? new MercureLiveUpdatesDriver({
40
+ hubUrl: mercureHubUrl,
41
+ jwt: mercureJwt ?? null,
42
+ })
43
+ : null);
44
+ }
45
+
46
+ setLiveUpdatesDriver(driver: LiveUpdatesDriverInterface): void {
47
+ this.liveUpdatesDriver = driver;
48
+ }
49
+
50
+ hasLiveUpdatesDriver(): boolean {
51
+ return this.liveUpdatesDriver !== null;
52
+ }
53
+
54
+ getLiveUpdatesDriver(): LiveUpdatesDriverInterface {
55
+ if (!this.liveUpdatesDriver) {
56
+ throw new LiveUpdatesError({
57
+ message:
58
+ 'Live updates are not configured: pass mercureHubUrl (and mercureJwt) ' +
59
+ 'to the client constructor, or inject a liveUpdatesDriver.',
60
+ code: 'ERR_LIVE_UPDATES_NOT_CONFIGURED',
61
+ });
62
+ }
63
+
64
+ return this.liveUpdatesDriver;
25
65
  }
26
66
 
27
67
  protected getRepositoryClasses(): RepositoryClass[] {
@@ -4,7 +4,101 @@ import schema from '../data/entity/message.json';
4
4
  export default class Message extends AbstractApiEntity {
5
5
  static readonly entityName = 'message';
6
6
 
7
+ // Schema-driven fields, resolved at runtime through the entity Proxy.
8
+ declare readonly content?: string | null;
9
+ declare readonly contentType?: string | null;
10
+ declare readonly dateCreated?: Date | null;
11
+ declare readonly format?: string | null;
12
+ declare readonly name?: string | null;
13
+ declare readonly origin?: string | null;
14
+ declare readonly versionMajor?: number | null;
15
+ declare readonly versionMinor?: number | null;
16
+
17
+ static readonly ORIGIN_CARD = 'card';
18
+ static readonly ORIGIN_CORE = 'core';
19
+ static readonly ORIGIN_NODE = 'node';
20
+ static readonly ORIGIN_USER = 'user';
21
+
22
+ static readonly CONTENT_TYPE_ACTIONS = 'actions';
23
+ static readonly CONTENT_TYPE_ANALYSIS = 'analysis';
24
+ static readonly CONTENT_TYPE_CONVERSATION = 'conversation';
25
+ static readonly CONTENT_TYPE_DEBUG = 'debug';
26
+ static readonly CONTENT_TYPE_DEFAULT = 'default';
27
+ static readonly CONTENT_TYPE_DOWNLOAD = 'download';
28
+ static readonly CONTENT_TYPE_ERROR = 'error';
29
+ static readonly CONTENT_TYPE_FORM = 'form';
30
+ static readonly CONTENT_TYPE_HTTP_RESPONSE = 'http_response';
31
+ static readonly CONTENT_TYPE_IMAGE = 'image';
32
+ static readonly CONTENT_TYPE_INFO = 'info';
33
+ static readonly CONTENT_TYPE_LIST = 'list';
34
+ static readonly CONTENT_TYPE_NAVIGATE = 'navigate';
35
+ static readonly CONTENT_TYPE_NAVIGATED = 'navigated';
36
+ static readonly CONTENT_TYPE_PROGRESS = 'progress';
37
+ static readonly CONTENT_TYPE_REFERENCE = 'reference';
38
+ static readonly CONTENT_TYPE_SESSION = 'session';
39
+ static readonly CONTENT_TYPE_SESSION_EXPIRE = 'session_expire';
40
+ static readonly CONTENT_TYPE_SESSION_STATUS = 'session_status';
41
+ static readonly CONTENT_TYPE_SUCCESS = 'success';
42
+ static readonly CONTENT_TYPE_THOUGHT = 'thought';
43
+ static readonly CONTENT_TYPE_UPLOAD = 'upload';
44
+ static readonly CONTENT_TYPE_URL = 'url';
45
+ static readonly CONTENT_TYPE_VIDEO = 'video';
46
+ static readonly CONTENT_TYPE_WARNING = 'warning';
47
+
48
+ static readonly FORMAT_BOOLEAN = 'boolean';
49
+ static readonly FORMAT_FLOAT = 'float';
50
+ static readonly FORMAT_HTML = 'html';
51
+ static readonly FORMAT_INTEGER = 'integer';
52
+ static readonly FORMAT_JSON = 'json';
53
+ static readonly FORMAT_MARKDOWN = 'markdown';
54
+ static readonly FORMAT_NULL = 'null';
55
+ static readonly FORMAT_TEXT = 'text';
56
+ static readonly FORMAT_YAML = 'yaml';
57
+
7
58
  static retrieveEntitySchema() {
8
59
  return schema;
9
60
  }
61
+
62
+ // A "reply" is a conversational message produced by the scenario,
63
+ // as opposed to user input or technical messages.
64
+ static isReply(message: Message): boolean {
65
+ return (
66
+ message.origin === Message.ORIGIN_NODE &&
67
+ message.contentType === Message.CONTENT_TYPE_CONVERSATION
68
+ );
69
+ }
70
+
71
+ // A conversational message from any origin (user input included) —
72
+ // what a chat history typically displays.
73
+ static isConversation(message: Message): boolean {
74
+ return message.contentType === Message.CONTENT_TYPE_CONVERSATION;
75
+ }
76
+
77
+ // For JSON messages, the server already parses the content into
78
+ // metadata.formattedContent; fall back to parsing the raw content.
79
+ // Note: schema fields are read through getDataValue() because the
80
+ // entity Proxy binds methods to the raw target, where `this.format`
81
+ // and friends are not resolved.
82
+ getParsedContent(): unknown {
83
+ const format = this.getDataValue('format');
84
+ const content = this.getDataValue('content');
85
+
86
+ if (format !== Message.FORMAT_JSON) {
87
+ return content;
88
+ }
89
+
90
+ const metadata = this.metadata;
91
+ if (metadata && !Array.isArray(metadata)) {
92
+ const formatted = (metadata as Record<string, unknown>).formattedContent;
93
+ if (formatted !== undefined && formatted !== null) {
94
+ return formatted;
95
+ }
96
+ }
97
+
98
+ if (typeof content === 'string' && content.trim() !== '') {
99
+ return JSON.parse(content);
100
+ }
101
+
102
+ return null;
103
+ }
10
104
  }
@@ -1,21 +1,79 @@
1
1
  import AbstractApiRepository from '@wexample/js-api/Common/AbstractApiRepository';
2
+ import LiveUpdatesError from '@wexample/js-api/Common/Errors/LiveUpdatesError';
3
+ import LiveUpdatesConnection, {
4
+ type LiveUpdatesConnectionStatus,
5
+ } from '@wexample/js-api/Common/LiveUpdates/LiveUpdatesConnection';
6
+ import SessionSubscribeInfoDriver from '../Common/SessionSubscribeInfoDriver.js';
7
+ import type SyrtisClient from '../Common/SyrtisClient.js';
2
8
  import Message from '../Entity/Message.js';
9
+ import Request from '../Entity/Request.js';
3
10
  import Session from '../Entity/Session.js';
4
11
  import type MessageRepository from './MessageRepository.js';
5
12
 
13
+ export type SessionMessagePayload = {
14
+ content: string;
15
+ name?: string | null;
16
+ contentType?: string;
17
+ format?: string;
18
+ templateId?: string | number | null;
19
+ stamps?: string[];
20
+ metadata?: Record<string, unknown> | unknown[] | null;
21
+ };
22
+
6
23
  export type SessionSendMessageOptions = {
7
24
  sessionSecureId: string;
25
+ // Single-message shortcut; content/name/contentType/... describe one message.
8
26
  content?: string | null;
9
- files?: File[];
10
27
  contentType?: string;
11
28
  format?: string;
12
29
  templateId?: string | number | null;
13
30
  stamps?: string[];
14
31
  name?: string | null;
15
32
  metadata?: Record<string, unknown> | unknown[] | null;
33
+ // Additional messages sent in the same POST (same scenario request).
34
+ // Cumulative with the content shortcut; same per-message defaults.
35
+ messages?: SessionMessagePayload[];
36
+ files?: File[];
16
37
  fileStamps?: Record<string, string[]>;
17
38
  parentRequestSecureId?: string | null;
18
39
  timeZone?: string | null;
40
+ // When true, the API waits for the whole response to be processed
41
+ // before returning the HTTP response.
42
+ sync?: boolean;
43
+ };
44
+
45
+ // Payload published by the API on the session Mercure topic:
46
+ // { entity_type: 'Message'|'Request', event: 'message.save'|..., data: {...} }
47
+ export type SessionLiveEvent = {
48
+ entityType: string;
49
+ event: string;
50
+ data: Record<string, unknown>;
51
+ };
52
+
53
+ // Response of GET session/subscribe-info/{secureId}.
54
+ export type SessionSubscribeInfo = {
55
+ hubUrl: string;
56
+ jwt: string;
57
+ topics: string[];
58
+ expiresAt: string;
59
+ };
60
+
61
+ export type SessionSubscribeOptions = {
62
+ sessionSecureId: string;
63
+ onMessage?: (message: Message, liveEvent: SessionLiveEvent) => void;
64
+ onRequest?: (request: Request, liveEvent: SessionLiveEvent) => void;
65
+ // Called for every event, including entity types without a dedicated handler.
66
+ onEvent?: (liveEvent: SessionLiveEvent) => void;
67
+ onStatusChange?: (
68
+ status: LiveUpdatesConnectionStatus,
69
+ previousStatus: LiveUpdatesConnectionStatus
70
+ ) => void;
71
+ };
72
+
73
+ export type SessionSendMessageAndWaitOptions = SessionSendMessageOptions & {
74
+ timeoutMs?: number;
75
+ // Predicate deciding which incoming message resolves the promise.
76
+ isReply?: (message: Message) => boolean;
19
77
  };
20
78
 
21
79
  export type SessionFetchHistoryOptions = {
@@ -27,55 +85,84 @@ export type SessionFetchHistoryOptions = {
27
85
  orderDirection?: 'ASC' | 'DESC' | null;
28
86
  };
29
87
 
88
+ export type SessionCreateOptions = {
89
+ scenarioSecureId: string;
90
+ title?: string | null;
91
+ };
92
+
93
+ export type SessionHistory = {
94
+ messages: Message[];
95
+ // Null when the API did not compute it (no length requested).
96
+ hasMore: boolean | null;
97
+ };
98
+
30
99
  export default class SessionRepository extends AbstractApiRepository<Session> {
31
100
  static getEntityType() {
32
101
  return Session;
33
102
  }
34
103
 
35
- async sendMessage(options: SessionSendMessageOptions): Promise<unknown> {
104
+ // Creates a new session on the given scenario and returns it hydrated
105
+ // (its secureId is then used for continue/history/subscribe).
106
+ // Input validation is the API's job — payload is sent as-is.
107
+ async createSession(options: SessionCreateOptions): Promise<Session> {
108
+ const data = await this.post({
109
+ endpoint: 'create',
110
+ payload: options,
111
+ });
112
+
113
+ const payload = this.extractPayload(data);
114
+
115
+ return this.createFromApiItem(
116
+ payload as Parameters<AbstractApiRepository<Session>['createFromApiItem']>[0]
117
+ );
118
+ }
119
+
120
+ async sendMessage(options: SessionSendMessageOptions): Promise<Message[]> {
36
121
  const {
37
122
  sessionSecureId,
38
123
  content = null,
39
124
  files = [],
40
- contentType = 'conversation',
41
- format = 'text',
42
- templateId = null,
43
- stamps = [],
44
- name = null,
45
- metadata = null,
125
+ contentType,
126
+ format,
127
+ templateId,
128
+ stamps,
129
+ name,
130
+ metadata,
131
+ messages = [],
46
132
  fileStamps = {},
47
133
  parentRequestSecureId = null,
48
134
  timeZone = null,
135
+ sync = false,
49
136
  } = options;
50
137
 
51
- const trimmedSecureId = String(sessionSecureId || '').trim();
52
- if (!trimmedSecureId) {
53
- throw new Error('Session secureId is required.');
54
- }
138
+ const messagePayloads = [];
55
139
 
56
140
  const trimmedContent = typeof content === 'string' ? content.trim() : '';
57
- if (!trimmedContent && files.length === 0) {
58
- throw new Error('Message content or at least one file is required.');
141
+ if (trimmedContent) {
142
+ messagePayloads.push(
143
+ this.buildMessagePayload({
144
+ content: trimmedContent,
145
+ contentType,
146
+ format,
147
+ templateId,
148
+ stamps,
149
+ name,
150
+ metadata,
151
+ })
152
+ );
59
153
  }
60
154
 
61
- const messages = [];
62
- if (trimmedContent) {
63
- messages.push({
64
- contentType,
65
- format,
66
- templateId,
67
- stamps,
68
- content: trimmedContent,
69
- metadata,
70
- name,
71
- });
155
+ for (const message of messages) {
156
+ messagePayloads.push(this.buildMessagePayload(message));
72
157
  }
73
158
 
74
- return this.client
159
+ const data = await this.client
75
160
  .requestFormDataFromJson({
76
- path: this.buildPath(`continue/${encodeURIComponent(trimmedSecureId)}`),
161
+ path: this.buildPath(
162
+ `continue/${encodeURIComponent(sessionSecureId)}${sync ? '/sync' : ''}`
163
+ ),
77
164
  data: {
78
- messages,
165
+ messages: messagePayloads,
79
166
  fileStamps,
80
167
  parentRequestSecureId,
81
168
  timeZone: timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone,
@@ -83,9 +170,161 @@ export default class SessionRepository extends AbstractApiRepository<Session> {
83
170
  files,
84
171
  })
85
172
  .json<unknown>();
173
+
174
+ return this.hydrateMessages(data);
175
+ }
176
+
177
+ protected buildMessagePayload(message: SessionMessagePayload) {
178
+ return {
179
+ content: message.content,
180
+ contentType: message.contentType ?? Message.CONTENT_TYPE_CONVERSATION,
181
+ format: message.format ?? Message.FORMAT_TEXT,
182
+ templateId: message.templateId ?? null,
183
+ stamps: message.stamps ?? [],
184
+ metadata: message.metadata ?? null,
185
+ name: message.name ?? null,
186
+ };
187
+ }
188
+
189
+ // Fetches a scoped, short-lived Mercure subscriber JWT for this session.
190
+ async fetchSubscribeInfo(sessionSecureId: string): Promise<SessionSubscribeInfo> {
191
+ const data = await this.client
192
+ .get({
193
+ path: this.buildPath(`subscribe-info/${encodeURIComponent(sessionSecureId)}`),
194
+ })
195
+ .json<unknown>();
196
+
197
+ const payload = this.extractPayload(data) as Record<string, unknown>;
198
+
199
+ if (typeof payload.hubUrl !== 'string' || typeof payload.jwt !== 'string') {
200
+ throw new Error('Invalid subscribe-info payload: missing "hubUrl" or "jwt".');
201
+ }
202
+
203
+ return {
204
+ hubUrl: payload.hubUrl,
205
+ jwt: payload.jwt,
206
+ topics: Array.isArray(payload.topics) ? (payload.topics as string[]) : [],
207
+ expiresAt: typeof payload.expiresAt === 'string' ? payload.expiresAt : '',
208
+ };
209
+ }
210
+
211
+ // Subscribes to the session live topic and dispatches hydrated entities.
212
+ // With no specific configuration, a scoped subscriber JWT is fetched from
213
+ // the API (and renewed on reconnection); mercureHubUrl/mercureJwt or a
214
+ // custom liveUpdatesDriver on the client take precedence. Returns the
215
+ // connection; call close() when done.
216
+ subscribe(options: SessionSubscribeOptions): LiveUpdatesConnection {
217
+ const client = this.client as SyrtisClient;
218
+
219
+ return new LiveUpdatesConnection({
220
+ driver: client.hasLiveUpdatesDriver()
221
+ ? client.getLiveUpdatesDriver()
222
+ : new SessionSubscribeInfoDriver(this, options.sessionSecureId),
223
+ topics: [this.buildLiveTopic(options.sessionSecureId)],
224
+ onStatusChange: options.onStatusChange,
225
+ onMessage: (payload) => {
226
+ const liveEvent = this.parseLiveEvent(payload);
227
+ if (!liveEvent) {
228
+ return;
229
+ }
230
+
231
+ options.onEvent?.(liveEvent);
232
+
233
+ if (liveEvent.entityType === 'Message') {
234
+ options.onMessage?.(Message.fromApi<Message>(liveEvent.data), liveEvent);
235
+ } else if (liveEvent.entityType === 'Request') {
236
+ options.onRequest?.(Request.fromApi<Request>(liveEvent.data), liveEvent);
237
+ }
238
+ },
239
+ });
240
+ }
241
+
242
+ // Sends a message without holding the HTTP response, then resolves with
243
+ // the first live message matching isReply (default: Message.isReply).
244
+ async sendMessageAndWaitForReply(options: SessionSendMessageAndWaitOptions): Promise<Message> {
245
+ const { timeoutMs = 120000, isReply = Message.isReply, ...sendOptions } = options;
246
+
247
+ return new Promise<Message>((resolve, reject) => {
248
+ let settled = false;
249
+ let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
250
+ let connection: LiveUpdatesConnection | null = null;
251
+
252
+ const settle = (finish: () => void) => {
253
+ settled = true;
254
+ if (timeoutHandle) {
255
+ clearTimeout(timeoutHandle);
256
+ }
257
+ connection?.close();
258
+ finish();
259
+ };
260
+
261
+ connection = this.subscribe({
262
+ sessionSecureId: sendOptions.sessionSecureId,
263
+ onMessage: (message) => {
264
+ if (!settled && isReply(message)) {
265
+ settle(() => resolve(message));
266
+ }
267
+ },
268
+ });
269
+
270
+ timeoutHandle = setTimeout(() => {
271
+ if (!settled) {
272
+ settle(() =>
273
+ reject(
274
+ new LiveUpdatesError({
275
+ message: `No reply received within ${timeoutMs}ms.`,
276
+ code: 'ERR_LIVE_UPDATES_REPLY_TIMEOUT',
277
+ })
278
+ )
279
+ );
280
+ }
281
+ }, timeoutMs);
282
+
283
+ this.sendMessage(sendOptions).catch((error) => {
284
+ if (!settled) {
285
+ settle(() => reject(error));
286
+ }
287
+ });
288
+ });
86
289
  }
87
290
 
88
- async fetchHistory(options: SessionFetchHistoryOptions): Promise<Message[]> {
291
+ protected buildLiveTopic(sessionSecureId: string): string {
292
+ return `entity/session/event/${sessionSecureId}`;
293
+ }
294
+
295
+ protected parseLiveEvent(payload: unknown): SessionLiveEvent | null {
296
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
297
+ return null;
298
+ }
299
+
300
+ const record = payload as Record<string, unknown>;
301
+ const entityType = record.entity_type;
302
+ const data = record.data;
303
+
304
+ if (typeof entityType !== 'string' || !data || typeof data !== 'object') {
305
+ return null;
306
+ }
307
+
308
+ return {
309
+ entityType,
310
+ event: typeof record.event === 'string' ? record.event : '',
311
+ data: data as Record<string, unknown>,
312
+ };
313
+ }
314
+
315
+ protected hydrateMessages(data: unknown): Message[] {
316
+ const payload = this.extractPayload(data);
317
+ const items = (payload as Record<string, unknown>).messages;
318
+
319
+ if (!Array.isArray(items)) {
320
+ throw new Error('Invalid API payload: missing "messages" array.');
321
+ }
322
+
323
+ const messageRepository = this.client.getRepository(Message) as MessageRepository;
324
+ return messageRepository.hydrateFromApiCollection(items);
325
+ }
326
+
327
+ async fetchHistory(options: SessionFetchHistoryOptions): Promise<SessionHistory> {
89
328
  const {
90
329
  sessionSecureId,
91
330
  page = 0,
@@ -130,7 +369,19 @@ export default class SessionRepository extends AbstractApiRepository<Session> {
130
369
  const payload = this.extractPayload(data);
131
370
  const items = this.extractItems(payload);
132
371
 
372
+ const pagination = (payload as Record<string, unknown>).pagination;
373
+ const hasMore =
374
+ pagination &&
375
+ typeof pagination === 'object' &&
376
+ typeof (pagination as Record<string, unknown>).hasMore === 'boolean'
377
+ ? ((pagination as Record<string, unknown>).hasMore as boolean)
378
+ : null;
379
+
133
380
  const messageRepository = this.client.getRepository(Message) as MessageRepository;
134
- return messageRepository.hydrateFromApiCollection(items);
381
+
382
+ return {
383
+ messages: messageRepository.hydrateFromApiCollection(items),
384
+ hasMore,
385
+ };
135
386
  }
136
387
  }